Compare commits

...
Author SHA1 Message Date
Alby96andClaude Opus 5.5 7f8cb57a08 docs: record M6 as closed (v0.6.0) and M7 as the current milestone (#61)
CI / Build and test (SQLite) (pull_request) Failing after 45s
CI / PostgreSQL 16 integration (pull_request) Skipped
CI / PostgreSQL 17 integration (pull_request) Skipped
CI / Docker image (pull_request) Skipped
CI / YAML check (pull_request) Successful in 1m1s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 22:35:34 +01:00
Alby96andClaude Opus 5.5 4b759ee96e docs: purchases and warehouse guide with screenshots, ADR 0035 and the 0.6.0 changelog (#61)
CI / Build and test (SQLite) (pull_request) Canceled after 0s
CI / PostgreSQL 16 integration (pull_request) Canceled after 0s
CI / PostgreSQL 17 integration (pull_request) Canceled after 0s
CI / Docker image (pull_request) Canceled after 0s
CI / YAML check (pull_request) Canceled after 0s
The Acquisti and Magazzino wiki pages now describe what M6 delivers, with real
screenshots of the demo company: stock, item movements, valuation, stock take, reorder
proposal, receipts, price differences, e-invoice import and pending self-invoices. The
user guide gains the buying and warehouse steps; the pages that said "arriva con M6"
(sales, items, dashboard, import, scheduled jobs, demo data) are brought up to date.
ADR 0035 records how documents post to the warehouse, the recomputed weighted average,
the invoice cost correction, the rebuild, the stock take, the base tables of existing
companies and where the Italian self-invoice and import rules live.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 22:24:43 +01:00
Alby96andClaude Opus 5.5 cd4cb85562 fix: tidy the warehouse screens and the supplier document labels (#55 #60)
Seen while checking M6 in the browser: the stock take toolbar crowded the panel title,
the reorder and stock take tables ran past their panel, and the movements dialog cut
the balance column. Confirmed supplier receipts have no number of their own and showed
"Bozza"; they now read "Senza numero". The self-invoice advice no longer doubles the
full stop, and a single price difference reads in the singular.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 22:24:43 +01:00
Alby96andClaude Opus 5.5 ced689b297 feat: warehouse and purchase screens, e-invoice import, demo purchases (#55 #56 #57 #58 #60)
Stock, stock take and reorder screens under /magazzino, with valuation, rebuild and the
movements of an item; the understock dashboard widget. Supplier e-invoices (XML, p7m, ZIP)
become draft purchase invoices with supplier, items and tax codes matched, the file attached
and duplicates refused; the TD code mapping stays in the Italian fiscal pack. Purchase
invoices show price differences against the order and the self-invoice still to issue,
with a pending list on the self-invoice screen. The opening stock import now writes an
opening movement. The demo company gets purchases, an opening stock, a pending
self-invoice and a stock take being counted.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 22:01:32 +01:00
Alby96andClaude Opus 5.5 eb301fa570 feat: stock take, reorder proposal and warehouse rebuild (#60)
A physical stock take freezes the book quantity and cost of a warehouse at a
date, takes counts typed or read from a scanner file, and posts the gains and
losses as INVP/INVN movements at that date. The reorder proposal lists the
items whose available and ordered quantity no longer covers the reorder point
and turns the accepted lines into draft supplier orders, one per supplier.
The warehouse can be rebuilt from its documents on demand and every Sunday
night, as a safety net after imports or corrections.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 21:35:34 +01:00
Alby96andClaude Opus 5.5 f8b72f4d17 feat: purchase and warehouse documents on the document screens (#55 #56 #58)
The document radars and records now serve /acquisti and /magazzino too:
supplier orders, receipts, supplier invoices and credit notes, self-invoices
and warehouse movements, with the supplier in place of the customer, the
supplier's number and date, the protocol and VAT date of registered invoices,
and reason and warehouses of a movement. Supplier invoices take their
protocol from the purchase numbering, refuse a second document with the same
supplier number in the same year and show price differences against their
order or receipt. The Italian pack advises the self-invoice a received
invoice needs (TD16-TD19, TD28) with its deadline, and the purchase service
drafts it with the ordinary rate. A credit note of an invoice now moves its
goods back instead of being skipped as already moved.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 21:25:25 +01:00
Alby96andClaude Opus 5.5 eeabb12f96 feat: post documents to the warehouse at weighted average cost (#59)
Confirmed delivery notes, invoices that move goods, supplier receipts and
warehouse movements now write stock movements in the same transaction;
cancelling removes them. Each change re-runs the history of the items
touched, so balances per warehouse, committed and ordered quantities and
the average and last cost stay consistent even when an old document is
cancelled. Supplier invoices give their cost to the receipts they invoice.
Immediate invoices, supplier invoices and credit notes get their warehouse
reasons; the self-invoice types TD20-TD29 join the base tables.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 21:13:27 +01:00
Alby96 20b2421eea Merge branch 'refs/heads/worktree-agent-a350efc9cb07bc00b' into feat/55-acquisti-magazzino 2026-11-12 21:09:11 +01:00
Alby96andClaude Opus 5.5 9a40adecfe feat: read FatturaPA invoices and signed p7m files (#57)
The import of supplier e-invoices needs a reading layer that turns a
received file into plain records, whatever form the file arrives in.

- Fiscal.Abstractions: IIncomingInvoiceReader, an optional pack feature,
  with the IncomingInvoiceFile records and the incoming.* error codes the
  import service and screens build on.
- Infrastructure: CmsSignedData, a minimal CMS SignedData (CAdES .p7m)
  reader on System.Formats.Asn1, since System.Security.Cryptography.Pkcs
  is a separate package. It accepts DER, BER with indefinite lengths and
  chunked content, base64 text and nested envelopes; it checks the
  message digest and the RSA (PKCS#1, PSS) or ECDSA signature with the
  embedded certificate and reports signer, tax code, validity and signing
  time. No trust chain or revocation check: no trusted list offline.
- Fiscal.Italy: FatturaPaReader for FPR12/FPA12 v1.2.x and FSM10, matched
  by local name, DTD prohibited and no resolver, BOM/windows-1252/missing
  declaration tolerated, batches as one invoice per body, attachments
  decoded; registered in ItalyFiscalPack.
- Tests build every sample and signed envelope in code (AsnWriter and
  self-signed certificates), nothing downloaded.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 21:08:29 +01:00
Alby96 2c56c0dff0 Merge M5 · Motore documenti e vendite (v0.5.0) (#124)
Wiki / Publish the wiki (push) Successful in 7s
Release / Image and release (push) Successful in 3m12s
CI / PostgreSQL 16 integration (push) Successful in 2m6s
CI / Build and test (SQLite) (push) Successful in 2m55s
CI / Docker image (push) Skipped
CI / YAML check (push) Successful in 9s
CI / PostgreSQL 17 integration (push) Successful in 1m47s
Document engine, sales cycle, printing and mail of documents, user guide in the wiki.

Closes #47 #48 #49 #50 #51 #52 #53 #54
2026-11-12 18:48:55 +01:00
Alby96andClaude Opus 5.5 cd3e22e8c7 docs: record the M5 pull request in STATUS (#54)
CI / Build and test (SQLite) (pull_request) Successful in 4m7s
CI / PostgreSQL 16 integration (pull_request) Skipped
CI / PostgreSQL 17 integration (pull_request) Skipped
CI / YAML check (pull_request) Successful in 14s
CI / Docker image (pull_request) Successful in 1m49s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 17:39:37 +01:00
Alby96andClaude Opus 5.5 4123ccacb2 docs: user guide with real screenshots, developer README and M5 closing (#53 #54)
CI / Build and test (SQLite) (pull_request) Canceled after 0s
CI / PostgreSQL 16 integration (pull_request) Canceled after 0s
CI / PostgreSQL 17 integration (pull_request) Canceled after 0s
CI / Docker image (pull_request) Canceled after 0s
CI / YAML check (pull_request) Canceled after 0s
The wiki becomes a guide for the people who use Khaemhat: a new "Guida all'uso"
page walks from sign-in to an invoice sent by e-mail, and Vendite is rewritten
around the real screens of 0.5.0 (radars, document mask, Crea …, deferred
invoicing, print preview, mail). Primi passi, Dati di esempio, Allegati, Log
and Impostazioni describe what this version does, including the SMTP variables.

README.md turns into the installation guide for developers: prerequisites,
run-dev, tests with PostgreSQL, migrations, image and wiki publishing.

The engine now writes confirmations, changes of state and deletions to the
Documents log section, the last step of #53. ADR 0034 records the print and
mail decisions; CHANGELOG 0.5.0 and STATUS close the milestone.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 17:38:14 +01:00
Alby96andClaude Opus 5.5 826042f828 feat: sales screens, deferred invoicing, printing and mail of documents (#49 #50 #51 #52)
Quotations, orders, delivery notes, invoices and credit notes get their radars and
one document screen (lines, header, transport, links, attachments) with the
transformations of the engine, so a quotation reaches the invoice without
retyping. The deferred invoicing groups the open delivery notes of a period by
customer, payment and destination into one invoice each.

Every document prints from one model: an HTML preview on screen and a PDF drawn
by the in-house writer, kept among the attachments as a new version. "Invia per
e-mail" proposes recipient, subject and text from the templates, attaches the
PDF and hands it to a background queue that talks SMTP itself (no external
library); the outcome goes to the log, section E-mail/PEC.

The demo company now has a year of sales in every state, made through the
engine, and run-dev.sh no longer writes to a stray B:\b folder under Git Bash.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 17:20:25 +01:00
Alby96andClaude Opus 5.5 f12848865d feat: document totals, VAT summary, stamp duty, withholding and installments (#48)
The engine now computes the totals of every document it saves: line amounts with
cascaded discounts, footer discount on goods, VAT summary per tax code with the tax
on the group total, prices with VAT split back once per group, split payment and
cash-basis exigibility, stamp duty above the threshold of the fiscal pack, social
security contribution, withholding (also on part of the amount) and ENASARCO taken
off the amount to pay. Installments come from the payment terms with end of month,
fixed day, the customer's excluded months and VAT on the first installment.

The figures live in two shared tables keyed by family (ADR 0033) and are rewritten
in the same transaction as the document. DocumentEditor serves the screens: radars,
values proposed by party and item, totals preview without saving, linked documents
and open documents to fulfil. The copy service can merge several documents of one
party, the base of deferred invoicing.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 15:55:58 +01:00
Alby96andClaude Opus 5.5 ddd2273f7e feat: document engine with kinds, states, atomic numbering and fulfilment (#47)
One engine for sales, purchases and warehouse documents (ADR 0032). Each document
type now carries a kind that decides its family of tables, life cycle, effects,
accepted lines, the kinds it fulfils and its permissions, so company-defined types
work without code.

- Six families of header and line tables plus document_links; document_types gets
  document_kind (seeded types filled by the migration and the Italian template),
  document_numerators gets last_date.
- DocumentStateMachine with the order, invoice and simple life cycles and the
  actions each state admits; issued invoices are immutable and are cancelled with
  a reason only before the file reaches the exchange system.
- DocumentNumberingService numbers at confirmation inside the transaction under
  the numerator lock (advisory lock on PostgreSQL, write lock on SQLite): no
  duplicates, a rollback gives the number back, out-of-sequence dates refused on
  gap-free numerators, the new year's numerator created on first use, gap report.
- DocumentEngine, the generic DocumentService<THeader, TLine> and
  DocumentCopyService: save, confirm or issue, cancel, close, reopen, delete,
  duplicate and transform; links are recorded at confirmation and removed at
  cancellation, and FulfillmentCalculator recomputes quantities and states.
- Tests: rules in Core, concurrent numbering on SQLite and PostgreSQL (data tests,
  run on PostgreSQL 18 locally), order to delivery notes to deferred invoice on a
  real instance. Wiki (Vendite, Tabelle azienda), CHANGELOG, STATUS, DATA-MODEL.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 15:30:24 +01:00
Alby96 fa9304834a Merge ci: smoke test dell'immagine senza falsi errori di pipe (#123)
CI / Build and test (SQLite) (push) Successful in 3m10s
CI / PostgreSQL 16 integration (push) Skipped
CI / PostgreSQL 17 integration (push) Skipped
CI / YAML check (push) Successful in 9s
CI / Docker image (push) Successful in 1m57s
2026-11-12 14:01:10 +01:00
Alby96andClaude Opus 5.5 5ba28483a8 ci: read the login page before grepping it in the image smoke test
CI / Build and test (SQLite) (pull_request) Successful in 2m44s
CI / PostgreSQL 16 integration (pull_request) Skipped
CI / PostgreSQL 17 integration (pull_request) Skipped
CI / YAML check (pull_request) Successful in 6s
CI / Docker image (pull_request) Successful in 1m28s
The Docker image job failed on main after the M4 merge although the
container was ready: grep -q stops at the first match and closes the pipe,
curl then fails with a write error (exit 23) and pipefail fails the step.
It depends on timing, which is why the same commit passed on the pull
request. The response and the headers are now read into variables first.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 13:44:29 +01:00
Alby96 02219df9de Merge docs: chiusura M4 (#122) 2026-11-12 13:43:38 +01:00
Alby96andClaude Opus 5.5 11f69b6111 docs: record M4 as closed (v0.4.0) and M5 as the current milestone
CI / Build and test (SQLite) (pull_request) Successful in 2m50s
CI / PostgreSQL 16 integration (pull_request) Skipped
CI / PostgreSQL 17 integration (pull_request) Skipped
CI / YAML check (pull_request) Successful in 6s
CI / Docker image (pull_request) Successful in 1m56s
STATUS is the resume point of every session; after the M4 merge, tag,
image and release it must point at M5 instead of the pending merge.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 13:13:05 +01:00
160 changed files with 22349 additions and 647 deletions

No files matched your search

+6 -2
View File
@@ -152,8 +152,12 @@ jobs:
curl -fsS --max-time 5 "http://$NAME-app:8080/health"
echo
test "$(curl -s -o /dev/null -w '%{http_code}' --max-time 5 "http://$NAME-app:8080/")" = "302"
curl -fsS --max-time 5 "http://$NAME-app:8080/login" | grep -q "Accedi"
curl -fsS -D - -o /dev/null --max-time 5 "http://$NAME-app:8080/login" | grep -qi "content-security-policy"
# Read the whole response first: grep -q closes the pipe at the first match, and with pipefail the
# write error of curl (exit 23) would fail the step depending on timing.
login="$(curl -fsS --max-time 5 "http://$NAME-app:8080/login")"
grep -q "Accedi" <<<"$login"
headers="$(curl -fsS -D - -o /dev/null --max-time 5 "http://$NAME-app:8080/login")"
grep -qi "content-security-policy" <<<"$headers"
test "$(docker exec "$NAME-app" sh -c 'stat -c %u:%g /proc/1')" = "99:100"
test "$(docker exec "$NAME-app" stat -c %u:%g /data)" = "99:100"
docker exec "$NAME-app" pg_dump --version
+119
View File
@@ -7,6 +7,125 @@ 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
collegamenti riga per riga, e le maschere del ciclo attivo: dal preventivo alla fattura stampata e inviata per
e-mail, con un anno di vendite nei dati di esempio e una guida all'uso nella wiki.
### Added
- Motore documenti (#47, ADR 0032): un solo motore per vendite, acquisti e magazzino. Ogni tipo documento ha un
**genere** (17: preventivo, ordine cliente, DDT, fatture immediate, accompagnatorie, differite e di acconto, note
di credito e di debito, parcella, pro forma, autofattura, ordine fornitore, DDT fornitore, fattura e nota di credito
fornitore, movimento di magazzino) che ne decide famiglia, ciclo di vita, effetti, righe ammesse, documenti evadibili
e permessi. Tabelle `sale_quotations`, `sale_orders`, `sale_documents`, `purchase_orders`, `purchase_documents`,
`inventory_documents` con le righe e `document_links`.
- Stati e azioni ammesse per stato (`DocumentStateMachine`): ciclo *documento* (bozza, confermato, evaso in parte,
evaso, chiuso, annullato), *fattura* (bozza, emessa, XML generato, inviata, consegnata, scartata, non consegnata,
annullata) e *semplice*; fattura emessa immutabile, annullamento con motivo solo prima dell'invio allo SDI.
- Numerazione alla conferma dentro la transazione e sotto il lock del numeratore (advisory lock su PostgreSQL, lock di
scrittura su SQLite): nessun numero doppio, un rollback restituisce il numero, controllo della data fuori sequenza
sui numeratori senza buchi, numeratore dell'anno nuovo creato da solo, elenco dei numeri mancanti.
- Evasione riga per riga: copia e trasformazione dei documenti con le quantità residue, collegamenti registrati alla
conferma e tolti all'annullamento, stato evaso/evaso in parte calcolato dalle righe, chiusura e riapertura del
residuo. Servizio generico `DocumentService<THeader, TLine>` per famiglia e `DocumentCopyService`.
- Totali dei documenti (#48, ADR 0033): importo di riga con sconti a cascata, spese e righe di sconto, sconto di
piede sulle merci, prezzi IVA compresa scorporati per aliquota, castelletto IVA per codice con imposta sul totale del
gruppo, esigibilità (immediata, differita, split payment), bollo sopra 77,47 euro di operazioni senza IVA (addebitato
al cliente o no), cassa previdenza con la sua IVA, ritenuta d'acconto (anche sul 50% o 20% per gli agenti), ENASARCO,
netto a pagare. Scadenze dalle condizioni di pagamento con fine mese, giorno fisso, mesi esclusi del cliente, IVA
sulla prima rata e arrotondamento sull'ultima. Tabelle `document_tax_summaries` e `document_installments`,
ricalcolate a ogni salvataggio.
- Copia di più documenti della stessa controparte in uno solo (`MergeAsync`), con una riga di riferimento per ognuno:
la base della fatturazione differita. Le note di credito e di debito ricordano la fattura che correggono.
- Maschere delle vendite (#49, #50): radar di preventivi, ordini, DDT, fatture e note con ricerca, filtri per tipo,
stato e anno; un'unica maschera documento con intestazione, righe (articolo con F4, sconti a cascata, righe
descrittive, di spesa e di sconto), Testata, Trasporto per DDT e fatture accompagnatorie, Totali, Scadenze, Note,
Allegati, Collegamenti e Storico; azioni Conferma, Emetti, Duplica, Chiudi, Riapri, Annulla con motivo, *Segna come
rifiutato* per i preventivi e **Crea …** con la scelta delle righe e delle quantità residue.
- Fatturazione differita guidata (#51): DDT confermati e non fatturati del periodo, per tutti i clienti o uno, una
fattura differita TD24 per cliente o per DDT, in bozza o già emessa, con i riferimenti ai DDT nelle righe.
- Stampa dei documenti (#52, ADR 0034): anteprima di stampa A4 e PDF disegnati dallo stesso modello (dati
dell'azienda e logo, controparte, campi, righe, riepilogo IVA, scadenze, totali, trasporto con le firme, diciture e
filigrane), generatore *Stampa del documento in PDF* con versioni negli allegati, documento segnato come stampato.
- Invio per e-mail (#52, ADR 0034): destinatari, oggetto e testo proposti dal modello con i campi `{{Numero}}`,
`{{Cliente}}`…, PDF allegato e salvato come nuova versione, coda in background con tre tentativi, client SMTP
scritto in casa (STARTTLS, TLS, AUTH PLAIN e LOGIN) configurato da `KHAEMHAT_SMTP_*`, esito nel log *E-mail/PEC*.
- Log, sezione *Documenti* (#53): conferme ed emissioni con il numero, chiusure, riaperture, annullamenti ed
eliminazioni delle bozze.
- Dati di esempio (#53): profilo dell'azienda demo e un anno di vendite costruite con il motore (6 preventivi, 4
ordini, 5 DDT, 8 fatture e pro forma, 1 nota di credito) in tutti gli stati, idempotenti.
- Wiki: pagina [Guida all'uso](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/wiki/Guida-utente) con il percorso
completo e le schermate; [Vendite](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/wiki/Vendite) riscritta con
le schermate reali; schermate dell'accesso in *Primi passi*.
### Changed
- `README.md` è ora la guida di installazione per chi sviluppa (prerequisiti, avvio, test, migrazioni, immagine).
- L'emissione di una fattura o di una nota richiede il codice IVA su ogni riga (non descrittiva).
- *Tipi documento*: nuovo campo obbligatorio **Genere** (i tipi di base lo ricevono dalla migrazione); *Numeratori*:
nuovo campo **Data dell'ultimo numero**.
- *Clienti*, condizioni di vendita: **mesi esclusi** (due mesi senza scadenze e il giorno del mese dopo in cui slittano).
### Fixed
- `scripts/run-dev.sh` sotto Git Bash su Windows scriveva i dati in una cartella `b` sul disco invece che in
`.data/dev`.
## [0.4.0] - 2026-11-12
M4 — Tabelle, anagrafiche, articoli. Il pacchetto fiscale italiano, il profilo e le tabelle dell'azienda con i dati
+162 -39
View File
@@ -5,72 +5,195 @@
# Khaemhat
**Gestionale ERP + CRM per piccole e medie imprese italiane**, scritto da zero in C# 14 su .NET 10 con interfaccia
Blazor Server, PostgreSQL (o SQLite per demo e test) e **nessuna libreria esterna**. Si installa **solo con Docker**:
l'unico artefatto distribuito è l'immagine nel registro pacchetti di Gitea.
Blazor Server, PostgreSQL (o SQLite per demo e test) e **nessuna libreria esterna**. Si distribuisce **solo come
immagine Docker** nel registro pacchetti di Gitea.
> **Stato:** sviluppo avviato. M0 (struttura, immagine Docker, CI) consegna la versione 0.0.1 con una pagina
> "in costruzione"; le funzioni arrivano milestone dopo milestone. Vedi [`docs/STATUS.md`](docs/STATUS.md) e la
Questo file è la **guida di installazione per chi sviluppa**: come preparare il computer, compilare, avviare,
provare e pubblicare. Chi **usa** il gestionale parte dalla
[Guida all'uso](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/wiki/Guida-utente) nella wiki; chi lo **installa**
su un server da [Installazione Docker](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/wiki/Installazione-Docker)
o [Installazione Unraid](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/wiki/Installazione-Unraid).
> **Stato:** sviluppo in corso, versioni 0.x. Ultima milestone chiusa: **M5 — Motore documenti e Vendite** (0.5.0).
> Punto di ripresa in [`docs/STATUS.md`](docs/STATUS.md), piano in
> [Roadmap](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/wiki/Roadmap).
Il nome viene da Khaemhat (Mahu), scriba reale e sovrintendente al doppio granaio dell'Alto e del Basso Egitto sotto
Amenhotep III: un contabile e un magazziniere dell'antichità. Vedi
[Origine del nome](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/wiki/Origine-del-nome).
## 1. Prerequisiti
## Cosa farà
| Strumento | Versione | A cosa serve |
|---|---|---|
| **.NET SDK** | 10.0.100 o successiva della stessa *feature band* (vedi [`global.json`](global.json)) | compilare, provare, avviare |
| **Git** | qualunque recente | il repository; su Windows anche **Git Bash**, che esegue gli script `scripts/*.sh` |
| **Docker** | facoltativo | costruire e provare l'immagine; PostgreSQL e Redis per i test sui motori reali |
| **PostgreSQL** | 16 o 17, facoltativo | i test di integrazione sul motore di produzione (`KHAEMHAT_TEST_PG`) |
- Anagrafiche, articoli, listini, tabelle; vendite e acquisti con motore documenti unico; magazzino.
- Contabilità generale, IVA, F24, LIPE, ritenute, bollo, cespiti, Intrastat, chiusura e bilancio CEE.
- Scadenzario, incassi e pagamenti, RiBa/SDD/SEPA, riconciliazione bancaria, solleciti.
- Fatturazione elettronica FatturaPA con canali SDI (PEC integrata, SdICoop, intermediari).
- CRM (lead, pipeline, attività, campagne, ticket), automazioni, API REST e server MCP.
- Più aziende sulla stessa istanza (un database di sistema + un database per azienda), moduli attivabili con
licenza, temi chiaro/scuro, dashboard a widget.
Non servono Node.js, npm, bundler, IDE particolari né pacchetti NuGet oltre a quelli ammessi: un editor qualunque
va bene (Visual Studio, Rider, VS Code con C# Dev Kit). Lingua dei messaggi del compilatore: per avere gli errori in
inglese, `DOTNET_CLI_UI_LANGUAGE=en`.
## Installazione
## 2. Clonare
```bash
docker pull gitea.encke-hake.ts.net/balbosoft/khaemhat:<versione>
git clone https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat.git
```
- Qualunque host Docker: [`deploy/docker-compose.yml`](deploy/docker-compose.yml) (con PostgreSQL) e
[`deploy/.env.example`](deploy/.env.example); per una prova veloce
[`deploy/docker-compose.sqlite.yml`](deploy/docker-compose.sqlite.yml).
- Unraid: template [`deploy/unraid/khaemhat.xml`](deploy/unraid/khaemhat.xml) o
[`deploy/docker-compose.unraid.yml`](deploy/docker-compose.unraid.yml) con [`deploy/.env.example`](deploy/.env.example).
- Guide: [Installazione Unraid](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/wiki/Installazione-Unraid) ·
[Installazione Docker](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/wiki/Installazione-Docker) ·
[Primi passi](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/wiki/Primi-passi).
In rete locale anche `http://192.168.30.23:3000/BalboSoft/Khaemhat.git` o, con una chiave SSH,
`ssh://git@192.168.30.23:2222/BalboSoft/Khaemhat.git`. Il ramo principale è `main`; si lavora su rami
`feat/<n>-descrizione`, `fix/…`, `docs/…` (vedi [`docs/DEVELOPMENT.md`](docs/DEVELOPMENT.md)).
## Sviluppo
## 3. Com'è fatto il repository
Serve l'SDK .NET 10 (`global.json`); Docker solo per costruire e provare l'immagine.
| Cartella | Contenuto |
|---|---|
| `src/Khaemhat.Core` | entità, regole, macchine a stati dei documenti, nessuna dipendenza |
| `src/Khaemhat.Data`, `.Data.Sqlite`, `.Data.PostgreSql` | micro-ORM, migrazioni, provider dei due motori |
| `src/Khaemhat.Application` | servizi applicativi: sicurezza, tabelle, anagrafiche, motore documenti, stampe, seed |
| `src/Khaemhat.Infrastructure` | file (PDF, fogli di calcolo, archivi), posta SMTP, cache, licenze, sicurezza: scritti in casa |
| `src/Khaemhat.Fiscal.Abstractions`, `.Fiscal.Italy` | il pacchetto paese: tutto ciò che è italiano |
| `src/Khaemhat.Web` | host Blazor Server, componenti, pagine, risorse dei testi in `Resources/it-IT/*.json` |
| `tests/*` | MSTest, un progetto per strato |
| `tools/*` | strumenti di sviluppo: licenze (`LicenseTool`), comuni e CAP (`PlacesTool`), modello dati (`DataModelTool`) |
| `docker/`, `deploy/` | Dockerfile ed entrypoint; compose, `.env.example`, template Unraid |
| `scripts/` | build, test, avvio, seed, migrazioni, pubblicazione |
| `docs/` | specifica, ADR, architettura, mockup e la wiki (`docs/wiki/`) |
## 4. Compilare
```bash
scripts/build.sh
```
Controlla l'allowlist dei pacchetti (`scripts/check-packages.sh` su `Directory.Packages.props`) e compila
`Khaemhat.sln` in Release con **warning come errori** e gli analyzer di piattaforma. L'equivalente a mano:
```bash
dotnet build Khaemhat.sln -c Release -warnaserror
```
## 5. Avviare in locale
```bash
scripts/run-dev.sh
```
Avvia Khaemhat su <http://localhost:5080> con SQLite in `.data/dev` (ignorata da git) e queste impostazioni di
sviluppo, ognuna sovrascrivibile esportando la variabile prima di lanciare lo script:
| Variabile | Valore di sviluppo |
|---|---|
| `KHAEMHAT_DATA_DIR`, `KHAEMHAT_SYSTEM_DB` | `.data/dev`, `sqlite://…/.data/dev/system.db` |
| `KHAEMHAT_SECRET_KEY` | una chiave fissa **solo per lo sviluppo** |
| `KHAEMHAT_SUPERUSER`, `KHAEMHAT_SUPERUSER_PASSWORD` | `root` e la password iniziale scritta nello script |
| `KHAEMHAT_COMPANY_CODE`, `KHAEMHAT_COMPANY_NAME` | `DEMO`, *Khaemhat Demo S.r.l.* |
| `KHAEMHAT_LICENSE_MODE` | `test`: tutti i moduli attivi con i codici di prova |
| `KHAEMHAT_SEED_DEMO` | `true`: la prima azienda nasce con i dati di esempio (anagrafiche, articoli, un anno di vendite) |
Al primo accesso Khaemhat chiede di cambiare la password e di collegare un'app di autenticazione (il super utente
ha la verifica in due passaggi obbligatoria): conserva la chiave e i codici di recupero. Per ripartire da zero ferma
il server e cancella `.data/dev`.
Altre cose utili in sviluppo:
- **Invio di e-mail**: senza `KHAEMHAT_SMTP_HOST` e `KHAEMHAT_SMTP_FROM` l'invio è spento. Per provarlo serve un
server SMTP di prova sulla tua macchina, ad esempio
`KHAEMHAT_SMTP_HOST=127.0.0.1 KHAEMHAT_SMTP_PORT=2525 KHAEMHAT_SMTP_SECURITY=NONE KHAEMHAT_SMTP_FROM=ufficio@example.com scripts/run-dev.sh`;
l'esito di ogni invio è nel log, sezione *E-mail/PEC*.
- **Dati di base e di esempio** su un database esistente: `scripts/seed.sh --base` oppure `scripts/seed.sh --demo`
(aggiungono solo ciò che manca; meglio con il server fermo).
- **Catalogo dei componenti**: <http://localhost:5080/sviluppo/componenti> mostra i mattoni dell'interfaccia.
- **Tutte le variabili** `KHAEMHAT_*` sono in
[Installazione Docker](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/wiki/Installazione-Docker) e
[`docs/DEPLOY.md`](docs/DEPLOY.md). Una configurazione non valida ferma l'avvio con l'elenco degli errori.
Prima di ricompilare ferma il server: su Windows l'eseguibile in esecuzione blocca le DLL e la build ritenta la copia
(avviso MSB3026) fino a fallire.
## 6. Provare
```bash
scripts/test.sh
scripts/test.sh --filter "FullyQualifiedName~Documents"
```
Esegue l'allowlist e tutti i test in Release. SQLite è sempre provato; i test che avviano
l'applicazione intera usano un'istanza vera su una porta libera. I test sul **PostgreSQL** reale partono quando
`KHAEMHAT_TEST_PG` indica un ruolo con `CREATEDB` (ogni test crea e cancella il proprio database):
```bash
docker run -d --name khaemhat-pg-test -e POSTGRES_PASSWORD=prova -p 55432:5432 postgres:17
KHAEMHAT_TEST_PG="postgres://postgres:prova@localhost:55432/postgres" scripts/test.sh
```
Senza la variabile quei test risultano *saltati*. In CI (`.gitea/workflows/ci.yml`) i test girano su ogni pull request verso `main`; il job PostgreSQL
(16 e 17) sui tag e all'avvio manuale.
Regole che i test fanno rispettare: nessun pacchetto fuori allowlist, dipendenze tra progetti nel verso giusto,
nessun testo italiano scritto nei componenti (vanno nelle risorse `Resources/it-IT/*.json`), chiavi di testo
esistenti, sezione del modello dati aggiornata.
## 7. Database e migrazioni
```bash
scripts/new-migration.sh company create_sales_documents # nuova migrazione numerata
scripts/gen-datamodel.sh # rigenera la parte generata di docs/DATA-MODEL.md
scripts/gen-datamodel.sh --check # solo verifica (la fa anche un test)
```
Le migrazioni si applicano da sole all'avvio, al database di sistema e a quello di ogni azienda. Il codice non deve
dipendere dal motore: ogni query passa dal micro-ORM e gira identica su SQLite e PostgreSQL.
## 8. Immagine Docker
```bash
scripts/build.sh # allowlist dei pacchetti + build con warning come errori
scripts/test.sh # tutti i test (PostgreSQL con KHAEMHAT_TEST_PG, Redis con KHAEMHAT_TEST_REDIS)
scripts/run-dev.sh # avvio locale su http://localhost:5080 con SQLite in .data/dev
docker build -f docker/Dockerfile -t khaemhat:dev .
docker compose -f deploy/docker-compose.sqlite.yml up # prova veloce con SQLite
```
Processo, rami e Definition of Done in [`docs/DEVELOPMENT.md`](docs/DEVELOPMENT.md).
L'immagine pubblicata è `gitea.encke-hake.ts.net/balbosoft/khaemhat:<versione>` (e `:latest`, mai in produzione). La
costruisce `.gitea/workflows/release.yml` quando si spinge un tag `vX.Y.Z` (segreto `REGISTRY_TOKEN` con
`write:package`), che crea anche la release Gitea con le note del [`CHANGELOG.md`](CHANGELOG.md). Se il runner non è
disponibile:
## Documentazione
```bash
GITEA_TOKEN=… scripts/publish-image.sh v0.5.0
```
Non si producono installer, eseguibili o pacchetti `.msi/.exe/.deb`: l'unico artefatto è l'immagine
([ADR 0010](docs/adr/0010-solo-docker-nessun-installer.md)). Le versioni restano **0.x** finché il prodotto è in
sviluppo.
## 9. Documentazione e wiki
La wiki è in `docs/wiki/` e si aggiorna nella stessa unità di lavoro del codice: una funzione senza documentazione
non è finita. Il workflow `wiki.yml` la pubblica nel wiki Gitea a ogni push su `main` che la tocca; a mano:
`scripts/publish-wiki.sh`. Le schermate stanno in `docs/wiki/img/` e si fanno sull'applicazione vera con i dati di
esempio. La stessa wiki è inclusa nell'immagine e si apre con `F1` dentro il gestionale.
| Cosa | Dove |
|---|---|
| Wiki (guida utente e amministratore) | <https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/wiki> (sorgente in [`docs/wiki/`](docs/wiki/)) |
| Specifica normativa | [`docs/SPEC.md`](docs/SPEC.md) |
| Regole operative ed emendamenti | [`CLAUDE.md`](CLAUDE.md) |
| Processo di sviluppo | [`docs/DEVELOPMENT.md`](docs/DEVELOPMENT.md) |
| Processo, rami, Definition of Done | [`docs/DEVELOPMENT.md`](docs/DEVELOPMENT.md) |
| Architettura, dati, moduli, API, MCP | [`docs/ARCHITECTURE.md`](docs/ARCHITECTURE.md), [`docs/DATA-MODEL.md`](docs/DATA-MODEL.md), [`docs/MODULES.md`](docs/MODULES.md), [`docs/API.md`](docs/API.md), [`docs/MCP.md`](docs/MCP.md) |
| Installazione e sicurezza | [`docs/DEPLOY.md`](docs/DEPLOY.md), [`docs/SECURITY.md`](docs/SECURITY.md) |
| Decisioni architetturali | [`docs/adr/`](docs/adr/) |
| Mockup | [`docs/mockups/`](docs/mockups/README.md) |
| Mockup (specifica visiva) | [`docs/mockups/`](docs/mockups/README.md) |
| Novità | [`CHANGELOG.md`](CHANGELOG.md) |
| Wiki pubblicata | <https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/wiki> |
## Pianificazione
## 10. Regole del codice in breve
Il lavoro è organizzato in [issue](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/issues) raggruppate per
- C# 14 su .NET 10, `Nullable` attivo, warning come errori, `.editorconfig`; JavaScript solo come interop minimo in
`wwwroot/js`.
- **Nessuna libreria esterna**: framework Microsoft, `Npgsql`, `Microsoft.Data.Sqlite` e, nei test, MSTest.
- Codice, commenti e commit in **inglese**; interfaccia in **italiano** dalle risorse.
- Tutto ciò che è fiscale italiano sta in `Khaemhat.Fiscal.Italy`.
- Commit *Conventional Commits* che dicono cosa cambia e perché e citano l'issue (`#n`); pull request verso `main`
con `Closes #n`.
Il lavoro è organizzato in [issue](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/issues) per
[milestone](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/milestones) (M0-M14) e nei
[progetti](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/projects) *Khaemhat 1.0 — Sviluppo* e
*Khaemhat 1.1+ — Fase 2*.
[progetti](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/projects).
Il nome viene da Khaemhat (Mahu), scriba reale e sovrintendente al doppio granaio dell'Alto e del Basso Egitto sotto
Amenhotep III: vedi [Origine del nome](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/wiki/Origine-del-nome).
+987
View File
File diff suppressed because it is too large. Load diff
+28 -9
View File
@@ -3,18 +3,20 @@
> Punto di ripresa per ogni sessione. Aggiornare a fine sessione.
**Ultimo aggiornamento:** 2026-11-12
**Milestone corrente:** M4 — Tabelle, anagrafiche, articoli: chiusa sul ramo `feat/37-tabelle-anagrafiche` (#46),
in attesa del merge in `main` con l'approvazione del titolare; poi tag `v0.4.0`, immagine e release.
**Prossimo passo:** dopo il merge, M5 — Motore documenti e Vendite (#47-#54). #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: profilo dell'azienda demo (indirizzo, partita IVA) prima dei documenti di M5; misure di riferimento su PostgreSQL in `docs/DATA-MODEL.md` §6.1; indicatore di robustezza della
password (mockup 003); schede *Layout salvati* e *Notifiche* (con le e-mail, M5) del profilo; rinomina e
filtro predefinito nei radar.
**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-0031.
- 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`,
@@ -50,7 +52,7 @@ filtro predefinito nei radar.
cestino e storico; anteprima di stampa A4; catalogo dei componenti e documento di prova per gli sviluppatori;
primi screenshot reali in `docs/wiki/img/`; ADR 0020-0024. Test: 368 verdi in locale, 21 di PostgreSQL saltati;
immagine costruita in locale e avviata da zero con SQLite.
- **M4 (chiusa, `v0.4.0`):** pacchetto fiscale `IT 2026.3` (codici IVA, nature, code list FatturaPA, motore IVA,
- **M4 (chiusa, `v0.4.0`, PR #121):** pacchetto fiscale `IT 2026.3` (codici IVA, nature, code list FatturaPA, motore IVA,
calendario, ritenute, F24; ADR 0025); validatori e `ViesClient`; 26 tabelle azienda con un'unica maschera, profilo
azienda, esercizi e cambi BCE (ADR 0026); dati di base con province e comuni ISTAT e CAP GeoNames (ADR 0028) e
`scripts/seed.sh --base|--demo`; codici automatici e compilazione automatica (ADR 0027); clienti, fornitori e
@@ -58,6 +60,23 @@ filtro predefinito nei radar.
aggiornamento massivo (ADR 0030); import/export guidato CSV/XLSX/JSON con tracciato del piano dei conti (ADR 0031);
21 anagrafiche e 120 articoli di esempio; screenshot reali nella wiki. Test: 631 verdi in locale, 21 di PostgreSQL
saltati; immagine costruita in locale e avviata da zero con SQLite e dati di esempio.
- **M5 (chiusa, `v0.5.0`, PR #124):** motore documenti (#47, ADR 0032): generi e definizioni dei tipi documento, sei famiglie
di tabelle con le righe e `document_links`, stati con azioni ammesse, numerazione atomica alla conferma (provata in
concorrenza su SQLite e su PostgreSQL 18 in locale), copia e trasformazione con evasione riga per riga; totali,
castelletto IVA, bollo, ritenute, cassa e scadenze (#48, ADR 0033); radar e maschera dei documenti di vendita con
*Crea …* (#49, #50); fatturazione differita guidata (#51); anteprima di stampa e PDF dallo stesso modello, invio per
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,
+65
View File
@@ -0,0 +1,65 @@
# ADR 0032 - Motore documenti: comportamento per genere, tabelle per famiglia, numerazione alla conferma
- **Stato:** accettata
- **Data:** 2026-11-12
- **Modifica:** SPEC §11.3; milestone M5, issue #47
## Contesto
SPEC §11.3 vuole un solo motore per tutti i documenti (vendita, acquisto, magazzino), guidato da definizioni
dichiarative, con tabelle per famiglia (`sale_quotations`, `sale_orders`, `sale_documents`, `purchase_orders`,
`purchase_documents`, `inventory_documents`, ognuna con le righe), `document_links` per l'evasione, gli stati
`Draft → Confirmed → (PartiallyFulfilled | Fulfilled) → Closed`, `Cancelled` e per le fatture
`Draft → Issued → SdiGenerated → SdiSent → (SdiDelivered | SdiRejected | SdiNotDelivered)`, la numerazione alla
conferma con la data non anteriore all'ultimo numero del sezionale. Restavano aperti: dove sta il comportamento di un
tipo documento (la tabella `document_types` è modificabile dall'utente e il suo `kind` dice solo la famiglia di
numerazione), come si numera per anno quando il numeratore è per anno, quando nasce un legame di evasione, che cosa
fa la copia, quali tabelle servono già adesso.
## Decisione
1. **Genere e definizione.** Il comportamento sta in codice, per **genere** (`DocumentKind`: preventivo, ordine
cliente, DDT, fattura immediata, accompagnatoria, differita, di acconto, nota di credito, nota di debito, parcella,
pro forma, autofattura, ordine fornitore, DDT fornitore, fattura fornitore, nota di credito fornitore, movimento di
magazzino). `DocumentBehaviors` dà per ogni genere: famiglia (tabella), direzione, ciclo di vita, effetti
(magazzino, impegnato, ordinato, contabilità, scadenze, e-fattura), tipi di riga ammessi, generi da cui evade
(sorgenti) e permessi. La tabella `document_types` riceve la colonna `document_kind`: ogni tipo dell'utente
sceglie un genere e aggiunge numeratore, causale di magazzino, TD SDI, causale contabile, registro IVA, modello di
stampa. `DocumentDefinition` è l'unione dei due (tipo + comportamento) e si legge con `DocumentDefinitionService`.
I tipi seminati prendono il genere dalla migrazione e dal modello del pacchetto paese.
2. **Tre cicli di vita.** `DocumentStateMachine` conosce tre cicli: *ordine* (preventivi, ordini, DDT, pro forma:
bozza, confermato, evaso parzialmente, evaso, chiuso, annullato), *fattura* (fatture e autofatture di vendita:
bozza, emessa, XML generato, inviata, consegnata, scartata, non consegnata, annullata) e *semplice* (fatture
fornitore, movimenti: bozza, confermato, annullato). Per ogni stato dice le azioni ammesse; un'azione non ammessa
è rifiutata con `document.action.not-allowed`. Si modifica solo una bozza, oltre a ordini e preventivi confermati
non evasi; la fattura emessa è immutabile: si annulla con un motivo finché l'XML non è inviato (o se scartato),
altrimenti si fa una nota di credito. Gli stati di evasione non sono azioni: li calcola `FulfillmentCalculator`.
3. **Numerazione alla conferma.** `DocumentNumberingService` numera nella stessa transazione della conferma, sotto il
lock `numerator:<codice>:<anno>` (advisory lock di transazione su PostgreSQL, lock di scrittura su SQLite): un
rollback restituisce il numero, quindi non nascono buchi. Il numeratore del tipo vale per il suo codice; per
l'anno della data si usa la riga (codice, anno) e, se manca, si crea copiando formato, prefisso e sezionale
dell'ultima. Sui numeratori **senza buchi** (fatture, autofatture, protocollo acquisti) la data non può
precedere l'ultima numerata (`document_numerators.last_date`) e la conferma chiede il periodo aperto quando il
genere ha effetto contabile. `FindGapsAsync` elenca i numeri mancanti di un numeratore. Un documento numerato non
si elimina: si annulla e il numero resta.
4. **Tabelle.** Sei testate e sei tabelle di righe con le stesse colonne (classi base `DocumentHeader` e
`DocumentLine`), più `document_links` (riga destinazione → riga sorgente, quantità). Le tabelle del castelletto IVA
e delle rate arrivano con il calcolo dei totali (#48), i campi di trasporto sono già nella testata.
5. **Evasione.** Una riga copiata da un documento evadibile tiene la riga d'origine (`source_family`,
`source_line_id`). Il legame in `document_links` nasce alla **conferma** del documento destinazione e sparisce al
suo annullamento; dopo ogni cambio `FulfillmentCalculator` ricalcola la quantità evasa delle righe sorgente e lo
stato del documento sorgente (confermato, evaso parzialmente, evaso). Le righe con saldo forzato contano come
evase; un documento chiuso o annullato non cambia stato.
6. **Copia.** `DocumentCopyService` crea una bozza da un documento esistente verso lo stesso tipo (duplicazione) o un
altro della stessa direzione (trasformazione). Se il genere destinazione evade il genere sorgente si copiano le
quantità residue e le righe tengono l'origine, altrimenti si copiano le quantità intere senza legame.
7. **Servizio generico.** `DocumentService<THeader, TLine>` (uno per famiglia) espone crea, leggi, salva, conferma,
annulla, chiudi, riapri, elimina e copia; il lavoro su più famiglie (evasione, copia) passa da `DocumentEngine`, che
tratta testate e righe tramite le classi base.
## Conseguenze
- Un tipo documento nuovo dell'utente funziona senza codice se usa un genere esistente; un genere nuovo è codice.
- Gli effetti sono dichiarati ma si applicano con i moduli: magazzino in M6, contabilità in M7, scadenze in M8,
e-fattura in M8. Il calcolo dei totali e delle rate è #48, le maschere sono #49-#51.
- La numerazione concorrente è provata su SQLite e PostgreSQL (test dei dati, eseguiti su PostgreSQL 16 e 17 ai tag).
@@ -0,0 +1,55 @@
# ADR 0033 - Totali, castelletto IVA e scadenze dei documenti
- **Stato:** accettata
- **Data:** 2026-11-12
- **Modifica:** SPEC §11.3; milestone M5, issue #48
## Contesto
SPEC §11.3 chiede un `DocumentTotalsCalculator` (imponibile di riga, sconti a cascata, castelletto per codice IVA,
spese, sconto di piede, bollo, ritenuta, cassa previdenza, split payment, reverse charge, IVA per cassa) e un
`InstallmentGenerator` (fine mese, giorno fisso, percentuali, IVA sulla prima rata, arrotondamento sull'ultima), con
tabelle `_tax_summary` e `_installments` per ogni famiglia. Restavano aperti: dove si applica lo sconto di piede,
come si gestiscono i prezzi IVA compresa, che cosa entra nella base della ritenuta e della cassa, dove si salvano
castelletto e scadenze, quando si ricalcolano.
## Decisione
1. **Calcolo puro.** `DocumentTotalsCalculator` e `InstallmentGenerator` sono funzioni senza database, provate con
casi numerici di riferimento. L'arrotondamento e il bollo vengono da `ITaxEngine` del pacchetto paese.
2. **Riga.** Importo = quantità × prezzo × (1 − s1)(1 − s2)…, al centesimo con metà lontano da zero. Spese e sconti
senza quantità valgono una volta; le righe di sconto sono negative; le righe descrittive non contano.
3. **Sconto di piede** (formula come `10+5`): si applica a ogni riga di merce, non alle spese, e solo nel castelletto.
La riga conserva il suo importo, il documento registra quanto lo sconto ha tolto (`footer_discount_amount`).
4. **Castelletto** per codice IVA, con l'imposta calcolata sul totale del gruppo (come `DatiRiepilogo`). Con i
**prezzi IVA compresa** si somma il lordo del gruppo e si scorpora una volta sola. L'esigibilità è quella del
codice IVA, del documento (IVA per cassa) o *S* con lo **split payment**. Il reverse charge non ha bisogno di
regole: i codici N6.x hanno aliquota zero.
5. **Cassa previdenza, ritenuta, ENASARCO.** La base è la somma delle righe non escluse
(`withholding_excluded`, ad esempio le spese anticipate in nome del cliente), dopo lo sconto di piede. La cassa
entra nel castelletto con l'IVA indicata o con quella della prima riga imponibile; la ritenuta si calcola sulla
quota della base (100% per i professionisti, 50% o 20% per gli agenti), con la cassa se è soggetta. Ritenuta,
ENASARCO e IVA in split payment si tolgono dal **netto a pagare**, non dal totale.
6. **Bollo** sulle fatture e note di vendita quando gli importi senza IVA che lo richiedono superano la soglia del
pacchetto paese (77,47 euro): è sempre indicato; entra nel totale solo se addebitato al cliente.
7. **Scadenze** dal netto a pagare e dalle rate della condizione di pagamento; con *IVA sulla prima rata* l'IVA
effettivamente incassata va tutta sulla prima. Fine mese e giorno fisso: con fine mese il giorno fisso è del mese
successivo, senza fine mese è il primo giorno fisso non anteriore. I **mesi esclusi** stanno nelle condizioni di
vendita del cliente e spostano la scadenza a un giorno del mese successivo (10 se non indicato). Le scadenze
esistono per fatture, note, fatture fornitore e, come previsione, per preventivi, ordini e pro forma.
8. **Due tabelle condivise invece di dodici.** Castelletto e scadenze stanno in `document_tax_summaries` e
`document_installments` con la colonna `family`, come `document_links`: le righe non hanno vincoli verso una
sola tabella e il codice resta unico per tutte le famiglie. Diverge dalla lettera di §11.3 (una coppia di tabelle
per famiglia), non dalla sostanza.
9. **Quando.** Il motore ricalcola a ogni salvataggio (bozze e righe di documenti ancora aperti) e riscrive
castelletto e scadenze nella stessa transazione. Un documento emesso non cambia più, quindi i suoi totali restano
quelli dell'emissione. Lo scadenzario vero (partite, incassi) arriva con M8 e parte da queste righe.
10. **Revisioni dei preventivi.** Modificare un preventivo confermato aumenta il numero di revisione: il numero
del documento resta lo stesso.
## Conseguenze
- Le maschere mostrano castelletto, totali e scadenze ricalcolati durante la modifica con lo stesso codice del
salvataggio (anteprima senza scrittura).
- Il file FatturaPA (M9) troverà lo sconto di piede da ripartire sulle righe e il castelletto già pronto.
- Lo sconto cassa resta fuori: si gestirà con gli incassi (M8).
@@ -0,0 +1,47 @@
# ADR 0034 - Stampa e invio dei documenti
- **Stato:** accettata
- **Data:** 2026-11-12
- **Modifica:** SPEC §9.4, §12.6; milestone M5, issue #52
## Contesto
SPEC §9.4 chiede l'anteprima di stampa (mockup 025) e il PDF di ogni documento come allegato versionato; §12.6 l'invio
per e-mail con modelli, allegati ed esito nel log. Il vincolo di §1 esclude librerie esterne per PDF, posta e modelli.
Restavano aperti: come tenere uguali anteprima e PDF, dove stanno le diciture, quali immagini accetta il PDF, come si
invia la posta senza una libreria, che cosa succede se il server di posta non risponde.
## Decisione
1. **Un solo modello di stampa.** `DocumentPrintService` costruisce un `DocumentPrintModel` (intestazione dell'azienda
dal profilo, controparte, campi, righe, riepilogo IVA, scadenze, totali, trasporto, firme, diciture, filigrana) già
formattato con la cultura italiana. L'anteprima HTML (`SalesPrintPage`) e il PDF (`DocumentPdfGenerator`, sopra il
`PdfWriter` di M3) disegnano lo stesso modello: un campo nuovo compare in tutti e due.
2. **Diciture nelle risorse.** Etichette, diciture di legge (split payment, pro forma non valida ai fini fiscali,
fattura differita) e filigrane (*Bozza*, *Annullato*, *Dato dimostrativo*) stanno in `Resources/it-IT/Print.json`.
I modelli di stampa configurabili per tipo documento di §9.4 restano per M12; fino ad allora il tipo documento
sceglie solo quali blocchi compaiono (il trasporto e le firme per DDT e fatture accompagnatorie).
3. **Logo.** Nell'anteprima compare qualunque immagine del profilo; nel PDF solo un **JPEG**, perché il `PdfWriter`
incorpora i JPEG senza decodificarli (DCTDecode) e un decodificatore PNG scritto in casa non vale il costo ora.
Con un PNG il PDF esce senza logo.
4. **Il PDF è un allegato.** Il generatore `documents.pdf` è un `IFileGenerator`: *Salva come allegato* e l'invio per
e-mail creano una nuova versione, così resta la copia esatta di ciò che è uscito. Il documento registra i flag
*stampato* e *inviato* (con la sola permission di lettura, perché non cambiano il contenuto) e lo storico.
5. **SMTP scritto in casa.** `SmtpMailSender` parla SMTP su `TcpClient`/`SslStream`: EHLO, STARTTLS o TLS implicito,
AUTH PLAIN o LOGIN, un messaggio per connessione, timeout di 60 secondi. `MimeMessageWriter` scrive
`multipart/mixed` con testo e allegati in base64 e intestazioni non ASCII come *encoded word*. Configurazione da
`KHAEMHAT_SMTP_*` finché non c'è la pagina *Impostazioni* (M12).
6. **Coda in memoria.** `MailQueue` è un servizio in background con un canale limitato a 500 messaggi: tre tentativi
a 30 e 60 secondi, ogni passo nel log, sezione *E-mail/PEC*. Chi invia non aspetta il server. Un messaggio in coda
quando il processo si ferma si perde e il log lo dice; una coda persistente arriva se servirà con le automazioni
(M12).
7. **Modelli con campi.** Oggetto e testo vengono da `Print.Mail.*` con i campi `{{Documento}}`, `{{Numero}}`,
`{{Data}}`, `{{Cliente}}`, `{{Azienda}}`, `{{Totale}}` (`MailTemplateRenderer`; un campo sconosciuto resta
com'è, così l'errore si vede). L'utente li modifica prima di inviare; i modelli per azienda arrivano con M12.
## Conseguenze
- Anteprima e PDF non divergono e si provano insieme (il modello ha i suoi test).
- Nessuna dipendenza nuova; il client SMTP è provato contro un server finto in-process.
- Limiti noti: niente PNG nel PDF, niente coda persistente, niente modelli per azienda, niente PEC dedicata (arriva
con il canale SDI via PEC in M9).
@@ -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).
+122 -121
View File
@@ -1,178 +1,179 @@
# Acquisti
> **Stato:** bozza · **Ultima revisione:** 2026-11-10 · **Versione software:** non ancora rilasciata (milestone M6)
> **Modulo di licenza:** CORE (XML delle autofatture e canale SDI con EINV, registrazione con ACCT) · **Permessi principali:** famiglia `purchases.*` (codici esatti definiti in sviluppo) · **Specifica:** SPEC §11.3, §11.5
> **Stato:** completa per la versione 0.6 · **Ultima revisione:** 2026-11-12 · **Versione software:** 0.6.0 (M6)
> **Modulo di licenza:** CORE (XML delle autofatture con EINV, registrazione contabile con ACCT) · **Permessi principali:** `purchases.order.*` (ordini fornitore), `inventory.entry.*` (DDT fornitore), `purchases.invoice.*` (fatture, note di credito, import, autofatture) · **Specifica:** SPEC §11.3, §11.5, ADR 0035
Il modulo **Acquisti** copre il ciclo passivo: **ordini ai fornitori** (anche generati dalla proposta di riordino),
**DDT di carico** con controllo delle quantità ricevute, **fatture di acquisto** con protocollo IVA e conti per riga,
**note di credito** dei fornitori, **import delle fatture passive** XML/P7M ricevute dallo SDI e le **autofatture e
integrazioni** (TD16-TD29) per reverse charge e acquisti dall'estero.
Il modulo **Acquisti** copre il ciclo passivo: **ordini ai fornitori** (anche dalla proposta di riordino),
**ricevimento della merce** con il DDT del fornitore, **fatture e note di credito dei fornitori** con il protocollo
IVA, **import delle fatture elettroniche** ricevute (XML, P7M, ZIP) e le **autofatture e integrazioni** (TD16-TD29)
per inversione contabile e acquisti dall'estero.
> **In questa versione** ci sono ordini, ricevimenti, fatture e note di credito fornitore con protocollo, carico a
> magazzino e costo medio, controllo dei prezzi rispetto a ordine e ricevimento, import delle fatture elettroniche e
> autofatture in bozza con la loro scadenza. Arrivano più avanti: la **registrazione contabile** e i registri IVA (M7),
> i **pagamenti** e lo scadenzario (M8), il **file XML** delle autofatture e lo scarico dal canale SDI (M9).
## Dove si trova
Menu **Acquisti** → *Ordini fornitori*, *DDT di carico*, *Fatture di acquisto*, *Import XML SDI*, *Autofatture*.
Menu **Acquisti** → *Ordini fornitori*, *Ricevimenti merce*, *Fatture passive*, *Importa fatture*, *Autofatture*.
Le maschere sono quelle comuni a tutti i documenti (toolbar, intestazione, schede, righe con castelletto e totali):
vedi [Interfaccia e scorciatoie](Interfaccia-e-scorciatoie) e [Vendite](Vendite) per il motore documenti.
Le maschere sono quelle comuni a tutti i documenti (toolbar, intestazione, schede, righe con castelletto e totali,
trasformazioni, stampa, allegati): vedi [Vendite](Vendite) per il funzionamento del motore documenti e
[Interfaccia e scorciatoie](Interfaccia-e-scorciatoie) per la tastiera.
```
Proposta di riordino ──► Ordine fornitore ──ricevi merce──► DDT di carico ──registra fattura──► Fattura di acquisto
▲
Fattura passiva XML/P7M (SDI) ──import──┘ (abbinamento all'ordine o al DDT)
Proposta di riordino ──► Ordine fornitore ──Crea DDT fornitore (carico)──► Ricevimento ──Crea Fattura fornitore──► Fattura
▲
Fattura elettronica XML / P7M / ZIP ──Importa fatture──► Fattura in bozza ─┘
Fattura di un fornitore estero o in reverse charge ──Crea autofattura──► Autofattura / integrazione (TD16-TD29)
```
## Ordini fornitori
![031 · Ordine fornitore generato dalla proposta di riordino](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/mockups/thumbs/031-ordine-fornitore.png)
*Mockup 031 — ordine fornitore confermato, nato dalla proposta di riordino, con il pannello Origine del fabbisogno (anteprima ridotta).*
Un **ordine fornitore** (`OF`) dice al fornitore che cosa ti serve; non muove il magazzino ma, una volta
**confermato**, aumenta l'**ordinato** degli articoli finché non arriva la merce (vedi [Magazzino](Magazzino)).
Azioni: **Invia al fornitore** (e-mail con il PDF dell'ordine), **Ricevi merce (DDT carico)**, **Chiudi residuo**.
- Scegliendo il fornitore si applicano le sue condizioni (pagamento, banca, porto, valuta).
- Scegliendo un articolo, Khaemhat propone il **prezzo del fornitore** dalla scheda articolo (*Fornitori*).
- Gli ordini nascono a mano, dalla **proposta di riordino** (un ordine in bozza per fornitore, vedi
[Magazzino](Magazzino#proposta-di-riordino)) o copiando un altro documento.
- Quando la merce arriva, **Crea DDT fornitore (carico)** porta le righe ancora da ricevere nel ricevimento: puoi scegliere
righe e quantità, così un ordine può essere ricevuto in più volte. Lo stato diventa *Evaso in parte* ed *Evaso*;
**Chiudi** chiude un residuo che non arriverà più.
- L'intestazione mostra la **data prevista** di consegna, calcolata come data dell'ordine + **lead time** del
fornitore, e lo stato di ricevimento (*Ricevuto 0%*…).
- Le righe riportano il **codice del fornitore** per l'articolo; il prezzo proposto è quello del fornitore.
- Il pannello **Origine del fabbisogno** spiega perché si ordina: sottoscorta, impegni da ordini clienti, lotto di
riordino.
- Schede: *Righe*, *Testata*, *Totali*, *Ricevimenti*, *Note*, *Allegati*, *Collegamenti*.
- Un ordine confermato aggiorna l'**ordinato** degli articoli (vedi [Magazzino](Magazzino)).
![Khaemhat 0.6.0 · ricevimento della merce](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/acquisti-ricevimento.png)
Gli ordini nascono a mano, dalla **proposta di riordino** (un ordine in bozza per fornitore, vedi
[Magazzino](Magazzino)) o dall'azione **Ordina a fornitore** di un ordine cliente.
## Ricevimenti merce (DDT fornitore)
## DDT di carico
Il **DDT fornitore (carico)** (`DDTF`) registra la merce arrivata. Non ha un numero interno: nella testata scrivi il
**numero e la data del DDT del fornitore**, che lo identificano (nell'elenco compare come *Senza numero*).
![032 · DDT di carico con controllo quantità ricevute](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/mockups/thumbs/032-ddt-di-carico.png)
*Mockup 032 — ricevimento con confronto ordinato/ricevuto, riga con 20 pezzi mancanti e aggiornamento del costo medio (anteprima ridotta).*
1. Dall'ordine premi **Crea DDT fornitore (carico)**, oppure crea un ricevimento e richiama l'ordine.
2. Controlla le **quantità ricevute** riga per riga e il **deposito** di arrivo.
3. **Conferma**: la merce viene **caricata a magazzino** con la causale `CAR` e aggiorna **costo medio** e **ultimo
costo** degli articoli; l'ordine segna le quantità evase.
Il **DDT di carico** registra la merce ricevuta. Azioni: **Registra fattura da questo DDT**, **Stampa etichette**,
**Riapri**.
Un ricevimento confermato resta modificabile finché non è fatturato; dal ricevimento **Crea Fattura fornitore**
prepara la fattura con le stesse righe.
1. Dall'ordine fornitore premi **Ricevi merce** oppure crea un DDT di carico e usa **Evadi da…** per richiamare
l'ordine.
2. Indica numero e data del **DDT del fornitore**.
3. Conta la merce: per ogni riga inserisci la quantità **ricevuta**; si può **scansionare l'EAN o il codice
fornitore** per contare. La colonna *Controllo* segnala le differenze (*OK*, *Mancanti 20*…).
4. **Conferma**: la merce viene **caricata a magazzino** (causale *Carico da fornitore*, deposito indicato), si
aggiornano **ultimo costo** e **costo medio ponderato** dell'articolo.
## Fatture passive
Se arriva meno del previsto, il **residuo** resta aperto sull'ordine; se non arriverà più si chiude con **Chiudi
residuo**. Un messaggio sotto le righe riassume differenze e variazioni del costo medio.
![Khaemhat 0.6.0 · fattura fornitore con differenza di prezzo](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/acquisti-fattura-differenze.png)
## Fatture di acquisto
![033 · Fattura di acquisto da XML con conti e centri di costo per riga](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/mockups/thumbs/033-fattura-di-acquisto.png)
*Mockup 033 — fattura di acquisto in bozza nata da XML, con protocollo, flag Verifica prezzi, righe con conto e centro di costo, castelletto con IVA detraibile (anteprima ridotta).*
Azioni: **Registra (protocolla)**, **Contabilizza**, **Confronta con ordine**, **Apri XML**.
La **fattura fornitore** (`FF`) e la **nota di credito fornitore** (`NCF`) registrano i documenti del fornitore.
| Dato | Descrizione |
|---|---|
| **Data di registrazione** e **data/numero del documento** del fornitore | la registrazione determina il periodo IVA |
| **Protocollo** | numero progressivo del registro IVA acquisti (es. `ACQ/2026/000613`), assegnato alla registrazione |
| **Conto e centro di costo per riga** | ogni riga ha il proprio conto di costo e centro di costo (proposti da articolo, categoria o fornitore) |
| **Indetraibilità** | codici IVA con indetraibilità parziale o totale (es. telefonia 50%): il castelletto mostra imponibile, imposta e quota **detraibile** |
| **Ritenute e cassa** | per i professionisti: ritenuta d'acconto, cassa previdenza; il totale mostra il **netto a pagare** |
| **Registrazione contabile** | scheda con l'anteprima della registrazione (con modulo Contabilità) |
| **N. documento fornitore** e **data** | numero e data scritti dal fornitore (nella testata) |
| **Data** | data di registrazione: decide il periodo IVA |
| **Protocollo** | numero progressivo del registro IVA acquisti (numeratore `PRA`), assegnato alla **conferma**; nell'elenco compare nella colonna *Protocollo* |
| **Righe** | articoli, righe descrittive e spese con il codice IVA di ogni riga; per i professionisti ritenuta d'acconto e cassa come nelle vendite |
| **Scadenze** | calcolate dal pagamento del fornitore |
Schede: *Righe*, *Testata*, *Totali*, *Scadenze*, *Ritenute e cassa*, *Registrazione contabile*, *Note*,
*Allegati*, *Collegamenti*.
La fattura nasce dal ricevimento (**Crea Fattura fornitore**), dall'ordine (per servizi o merce senza DDT), dall'**import
della fattura elettronica** (vedi sotto) o a mano. **Conferma** assegna il protocollo e la rende definitiva; una
fattura confermata si corregge con una **nota di credito fornitore** (**Crea Nota di credito fornitore**).
**Registra (protocolla)** assegna il protocollo e rende la fattura definitiva; **Contabilizza** crea la registrazione
(automatica alla conferma o in batch, secondo le preferenze). La fattura può nascere:
**Magazzino.** Una fattura di merce senza DDT carica il magazzino alla conferma; una fattura nata da un ricevimento
non carica di nuovo, ma il suo **prezzo corregge il costo** del carico. La nota di credito fornitore scarica la merce
resa (causale `RESF`).
- dal **DDT di carico** (**Registra fattura da questo DDT**), che la collega ai carichi;
- dall'**import XML** (vedi sotto);
- a mano, ad esempio per fatture cartacee o estere.
**Controllo dei prezzi.** Se una riga della fattura ha un prezzo diverso da quello dell'ordine o del ricevimento da
cui viene, sopra le righe compare un avviso con la differenza totale e, riga per riga, il prezzo atteso e quello
fatturato. È un avviso: decidi tu se registrare la fattura o chiedere una nota di credito.
Le **note di credito dei fornitori** si registrano allo stesso modo e chiudono le partite collegate.
## Importare le fatture elettroniche
## Import delle fatture passive XML/P7M
![Khaemhat 0.6.0 · import delle fatture passive](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/acquisti-importa-fatture.png)
![034 · Import fatture passive XML/P7M](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/mockups/thumbs/034-import-xml-sdi.png)
*Mockup 034 — quattro file in import (pronto, con ritenuta e cassa, fornitore da creare, duplicato) e mappatura delle righe sull'ordine con differenza di prezzo (anteprima ridotta).*
**Acquisti → Importa fatture** (o il link nell'elenco delle fatture passive) registra in bozza le fatture ricevute
dallo SDI o dal tuo intermediario.
1. Carica i file con **Carica XML / P7M / ZIP**, oppure **Leggi inbox** (cartella di ingresso dell'istanza) o
**Scarica dal canale SDI** (con il modulo Fatturazione elettronica).
2. Per ogni file Khaemhat legge fornitore, numero, data, tipo documento (TD) e totale e mostra un **esito**:
*Pronto*, *Fornitore da creare*, *Duplicato*, oppure avvisi (ad esempio *Ritenuta 20% · cassa 4%*).
3. Il **fornitore** viene riconosciuto da **partita IVA o codice fiscale**; se non esiste si crea al volo dai dati
dell'XML.
4. **Mappatura righe**: ogni riga XML viene abbinata a un articolo cercando, in ordine, il **codice del fornitore**,
l'**EAN** e la **descrizione** (ricerca approssimata). Le righe non abbinate diventano descrittive o si abbinano a
mano.
5. **Abbina a ordine**: confronta prezzi e quantità con l'ordine fornitore; le differenze sono evidenziate (es.
*+3,4%*).
6. **Salva bozza** o **Registra fattura di acquisto**. Se ci sono differenze la fattura nasce **in bozza** con il
flag *Verifica prezzi*.
1. **Caricamento**: scegli uno o più file: **XML FatturaPA**, file firmati **.p7m** o archivi **ZIP** che li
contengono (fino a 50 MB per file). I file che non sono fatture elettroniche leggibili sono elencati a parte con il
motivo.
2. **Controllo**: per ogni fattura vedi fornitore (nuovo o già in anagrafica), numero, data, tipo, totale e un esito:
*Pronta*, oppure *Già registrata* (stesso fornitore, stesso numero, stesso anno), *Non è un acquisto* (per esempio
un'autofattura emessa dall'azienda stessa), *Totale diverso* (il totale del file non torna con le righe), *Firma non
verificata*, *Sconto sul totale*. **Leggi** mostra righe, riepilogo IVA e pagamento del file.
3. **Registrazione**: spunta le fatture e premi **Registra in bozza**. Per ognuna Khaemhat:
- trova il **fornitore** dalla partita IVA o dal codice fiscale, o lo **crea** dai dati del file;
- crea una **fattura fornitore** (tipi TD01, TD02, TD03, TD05, TD06, TD24-TD27) o una **nota di credito fornitore**
(TD04, TD08) in bozza, con numero e data del fornitore e la causale nelle note;
- abbina ogni riga a un **articolo** cercando il **codice del fornitore** (scheda articolo, *Fornitori*), poi l'**EAN**,
poi il **codice articolo**; le righe non abbinate diventano righe libere con descrizione, prezzo e IVA;
- riporta gli **sconti** percentuali come sconto di riga e gli altri nel prezzo netto;
- sceglie il **codice IVA** dell'azienda con la stessa aliquota e natura;
- **allega il file** originale alla fattura (scheda *Allegati*, tipo *Fattura elettronica*).
L'**XML originale** viene allegato alla fattura; per i file **P7M** la **firma CAdES** viene verificata. I file già
importati sono riconosciuti come duplicati.
Le fatture importate restano **in bozza**: controllale e confermale per protocollarle. Se un codice IVA manca (per
esempio una natura non usata finora), aggiungilo in [Tabelle azienda](Tabelle-azienda) → *Codici IVA* e ripeti
l'import.
## Autofatture e integrazioni (TD16-TD29)
![035 · Autofattura / integrazione reverse charge](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/mockups/thumbs/035-autofattura-integrazione.png)
*Mockup 035 — integrazione TD17 per servizi da un fornitore estero: IVA integrata, effetto neutro, registri RC vendite e acquisti, scadenza di invio allo SDI (anteprima ridotta).*
![Khaemhat 0.6.0 · integrazione da emettere su una fattura intracomunitaria](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/acquisti-fattura-autofattura.png)
Quando l'IVA è dovuta dall'acquirente (inversione contabile) l'azienda deve **integrare** la fattura ricevuta o
emettere un'**autofattura**, trasmettendola allo SDI. In Khaemhat questi documenti stanno in **Acquisti →
Autofatture** e nascono dalla fattura di acquisto d'origine.
Quando l'IVA è dovuta da chi compra (inversione contabile, acquisti dall'estero) l'azienda deve **integrare** la
fattura ricevuta o emettere un'**autofattura** e trasmetterla allo SDI. Khaemhat lo riconosce da solo dalla fattura
fornitore (paese del fornitore, beni o servizi, natura IVA delle righe) e mostra sopra le righe quale documento serve e **entro quando**:
| Codice | Documento | Quando si usa |
| Tipo | Quando | Scadenza |
|---|---|---|
| **TD16** | Integrazione fattura reverse charge interno | acquisti nazionali in inversione contabile (art. 17 c.6 DPR 633/72, es. subappalto edile) |
| **TD17** | Integrazione/autofattura per acquisto di servizi dall'estero | servizi da fornitori UE ed extra-UE |
| **TD18** | Integrazione per acquisto di beni intracomunitari | beni da fornitori UE |
| **TD19** | Integrazione/autofattura per acquisto di beni ex art. 17 c.2 DPR 633/72 | beni già in Italia acquistati da soggetti non residenti |
| **TD20** | Autofattura per regolarizzazione e integrazione delle fatture | regolarizzazione nei casi previsti (definizione aggiornata dalle specifiche v1.9) |
| **TD21** | Autofattura per splafonamento | acquisti oltre il plafond dell'esportatore abituale |
| **TD22** | Estrazione beni da deposito IVA | |
| **TD23** | Estrazione beni da deposito IVA con versamento dell'IVA | |
| **TD28** | Acquisti da San Marino con IVA | fatture cartacee con IVA da operatori sammarinesi |
| **TD29** | Comunicazione per omessa o irregolare fatturazione | introdotto con le specifiche v1.9 (dal 1° aprile 2025) |
| **AF16** (TD16) | inversione contabile interna: righe con natura N6.x (subappalti, rottami, cellulari…) | 15 del mese dopo il ricevimento |
| **AF17** (TD17) | servizi da un fornitore estero, UE o extra UE | 15 del mese dopo |
| **AF18** (TD18) | beni da un fornitore di un altro Paese UE | 15 del mese dopo |
| **AF19** (TD19) | beni già in Italia comprati da un soggetto non residente (art. 17 c.2) | 15 del mese dopo |
| **AF28** (TD28) | acquisti da San Marino con IVA in fattura | 15 del mese dopo |
| **AF20**, **AF29** | regolarizzazione di una fattura non ricevuta o irregolare | 90 giorni |
| AF21, AF22, AF23 | splafonamento, estrazione da deposito IVA | a mano, quando servono |
Come funziona (esempio TD17, mockup 035):
![Khaemhat 0.6.0 · integrazioni da emettere](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/acquisti-autofatture-in-attesa.png)
1. La fattura estera viene registrata negli acquisti.
2. Si crea l'integrazione: le righe sono **riprese dalla fattura estera** con imponibile e aliquota; Khaemhat
calcola l'**IVA integrata**.
3. **Conferma e genera XML**: nell'XML il **fornitore estero** compare come cedente/prestatore e la **nostra azienda**
come cessionario/committente.
4. La registrazione va contemporaneamente nel **registro IVA vendite RC** e nel **registro IVA acquisti RC**: l'effetto
è **neutro** (IVA a debito = IVA a credito, salvo indetraibilità). Il pannello *Effetto contabile* mostra le due
righe.
5. L'XML va inviato **entro il 15 del mese successivo**: Khaemhat mostra la scadenza nel documento e un promemoria
nella dashboard.
**Acquisti → Autofatture** elenca in alto le **integrazioni da emettere**, la scadenza più vicina per prima. **Crea
autofattura** (qui o nella fattura fornitore) prepara il documento in bozza: le righe della fattura con il **codice IVA
ordinario** al posto della natura, il numero e la data della fattura del fornitore come documento collegato, la data
di oggi. Controllalo ed **emettilo**: prende il numero dal numeratore `AUT` delle autofatture.
Schede: *Righe*, *Testata*, *Registrazione IVA*, *XML SDI*, *Collegamenti*. Le definizioni ufficiali dei codici sono
in [Fiscalità italiana](Fiscalita-italiana).
Il **file XML** dell'autofattura (con il fornitore come cedente e l'azienda come cessionario) e l'invio allo SDI
arrivano con la [Fatturazione elettronica](Fatturazione-elettronica) (M9); la doppia registrazione nei registri IVA
vendite e acquisti con la [Contabilità](Contabilita) (M7). Le definizioni ufficiali dei codici TD sono in
[Fiscalità italiana](Fiscalita-italiana).
## Fatture da fornitori forfettari
Le fatture dei fornitori in **regime forfettario** non hanno IVA (natura N2.2 nell'XML del fornitore) e riportano il
**bollo** quando dovuto; non sono soggette a ritenuta d'acconto. Nella scheda del fornitore il flag *Regime
forfettario* (gruppo *Ritenute e contributi*) indica questa situazione; i controlli automatici sulla fattura
importata saranno definiti in sviluppo.
Le fatture dei fornitori in **regime forfettario** non hanno IVA (natura N2.2) e riportano il **bollo** quando dovuto;
non sono soggette a ritenuta. All'import la riga prende il codice IVA dell'azienda con natura N2.2; non serve
nessuna autofattura.
## Stati
Ordini e DDT di carico seguono gli stati del motore documenti: *Bozza*, *Confermato*, *Ricevuto parzialmente* /
*Ricevuto*, *Chiuso*, *Annullato*. Le fatture di acquisto sono *Bozza* finché non vengono **registrate
(protocollate)**; i badge indicano anche *Da XML SDI*, *Verifica prezzi*, *Caricato a magazzino*, *Da fatturare*.
| Documento | Stati |
|---|---|
| Ordine fornitore, ricevimento | *Bozza*, *Confermato*, *Evaso in parte*, *Evaso*, *Chiuso*, *Annullato* |
| Fattura e nota di credito fornitore | *Bozza*, *Confermato* (protocollata), *Annullato* |
| Autofattura | *Bozza*, *Emessa* e, con la fatturazione elettronica, gli stati dello SDI |
## Permessi e licenza
Ordini, carichi, fatture di acquisto e import da file sono nel modulo **CORE**. La generazione e l'invio dell'XML
delle autofatture e lo scarico dal canale SDI richiedono **EINV**; la registrazione contabile e i registri IVA
**ACCT**; i pagamenti **FIN**. Costi e margini sono visibili solo a chi ha il permesso `items.cost.read`.
Ordini, ricevimenti, fatture, import e autofatture sono nel modulo **CORE**. Gli ordini richiedono
`purchases.order.read`/`write`; i ricevimenti, che muovono il magazzino, `inventory.entry.read`/`write` (e
`inventory.entry.post` per confermarli); fatture, note di credito, import e autofatture `purchases.invoice.read`/`write`.
L'XML delle autofatture richiederà **EINV**, la registrazione contabile **ACCT**, i pagamenti **FIN**. Costi e margini
sono visibili solo con `items.cost.read`.
## Domande frequenti
- **L'import segna "Duplicato".** La fattura risulta già importata: non va registrata una seconda volta (il
criterio esatto di riconoscimento sarà definito in sviluppo).
- **Una riga dell'XML non trova l'articolo.** Aggiungi il codice del fornitore nella scheda articolo (*Fornitori*):
la volta successiva l'abbinamento sarà automatico.
- **Ho ricevuto meno merce di quella ordinata.** Conferma il DDT con la quantità ricevuta: il residuo resta aperto
sull'ordine.
- **L'import dice "Già registrata".** Lo stesso fornitore ha già un documento con quel numero nello stesso anno: non
va registrata due volte.
- **Una riga dell'XML non trova l'articolo.** Aggiungi il codice che usa il fornitore nella scheda articolo
(*Fornitori*, codice fornitore): dalla volta successiva l'abbinamento è automatico.
- **Ho ricevuto meno merce di quella ordinata.** Conferma il ricevimento con la quantità arrivata: il residuo resta
aperto sull'ordine e l'ordinato degli articoli lo tiene in conto.
- **La fattura ha un prezzo diverso dall'ordine.** L'avviso sopra le righe lo segnala; se la fattura è giusta
confermala e il costo medio si allinea al prezzo fatturato.
- **Non vedo l'avviso dell'autofattura.** Compare sulle fatture di fornitori esteri o con righe in natura N6.x,
finché non c'è un'autofattura collegata. L'elenco *Integrazioni da emettere* mostra solo le fatture **confermate**.
## Pagine correlate
+6 -1
View File
@@ -1,6 +1,6 @@
# Allegati e file
> **Stato:** completa per M3 (invio e-mail e scanner con M5) · **Ultima revisione:** 2026-11-11 · **Versione software:** 0.3.0 (milestone M3)
> **Stato:** completa per M5 (acquisizione da scanner con M13) · **Ultima revisione:** 2026-11-12 · **Versione software:** 0.5.0
> **Modulo di licenza:** CORE · **Permessi principali:** `attachments.read`, `attachments.write`, `attachments.delete` · **Specifica:** SPEC §9.4
Ogni documento e ogni anagrafica può avere **allegati**: file caricati dall'utente (l'ordine del cliente in PDF, una
@@ -79,6 +79,11 @@ La sezione **Genera file** del pannello elenca le uscite disponibili per il docu
**Rigenera** non sovrascrive mai: crea la versione successiva (`v2`, `v3`…) e lascia consultabili le precedenti.
**In 0.5.0** i documenti di vendita (preventivi, ordini, DDT, fatture, note, pro forma) hanno il generatore **Stampa
del documento in PDF**: lo stesso disegno dell'anteprima di stampa (vedi [Vendite](Vendite#stampa-e-pdf)). Lo usano
anche **Salva come allegato** dell'anteprima e **Invia per e-mail**, che allega al messaggio la versione appena
creata: così tra gli allegati resta sempre la copia esatta di ciò che è stato stampato o inviato.
Anche i **report** producono file (XLSX, CSV, PDF) scaricabili e, se pianificati, inviati per e-mail come allegati.
Le **stampe massive** (ad esempio tutte le fatture del mese) producono un unico **ZIP** scaricato direttamente,
senza file temporanei.
+9 -7
View File
@@ -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
+4 -1
View File
@@ -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,
+3 -1
View File
@@ -1,6 +1,6 @@
# Changelog
> **Stato:** completa per 0.4.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,8 @@ 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). |
| 0.2.0 | 2026-11-11 | M2 — Sistema e sicurezza: avvio da variabili d'ambiente, super utente e prima azienda, accesso con password e verifica in due passaggi, utenti, ruoli e permessi, licenze e moduli con codici di prova, log per sezioni, attività programmate. |
+1 -1
View File
@@ -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 |
+29 -2
View File
@@ -1,6 +1,6 @@
# Dati di base e di esempio
> **Stato:** completa per M4 · **Ultima revisione:** 2026-11-12 · **Versione software:** 0.4.0 (dati di esempio di documenti 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
@@ -133,7 +133,34 @@ i controlli; non si verificano sul VIES (ADR 0029). Gli agenti di esempio non so
Ci sono poi **120 articoli** in dieci categorie con i listini *Pubblico* e *Rivenditori* derivati dal base, prezzi
dell'anno precedente, fornitori abituali, UM e codici alternativi, sostitutivi e i prezzi netti e i codici di un
cliente (ADR 0030, vedi [Articoli e listini](Articoli-e-listini)). I codici a barre di esempio iniziano con `200`,
prefisso riservato all'uso interno. Il resto della tabella arriva con le milestone dei rispettivi moduli.
prefisso riservato all'uso interno.
**Da M5** l'azienda di esempio ha anche il **profilo** compilato (indirizzo, partita IVA, REA, nota a piè di
pagina delle stampe) e **un anno di vendite** costruite con il motore dei documenti, con date dal 1° gennaio a oggi:
| Documenti | Stati |
|---|---|
| 6 preventivi | 2 trasformati in ordine, 1 rifiutato, 1 con la validità scaduta, 1 in attesa di risposta, 1 in bozza |
| 4 ordini clienti | 3 evasi (uno in due consegne), 1 ancora da consegnare |
| 5 DDT | 2 già fatturati in differita, 3 da fatturare (prova la [fatturazione differita](Vendite#fatturazione-differita)) |
| 8 fatture | 5 immediate (una in bozza), 2 differite, 1 pro forma |
| 1 nota di credito | reso di un articolo difettoso, collegata alla fattura |
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.
**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.
+193
View File
@@ -0,0 +1,193 @@
# Guida all'uso
> **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
**installare** Khaemhat parte invece da [Installazione con Docker](Installazione-Docker) o
[Installazione su Unraid](Installazione-Unraid) e da [Primi passi](Primi-passi).
## Che cosa c'è in questa versione
| 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, 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, 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.
## 1. Entrare
![Pagina di accesso](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/accesso-login.png)
Scegli l'**azienda**, scrivi **nome utente** e **password** e premi **Accedi**. Se il tuo account ha la verifica in
due passaggi, Khaemhat chiede il codice a 6 cifre dell'app di autenticazione (o un codice di recupero). Al primo
accesso può chiederti di cambiare la password. Vedi [Primi passi](Primi-passi) e
[Utenti e permessi](Utenti-e-permessi).
## 2. Orientarsi
![La Home](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/interfaccia-home.png)
- **Barra superiore**: logo e versione, l'**azienda** su cui lavori (si cambia da qui), la **ricerca globale**
(`Ctrl+K`), cronologia, **notifiche**, tema chiaro o scuro, **aiuto** (`F1`) e il menu del tuo profilo.
- **Menu a sinistra**: le aree del gestionale; si comprime per avere più spazio.
- **Schede**: ogni maschera si apre in una scheda; puoi tenerne aperte più insieme e passare dall'una all'altra.
- **Barra di stato** in basso: azienda, esercizio, utente, stato della connessione e versione.
La **Home** è una dashboard a widget che ognuno personalizza. Le scorciatoie da tastiera sono elencate in
[Interfaccia e scorciatoie](Interfaccia-e-scorciatoie#tabella-completa-delle-scorciatoie); la dashboard in
[Dashboard](Dashboard).
![Ricerca globale](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/interfaccia-ricerca.png)
## 3. Preparare l'azienda
![Codici IVA](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/tabelle-codici-iva.png)
Prima dei documenti controlla in **Tabelle azienda**:
1. **Profilo azienda**: ragione sociale, partita IVA, indirizzo, REA, contatti, logo e la nota a piè di pagina delle
stampe. Questi dati compaiono su ogni documento stampato.
2. **Esercizi e periodi**: l'esercizio dell'anno deve essere aperto, altrimenti i documenti non si confermano.
3. **Pagamenti**, **banche**, **codici IVA**, **depositi**: le tabelle di base sono già caricate; aggiungi le tue.
4. **Tipi documento** e **numeratori**: il formato dei numeri (`7/2026`, `OC-2026-0004`) e i sezionali.
5. **Codici automatici**: come si numerano clienti, fornitori e articoli.
Dettagli in [Tabelle azienda](Tabelle-azienda) e [Dati di base e di esempio](Dati-di-base-e-esempio).
## 4. Clienti e fornitori
![Radar dei clienti](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/anagrafiche-radar.png)
**Anagrafiche → Clienti** apre il **radar**, l'elenco con ricerca, filtri, colonne a scelta e viste salvate.
`Ctrl+N` crea un cliente; un doppio clic apre la scheda.
![Scheda cliente](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/anagrafiche-scheda.png)
Nella scheda compili i dati anagrafici e fiscali (partita IVA e codice fiscale sono controllati; la partita IVA UE si
verifica sul VIES), gli indirizzi di consegna, i contatti e le **condizioni commerciali**: pagamento, listino,
agente, banca. I documenti di vendita le propongono da soli. Vedi [Anagrafiche](Anagrafiche).
## 5. Articoli e prezzi
![Scheda articolo](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/articoli-scheda.png)
**Anagrafiche → Articoli**: codice, descrizione, categoria, unità di misura, codice IVA, prezzo, codici a barre,
fornitori abituali. **Listini** gestisce i prezzi per listino con date di validità; nella scheda del cliente puoi
fissare prezzi netti. Vedi [Articoli e listini](Articoli-e-listini).
![Griglia dei listini](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/listini-griglia.png)
## 6. Vendere
![Radar delle fatture](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/vendite-fatture-radar.png)
Il menu **Vendite** raccoglie preventivi, ordini, DDT, fatture e note di credito. Il percorso tipico:
1. **Preventivo** → **Crea Ordine cliente** quando il cliente accetta.
2. **Ordine** → **Crea DDT** a ogni consegna (anche parziale) oppure **Crea Fattura immediata**.
3. **Fatturazione differita** a fine mese: tutti i DDT del periodo diventano fatture, una per cliente.
4. **Nota di credito** dalla fattura per un reso o una correzione.
![Fattura emessa](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/vendite-documento.png)
Nella maschera del documento scegli il cliente, inserisci le righe (`F4` cerca l'articolo) e controlla castelletto
IVA, scadenze e totali; **Conferma** (o **Emetti** per le fatture) assegna il numero. I documenti restano collegati
riga per riga, così Khaemhat sa che cosa resta da consegnare o da fatturare.
![Fatturazione differita](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/vendite-fatturazione-differita.png)
Tutto il ciclo è spiegato in [Vendite](Vendite).
## 7. Stampare e inviare
![Anteprima di stampa](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/vendite-stampa.png)
La **stampante** della toolbar (`Ctrl+P`) apre l'anteprima: **Stampa** con la stampante del computer, **Apri PDF** o
**Scarica PDF**, **Salva come allegato** per conservarne una copia.
![Invio per e-mail](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/vendite-email.png)
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. Comprare
![Fattura fornitore con differenza di prezzo](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/acquisti-fattura-differenze.png)
Il ciclo passivo usa le stesse maschere delle vendite. In **Acquisti → Ordini fornitori** prepari l'ordine (il prezzo
è quello del fornitore nella scheda articolo); quando arriva la merce **Crea DDT fornitore (carico)** registra il
ricevimento, anche in più volte, e alla conferma carica il magazzino. **Crea Fattura fornitore** prepara la fattura:
alla conferma prende il **protocollo** IVA. Se il prezzo fatturato è diverso da quello dell'ordine o del ricevimento,
un avviso sopra le righe lo segnala.
![Import delle fatture passive](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/acquisti-importa-fatture.png)
Le fatture elettroniche ricevute si caricano da **Acquisti → Importa fatture**: XML, P7M o ZIP, anche molti file
insieme. Khaemhat trova o crea il fornitore, abbina gli articoli, scarta i doppioni e registra le fatture in bozza con
il file allegato. Per le fatture di fornitori esteri o in inversione contabile indica quale **autofattura** serve ed
entro quando; **Acquisti → Autofatture** le elenca tutte. Vedi [Acquisti](Acquisti).
## 9. Il magazzino
![Giacenze e disponibilità](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/magazzino-giacenze.png)
**Magazzino → Giacenze** mostra per ogni articolo giacenza, impegnato, ordinato, disponibile, costo medio e valore,
con lo stato rispetto a scorta minima e punto di riordino; apri una riga per vedere i movimenti. I documenti
confermati muovono il magazzino da soli: non serve registrare a parte carichi e scarichi.
![Proposta di riordino](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/magazzino-riordino.png)
**Proposte di riordino** calcola che cosa ordinare e a quale fornitore e crea gli ordini in bozza, uno per fornitore.
**Inventario** guida il conteggio fisico (anche dal file del lettore di codici a barre) e registra le rettifiche;
**Valorizzazione** calcola il valore del magazzino a una data con le classi ABC. Vedi [Magazzino](Magazzino).
## 10. Allegati
![Pannello allegati](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/allegati-pannello.png)
Ogni anagrafica e ogni documento ha la scheda **Allegati**: carichi file dal computer, li vedi in anteprima, scarichi tutto in un archivio ZIP. I PDF che Khaemhat genera sono **versionati**: ogni stampa salvata o
e-mail inviata aggiunge una versione e le precedenti restano. Vedi [Allegati e file](Allegati-e-file).
## 11. Importare ed esportare
![Mappatura delle colonne](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/import-export-mappatura.png)
**Amministrazione → Import/Export** porta in Khaemhat clienti, fornitori, articoli, 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).
## 12. Personalizzare
![Il mio profilo](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/preferenze-profilo.png)
Dal menu del tuo nome, **Il mio profilo**: tema chiaro, scuro o automatico, colore d'accento, densità e carattere,
dati personali, password e verifica in due passaggi, sessioni aperte e pagina iniziale. Le preferenze dell'azienda (ad esempio i decimali dei
prezzi) sono in **Tabelle azienda → Preferenze**. Vedi [Preferenze utente](Preferenze-utente).
![Tema scuro](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/design-tema-scuro.png)
## Se qualcosa non va
- **`F1`** apre l'aiuto della pagina in cui sei: la pagina di questa wiki, anche senza connessione a Gitea.
- La pagina di errore riporta un **codice di traccia**: comunicalo all'amministratore, che lo ritrova nel
[Log](Log).
- Le domande più comuni sono in [FAQ](FAQ); i termini del gestionale nel [Glossario](Glossario).
## Pagine correlate
[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)
+5 -1
View File
@@ -1,6 +1,6 @@
# Khaemhat
> **Stato:** bozza · **Ultima revisione:** 2026-11-12 · **Versione software:** 0.4.0 (M4; sviluppo in corso)
> **Stato:** completa per 0.6.0 · **Ultima revisione:** 2026-11-12 · **Versione software:** 0.6.0 (M6; sviluppo in corso)
![Khaemhat](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/assets/icon-v1.0-128.png)
@@ -18,8 +18,12 @@ Il nome viene da uno scriba dell'antico Egitto che sovrintendeva ai granai del r
## Per iniziare
> **Usi Khaemhat?** Parti dalla **[Guida all'uso](Guida-utente)**: dall'accesso alla fattura inviata al cliente, con
> le schermate della versione attuale e che cosa c'è e che cosa arriva.
| Se vuoi… | Leggi |
|---|---|
| Imparare a usare il gestionale | [Guida all'uso](Guida-utente) |
| Installare Khaemhat su Unraid | [Installazione-Unraid](Installazione-Unraid) |
| Installarlo con Docker Compose | [Installazione-Docker](Installazione-Docker) |
| Fare il primo accesso e configurare l'azienda | [Primi-passi](Primi-passi) |
+8 -5
View File
@@ -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)
+14
View File
@@ -55,6 +55,20 @@ Khaemhat invia e-mail (inviti, recupero password, documenti, report, avvisi) tra
I valori iniziali possono arrivare dalle variabili `KHAEMHAT_SMTP_HOST`, `_PORT`, `_USER`, `_PASSWORD`, `_FROM`,
`_SECURITY`; quelli salvati qui li sovrascrivono.
> **In 0.5.0** la pagina *Impostazioni* non c'è ancora (arriva con M12): il server SMTP si configura **solo con le
> variabili d'ambiente** e serve all'invio dei documenti per e-mail (vedi [Vendite](Vendite#invio-per-e-mail)).
>
> | Variabile | Valore |
> |---|---|
> | `KHAEMHAT_SMTP_HOST` | nome del server; senza, l'invio è spento |
> | `KHAEMHAT_SMTP_FROM` | indirizzo del mittente (solo l'indirizzo, ad esempio `ufficio@azienda.it`); obbligatorio insieme all'host |
> | `KHAEMHAT_SMTP_SECURITY` | `STARTTLS` (predefinito), `SSL` (o `TLS`, connessione cifrata dall'inizio) oppure `NONE` (solo su reti fidate) |
> | `KHAEMHAT_SMTP_PORT` | predefinita 587, oppure 465 con `SSL` |
> | `KHAEMHAT_SMTP_USER`, `KHAEMHAT_SMTP_PASSWORD` | credenziali, se il server le chiede (AUTH PLAIN o LOGIN); la password anche come `KHAEMHAT_SMTP_PASSWORD_FILE` |
>
> Il client SMTP è scritto in Khaemhat, senza librerie esterne: un messaggio per connessione, tre tentativi, l'esito
> nel [Log](Log), sezione *E-mail / PEC*.
**Prova:** premi **Invia e-mail di prova** dopo aver salvato: arriva un messaggio all'indirizzo indicato. L'esito
compare anche in [Stato sistema](Stato-sistema) (controllo *SMTP*) e nel [Log](Log), sezione *E-mail / PEC*.
+2 -2
View File
@@ -59,7 +59,7 @@ Ogni modulo scrive nella **propria sezione**. Il pannello a sinistra le elenca c
| **Autenticazione** | accessi, errori di password, blocchi, 2FA, nuovi dispositivi |
| **Database** | connessioni, manutenzione |
| **Migrazioni** | migrazioni applicate e loro esito |
| **Documenti** | creazione, emissione, annullamento di documenti |
| **Documenti** | conferma ed emissione con il numero assegnato, chiusura, riapertura, annullamento, eliminazione delle bozze (da 0.5.0) |
| **Contabilità** | registrazioni, liquidazioni, chiusure |
| **Magazzino** | movimenti, ricostruzioni |
| **SDI / e-invoicing** | generazione XML, invii, notifiche, scarti |
@@ -68,7 +68,7 @@ Ogni modulo scrive nella **propria sezione**. Il pannello a sinistra le elenca c
| **Attività programmate** | inizio, fine, durata, esito di ogni esecuzione |
| **Backup** | backup, copie remote, verifiche, ripristini |
| **API / MCP** | chiamate API e strumenti MCP |
| **E-mail / PEC** | invii e letture di posta |
| **E-mail / PEC** | invii e letture di posta: da 0.5.0 ogni messaggio messo in coda, inviato, ritentato o fallito, con la risposta del server SMTP |
| **Integrazioni** | VIES, cambi BCE, intermediari SDI |
| **UI / circuiti** | errori dell'interfaccia con lo stack completo |
| **Prestazioni** | query oltre 500 ms, richieste lente, garbage collection |
+136 -90
View File
@@ -1,148 +1,194 @@
# Magazzino
> **Stato:** bozza · **Ultima revisione:** 2026-11-10 · **Versione software:** non ancora rilasciata (milestone M6)
> **Modulo di licenza:** CORE · **Permessi principali:** `inventory.entry.post`, `items.cost.read`, famiglia `inventory.*` · **Specifica:** SPEC §11.6, §22
> **Stato:** completa per la versione 0.6 · **Ultima revisione:** 2026-11-12 · **Versione software:** 0.6.0 (M6)
> **Modulo di licenza:** CORE · **Permessi principali:** `inventory.stock.read` (giacenze), `inventory.entry.*` (movimenti, inventario), `inventory.entry.post` (conferma, rettifiche, ricostruzione), `items.cost.read` (costi e valori) · **Specifica:** SPEC §11.6, ADR 0035
Il **magazzino** tiene la quantità e il valore di ogni articolo in ogni **deposito**. Le giacenze si aggiornano da
sole con i documenti (DDT, fatture accompagnatorie, carichi, resi) e con i movimenti manuali; da qui si fanno
trasferimenti tra depositi, inventari fisici, la proposta di riordino e la valorizzazione.
sole quando confermi un documento che muove la merce (DDT, fatture accompagnatorie, carichi dai fornitori, resi,
movimenti manuali); da qui consulti giacenze e movimenti, fai l'**inventario fisico**, generi la **proposta di
riordino** e calcoli la **valorizzazione** a una data.
> **In questa versione** ci sono giacenze per deposito, impegnato e ordinato, costo medio ponderato, movimenti per
> articolo, movimenti manuali e trasferimenti, inventario fisico con import dei conteggi, proposta di riordino,
> valorizzazione con analisi ABC e ricostruzione. Arrivano più avanti: le **scritture contabili** delle rimanenze e il
> **libro inventari** (M7), i report di magazzino stampabili (M13), FIFO e LIFO a lotti (dopo la 1.0).
## Dove si trova
Menu **Magazzino** → *Giacenze*, *Movimenti*, *Inventario fisico*, *Sottoscorta* (proposta di riordino),
*Trasferimenti*. I depositi e le causali di magazzino sono in [Tabelle azienda](Tabelle-azienda).
Menu **Magazzino** → *Giacenze*, *Movimenti*, *Inventario*, *Proposte di riordino*. I **depositi** e le **causali
di magazzino** sono in [Tabelle azienda](Tabelle-azienda); scorta minima, punto e lotto di riordino e fornitori
abituali sono nella scheda dell'articolo (vedi [Articoli e listini](Articoli-e-listini)).
## Le quattro quantità
## Le quantità
| Quantità | Significato | Da dove nasce |
|---|---|---|
| **Giacenza** | merce fisicamente presente nel deposito | carichi e scarichi confermati |
| **Impegnato** | merce riservata a ordini clienti confermati e non ancora evasi | ordini clienti, trasferimenti in bozza |
| **Ordinato** | merce in arrivo dai fornitori | ordini fornitore confermati e non ancora ricevuti |
| **Disponibile** | **giacenza - impegnato** | calcolata |
| **Giacenza** | merce presente nel deposito | movimenti dei documenti confermati |
| **Impegnato** | merce riservata a ordini clienti confermati e non ancora evasi | residuo degli ordini clienti |
| **Ordinato** | merce in arrivo dai fornitori | residuo degli ordini fornitore confermati |
| **Disponibile** | giacenza meno impegnato | calcolata |
Il sistema registra anche la merce **in transito** e il **valore medio** per articolo e deposito. Tutte queste
quantità sono aggiornate **nella stessa transazione** del documento che le muove: non c'è mai un momento in cui il
documento è confermato e la giacenza no.
Tutte si aggiornano **nella stessa operazione** che conferma il documento: non c'è mai un momento in cui il documento
è confermato e la giacenza no. Se annulli il documento, i suoi movimenti spariscono e le quantità tornano come prima.
## Quali documenti muovono il magazzino
Ogni tipo documento ha una **causale di magazzino** (in *Tabelle azienda → Tipi documento*) che decide se carica,
scarica o trasferisce. Con i tipi di base:
| Documento | Causale | Effetto |
|---|---|---|
| DDT, fattura immediata, fattura accompagnatoria | `SCA` scarico per vendita | scarica al costo medio |
| DDT fornitore (carico), fattura fornitore | `CAR` carico da acquisto | carica e aggiorna il costo medio |
| Nota di credito fornitore | `RESF` reso a fornitore | scarica |
| Movimento di magazzino (`MM`) | quella scelta nel movimento | carico, scarico o trasferimento |
| Ordini clienti e fornitori, preventivi, fatture differite | nessuna | solo impegnato e ordinato |
Una fattura nata da un DDT **non muove di nuovo** la merce: le sue righe trovano il carico o lo scarico già fatto
dal DDT. Il prezzo della fattura fornitore però **corregge il costo** del carico: se il fornitore fattura a un prezzo
diverso da quello del DDT, il costo medio viene ricalcolato con il prezzo fatturato.
Le causali di base sono: `CAR` carico da acquisto, `SCA` scarico per vendita, `RESC` reso da cliente, `RESF` reso a
fornitore, `TRA` trasferimento tra depositi, `INVP` e `INVN` rettifiche inventariali, `CVU` e `CVR` uscita e rientro
in conto visione (solo quantità), `OMA` omaggio, `AUTO` autoconsumo, `APE` esistenza iniziale. Per un'azienda creata
con una versione precedente le causali e i tipi documento mancanti si aggiungono con **Aggiorna da tabelle base** nel
menu `…` della tabella (vedi [Tabelle azienda](Tabelle-azienda)) o, per tutte le tabelle, con `scripts/seed.sh --base`.
## Giacenze e disponibilità
![036 · Giacenze, disponibilità, sottoscorta](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/mockups/thumbs/036-giacenze.png)
*Mockup 036 — striscia di indicatori (valore magazzino, articoli gestiti, sottoscorta, sotto riordino, in arrivo) e griglia giacenze con stato (anteprima ridotta).*
![Khaemhat 0.6.0 · giacenze e disponibilità](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/magazzino-giacenze.png)
In alto una **striscia di indicatori**: valore del magazzino, articoli gestiti, articoli **sottoscorta**, articoli
**sotto il punto di riordino**, valore **in arrivo** (ordinato).
In alto la striscia degli indicatori: **articoli in giacenza**, **sottoscorta**, **esauriti**, **articoli in
arrivo** (con ordini fornitore aperti) e **valore di magazzino** (visibile solo con `items.cost.read`).
La griglia mostra per ogni articolo: categoria, UM, **giacenza**, **impegnato**, **ordinato**, **disponibile**,
**scorta minima**, **punto di riordino**, **costo medio**, **valore** e uno **stato**:
Sotto, il filtro **Deposito** (tutti o uno solo) e la casella **Anche gli articoli senza giacenza**; poi il radar
con ricerca per codice o descrizione e i filtri rapidi **Categoria** e **Stato**. Per ogni articolo: categoria, unità,
giacenza, impegnato, ordinato, disponibile, scorta minima, costo medio, valore e uno **stato**:
| Stato | Quando |
|---|---|
| *OK* | disponibilità sopra il punto di riordino |
| *Sotto riordino* | disponibilità sotto il punto di riordino |
| *Sottoscorta* | disponibilità sotto la scorta minima (riga evidenziata) |
| *Esaurito · in arrivo* | giacenza a zero con ordini fornitore aperti |
| *Disponibile* | il disponibile più l'ordinato supera il punto di riordino |
| *Da riordinare* | disponibile più ordinato pari o sotto il punto di riordino |
| *Sottoscorta* | disponibile sotto la scorta minima |
| *Esaurito* | disponibile sotto zero, o a zero per un articolo con scorta minima o punto di riordino |
Filtri: ricerca (articolo, EAN, descrizione), **Deposito**, **Categoria**, **Mostra** (*Solo gestiti a magazzino*),
chip *Evidenzia sottoscorta*. Azioni: **Proposta di riordino**, **Inventario**. Il dettaglio per deposito di un
singolo articolo è anche nella scheda articolo (vedi [Articoli e listini](Articoli-e-listini)).
Le colonne *Ultimo carico* e *Ultimo scarico* si aggiungono dal selettore delle colonne del radar. I pulsanti
portano alla **proposta di riordino** e all'**inventario**, aprono la **valorizzazione** e la **ricostruzione**.
## Movimenti e trasferimenti
## Movimenti di un articolo
![037 · Movimento di magazzino manuale (trasferimento)](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/mockups/thumbs/037-movimento-magazzino.png)
*Mockup 037 — trasferimento in bozza dal deposito SEDE al deposito furgone, con disponibilità all'origine e valore (anteprima ridotta).*
![Khaemhat 0.6.0 · movimenti di un articolo](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/magazzino-movimenti-articolo.png)
I **movimenti manuali** servono per tutto ciò che non passa da un documento di vendita o acquisto: carichi e scarichi
rettificativi, omaggi interni, consumi, **trasferimenti** tra depositi. Ogni movimento ha una **causale di
magazzino** che ne stabilisce l'effetto (carico, scarico, trasferimento).
Apri una riga delle giacenze (doppio clic o **Invio**) per vedere i movimenti dell'articolo in ordine di data: il
documento che li ha generati (il link lo apre), la causale, il cliente o fornitore, il deposito, la quantità, il
costo unitario e il **saldo progressivo**. **Apri l'articolo** porta alla scheda. Il widget *Sottoscorta* della
[Dashboard](Dashboard) apre direttamente questa finestra sull'articolo scelto.
Per un trasferimento:
## Movimenti manuali e trasferimenti
1. **Magazzino → Trasferimenti** (o *Movimenti*), **Nuovo**.
2. Scegli la causale di trasferimento, il **deposito di origine** e quello di **destinazione**.
3. Inserisci le righe: la colonna *Disp. origine* mostra quanto è disponibile nel deposito di partenza.
4. Se serve, **Stampa lista prelievo** per chi prepara la merce.
5. **Conferma**.
Per tutto ciò che non passa da un documento di vendita o acquisto (rettifiche, omaggi, autoconsumi, conto visione,
trasferimenti) usa **Magazzino → Movimenti** e crea un **Movimento di magazzino**: è un documento come gli altri
(vedi [Vendite](Vendite) per la maschera), con in più la **causale** e il **deposito**.
Un trasferimento genera **due movimenti collegati** (scarico dall'origine e carico nella destinazione) nella stessa
transazione. Finché il movimento è in bozza la merce dell'origine risulta **impegnata**.
1. Scegli la **causale**: decide se il movimento carica, scarica o trasferisce.
2. Indica il **deposito**; per un trasferimento anche il **deposito di destinazione**, diverso dall'origine.
3. Inserisci le righe con articolo e quantità; nei carichi il prezzo è il costo unitario.
4. **Conferma**: il magazzino si aggiorna. Un trasferimento scarica l'origine e carica la destinazione al costo medio,
senza cambiare il valore complessivo.
Un movimento confermato si può annullare: i suoi movimenti vengono tolti e le giacenze ricalcolate.
## Inventario fisico
![038 · Inventario fisico con conteggi e rettifiche](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/mockups/thumbs/038-inventario-fisico.png)
*Mockup 038 — inventario guidato in cinque passi, griglia con giacenza teorica, contato, differenza, valore e rettifica (anteprima ridotta).*
![Khaemhat 0.6.0 · inventario fisico in conteggio](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/magazzino-inventario.png)
L'inventario è una procedura guidata:
L'inventario confronta la merce contata con la **giacenza contabile** e trasforma le differenze in rettifiche.
1. **Preparazione**: scegli il **deposito**, la **data** e il criterio di **valorizzazione** (es. costo medio);
l'opzione **Blocca movimenti durante il conteggio** congela le giacenze del deposito.
2. **Conteggio**: **Stampa liste di conteggio** (anche per ubicazione e squadra) e inserisci i quantitativi contati
nella griglia oppure **Importa conteggi CSV**.
3. **Verifica differenze**: la griglia confronta **giacenza teorica** e **contato** e mostra differenza e valore;
il filtro *Solo differenze e da contare* aiuta a chiudere il lavoro.
4. **Rettifiche**: **Genera rettifiche** crea i movimenti di carico o scarico per allineare la giacenza al contato.
5. **Chiusura**: sblocca il deposito.
1. **Apertura**: in **Magazzino → Inventario** scegli il **deposito**, la **data del conteggio**, se vuoi una
**categoria** e una descrizione, poi **Apri inventario**. Khaemhat fotografa la giacenza contabile di ogni articolo
gestito a magazzino a quella data.
2. **Conteggio**: scrivi le quantità contate nella colonna *Contato* e premi **Salva conteggi**, oppure **Importa
conteggi** da un file CSV o di testo del lettore di codici a barre: una riga per articolo con *codice articolo* e
*quantità*, separati da punto e virgola, tabulazione o virgola (con la virgola la quantità usa il punto decimale).
Una riga di intestazione viene saltata; i codici non in lista sono segnalati.
3. **Verifica differenze**: il filtro **Mostra** (*Tutti*, *Da contare*, *Con differenze*) aiuta a chiudere il
lavoro; le righe con differenza sono evidenziate e la striscia in alto riassume articoli contati, differenze e
valore delle differenze.
4. **Registrazione**: **Registra rettifiche** crea alla data del conteggio un movimento `INVP` per le eccedenze e uno
`INVN` per gli ammanchi, e chiude l'inventario. Gli articoli **non contati restano come sono**.
**Annulla inventario** lo chiude senza muovere il magazzino; i conteggi restano consultabili. I movimenti successivi
alla data del conteggio non disturbano: le rettifiche sono alla data del conteggio e la giacenza di oggi tiene conto
di entrambi.
## Proposta di riordino
![039 · Proposta di riordino fornitori dal sottoscorta](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/mockups/thumbs/039-proposta-di-riordino.png)
*Mockup 039 — proposta di riordino: indicatori, criterio di calcolo, quantità proposta modificabile e fornitore per riga (anteprima ridotta).*
![Khaemhat 0.6.0 · proposta di riordino](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/magazzino-riordino.png)
La proposta elenca gli articoli sotto il punto di riordino con giacenza, impegnato, ordinato, disponibile, scorta
minima, punto e **lotto** di riordino, **quantità proposta** (modificabile), **fornitore** abituale, lead time,
prezzo e valore. In alto gli indicatori: articoli sotto riordino, proposte, valore, fornitori coinvolti, articoli
già coperti da ordini.
La proposta elenca gli articoli il cui **disponibile più ordinato** non copre più il **punto di riordino** (o, se manca,
la **scorta minima**). Per ogni articolo propone:
1. Scegli **deposito**, **fornitore** (o tutti) e il **criterio di calcolo** (es. *disponibile + ordinato < punto
di riordino*, con o senza l'impegnato).
2. **Ricalcola**, controlla e correggi le quantità proposte, togli la spunta alle righe da non ordinare.
3. **Genera ordini fornitore**: Khaemhat crea **un ordine in bozza per fornitore** (vedi [Acquisti](Acquisti)).
- la **quantità**: il **lotto di riordino** dell'articolo se c'è, altrimenti quanto riporta al punto di riordino (o
alla scorta minima); mai meno del **minimo d'ordine** del fornitore;
- il **fornitore abituale** (il preferito nella scheda articolo, *Fornitori*) con il suo prezzo e la **data di arrivo
prevista** dal lead time.
Il mockup indica come fabbisogno il maggiore tra il lotto e la differenza fra punto di riordino e disponibile più
ordinato; la formula definitiva (compresi gli arrotondamenti al lotto) sarà fissata in sviluppo. La proposta può
anche essere eseguita da una procedura pianificata o alimentata da una regola di automazione (evento *articolo sotto
il punto di riordino*, vedi [Automazioni](Automazioni)).
Correggi le quantità, cambia il fornitore di una riga o togli la spunta alle righe da non ordinare; **Ricalcola**
rilegge le giacenze. **Genera ordini fornitore** crea **un ordine in bozza per fornitore** con prezzi e condizioni del
fornitore: controllali e confermali da **Acquisti → Ordini fornitori** (vedi [Acquisti](Acquisti)). Le righe senza
fornitore non vengono ordinate.
## Costo medio e valorizzazione
- Il criterio di valorizzazione è il **costo medio ponderato**: a ogni carico il nuovo costo medio è
(valore della giacenza esistente + valore del carico) / (giacenza esistente + quantità caricata). FIFO e LIFO sono
predisposti ma non attivi.
- Il **valore** di una giacenza è quantità x costo medio.
- La **valorizzazione a data** ricostruisce quantità e valore a una data passata (ad esempio al 31 dicembre).
- Le **rimanenze finali** valorizzate alimentano la chiusura dell'esercizio e il **libro inventari** (vedi
[Contabilità](Contabilita)); sono disponibili le **scritture ausiliarie di magazzino** e l'**analisi ABC**.
![Khaemhat 0.6.0 · valorizzazione con classi ABC](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/magazzino-valorizzazione.png)
- Il criterio è il **costo medio ponderato** per articolo, su tutti i depositi: a ogni carico con valore il nuovo
costo medio è (valore della giacenza + valore del carico) / (giacenza + quantità caricata). Scarichi, trasferimenti
e conto visione escono al costo medio del momento e non lo cambiano.
- La scheda articolo mostra **costo medio** e **ultimo costo** calcolati dai movimenti.
- La **valorizzazione** (pulsante nelle giacenze) calcola quantità e valore **a una data** qualsiasi, anche passata,
con il criterio scelto: *costo medio ponderato*, *ultimo costo* o *costo standard*. Divide gli articoli in **classi
ABC**: A gli articoli che fanno l'80% del valore, B fino al 95%, C il resto.
- FIFO e LIFO sono previsti con la gestione a lotti; le rimanenze alimenteranno la chiusura dell'esercizio e il libro
inventari con la [Contabilità](Contabilita) (M7).
## Ricostruzione
Se le giacenze risultassero non allineate (ad esempio dopo un ripristino o un import), la **ricostruzione** ricalcola
giacenze, impegnato, ordinato e costi medi ripercorrendo tutti i movimenti. È una procedura eseguibile a mano o da
attività programmata e non modifica i documenti. Vedi [Automazioni](Automazioni) e
[Attività programmate](Attivita-programmate).
Se le giacenze sembrano non tornare (dopo un ripristino, un import diretto nel database, un cambio di causale su un
tipo documento), **Ricostruisci** nelle giacenze riscrive tutti i movimenti dai documenti in vigore, dal più vecchio,
e ricalcola giacenze, impegnato, ordinato e costi. I documenti non cambiano e i dati restano consultabili durante il
lavoro, che mostra l'avanzamento. Richiede `inventory.entry.post`.
## Stati dei movimenti
La stessa ricostruzione gira ogni **domenica alle 2:15** come attività di sistema *Ricostruzione del magazzino* (vedi
[Attività programmate](Attivita-programmate)), su tutte le aziende attive.
| Stato | Effetto |
|---|---|
| **Bozza** | nessun effetto sulla giacenza (nei trasferimenti l'origine è impegnata) |
| **Confermato** | giacenze aggiornate; righe non più modificabili |
| **Annullato** | movimenti stornati |
## Esistenze iniziali
Per partire con le giacenze di un altro gestionale importa il tracciato **Giacenze iniziali** da
[Import ed export](Import-Export): articolo, deposito, quantità e costo unitario. Khaemhat crea e conferma un
movimento con causale `APE` per deposito, alla data dell'import.
## Permessi e licenza
Il magazzino è nel modulo **CORE**. Confermare un movimento richiede `inventory.entry.post`; vedere costi e valori
richiede `items.cost.read`.
Il magazzino è nel modulo **CORE**. Vedere giacenze e movimenti richiede `inventory.stock.read`; scrivere movimenti
e conteggi `inventory.entry.write`; confermare i movimenti, registrare le rettifiche e ricostruire
`inventory.entry.post`. Costi, valori e valorizzazione sono visibili solo con `items.cost.read`.
## Domande frequenti
- **Il disponibile è negativo.** Gli ordini clienti confermati impegnano più merce di quella in giacenza: ordina al
fornitore o rivedi le consegne.
- **Il costo medio è cambiato dopo un carico.** È il comportamento previsto del costo medio ponderato; il messaggio
sul DDT di carico indica il vecchio e il nuovo valore.
- **Durante l'inventario non riesco a scaricare merce dal deposito.** È attivo il blocco dei movimenti: termina la
procedura o disattiva il blocco.
- **La giacenza è negativa.** È stato confermato uno scarico senza merce a sufficienza (Khaemhat non lo blocca, per
non fermare le consegne): registra il carico mancante o fai un inventario.
- **Il costo medio è cambiato dopo una fattura fornitore.** Il prezzo fatturato era diverso da quello del DDT di
carico: il costo del carico viene corretto con il prezzo della fattura.
- **Un articolo non compare nelle giacenze.** Non ha movimenti: spunta *Anche gli articoli senza giacenza*. Se non
compare comunque, nella scheda non è *gestito a magazzino* o non è un bene.
- **L'articolo non è nella proposta di riordino.** Non ha punto di riordino né scorta minima, oppure l'ordinato già
lo copre.
## Pagine correlate
[Articoli e listini](Articoli-e-listini) · [Acquisti](Acquisti) · [Vendite](Vendite) ·
[Tabelle azienda](Tabelle-azienda) · [Report](Report) · [Contabilità](Contabilita) · [Automazioni](Automazioni)
[Tabelle azienda](Tabelle-azienda) · [Import ed export](Import-Export) · [Dashboard](Dashboard) ·
[Attività programmate](Attivita-programmate)
+16 -6
View File
@@ -1,6 +1,6 @@
# Primi passi
> **Stato:** parziale (passi 1-4 completi) · **Ultima revisione:** 2026-11-11 · **Versione software:** 0.2.0 (passi 1-4), passi successivi M3-M5
> **Stato:** parziale (passi 1-4, 7, 10 e 12 completi; amministrazione da interfaccia con M12) · **Ultima revisione:** 2026-11-12 · **Versione software:** 0.5.0
> **Modulo di licenza:** CORE · **Livello richiesto:** super utente, poi amministratore · **Specifica:** SPEC §5.4, §7, §8, §12, §14
Questa pagina accompagna chi ha appena installato Khaemhat dal primo avvio del container fino alla prima fattura
@@ -57,6 +57,10 @@ disattivata al primo cambio password.
*Mockup 001 — pagina di accesso: a sinistra marca e funzioni principali, a destra il modulo con azienda, nome utente,
password e l'avviso della modalità Trial (anteprima ridotta).*
![Khaemhat 0.5.0 · pagina di accesso](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/accesso-login.png)
*La pagina di accesso di Khaemhat 0.5.0.*
1. Nel campo **Azienda** lascia la prima azienda, già proposta (quella creata dal container, ad esempio
*Khaemhat Demo S.r.l.*). Il super utente e gli amministratori possono anche scegliere **Nessuna (account di
istanza)** per lavorare solo sulle pagine di amministrazione dell'istanza.
@@ -111,6 +115,10 @@ telefono. Non c'è un codice QR, perché generarlo richiederebbe una libreria es
*Mockup 002 — verifica in due passaggi: sei caselle per il codice, pulsante Verifica e nota sul codice che cambia
ogni 30 secondi (anteprima ridotta).*
![Khaemhat 0.5.0 · verifica in due passaggi](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/accesso-verifica.png)
*La verifica in due passaggi di Khaemhat 0.5.0: il codice dell'app oppure un codice di recupero.*
Agli accessi successivi, dopo la password, compare la schermata **Verifica in due passaggi**: scrivi le 6 cifre
mostrate dall'app e premi **Verifica**. Il codice cambia ogni 30 secondi.
@@ -275,12 +283,14 @@ Con l'azienda configurata puoi emettere la prima fattura:
4. Scegli il cliente: pagamento, listino e agente vengono proposti dalla sua scheda.
5. Nella scheda **Righe** aggiungi l'articolo (`F4` apre la ricerca), la quantità e controlla prezzo e IVA.
6. Premi **Salva** (`Ctrl+S`): la fattura è in *bozza*.
7. Premi **Conferma ed emetti**: la fattura riceve il numero, diventa immutabile e, con il modulo ACCT attivo,
viene contabilizzata.
8. Dalla toolbar genera il PDF o l'XML FatturaPA: ogni file generato diventa un allegato della fattura.
7. Premi **Emetti**: la fattura riceve il numero e diventa immutabile.
8. Premi la **stampante** (`Ctrl+P`): l'anteprima di stampa offre il PDF e **Salva come allegato**; dal menu **⋯**
**Invia per e-mail** manda il PDF al cliente (serve il server SMTP, vedi [Impostazioni](Impostazioni#e-mail-smtp)).
La guida completa è in [Vendite](Vendite); l'invio allo SDI richiede il modulo EINV (vedi
[Fatturazione elettronica](Fatturazione-elettronica)).
![Khaemhat 0.5.0 · una fattura emessa](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/vendite-documento.png)
La guida completa è in [Vendite](Vendite). La contabilizzazione arriva con M7 e l'XML FatturaPA per lo SDI con M9
(modulo EINV, vedi [Fatturazione elettronica](Fatturazione-elettronica)).
## Domande frequenti
+1 -1
View File
@@ -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). **In corso:** M5.
**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 -2
View File
@@ -113,7 +113,7 @@ periodo (vedi [IVA](IVA)) e la chiusura dell'esercizio lo rende di sola lettura
| **Categorie controparte** | classificazione di clienti e fornitori |
| **Listini** | intestazioni dei listini: valuta, IVA inclusa, validità, **Listino base** (uno solo, in partenza `BASE`), **Derivato da** con ricarico % e arrotondamento (i prezzi sono in [Articoli e listini](Articoli-e-listini)) |
| **Politiche di sconto** | sconti in cascata con un codice, come formula (`10+5`), da richiamare nelle condizioni |
| **Tipi documento** | catalogo dei documenti con numeratore, causale di magazzino, causale contabile, registro IVA, codice TD, modello di stampa |
| **Tipi documento** | catalogo dei documenti con **genere** (obbligatorio), numeratore, causale di magazzino, causale contabile, registro IVA, codice TD, modello di stampa |
| **Centri di costo** | per l'analisi dei costi e dei ricavi |
| **Commesse** | progetti o cantieri a cui imputare costi e ricavi |
@@ -156,7 +156,14 @@ clienti `OC-{year}-{number:D4}` (`OC-2026-0042`), autofatture `{number}/AF/{year
Il numero è assegnato in modo atomico **alla conferma** del documento (da M5); per fatture, note di credito,
protocollo acquisti e registrazioni contabili **non sono ammessi buchi** nella numerazione (opzione *Ammessi buchi di numerazione*
spenta). I numeratori sono per anno: il caricamento di base crea quelli dell'anno in corso.
spenta) e la data di un documento non può precedere la **data dell'ultimo numero** del numeratore. I numeratori sono
per anno: il caricamento di base crea quelli dell'anno in corso e il primo documento di un anno nuovo crea da solo il
numeratore di quell'anno, con le stesse regole e dal numero 1.
Il **genere** di un tipo documento dice come si comportano i suoi documenti: famiglia, ciclo di vita, effetti, righe
ammesse e documenti che può evadere (vedi [Vendite](Vendite#il-motore-dei-documenti-in-sintesi)). I tipi di base hanno
già il genere; un tipo nuovo dell'azienda (ad esempio una seconda fattura immediata con un altro sezionale) sceglie uno
dei generi esistenti e funziona senza altre impostazioni.
## Preferenze e codici automatici
+275 -212
View File
@@ -1,288 +1,351 @@
# Vendite
> **Stato:** bozza · **Ultima revisione:** 2026-11-10 · **Versione software:** non ancora rilasciata (milestone M5)
> **Modulo di licenza:** CORE (XML SDI con EINV, contabilizzazione con ACCT, partite con FIN) · **Permessi principali:** `sales.invoice.issue`, `sales.deliverynote.reopen`, famiglia `sales.*` · **Specifica:** SPEC §11.3, §11.4
> **Stato:** completa per la versione 0.5 · **Ultima revisione:** 2026-11-12 · **Versione software:** 0.5.0 (M5)
> **Modulo di licenza:** CORE (XML SDI con EINV, contabilizzazione con ACCT, partite con FIN) · **Permessi principali:** `sales.quote.*`, `sales.order.*`, `sales.delivery.*`, `sales.invoice.*` (emissione `sales.invoice.issue`) · **Specifica:** SPEC §9.4, §11.3, §11.4, §12.6
Il modulo **Vendite** gestisce l'intero ciclo attivo: **preventivi**, **ordini clienti**, **DDT**, **fatture**
(immediate, accompagnatorie, differite, acconti, semplificate), **note di credito e di debito**, **pro-forma**,
**parcelle**, la **fatturazione differita** guidata e i corrispettivi registrati a mano. Tutti i documenti usano lo
stesso motore e la stessa maschera.
Il modulo **Vendite** gestisce il ciclo attivo: **preventivi**, **ordini clienti**, **DDT**, **fatture** (immediate,
accompagnatorie, differite, di acconto, parcelle), **note di credito e di debito**, **pro forma** e la
**fatturazione differita** dei DDT. Tutti i documenti usano lo stesso motore e la stessa maschera, si stampano in PDF
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. 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'è.
## Dove si trova
Menu **Vendite** → *Preventivi*, *Ordini clienti*, *DDT*, *Fatture*, *Note di credito*, *Fatturazione differita*.
Le pro forma, le fatture di acconto e le parcelle stanno nell'elenco *Fatture*; le note di debito in *Note di credito*.
## Il motore dei documenti in sintesi
## Un giro completo in cinque minuti
Ogni tipo di documento è descritto da una definizione che stabilisce: numeratore e sezionale, causale di magazzino
(se il documento carica o scarica merce), **effetti** (impegno, scarico, partite, registrazione contabile), da quali
documenti può essere **evaso** (ad esempio un DDT da un ordine), tipo documento SDI (TD), causale contabile, registro
IVA e modello di stampa.
Con l'azienda di esempio (vedi [Dati di base e di esempio](Dati-di-base-e-esempio)) trovi già un anno di vendite in
tutti gli stati. Per provare il ciclo da zero:
1. **Vendite → Preventivi → Nuovo preventivo** (`Ctrl+N`): scegli il cliente, aggiungi due righe, **Conferma**.
2. Sul preventivo premi **Crea Ordine cliente**: le righe passano all'ordine, collegate al preventivo.
3. Sull'ordine confermato premi **Crea DDT**: puoi consegnare solo una parte delle quantità.
4. **Vendite → Fatturazione differita**: indica il mese, **Cerca i DDT**, **Genera fatture**.
5. Apri la fattura, premi la **stampante** (`Ctrl+P`) per l'anteprima e il PDF, poi **⋯ → Invia per e-mail**.
## Gli elenchi (radar)
![Khaemhat 0.5.0 · radar delle fatture di vendita](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/vendite-fatture-radar.png)
*Le fatture dell'azienda di esempio: numero, data, tipo, cliente, riferimento, imponibile, totale e stato. Le bozze
non hanno ancora un numero.*
Ogni voce del menu apre un **radar** (vedi [Interfaccia e scorciatoie](Interfaccia-e-scorciatoie#radar)): cerca per
numero, riferimento o cliente, filtra per **tipo**, **stato** e **anno**, ordina, scegli le colonne e salva la vista.
Un doppio clic (o `Invio`) apre il documento in una nuova scheda.
![Khaemhat 0.5.0 · radar dei preventivi](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/vendite-preventivi-radar.png)
*I preventivi: quelli evasi sono diventati ordini, uno è stato rifiutato, uno è in bozza.*
**Nuovo** chiede il tipo quando l'elenco ne raccoglie più d'uno (ad esempio fattura immediata, accompagnatoria,
differita, di acconto, parcella o pro forma):
![Khaemhat 0.5.0 · scelta del tipo di fattura](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/vendite-nuovo-tipo.png)
## La maschera del documento
![Khaemhat 0.5.0 · fattura immediata, scheda Righe](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/vendite-documento.png)
*Una fattura emessa: toolbar, intestazione con tipo, numero, stato, cliente e totale; righe; castelletto IVA,
scadenze e totali.*
- **Toolbar**: nuovo, salva (`Ctrl+S`), annulla le modifiche, elimina (solo bozze), **stampa** (`Ctrl+P`),
**allegati**, le azioni del documento (*Conferma*, *Emetti*, *Crea …*) e il menu **⋯** con *Duplica*, *Chiudi*,
*Riapri*, *Annulla documento*, *Invia per e-mail*. A destra il **radar** e i pulsanti per il documento precedente e
successivo.
- **Intestazione**: tipo e numero (in bozza *Numero alla conferma*), data, stato, badge *Dato dimostrativo* per i dati
di esempio; cliente con codice, località e partita IVA, condizioni proposte (pagamento, listino, agente); il totale
del documento con imponibile e IVA.
- **Schede**: *Righe* (si apre lì), *Testata*, *Trasporto* (DDT e fatture accompagnatorie), *Totali*, *Scadenze*,
*Note*, *Allegati*, *Collegamenti*, *Storico*. Il numero accanto al nome della scheda conta righe, rate o
collegamenti.
### Righe
Ogni riga ha articolo (`F4` per cercarlo), descrizione, unità di misura, quantità, prezzo, sconti a cascata (`10+3`),
codice IVA e importo. Scegliendo l'articolo Khaemhat propone descrizione, unità, codice IVA e prezzo secondo l'ordine
*prezzo netto del cliente → listino del cliente → listino base → prezzo dell'articolo* (vedi
[Articoli e listini](Articoli-e-listini)). Oltre alle righe di merce ci sono le righe **descrittive** (solo testo),
le righe di **spesa** (trasporto, incasso) e le righe di **sconto**; i DDT non accettano spese né sconti.
Sotto le righe: **castelletto IVA** (imponibile e imposta per codice IVA), **scadenze** (le rate della condizione di
pagamento) e **totali**.
### Testata
![Khaemhat 0.5.0 · fattura, scheda Testata](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/vendite-documento-testata.png)
*La Testata con i gruppi Documento, Cliente, Condizioni e Dati fiscali.*
| Gruppo | Campi |
|---|---|
| **Documento** | tipo, numero (alla conferma), **data** *, validità (preventivi), data di consegna (ordini), revisione, riferimento e data del cliente, documento rettificato (note) |
| **Cliente** | **cliente** *, agente, valuta, listino |
| **Condizioni** | pagamento, modalità, banca, sconto di piede, prezzi IVA inclusa |
| **Dati fiscali** | esigibilità IVA, split payment, bollo a carico del cliente, CIG e CUP per la PA |
| **Ritenuta, cassa previdenza, ENASARCO** | per parcelle e provvigioni: aliquote, base, tipo e causale della ritenuta, cassa |
| **Note** | note stampate sul documento |
Scegliendo il cliente Khaemhat propone destinazione, listino, pagamento, agente e banca dalle sue **condizioni
commerciali** (vedi [Anagrafiche](Anagrafiche)). Per emettere una fattura ogni riga (tranne le descrittive) deve
avere il codice IVA.
### Trasporto (DDT e fatture accompagnatorie)
![Khaemhat 0.5.0 · DDT, scheda Trasporto](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/vendite-ddt-trasporto.png)
*Causale del trasporto, trasporto a cura del mittente, del destinatario o del vettore, porto, aspetto dei beni,
colli, pesi, inizio del trasporto.*
I dati di trasporto finiscono nella stampa insieme agli spazi per le **firme** del conducente, del vettore e del
destinatario.
### Collegamenti
![Khaemhat 0.5.0 · ordine cliente, scheda Collegamenti](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/vendite-collegamenti.png)
*Un ordine evaso: da quale preventivo nasce e quali DDT lo hanno evaso, con le quantità.*
I documenti sono **collegati riga per riga**: quando un DDT evade un ordine, ogni riga del DDT ricorda la riga
d'ordine di origine e la quantità evasa. Così Khaemhat calcola i **residui**, permette di riaprirli e scrive nel file
XML della fattura i riferimenti all'ordine (*DatiOrdineAcquisto*) e ai DDT (*DatiDDT*).
d'ordine e la quantità evasa. Così Khaemhat calcola i **residui** e lo stato (*Evaso in parte*, *Evaso*). Il
collegamento vale dalla **conferma** del documento che evade: una bozza non toglie nulla al residuo, un documento
annullato lo restituisce. Una nota di credito mostra qui la fattura che rettifica.
## Dal preventivo alla fattura: Crea …
```
Preventivo ──trasforma──► Ordine cliente ──evadi──► DDT ──fattura differita──► Fattura TD24
└────────────── evadi ──────────────► Fattura immediata TD01
Preventivo ──Crea Ordine──► Ordine cliente ──Crea DDT──► DDT ──Fatturazione differita──► Fattura differita (TD24)
└──────────── Crea Fattura immediata ─────────────► Fattura immediata (TD01)
Fattura ──Crea Nota di credito──► Nota di credito (TD04)
```
Alla **conferma**, in un'unica operazione indivisibile, il documento riceve il numero, muove il magazzino, genera
le scadenze e le partite, crea la registrazione contabile e gli allegati: o riesce tutto o non cambia nulla.
![Khaemhat 0.5.0 · Crea ordine dal preventivo](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/vendite-trasforma.png)
*Crea Ordine cliente da un preventivo: si scelgono le righe; per un documento che evade, la quantità proposta è
quella ancora da evadere.*
## La maschera di un documento di vendita
I pulsanti **Crea …** della toolbar elencano i documenti che si possono generare da quello aperto. Se il nuovo tipo
**evade** il vecchio (preventivo → ordine, ordine → DDT o fattura, DDT → fattura differita) le righe prendono solo le
**quantità residue**, che puoi ridurre, e restano collegate; altrimenti (ad esempio fattura → nota di credito) le
righe si **copiano**. Il nuovo documento nasce in **bozza** e si apre in una nuova scheda. **Duplica** crea invece un
documento dello stesso tipo con la data di oggi.
![020 · Fattura di vendita · righe](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/mockups/thumbs/020-fattura-vendita-righe.png)
*Mockup 020 — fattura in bozza: toolbar con Conferma ed emetti, XML SDI, Contabilizza, Evadi da…; intestazione; righe con riga descrittiva; castelletto IVA, scadenze e totali (anteprima ridotta).*
## Preventivi
![021 · Fattura di vendita · testata](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/mockups/thumbs/021-fattura-vendita-testata.png)
*Mockup 021 — scheda Testata con i gruppi Documento, Controparte, Condizioni, Magazzino e trasporto (anteprima ridotta).*
Il preventivo ha una **validità** (giorni o data) che compare nella stampa. Quando il cliente accetta, **Crea Ordine
cliente**; se rifiuta, **⋯ → Segna come rifiutato** (il preventivo passa a *Chiuso*). Un preventivo trasformato in
ordine risulta *Evaso*.
![022 · Fattura di vendita · tema scuro](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/mockups/thumbs/022-fattura-vendita-tema-scuro.png)
*Mockup 022 — la stessa fattura in tema scuro con accento Malachite (anteprima ridotta).*
## Ordini clienti
La struttura è quella descritta in [Interfaccia e scorciatoie](Interfaccia-e-scorciatoie): toolbar, intestazione a
tre blocchi, schede **Righe** (si apre lì), *Testata*, *Totali*, *Trasporto*, *Scadenze*, *Dati SDI/PA*, *Note*,
*Allegati*, *Collegamenti*, *Storico*.
L'ordine raccoglie gli impegni presi con il cliente. Da un ordine confermato si creano **DDT** o **fatture
immediate**, anche più di uno, finché resta un residuo; la scheda *Collegamenti* mostra chi ha evaso cosa. **⋯ →
Chiudi** chiude il residuo che non verrà consegnato, **Riapri** lo riporta aperto. Per la PA la Testata raccoglie CIG
e CUP, riportati nella stampa.
| Gruppo della Testata | Campi |
## DDT (documenti di trasporto)
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. Alla conferma il DDT
**scarica il magazzino** (causale `SCA`); la fattura differita che lo fattura non scarica di nuovo.
## Fatture
1. **Vendite → Fatture → Nuova fattura**, scegli il tipo, oppure parti da un ordine con **Crea Fattura immediata**.
2. Scegli il cliente: condizioni, listino, agente e destinazione vengono proposti.
3. Inserisci le righe e controlla castelletto IVA, scadenze e totali.
4. **Emetti** (permesso `sales.invoice.issue`): assegna il numero e blocca il documento.
Una fattura **emessa non si modifica**. Per correggerla si emette una **nota di credito**; finché il file XML non è
stato inviato allo SDI si può **annullare** indicando il motivo (il numero resta usato).
## Note di credito (TD04) e di debito (TD05)
![Khaemhat 0.5.0 · nota di credito](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/vendite-nota-credito.png)
*Una nota di credito che storna un articolo difettoso: l'intestazione indica la fattura rettificata.*
Si crea dalla fattura con **Crea Nota di credito** (le righe si copiano e si tolgono quelle che non vanno stornate) o
da **Vendite → Note di credito → Nuova nota**. Usa lo stesso numeratore delle fatture.
## Pro forma e parcelle
La **pro forma** è un documento **non fiscale** (ad esempio per chiedere un anticipo): stessa maschera della fattura,
numerazione propria (`PF-2026-0001`), nessun file XML e nessun effetto contabile; si trasforma in fattura quando
serve. La **parcella** (TD06) calcola la **cassa previdenza** e la **ritenuta d'acconto** e mostra il **netto a
pagare**; gli acconti su parcella usano TD03.
## Fatturazione differita
![Khaemhat 0.5.0 · fatturazione differita](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/vendite-fatturazione-differita.png)
*Ottobre: tre DDT da fatturare, uno per cliente; a destra la fattura in cui finirà ciascuno.*
1. **Periodo e cliente**: *DDT dal* e *DDT al*, un cliente (vuoto per tutti), la **data delle fatture** e il
**raggruppamento** (*una fattura per cliente* o *una fattura per DDT*). Spunta *Emetti subito le fatture* per
numerarle subito; altrimenti restano in bozza da controllare. Premi **Cerca i DDT**.
2. **Scelta dei DDT**: l'elenco mostra i DDT confermati e non ancora fatturati con la fattura che verrà generata;
togli la spunta a quelli da fatturare più avanti.
3. **Genera fatture**: crea una fattura differita (TD24) per gruppo, con i riferimenti ai DDT nelle righe; i DDT
diventano *Evasi*. Il riepilogo indica quante fatture sono state create; un clic le apre.
Con *una fattura per cliente* i DDT dello stesso cliente finiscono in una sola fattura, che prende pagamento,
banca e condizioni dal primo DDT; se un cliente ha DDT con condizioni diverse scegli *una fattura per DDT*. La fattura differita va emessa entro il giorno 15 del mese successivo a quello delle consegne.
## Stampa e PDF
![Khaemhat 0.5.0 · anteprima di stampa di una fattura](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/vendite-stampa.png)
*L'anteprima di stampa: intestazione dell'azienda, cliente, righe, riepilogo IVA, scadenze e totali.*
La **stampante** della toolbar (`Ctrl+P`) salva il documento se serve e apre l'**anteprima di stampa**:
| Pulsante | Che cosa fa |
|---|---|
| **Documento** | Tipo documento, Sezionale/Numero, **Data** *, Registro IVA, Competenza IVA, Valuta, Cambio, Vostro riferimento |
| **Controparte** | **Cliente** *, Destinazione, Fatturare a, Agente, Listino |
| **Condizioni** | Pagamento, Inizio rate (es. fine mese), Banca azienda, Sconto piede %, Spese incasso, Bollo (automatico) |
| **Magazzino e trasporto** | Causale magazzino, Deposito, Vettore, Porto, Colli |
| **Stampa** | la stampa del browser (scegli la stampante o *Salva come PDF*) |
| **Apri PDF** / **Scarica PDF** | il PDF disegnato da Khaemhat, identico all'anteprima |
| **Salva come allegato** | conserva il PDF tra gli **allegati** del documento come nuova versione e segna il documento come *stampato* |
| 75% · 100% · 125% | lo zoom dell'anteprima |
Scegliendo il cliente, Khaemhat propone destinazione, listino, pagamento, agente e banca dalle sue condizioni
commerciali; dal tipo documento propone causale e deposito.
La stampa riporta i dati dell'azienda dal **profilo azienda** (ragione sociale, indirizzo, partita IVA, REA, capitale
sociale, contatti e la nota a piè di pagina; vedi [Tabelle azienda](Tabelle-azienda)), il logo (nel PDF se è un
JPEG), il cliente, i campi utili (pagamento, banca, riferimento, validità, agente, CIG e CUP), le righe, il
**riepilogo IVA**, le **scadenze**, i totali con bollo e ritenuta e le diciture previste (split payment, pro forma non
valida ai fini fiscali, fattura differita con i DDT). Le bozze, i documenti annullati e i dati dimostrativi portano
una scritta in evidenza. Il DDT ha in più il riquadro del trasporto e le firme:
Le **righe** hanno: articolo, descrizione, UM, quantità, prezzo, sconti (anche `5+2`), codice IVA, importo, deposito,
data di consegna. Le righe descrittive (solo testo) servono per riferimenti e note. Sotto la griglia: **castelletto
IVA** (imponibile e imposta per codice IVA, esigibilità), **scadenze** (rate con data, metodo e importo) e
**totali**.
![Khaemhat 0.5.0 · anteprima di stampa di un DDT](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/vendite-stampa-ddt.png)
Ogni PDF salvato diventa un **allegato versionato** (vedi [Allegati e file](Allegati-e-file)): nella scheda
*Allegati* si vedono tutte le versioni, con chi le ha create e quando. Il generatore si chiama *Stampa del documento
in PDF*.
## Invio per e-mail
![Khaemhat 0.5.0 · invio di una fattura per e-mail](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/vendite-email.png)
*Destinatario dall'anagrafica del cliente, oggetto e testo dal modello; il PDF parte in allegato.*
**⋯ → Invia per e-mail** (su un documento salvato) propone:
- **Destinatari**: l'e-mail del cliente; più indirizzi separati da virgola o punto e virgola.
- **Oggetto** e **Messaggio** dal modello, con i campi `{{Documento}}`, `{{Numero}}`, `{{Data}}`, `{{Cliente}}`,
`{{Azienda}}` e `{{Totale}}` già compilati. Puoi cambiare tutto prima di inviare.
**Invia** salva il PDF tra gli allegati come nuova versione, lo allega al messaggio, mette il messaggio **in coda** e
segna il documento come *inviato*. Il messaggio parte in background: tre tentativi a distanza crescente; l'esito (o
l'errore del server) è nel [Log](Log), sezione **E-mail/PEC**. La coda vive in memoria: un messaggio ancora in attesa
quando Khaemhat si ferma non parte, e il log lo dice.
L'invio richiede un **server SMTP** configurato dall'amministratore con le variabili `KHAEMHAT_SMTP_*` (vedi
[Impostazioni](Impostazioni#e-mail-smtp)); senza, la finestra lo segnala e il pulsante *Invia* è spento.
## Tipi di documento e codici TD
| Documento | Codice TD (SDI) | Note |
|---|---|---|
| Fattura immediata | **TD01** | emessa contestualmente alla cessione o prestazione |
| Fattura accompagnatoria | **TD01** | fattura con i dati di trasporto, fa anche da documento di trasporto e scarica il magazzino |
| Fattura accompagnatoria | **TD01** | fattura con i dati di trasporto, fa anche da documento di trasporto |
| Fattura di acconto/anticipo su fattura | **TD02** | |
| Fattura di acconto/anticipo su parcella | **TD03** | |
| Nota di credito | **TD04** | riferita alla fattura da stornare |
| Nota di debito | **TD05** | |
| Parcella | **TD06** | con ritenuta d'acconto e cassa previdenza |
| Fattura semplificata | **TD07** | per importi fino a 400 euro |
| Nota di credito semplificata | **TD08** | |
| Nota di debito semplificata | **TD09** | |
| Nota di credito / di debito semplificata | **TD08** / **TD09** | |
| Fattura differita (beni con DDT, servizi documentati) | **TD24** | art. 21, comma 4, lett. a) DPR 633/72 |
| Fattura differita (triangolazioni interne) | **TD25** | art. 21, comma 4, terzo periodo, lett. b) |
| Cessione di beni ammortizzabili e passaggi interni | **TD26** | anche dalle dismissioni dei cespiti |
| Cessione di beni ammortizzabili e passaggi interni | **TD26** | |
| Autoconsumo o cessioni gratuite senza rivalsa (omaggi) | **TD27** | |
| Pro-forma | — | non è un documento fiscale: niente numerazione fiscale né XML |
| Pro forma | — | non è un documento fiscale: niente numerazione fiscale né XML |
Le autofatture e le integrazioni (TD16-TD29) sono negli [Acquisti](Acquisti). L'elenco completo dei codici è in
[Fiscalità italiana](Fiscalita-italiana).
## Preventivi
![026 · Preventivo / offerta con revisioni](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/mockups/thumbs/026-preventivo-offerta.png)
*Mockup 026 — preventivo inviato, revisione 2 di 2, collegato a un'opportunità CRM; azioni Trasforma in ordine, Nuova revisione, Accettato, Rifiutato (anteprima ridotta).*
Il preventivo (offerta) ha una **validità** (es. 30 giorni, con data di scadenza) e uno stato (*Bozza*, *Inviato*,
*Accettato*, *Rifiutato*). Le schede sono *Righe*, *Testata*, *Totali*, *Condizioni e note*, *Revisioni*, *Allegati*,
*CRM*; sotto le righe il pannello **Revisioni** elenca le versioni con data, totale ed esito (*Superata*, *Inviata*).
1. Crea il preventivo, inserisci le righe e invialo per e-mail.
2. Se il cliente chiede modifiche usa **Nuova revisione**: la versione precedente resta consultabile come
*superata*.
3. Segna l'esito con **Accettato** o **Rifiutato**.
4. **Trasforma in ordine** crea l'ordine cliente con le stesse righe e collega i due documenti.
Con il modulo CRM il preventivo è collegato all'**opportunità** e ne aggiorna valore e fase (vedi [CRM](CRM)).
L'intestazione mostra anche il **margine** a chi può vedere i costi.
## Ordini clienti
![027 · Ordine cliente · evasione e residui](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/mockups/thumbs/027-ordine-cliente.png)
*Mockup 027 — ordine di una PA con split payment, evaso al 38%: righe con ordinato, evaso, residuo, disponibile e stato; documenti collegati (anteprima ridotta).*
Azioni contestuali: **Genera DDT**, **Genera fattura**, **Impegna**, **Ordina a fornitore**, **Chiudi residuo**.
- **Evasione**: la griglia *Righe e stato di evasione* mostra per ogni riga quantità ordinata, evasa, residua e
disponibile, con uno stato (*Evaso*, *Parziale*, *Impegnato*, *Da ordinare*, *Aperto*) e una barra di avanzamento.
Il pannello **Documenti collegati** elenca DDT e fatture già generati e gli ordini fornitore nati dall'ordine.
- **Impegnato**: un ordine confermato **impegna** la merce, che resta in giacenza ma non è più disponibile per altri.
- **Residui**: le quantità non evase restano aperte finché non vengono consegnate o chiuse con **Chiudi residuo**.
- **Ordina a fornitore**: per le righe non disponibili crea un ordine fornitore.
- **Fido e scaduto**: se il cliente supera il fido o ha pagamenti scaduti, la conferma è bloccata; chi ha il
permesso di forzatura può procedere indicando il motivo.
- **Dati PA**: per la pubblica amministrazione la scheda *Dati PA (CIG/CUP)* raccoglie CIG, CUP e riferimenti alla
determina, riportati poi nell'XML della fattura.
## DDT (documenti di trasporto)
![028 · DDT · dati di trasporto, colli, firme](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/mockups/thumbs/028-ddt-trasporto.png)
*Mockup 028 — DDT confermato e scaricato, da fatturare: scheda Trasporto con causale, vettore, porto, colli e pesi, firme (anteprima ridotta).*
Il DDT accompagna la merce e **scarica il magazzino** alla conferma. Azioni: **Stampa 3 copie**, **Fattura questo
DDT**, **Etichette colli**, **Riapri**.
| Gruppo (scheda Trasporto) | Campi |
|---|---|
| **Trasporto** | Causale del trasporto (vendita, reso, conto visione…), Trasporto a mezzo (mittente, destinatario, vettore), Vettore, Porto, resa (Incoterms), Inizio trasporto (data e ora), Targa, Annotazioni |
| **Colli e pesi** | Aspetto esteriore dei beni, Numero colli, Peso lordo, Peso netto, Volume, Pallet, Tracking |
| **Firme** | Conducente, Vettore, Destinatario (firme sulla stampa) |
Il DDT si stampa in **tre copie**. Un DDT confermato ha le righe non modificabili; **Riapri** (permesso
`sales.deliverynote.reopen`) storna lo scarico e lo rigenera alla nuova conferma. I **resi** da cliente si
registrano con un DDT con causale di reso, che ricarica il magazzino.
## Fatture
1. **Vendite → Fatture**, **Nuovo** (`Ctrl+N`) oppure parti da un ordine o da un DDT con **Evadi da…**.
2. Scegli il cliente (F4 per cercare): condizioni, listino, agente e destinazione vengono proposti.
3. Inserisci le righe: il prezzo segue l'ordine *netto cliente → listino cliente → listino base → prezzo articolo*
(vedi [Articoli e listini](Articoli-e-listini)).
4. Controlla castelletto IVA, scadenze e totali.
5. **Conferma ed emetti**: assegna il numero, blocca il documento, scarica il magazzino (accompagnatoria), genera
scadenze e registrazione contabile.
6. **XML SDI** genera il file FatturaPA, che si invia dal canale configurato (vedi
[Fatturazione elettronica](Fatturazione-elettronica)).
Una fattura **emessa non si modifica**. Per correggerla si emette una **nota di credito**; se l'XML non è ancora
stato inviato allo SDI si può **annullare** indicando il motivo.
## Note di credito (TD04)
![029 · Nota di credito TD04](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/mockups/thumbs/029-nota-di-credito.png)
*Mockup 029 — nota di credito che storna una riga della fattura per reso merce difettosa, con rientro a magazzino e compensazione della partita (anteprima ridotta).*
La nota di credito indica la **fattura stornata**, il **motivo** e la causale (ad esempio *reso da cliente*); se
c'è un reso la merce **rientra a magazzino**. Il pannello **Partite** mostra l'effetto sulla partita della fattura
(ad esempio *chiude parzialmente la rata 1/1*). L'XML è di tipo TD04 e riporta il riferimento alla fattura
d'origine. La nota di debito (TD05) funziona allo stesso modo per gli addebiti integrativi.
## Pro-forma
Documento **non fiscale** (ad esempio per chiedere un anticipo): stessa maschera della fattura, senza numerazione
fiscale, senza XML e senza registrazione contabile. Si trasforma in fattura quando serve.
## Parcelle (TD06)
Per le aziende o gli studi che emettono parcelle: la parcella calcola la **cassa previdenza** (contributo
integrativo, con IVA propria) e la **ritenuta d'acconto** che il cliente tratterrà, e mostra il **netto a pagare**.
Gli acconti su parcella usano TD03.
## Fatturazione differita guidata
![030 · Fatturazione differita · procedura guidata](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/mockups/thumbs/030-fatturazione-differita.png)
*Mockup 030 — procedura in quattro passi: parametri, selezione dei DDT non fatturati nel periodo, anteprima delle fatture, generazione (anteprima ridotta).*
1. **Parametri**: DDT dal… al…, **data fattura**, **sezionale**, tipo (*Fattura differita TD24*), **raggruppa**
(*per cliente, rispettando la preferenza* di raggruppamento del cliente), *Genera XML SDI*, *Invia e-mail al
cliente*.
2. **Selezione DDT**: elenco dei DDT non fatturati nel periodo con la fattura che verrà generata; togli la spunta
ai DDT da escludere.
3. **Anteprima fatture**: numero di fatture e totale.
4. **Generazione**: numera le fatture, le contabilizza e, se richiesto, genera l'XML. I riferimenti ai DDT sono
riportati in riga e nell'XML (*DatiDDT*).
La fattura differita va emessa entro il giorno 15 del mese successivo a quello delle consegne. La stessa procedura
è eseguibile da attività programmata (vedi [Automazioni](Automazioni)).
[Fiscalità italiana](Fiscalita-italiana). I tipi, i numeratori e i sezionali si configurano in *Tipi documento* (vedi
[Tabelle azienda](Tabelle-azienda)).
## Stati
| Documenti (preventivi, ordini, DDT) | Significato |
| Preventivi, ordini, DDT, pro forma | Significato |
|---|---|
| **Bozza** | modificabile, senza numero definitivo, nessun effetto |
| **Confermato** | numerato, effetti applicati (impegno, scarico) |
| **Evaso parzialmente** / **Evaso** | una parte o tutto è passato al documento successivo |
| **Chiuso** | concluso (anche con residuo chiuso a mano) |
| **Annullato** | annullato con motivo |
| **Bozza** | modificabile, senza numero, nessun effetto |
| **Confermato** | numerato; le righe si possono ancora cambiare finché non sono evase |
| **Evaso in parte** / **Evaso** | una parte o tutto è passato al documento successivo |
| **Chiuso** | concluso, anche con residuo chiuso a mano (o preventivo rifiutato) |
| **Annullato** | annullato con motivo; il numero resta usato |
| Fatture e note | Significato |
|---|---|
| **Bozza** | modificabile |
| **Emessa** | numerata, contabilizzata, immutabile |
| **XML generato** | file FatturaPA pronto |
| **Inviata allo SDI** | in attesa di esito |
| **Consegnata** | recapitata al cliente |
| **Scartata** | rifiutata dallo SDI: va corretta e rigenerata |
| **Non consegnata** | impossibile recapitarla: è disponibile nell'area riservata del cliente |
| **Emessa** | numerata e immutabile |
| **XML generato**, **Inviata allo SdI**, **Consegnata**, **Scartata**, **Non consegnata** | gli stati della fatturazione elettronica (M9) |
Altri badge indicano lo stato contabile (*Non contabilizzata*), del magazzino (*Scaricato*) o della fatturazione
(*Da fatturare*).
Che cosa si può fare:
- Si **modifica** una bozza; di ordini, preventivi, DDT e pro forma confermati si possono ancora cambiare le righe
finché non sono evasi del tutto, ma una quantità non scende sotto quella già evasa e una riga evasa non si toglie.
- Si **elimina** solo una bozza, che non ha mai avuto un numero.
- Si **annulla** un documento confermato non ancora evaso: il numero resta e le quantità che aveva evaso tornano ai
documenti d'origine. Una fattura si annulla **con un motivo** finché il file non è stato inviato allo SDI; dopo, si
fa una nota di credito.
- Si **chiude** il residuo di un documento evaso in parte; **Riapri** lo riporta allo stato che dicono le sue righe.
- Si **duplica** o si **crea** un altro documento da uno in qualunque stato.
## Numerazione
- Formato `{prefisso}/{anno}/{numero a 6 cifre}`, ad esempio `FT/2026/000418`, per **sezionale** (FT, NC, DDT…) e
anno, configurato nei numeratori (vedi [Tabelle azienda](Tabelle-azienda)).
- Il numero è assegnato **alla conferma**, in modo atomico: le bozze non consumano numeri.
- Per fatture e note di credito **non sono ammessi buchi** e la data non può essere anteriore a quella dell'ultimo
documento numerato nello stesso sezionale.
- La data deve cadere in un **periodo fiscale aperto** (vedi esercizi e periodi in [Tabelle azienda](Tabelle-azienda)).
- Il formato è quello del numeratore del tipo documento, per **sezionale** e anno: ad esempio `{number}/{year}` per
fatture, note e DDT (`7/2026`), `OC-{year}-{number:D4}` per gli ordini (`OC-2026-0004`), `PRE-{year}-{number:D4}`
per i preventivi.
- Il numero è assegnato **alla conferma**, in modo atomico: le bozze non consumano numeri, due conferme contemporanee
non ricevono mai lo stesso numero e una conferma non riuscita restituisce il numero. Fatture, note di credito e note
di debito condividono il numeratore delle fatture.
- Per fatture e note **non sono ammessi buchi** e la data non può essere anteriore a quella dell'ultimo documento
numerato nello stesso numeratore.
- La data deve cadere in un **esercizio aperto** (vedi [Tabelle azienda](Tabelle-azienda)); con il primo documento
di un anno nuovo la numerazione riparte da 1.
## Calcolo dei totali
| Elemento | Regola |
|---|---|
| **Imponibile di riga** | quantità x prezzo x (1 - sconto 1) x (1 - sconto 2)…, arrotondato a 2 decimali (arrotondamento commerciale) |
| **Imponibile di riga** | quantità × prezzo × (1 − sconto 1) × (1 − sconto 2)…, arrotondato a 2 decimali (arrotondamento commerciale) |
| **Castelletto IVA** | imponibili raggruppati per codice IVA; imposta calcolata per aliquota sul totale del gruppo |
| **Spese** | trasporto, incasso ecc. con il proprio codice IVA |
| **Sconto piede** | ripartito sulle righe |
| **Bollo** | 2,00 euro automatici se le operazioni esenti, non imponibili o fuori campo IVA superano 77,47 euro; la scheda del cliente indica se è a carico del cliente |
| **Sconto di piede** | ripartito sulle righe |
| **Bollo** | 2,00 euro automatici se le operazioni esenti, non imponibili o fuori campo IVA superano 77,47 euro; la scheda del cliente indica se è a suo carico |
| **Ritenuta d'acconto** | sulle parcelle, calcolata sull'imponibile previsto; il netto a pagare la esclude |
| **Cassa previdenza** | contributo sulle parcelle, con IVA propria |
| **Split payment** | per PA e soggetti obbligati: l'IVA è esposta ma versata dal cliente all'Erario; il totale *da versare* è il solo imponibile (esigibilità **S**) |
| **Split payment** | per PA e soggetti obbligati: l'IVA è esposta ma versata dal cliente all'Erario (esigibilità **S**) |
| **Reverse charge** | fattura senza IVA con natura N6.x: l'imposta la integra il cliente |
| **IVA per cassa** | esigibilità differita al pagamento per chi ha aderito al regime (gestione completa prevista in fase 2) |
**Scadenze**: generate dalla condizione di pagamento (rate, giorni, fine mese, giorno fisso, percentuali, IVA sulla
prima rata, sconto cassa); l'eventuale differenza di arrotondamento va sull'ultima rata.
## Stampa, PDF ed e-mail
![025 · Anteprima di stampa / PDF](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/mockups/thumbs/025-anteprima-stampa-pdf.png)
*Mockup 025 — anteprima di stampa della fattura: modello, copie, lingua, zoom (anteprima ridotta).*
`Ctrl+P` apre l'**anteprima di stampa** in una nuova scheda: si scelgono **modello**, numero di **copie** e
**lingua**, si ingrandisce (50%, 100%, adatta) e si stampa, si scarica il PDF o lo si invia. La stampa contiene le
diciture di legge previste ed è sempre in tema chiaro. Ogni PDF generato diventa un **allegato versionato** del
documento (vedi [Allegati e file](Allegati-e-file)).
L'invio per **e-mail o PEC** allega il PDF (e, se richiesto, l'XML o la copia di cortesia ZIP) usando i modelli
e-mail dell'azienda; il canale preferito è nelle condizioni del cliente.
## Collegamenti, duplicazione e corrispettivi
- **Collegamenti**: la scheda omonima mostra i documenti di origine e quelli generati (ordine → DDT → fattura) con
le quantità; l'icona *Collegamenti* della toolbar apre lo stesso elenco.
- **Duplica** crea un nuovo documento in bozza con le stesse righe; la **trasformazione** cambia tipo mantenendo i
collegamenti (preventivo → ordine).
- **Corrispettivi**: le vendite al dettaglio si registrano a mano come corrispettivi giornalieri.
## Report
Giornale vendite, fatturato per cliente, agente, categoria e articolo (vedi [Report](Report)), DDT da fatturare,
ordini aperti, provvigioni agenti, margini (con il modulo REPORT).
prima rata); l'eventuale differenza di arrotondamento va sull'ultima rata.
## Permessi e licenza
Le vendite sono nel modulo **CORE**. Emettere una fattura richiede `sales.invoice.issue`; riaprire un DDT
`sales.deliverynote.reopen`; forzare un blocco di fido un permesso di tipo `override`. La generazione e l'invio
dell'XML richiedono **EINV**, la registrazione contabile **ACCT**, partite e incassi **FIN**.
Le vendite sono nel modulo **CORE**. Ogni famiglia ha due permessi, lettura (`.read`) e scrittura (`.write`):
`sales.quote`, `sales.order`, `sales.delivery`, `sales.invoice` (fatture, note e pro forma). La scrittura vale per
creare, modificare, confermare, chiudere, riaprire e annullare; per le fatture e le note **emettere** e annullare
richiede in più `sales.invoice.issue` ed eliminare una bozza `sales.invoice.delete`. Stampare richiede la sola
lettura. Vedi [Utenti e permessi](Utenti-e-permessi).
## Domande frequenti
- **Non riesco a confermare la fattura: "data anteriore all'ultima numerata".** Nello stesso sezionale esiste una
fattura con data successiva: correggi la data o usa un altro sezionale.
- **Il bollo non viene calcolato.** Il bollo è automatico solo se la parte esente, non imponibile o fuori campo
supera 77,47 euro; controlla i codici IVA delle righe.
- **Devo correggere una fattura già inviata.** Emetti una nota di credito (TD04) e una nuova fattura.
- **"Indica il codice IVA" su una riga.** Fatture e note si emettono solo con il codice IVA su ogni riga di merce,
spesa o sconto: sceglilo nella riga o nella scheda dell'articolo.
- **Il bollo non viene calcolato.** È automatico solo se la parte esente, non imponibile o fuori campo supera 77,47
euro; controlla i codici IVA delle righe.
- **Un DDT non compare nella fatturazione differita.** Deve essere *Confermato*, non già fatturato e con data nel
periodo; se hai indicato un cliente, deve essere suo.
- **"Invia per e-mail" è spento.** Il documento ha modifiche non salvate: salvalo. Se la finestra dice che manca il
server SMTP, chiedi all'amministratore di configurarlo.
- **Ho inviato l'e-mail ma il cliente non l'ha ricevuta.** Guarda il [Log](Log), sezione *E-mail/PEC*: c'è la
risposta del server per ogni tentativo.
- **Devo correggere una fattura già inviata allo SDI.** Emetti una nota di credito (TD04) e una nuova fattura.
## Pagine correlate
[Anagrafiche](Anagrafiche) · [Articoli e listini](Articoli-e-listini) · [Magazzino](Magazzino) ·
[Allegati e file](Allegati-e-file) · [Fatturazione elettronica](Fatturazione-elettronica) ·
[Contabilità](Contabilita) · [Scadenzario](Scadenzario) · [CRM](CRM) · [Fiscalità italiana](Fiscalita-italiana)
[Anagrafiche](Anagrafiche) · [Articoli e listini](Articoli-e-listini) · [Tabelle azienda](Tabelle-azienda) ·
[Allegati e file](Allegati-e-file) · [Log](Log) · [Magazzino](Magazzino) ·
[Fatturazione elettronica](Fatturazione-elettronica) · [Contabilità](Contabilita) · [Scadenzario](Scadenzario) ·
[Fiscalità italiana](Fiscalita-italiana)
+3
View File
@@ -1,5 +1,8 @@
**[Khaemhat](Home)**
**Guida**
- [Guida all'uso](Guida-utente)
**Installazione**
- [Primi passi](Primi-passi)
- [Unraid](Installazione-Unraid)
Binary file not shown.

After

Width:  |  Height:  |  Size: 188 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 182 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 74 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 113 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 121 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 69 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 119 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 177 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 178 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 199 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 166 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 220 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 90 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 99 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 145 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 118 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 102 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 92 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 99 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 105 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 109 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 87 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 115 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 124 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 121 KiB

+6 -2
View File
@@ -3,7 +3,8 @@
# Any KHAEMHAT_* variable already set in the shell wins over the defaults below.
set -euo pipefail
root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
# Under Git Bash on Windows, pwd -W gives B:/... instead of /b/..., which .NET would read as a folder b on the drive.
root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && (pwd -W 2>/dev/null || pwd))"
cd "$root"
data_dir="$root/.data/dev"
@@ -11,7 +12,10 @@ mkdir -p "$data_dir"
export ASPNETCORE_ENVIRONMENT="${ASPNETCORE_ENVIRONMENT:-Development}"
export KHAEMHAT_DATA_DIR="${KHAEMHAT_DATA_DIR:-$data_dir}"
export KHAEMHAT_SYSTEM_DB="${KHAEMHAT_SYSTEM_DB:-sqlite://$data_dir/system.db}"
# sqlite:///home/... on Linux and macOS, sqlite:///B:/... on Windows.
db_path="$data_dir"
[[ "$db_path" == /* ]] || db_path="/$db_path"
export KHAEMHAT_SYSTEM_DB="${KHAEMHAT_SYSTEM_DB:-sqlite://$db_path/system.db}"
# Development-only key: never use it outside this script.
export KHAEMHAT_SECRET_KEY="${KHAEMHAT_SECRET_KEY:-a2hhZW1oYXQtZGV2ZWxvcG1lbnQtb25seS1ub3QtYS1zZWNyZXQ=}"
export KHAEMHAT_SUPERUSER="${KHAEMHAT_SUPERUSER:-root}"
@@ -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),
@@ -0,0 +1,201 @@
using Khaemhat.Core.Documents;
using Khaemhat.Core.Parties;
using Khaemhat.Core.Tables;
using Khaemhat.Data;
using Khaemhat.Data.Querying;
using Khaemhat.Fiscal.Abstractions;
namespace Khaemhat.Application.Documents;
/// <summary>The totals of a stored document: its tax summary and installments, as written by the last save.</summary>
/// <param name="Summary">The tax summary.</param>
/// <param name="Installments">The installments.</param>
public sealed record DocumentFigures(IReadOnlyList<DocumentTaxSummary> Summary, IReadOnlyList<DocumentInstallment> Installments)
{
/// <summary>No figures.</summary>
public static DocumentFigures Empty { get; } = new([], []);
}
/// <summary>
/// Applies <see cref="DocumentTotalsCalculator"/> and <see cref="InstallmentGenerator"/> to a document being saved:
/// writes the line amounts and header totals, then replaces its tax summary and installments (issue #48).
/// </summary>
internal static class DocumentCalculation
{
/// <summary>Computes the totals of a document in place.</summary>
/// <param name="uow">The unit of work.</param>
/// <param name="engine">The country's tax engine.</param>
/// <param name="behavior">The behaviour of the document.</param>
/// <param name="record">The document.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The tax summary and installments to write once the document has its id.</returns>
public static async Task<DocumentFigures> ApplyAsync(IUnitOfWork uow, ITaxEngine engine, DocumentBehavior behavior, DocumentRecord record, CancellationToken cancellationToken)
{
var header = record.Header;
var taxCodes = await TaxCodesAsync(uow, record, cancellationToken).ConfigureAwait(false);
var options = new TotalsOptions
{
PricesIncludeTax = header.PricesIncludeTax,
FooterDiscount = header.FooterDiscount,
Exigibility = header.Exigibility,
SplitPayment = header.SplitPayment,
StampDutyApplies = behavior.Direction == DocumentDirection.Sale && behavior.Has(DocumentEffects.EInvoice),
StampDutyCharged = header.StampDutyCharged,
WithholdingRate = header.WithholdingRate,
WithholdingBasePercent = header.WithholdingBasePercent <= 0m ? 100m : header.WithholdingBasePercent,
SocialSecurityRate = header.SocialSecurityRate,
SocialSecurityTax = header.SocialSecurityTaxCodeId is { } id && taxCodes.TryGetValue(id, out var own) ? own : null,
SocialSecurityWithheld = header.SocialSecurityWithheld,
EnasarcoRate = header.EnasarcoRate,
};
var lines = record.Lines
.Select(l => new TotalsLine(l.Kind, l.Quantity, l.Price, l.DiscountFormula,
l.TaxCodeId is { } t && taxCodes.TryGetValue(t, out var tax) ? tax : null, l.WithholdingExcluded))
.ToList();
var totals = DocumentTotalsCalculator.Compute(lines, options, engine);
for (var i = 0; i < record.Lines.Count; i++)
{
record.Lines[i].TaxableAmount = totals.LineAmounts[i];
}
header.TaxableAmount = totals.Taxable;
header.TaxAmount = totals.Tax;
header.TotalAmount = totals.Total;
header.ExpensesAmount = totals.Expenses;
header.FooterDiscountAmount = totals.FooterDiscountAmount;
header.StampDuty = totals.StampDuty;
header.WithholdingAmount = totals.Withholding;
header.SocialSecurityAmount = totals.SocialSecurity;
header.EnasarcoAmount = totals.Enasarco;
header.NetAmount = totals.Net;
var summary = totals.Summary.Select(s => new DocumentTaxSummary
{
Family = record.Family,
TaxCodeId = s.Tax.TaxCodeId,
Rate = s.Tax.Rate,
Nature = s.Tax.Nature,
Exigibility = s.Tax.Exigibility,
NonDeductiblePercent = s.Tax.NonDeductiblePercent,
LegalReference = s.Tax.LegalReference,
Taxable = s.Taxable,
Tax = s.TaxAmount,
NonDeductibleTax = s.NonDeductibleTax,
}).ToList();
var installments = new List<DocumentInstallment>();
if (behavior.Has(DocumentEffects.Installments) || behavior.Kind is DocumentKind.ProForma or DocumentKind.SalesOrder or DocumentKind.Quotation)
{
installments = await InstallmentsAsync(uow, engine, behavior, record, totals, cancellationToken).ConfigureAwait(false);
}
return new DocumentFigures(summary, installments);
}
/// <summary>Replaces the tax summary and installments of a document.</summary>
/// <param name="uow">The unit of work.</param>
/// <param name="family">The family.</param>
/// <param name="documentId">The document.</param>
/// <param name="figures">The new rows.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
public static async Task WriteAsync(IUnitOfWork uow, DocumentFamily family, long documentId, DocumentFigures figures, CancellationToken cancellationToken)
{
var summaries = uow.Repository<DocumentTaxSummary, long>();
var installments = uow.Repository<DocumentInstallment, long>();
var where = SqlFragment.Of($"family = {family.ToString()} AND document_id = {documentId}");
foreach (var old in (await summaries.ListAsync(Query.For<DocumentTaxSummary>().Where(where), cancellationToken).ConfigureAwait(false)).Items)
{
await summaries.DeleteAsync(old.Id, cancellationToken).ConfigureAwait(false);
}
foreach (var old in (await installments.ListAsync(Query.For<DocumentInstallment>().Where(where), cancellationToken).ConfigureAwait(false)).Items)
{
await installments.DeleteAsync(old.Id, cancellationToken).ConfigureAwait(false);
}
foreach (var row in figures.Summary)
{
row.Id = 0;
row.Family = family;
row.DocumentId = documentId;
await summaries.InsertAsync(row, cancellationToken).ConfigureAwait(false);
}
foreach (var row in figures.Installments)
{
row.Id = 0;
row.Family = family;
row.DocumentId = documentId;
await installments.InsertAsync(row, cancellationToken).ConfigureAwait(false);
}
}
/// <summary>Reads the tax summary and installments of a document.</summary>
/// <param name="uow">The unit of work.</param>
/// <param name="family">The family.</param>
/// <param name="documentId">The document.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The rows.</returns>
public static async Task<DocumentFigures> ReadAsync(IUnitOfWork uow, DocumentFamily family, long documentId, CancellationToken cancellationToken)
{
var where = SqlFragment.Of($"family = {family.ToString()} AND document_id = {documentId}");
var summary = await uow.Repository<DocumentTaxSummary, long>()
.ListAsync(Query.For<DocumentTaxSummary>().Where(where).OrderByDescending(s => s.Rate), cancellationToken).ConfigureAwait(false);
var installments = await uow.Repository<DocumentInstallment, long>()
.ListAsync(Query.For<DocumentInstallment>().Where(where).OrderBy(s => s.Number), cancellationToken).ConfigureAwait(false);
return new DocumentFigures(summary.Items, installments.Items);
}
private static async Task<Dictionary<long, TotalsTax>> TaxCodesAsync(IUnitOfWork uow, DocumentRecord record, CancellationToken cancellationToken)
{
var ids = record.Lines.Where(l => l.TaxCodeId is not null).Select(l => l.TaxCodeId!.Value).ToHashSet();
if (record.Header.SocialSecurityTaxCodeId is { } own)
{
ids.Add(own);
}
if (ids.Count == 0)
{
return [];
}
var list = ids.ToList();
var codes = await uow.Repository<TaxCode, long>().ListAsync(Query.For<TaxCode>().Where(c => list.Contains(c.Id)), cancellationToken).ConfigureAwait(false);
return codes.Items.ToDictionary(c => c.Id, c => new TotalsTax(c.Id, c.Rate, string.IsNullOrWhiteSpace(c.Nature) ? null : c.Nature,
c.Exigibility, c.NonDeductiblePercent, c.LegalReference));
}
private static async Task<List<DocumentInstallment>> InstallmentsAsync(
IUnitOfWork uow, ITaxEngine engine, DocumentBehavior behavior, DocumentRecord record, DocumentTotals totals, CancellationToken cancellationToken)
{
var header = record.Header;
PaymentTerm? term = null;
IReadOnlyList<PaymentTermLine> termLines = [];
if (header.PaymentTermId is { } termId)
{
term = await uow.Repository<PaymentTerm, long>().GetAsync(termId, cancellationToken).ConfigureAwait(false);
termLines = (await uow.Repository<PaymentTermLine, long>()
.ListAsync(Query.For<PaymentTermLine>().Where(l => l.PaymentTermId == termId).OrderBy(l => l.Number), cancellationToken).ConfigureAwait(false)).Items;
}
ExcludedMonths? excluded = null;
if (behavior.Direction == DocumentDirection.Sale && header.PartyId is { } partyId)
{
var terms = await uow.Repository<PartySalesTerms, long>()
.FindAsync(Query.For<PartySalesTerms>().Where(t => t.PartyId == partyId), cancellationToken).ConfigureAwait(false);
if (terms is { } t && (t.ExcludedMonth1 is not null || t.ExcludedMonth2 is not null))
{
excluded = new ExcludedMonths(t.ExcludedMonth1, t.ExcludedMonth2, t.ExcludedMonthsDay ?? 10);
}
}
var paidTax = totals.Tax - totals.SplitPaymentTax;
var dues = InstallmentGenerator.Generate(
header.DocumentDate, totals.Net, paidTax,
[.. termLines.Select(l => new InstallmentRule(l.Days, l.EndOfMonth, l.FixedDay, l.Percent))],
term?.VatOnFirstInstallment ?? false, excluded, engine.Round);
var method = header.PaymentMethodId ?? term?.PaymentMethodId;
return [.. dues.Select(d => new DocumentInstallment { Number = d.Number, DueDate = d.DueDate, Amount = d.Amount, PaymentMethodId = method })];
}
}
@@ -0,0 +1,257 @@
using System.Globalization;
using Khaemhat.Application.Security;
using Khaemhat.Core.Documents;
using Khaemhat.Data;
namespace Khaemhat.Application.Documents;
/// <summary>
/// Makes a new draft from an existing document (SPEC §11.3, ADR 0032): a duplicate of the same type, or a
/// transformation to another type of the same direction. When the new kind fulfils the old one (order to delivery note,
/// delivery note to deferred invoice) the lines take what is left to fulfil and remember where they come from; the
/// link is recorded when the new document is confirmed.
/// </summary>
public sealed class DocumentCopyService
{
private readonly DocumentEngine _engine;
private readonly PermissionService _permissions;
private readonly TimeProvider _clock;
/// <summary>Creates the service.</summary>
/// <param name="engine">The engine.</param>
/// <param name="permissions">The permissions.</param>
/// <param name="clock">The clock.</param>
public DocumentCopyService(DocumentEngine engine, PermissionService permissions, TimeProvider clock)
{
ArgumentNullException.ThrowIfNull(engine);
ArgumentNullException.ThrowIfNull(permissions);
ArgumentNullException.ThrowIfNull(clock);
_engine = engine;
_permissions = permissions;
_clock = clock;
}
/// <summary>Copies a document into a new draft and saves it.</summary>
/// <param name="actor">Who copies.</param>
/// <param name="companyCode">The company.</param>
/// <param name="family">The family of the source.</param>
/// <param name="id">The source.</param>
/// <param name="targetTypeCode">The type of the new document, such as <c>DDT</c>.</param>
/// <param name="lineIds">The lines to copy; all when empty.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The new draft.</returns>
/// <exception cref="ValidationFailedException">The copy is not possible.</exception>
public Task<DocumentRecord> CopyAsync(
Actor actor, string companyCode, DocumentFamily family, long id, string targetTypeCode, IReadOnlyCollection<long>? lineIds = null,
CancellationToken cancellationToken = default) =>
MergeAsync(actor, companyCode, family, [id], targetTypeCode, null, lineIds, cancellationToken);
/// <summary>
/// Copies several documents of the same party into one new draft and saves it (deferred invoice from delivery
/// notes, delivery note from several orders): the header comes from the first, each source adds a reference line
/// and its lines.
/// </summary>
/// <param name="actor">Who copies.</param>
/// <param name="companyCode">The company.</param>
/// <param name="family">The family of the sources.</param>
/// <param name="ids">The sources, in order.</param>
/// <param name="targetTypeCode">The type of the new document.</param>
/// <param name="date">The date of the new document; today when empty.</param>
/// <param name="lineIds">The lines to copy; all when empty.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The new draft.</returns>
/// <exception cref="ValidationFailedException">The copy is not possible.</exception>
public async Task<DocumentRecord> MergeAsync(
Actor actor, string companyCode, DocumentFamily family, IReadOnlyList<long> ids, string targetTypeCode, DateOnly? date = null,
IReadOnlyCollection<long>? lineIds = null, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(actor);
ArgumentNullException.ThrowIfNull(ids);
if (ids.Count == 0)
{
throw new ValidationFailedException([":" + DocumentErrors.CopyNothingLeft]);
}
var sources = new List<DocumentRecord>();
foreach (var id in ids)
{
sources.Add(await _engine.GetAsync(actor, companyCode, family, id, cancellationToken).ConfigureAwait(false)
?? throw new KeyNotFoundException(DocumentErrors.NotFound));
}
var company = CompanyCodes.Normalize(companyCode);
DocumentDefinition target;
await using (var uow = await _engine.Factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false))
{
target = await DocumentDefinitionService.GetAsync(uow, targetTypeCode, cancellationToken).ConfigureAwait(false);
}
await _permissions.DemandAsync(actor, target.Behavior.WritePermission, cancellationToken).ConfigureAwait(false);
if (sources.Select(s => s.Header.PartyId).Distinct().Count() > 1)
{
throw new ValidationFailedException([":" + DocumentErrors.CopyParties]);
}
var copy = new DocumentRecord
{
Family = target.Family,
Header = Header(sources[0], target, date ?? DateOnly.FromDateTime(_clock.GetLocalNow().DateTime)),
};
var wanted = lineIds is { Count: > 0 } ? lineIds.ToHashSet() : null;
var anyFulfils = false;
foreach (var source in sources)
{
var sourceBehavior = DocumentBehaviors.Of(source.Header.Kind);
DocumentStateMachine.Apply(sourceBehavior.Lifecycle, source.Header.Status, DocumentAction.Copy);
if (sourceBehavior.Direction != target.Behavior.Direction)
{
throw new ValidationFailedException([nameof(DocumentHeader.DocumentTypeId) + ":" + DocumentErrors.CopyDirection]);
}
var fulfils = target.Behavior.Fulfils(source.Header.Kind);
anyFulfils |= fulfils;
if (fulfils && (source.Header.Status is DocumentStatus.Draft or DocumentStatus.Closed or DocumentStatus.Cancelled))
{
throw new ValidationFailedException([":" + DocumentErrors.CopySourceNotOpen]);
}
var lines = new List<DocumentLine>();
foreach (var line in source.Lines.Where(l => wanted is null || wanted.Contains(l.Id)))
{
if (!target.Behavior.Lines.Contains(line.Kind))
{
continue;
}
var quantity = line.Quantity;
if (fulfils && DocumentLine.CarriesQuantity(line.Kind))
{
quantity = line.Residual;
if (quantity <= 0)
{
continue;
}
}
lines.Add(Line(line, target.Family, quantity, fulfils ? source.Family : null));
}
if (sources.Count > 1 && lines.Count > 0 && source.Header.DocumentNumber is { } number
&& target.Behavior.Lines.Contains(DocumentLineKind.Description))
{
var reference = DocumentStores.Of(target.Family).NewLine();
reference.Kind = DocumentLineKind.Description;
reference.Description = ReferenceLabel(source.Header.Kind) + " " + number + " del "
+ source.Header.DocumentDate.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture);
copy.Lines.Add(reference);
}
copy.Lines.AddRange(lines);
}
if (anyFulfils && !copy.Lines.Any(l => l.SourceLineId is not null))
{
throw new ValidationFailedException([":" + DocumentErrors.CopyNothingLeft]);
}
return await _engine.SaveAsync(actor, company, copy, cancellationToken).ConfigureAwait(false);
}
// The reference printed before the lines of each source (the documents are written in Italian).
private static string ReferenceLabel(DocumentKind kind) => kind switch
{
DocumentKind.DeliveryNote or DocumentKind.PurchaseDeliveryNote => "Rif. DDT n.",
DocumentKind.SalesOrder or DocumentKind.PurchaseOrder => "Rif. ordine n.",
DocumentKind.Quotation => "Rif. preventivo n.",
_ => "Rif. documento n.",
};
private static DocumentHeader Header(DocumentRecord record, DocumentDefinition target, DateOnly today)
{
var source = record.Header;
var header = DocumentStores.Of(target.Family).NewHeader();
header.DocumentTypeId = target.Type.Id;
header.Kind = target.Kind;
header.Status = DocumentStatus.Draft;
header.IsDemo = source.IsDemo;
header.DocumentDate = today;
header.Year = today.Year;
header.PartyId = source.PartyId;
header.DestinationId = source.DestinationId;
header.CurrencyCode = source.CurrencyCode;
header.ExchangeRate = source.ExchangeRate;
header.PriceListId = source.PriceListId;
header.PaymentTermId = source.PaymentTermId;
header.PaymentMethodId = source.PaymentMethodId;
header.BankAccountId = source.BankAccountId;
header.SalespersonId = source.SalespersonId;
header.WarehouseId = source.WarehouseId;
header.InventoryReasonId = target.Type.InventoryReasonId ?? source.InventoryReasonId;
header.TransportReasonId = source.TransportReasonId;
header.ShippingTermId = source.ShippingTermId;
header.CarrierId = source.CarrierId;
header.GoodsAppearanceId = source.GoodsAppearanceId;
header.DeliveryDate = source.DeliveryDate;
header.FooterDiscount = source.FooterDiscount;
header.Notes = source.Notes;
header.ExternalReference = source.ExternalReference;
header.ExternalDate = source.ExternalDate;
header.PricesIncludeTax = source.PricesIncludeTax;
header.Exigibility = source.Exigibility;
header.SplitPayment = source.SplitPayment;
header.StampDutyCharged = source.StampDutyCharged;
header.WithholdingRate = source.WithholdingRate;
header.WithholdingBasePercent = source.WithholdingBasePercent;
header.WithholdingType = source.WithholdingType;
header.WithholdingReason = source.WithholdingReason;
header.SocialSecurityFund = source.SocialSecurityFund;
header.SocialSecurityRate = source.SocialSecurityRate;
header.SocialSecurityTaxCodeId = source.SocialSecurityTaxCodeId;
header.SocialSecurityWithheld = source.SocialSecurityWithheld;
header.EnasarcoRate = source.EnasarcoRate;
header.Cig = source.Cig;
header.Cup = source.Cup;
header.TransportBy = source.TransportBy;
if (target.Kind is DocumentKind.CreditNote or DocumentKind.DebitNote or DocumentKind.PurchaseCreditNote
&& DocumentBehaviors.Of(source.Kind).Lifecycle != DocumentLifecycle.Order && record.Family == target.Family)
{
// A note refers to the invoice it corrects (DatiFattureCollegate).
header.RelatedDocumentId = source.Id;
header.RelatedNumber = source.DocumentNumber;
header.RelatedDate = source.DocumentDate;
}
return header;
}
private static DocumentLine Line(DocumentLine source, DocumentFamily family, decimal quantity, DocumentFamily? sourceFamily)
{
var line = DocumentStores.Of(family).NewLine();
line.Kind = source.Kind;
line.ItemId = source.ItemId;
line.Description = source.Description;
line.UnitOfMeasureId = source.UnitOfMeasureId;
line.Quantity = quantity;
line.Price = source.Price;
line.PriceSource = source.PriceSource;
line.DiscountFormula = source.DiscountFormula;
line.TaxCodeId = source.TaxCodeId;
line.TaxableAmount = source.Quantity == 0 || quantity == source.Quantity
? source.TaxableAmount
: Math.Round(source.TaxableAmount * quantity / source.Quantity, 2, MidpointRounding.AwayFromZero);
line.WarehouseId = source.WarehouseId;
line.DeliveryDate = source.DeliveryDate;
line.AccountCode = source.AccountCode;
line.CostCenterId = source.CostCenterId;
line.JobId = source.JobId;
line.Notes = source.Notes;
line.WithholdingExcluded = source.WithholdingExcluded;
if (sourceFamily is not null && DocumentLine.CarriesQuantity(source.Kind))
{
line.SourceFamily = sourceFamily;
line.SourceLineId = source.Id;
}
return line;
}
}
@@ -0,0 +1,97 @@
using Khaemhat.Application.Security;
using Khaemhat.Core.Documents;
using Khaemhat.Core.Tables;
using Khaemhat.Data;
using Khaemhat.Data.Querying;
namespace Khaemhat.Application.Documents;
/// <summary>
/// A document type of the company with the behaviour of its kind (SPEC §11.3, ADR 0032): code, kind, direction,
/// numerator, warehouse reason, effects, sources for fulfilment, SDI type, journal template, VAT register, print
/// template.
/// </summary>
/// <param name="Type">The row of <c>document_types</c>.</param>
/// <param name="Behavior">The behaviour of its kind.</param>
public sealed record DocumentDefinition(DocumentType Type, DocumentBehavior Behavior)
{
/// <summary>The code of the type.</summary>
public string Code => Type.Code;
/// <summary>The kind.</summary>
public DocumentKind Kind => Behavior.Kind;
/// <summary>The family (tables).</summary>
public DocumentFamily Family => Behavior.Family;
/// <summary>The life cycle.</summary>
public DocumentLifecycle Lifecycle => Behavior.Lifecycle;
/// <summary>The action that confirms the documents: issue for invoices, confirm for the others.</summary>
public DocumentAction ConfirmAction => Lifecycle == DocumentLifecycle.Invoice ? DocumentAction.Issue : DocumentAction.Confirm;
}
/// <summary>Reads the definitions of the company's document types.</summary>
public static class DocumentDefinitionService
{
/// <summary>Error: the document type does not exist.</summary>
public const string TypeMissing = "document.type.missing";
/// <summary>Error: the document type has no kind.</summary>
public const string TypeWithoutKind = "document.type.no-kind";
/// <summary>Error: the document type is disabled.</summary>
public const string TypeDisabled = "document.type.disabled";
/// <summary>The definition of a document type.</summary>
/// <param name="uow">A company unit of work.</param>
/// <param name="typeId">The type.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The definition.</returns>
/// <exception cref="ValidationFailedException">The type is missing or has no kind.</exception>
public static async Task<DocumentDefinition> GetAsync(IUnitOfWork uow, long typeId, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(uow);
var type = await uow.Repository<DocumentType, long>().GetAsync(typeId, cancellationToken).ConfigureAwait(false)
?? throw new ValidationFailedException([nameof(DocumentHeader.DocumentTypeId) + ":" + TypeMissing]);
return Of(type);
}
/// <summary>The definition of a document type by code.</summary>
/// <param name="uow">A company unit of work.</param>
/// <param name="code">The code, such as <c>FI</c>.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The definition.</returns>
/// <exception cref="ValidationFailedException">The type is missing or has no kind.</exception>
public static async Task<DocumentDefinition> GetAsync(IUnitOfWork uow, string code, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(uow);
var normalized = (code ?? string.Empty).Trim().ToUpperInvariant();
var type = await uow.Repository<DocumentType, long>().FindAsync(Query.For<DocumentType>().Where(t => t.Code == normalized), cancellationToken).ConfigureAwait(false)
?? throw new ValidationFailedException([nameof(DocumentHeader.DocumentTypeId) + ":" + TypeMissing]);
return Of(type);
}
/// <summary>The definitions of every usable type (enabled, with a kind), by code.</summary>
/// <param name="uow">A company unit of work.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The definitions.</returns>
public static async Task<IReadOnlyList<DocumentDefinition>> ListAsync(IUnitOfWork uow, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(uow);
var types = await uow.Repository<DocumentType, long>().ListAsync(Query.For<DocumentType>().OrderBy(t => t.Code), cancellationToken).ConfigureAwait(false);
return [.. types.Items.Where(t => !t.Disabled && t.DocumentKind is not null).Select(Of)];
}
/// <summary>The definition of a type row.</summary>
/// <param name="type">The row.</param>
/// <returns>The definition.</returns>
/// <exception cref="ValidationFailedException">The type has no kind.</exception>
public static DocumentDefinition Of(DocumentType type)
{
ArgumentNullException.ThrowIfNull(type);
return type.DocumentKind is { } kind
? new DocumentDefinition(type, DocumentBehaviors.Of(kind))
: throw new ValidationFailedException([nameof(DocumentHeader.DocumentTypeId) + ":" + TypeWithoutKind]);
}
}
@@ -0,0 +1,445 @@
using Khaemhat.Application.Items;
using Khaemhat.Application.Querying;
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.Core.Tax;
using Khaemhat.Data;
using Khaemhat.Data.Querying;
namespace Khaemhat.Application.Documents;
/// <summary>A document in a radar.</summary>
/// <param name="Id">The document.</param>
/// <param name="Family">The family.</param>
/// <param name="Kind">The kind.</param>
/// <param name="TypeCode">The code of the document type.</param>
/// <param name="DocumentNumber">The number as printed; empty for drafts.</param>
/// <param name="Date">The date.</param>
/// <param name="PartyId">The party.</param>
/// <param name="PartyCode">The code of the party.</param>
/// <param name="PartyName">The name of the party.</param>
/// <param name="Status">The state.</param>
/// <param name="Taxable">The taxable amount.</param>
/// <param name="Total">The total.</param>
/// <param name="Net">The amount to pay.</param>
/// <param name="Reference">The reference of the other side.</param>
/// <param name="DeliveryDate">The delivery date.</param>
/// <param name="ValidUntil">Until when a quotation is valid.</param>
/// <param name="Revision">The revision of a quotation.</param>
/// <param name="IsDemo">Demo data.</param>
public sealed record DocumentRow(
long Id, DocumentFamily Family, DocumentKind Kind, string TypeCode, string? DocumentNumber, DateOnly Date, long? PartyId, string? PartyCode,
string? PartyName, DocumentStatus Status, decimal Taxable, decimal Total, decimal Net, string? Reference, DateOnly? DeliveryDate,
DateOnly? ValidUntil, int Revision, bool IsDemo);
/// <summary>A document linked to another one.</summary>
/// <param name="Family">The family.</param>
/// <param name="Id">The document.</param>
/// <param name="Kind">The kind.</param>
/// <param name="DocumentNumber">The number.</param>
/// <param name="Date">The date.</param>
/// <param name="Status">The state.</param>
/// <param name="Total">The total.</param>
/// <param name="Direction">Where it stands: before (source), after (fulfils it) or corrected (note).</param>
/// <param name="Quantity">The quantity fulfilled between the two.</param>
public sealed record LinkedDocument(
DocumentFamily Family, long Id, DocumentKind Kind, string? DocumentNumber, DateOnly Date, DocumentStatus Status, decimal Total,
LinkDirection Direction, decimal Quantity);
/// <summary>How a linked document relates to the one shown.</summary>
public enum LinkDirection
{
/// <summary>The document shown fulfils it (an order of a delivery note).</summary>
Source = 0,
/// <summary>It fulfils the document shown (a delivery note of an order).</summary>
Target = 1,
/// <summary>The invoice a note corrects, or a note that corrects the invoice shown.</summary>
Related = 2,
}
/// <summary>An open document with something left to fulfil, for the guided fulfilment and the deferred invoicing.</summary>
/// <param name="Row">The document.</param>
/// <param name="Lines">The lines with a residual.</param>
public sealed record OpenDocument(DocumentRow Row, IReadOnlyList<DocumentLine> Lines);
/// <summary>
/// What the document screens need besides the engine (SPEC §11.3-§11.4): radars, the values proposed by the party and
/// by the item, totals computed while editing, the documents linked and the open documents to fulfil.
/// </summary>
public sealed class DocumentEditor
{
private readonly IUnitOfWorkFactory _factory;
private readonly PermissionService _permissions;
private readonly CompanyFiscalContext _packs;
/// <summary>Creates the service.</summary>
/// <param name="factory">The units of work.</param>
/// <param name="permissions">The permissions.</param>
/// <param name="packs">The fiscal packs.</param>
public DocumentEditor(IUnitOfWorkFactory factory, PermissionService permissions, CompanyFiscalContext packs)
{
ArgumentNullException.ThrowIfNull(factory);
ArgumentNullException.ThrowIfNull(permissions);
ArgumentNullException.ThrowIfNull(packs);
_factory = factory;
_permissions = permissions;
_packs = packs;
}
/// <summary>A page of documents of some kinds of a family.</summary>
/// <param name="actor">Who reads.</param>
/// <param name="companyCode">The company.</param>
/// <param name="family">The family.</param>
/// <param name="kinds">The kinds; all of the family when empty.</param>
/// <param name="query">The request; the search also looks at the code and name of the party.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The page.</returns>
public async Task<ListPage<DocumentRow>> ListAsync(
Actor actor, string companyCode, DocumentFamily family, IReadOnlyCollection<DocumentKind> kinds, ListQuery query, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(kinds);
ArgumentNullException.ThrowIfNull(query);
var wanted = kinds.Count > 0 ? kinds : DocumentBehaviors.KindsOf(family);
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, DocumentBehaviors.Of(wanted.First()).ReadPermission, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
var conditions = new List<SqlFragment>
{
SqlFragment.Literal("kind IN (") + SqlFragment.Join(", ", wanted.Select(k => SqlFragment.Parameter(k.ToString()))) + SqlFragment.Literal(")"),
};
var list = query;
if (!string.IsNullOrWhiteSpace(query.Search))
{
var pattern = "%" + query.Search.Trim().ToLowerInvariant() + "%";
var parties = await uow.Repository<Party, long>().ListAsync(
Query.For<Party>().Where(SqlFragment.Of($"(LOWER(name) LIKE {pattern} OR LOWER(code) LIKE {pattern})")).Take(500), cancellationToken).ConfigureAwait(false);
var any = new List<SqlFragment>
{
SqlFragment.Of($"LOWER(document_number) LIKE {pattern}"),
SqlFragment.Of($"LOWER(external_reference) LIKE {pattern}"),
};
if (parties.Items.Count > 0)
{
any.Add(SqlFragment.Literal("party_id IN (") + SqlFragment.Join(", ", parties.Items.Select(p => SqlFragment.Parameter(p.Id))) + SqlFragment.Literal(")"));
}
conditions.Add(SqlFragment.Join(" OR ", any).Parenthesize());
list = query with { Search = null };
}
var page = await DocumentStores.Of(family).ListAsync(uow, list, conditions, cancellationToken).ConfigureAwait(false);
return new ListPage<DocumentRow>(await RowsAsync(uow, family, page.Items, cancellationToken).ConfigureAwait(false), page.Total, page.Totals);
}
/// <summary>
/// Proposes the values of a party on a draft (SPEC §11.3): destination, price list, payment, bank, agent, carrier,
/// warehouse, currency, split payment, stamp duty, withholding and social security; the VAT code of the lines when
/// the party has its own (declaration of intent, exemption).
/// </summary>
/// <param name="actor">Who edits.</param>
/// <param name="companyCode">The company.</param>
/// <param name="record">The document, changed in place.</param>
/// <param name="partyId">The party; none clears it.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
public async Task ApplyPartyAsync(Actor actor, string companyCode, DocumentRecord record, long? partyId, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(record);
var behavior = DocumentBehaviors.Of(record.Header.Kind);
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, behavior.WritePermission, cancellationToken).ConfigureAwait(false);
var header = record.Header;
header.PartyId = partyId;
header.DestinationId = null;
if (partyId is not { } id)
{
return;
}
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
var party = await uow.Repository<Party, long>().GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException("party.not-found");
var fiscal = await uow.Repository<PartyFiscal, long>().FindAsync(Query.For<PartyFiscal>().Where(f => f.PartyId == id), cancellationToken).ConfigureAwait(false);
header.CurrencyCode = party.CurrencyCode;
header.SalespersonId = party.SalespersonId ?? header.SalespersonId;
if (behavior.Direction == DocumentDirection.Sale)
{
var terms = await uow.Repository<PartySalesTerms, long>().FindAsync(Query.For<PartySalesTerms>().Where(t => t.PartyId == id), cancellationToken).ConfigureAwait(false);
header.PriceListId = terms?.PriceListId;
header.PaymentTermId = terms?.PaymentTermId ?? header.PaymentTermId;
header.BankAccountId = terms?.CompanyBankAccountId ?? header.BankAccountId;
header.CarrierId = terms?.CarrierId ?? header.CarrierId;
header.ShippingTermId = terms?.ShippingTermId ?? header.ShippingTermId;
header.WarehouseId = terms?.WarehouseId ?? header.WarehouseId;
var addresses = await uow.Repository<PartyAddress, long>()
.ListAsync(Query.For<PartyAddress>().Where(a => a.PartyId == id && a.Kind == PartyAddressKind.Delivery), cancellationToken).ConfigureAwait(false);
header.DestinationId = (addresses.Items.FirstOrDefault(a => a.IsDefault) ?? (addresses.Items.Count == 1 ? addresses.Items[0] : null))?.Id;
if (header.BankAccountId is null)
{
var profile = await uow.Repository<CompanyProfile, long>().FindAsync(Query.For<CompanyProfile>(), cancellationToken).ConfigureAwait(false);
header.BankAccountId = profile?.DefaultBankAccountId;
}
}
else
{
var terms = await uow.Repository<PartyPurchaseTerms, long>().FindAsync(Query.For<PartyPurchaseTerms>().Where(t => t.PartyId == id), cancellationToken).ConfigureAwait(false);
header.PaymentTermId = terms?.PaymentTermId ?? header.PaymentTermId;
header.ShippingTermId = terms?.ShippingTermId ?? header.ShippingTermId;
}
header.PaymentMethodId = header.PaymentTermId is { } termId
? (await uow.Repository<PaymentTerm, long>().GetAsync(termId, cancellationToken).ConfigureAwait(false))?.PaymentMethodId
: null;
header.SplitPayment = fiscal?.SplitPayment ?? false;
header.StampDutyCharged = fiscal?.StampDutyCharged ?? true;
header.Exigibility = fiscal?.Exigibility?.Trim().ToUpperInvariant() switch
{
"D" => TaxExigibility.Deferred,
"S" => TaxExigibility.SplitPayment,
_ => null,
};
var withholding = fiscal is { Withholding: true } && behavior.Kind != DocumentKind.DeliveryNote;
header.WithholdingRate = withholding ? fiscal!.WithholdingRate ?? 20m : null;
header.WithholdingBasePercent = 100m;
header.WithholdingType = withholding ? "RT01" : null;
header.WithholdingReason = withholding ? fiscal!.WithholdingReason ?? "A" : null;
header.SocialSecurityFund = string.IsNullOrWhiteSpace(fiscal?.PensionFund) ? null : fiscal.PensionFund;
header.SocialSecurityRate = header.SocialSecurityFund is null ? null : fiscal!.PensionFundRate;
header.SocialSecurityWithheld = header.SocialSecurityFund == "TC22";
header.EnasarcoRate = behavior.Direction == DocumentDirection.Purchase && fiscal is { Enasarco: true } ? 8.5m : null;
if (PartyTaxCode(fiscal, header.DocumentDate) is { } taxCode)
{
foreach (var line in record.Lines.Where(l => l.Kind != DocumentLineKind.Description))
{
line.TaxCodeId = taxCode;
}
}
}
/// <summary>
/// Fills a line from an item: description, unit, VAT, price and discounts (net price of the party, list, base list,
/// item) and quantity one when empty.
/// </summary>
/// <param name="actor">Who edits.</param>
/// <param name="companyCode">The company.</param>
/// <param name="record">The document.</param>
/// <param name="line">The line, changed in place.</param>
/// <param name="itemId">The item.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
public async Task FillLineAsync(Actor actor, string companyCode, DocumentRecord record, DocumentLine line, long itemId, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(record);
ArgumentNullException.ThrowIfNull(line);
var behavior = DocumentBehaviors.Of(record.Header.Kind);
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, behavior.WritePermission, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
var item = await uow.Repository<Item, long>().GetAsync(itemId, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(ItemService.NotFound);
line.Kind = DocumentLineKind.Item;
line.ItemId = item.Id;
line.Description = item.Description;
line.UnitOfMeasureId = item.UnitOfMeasureId;
if (line.Quantity == 0m)
{
line.Quantity = 1m;
}
PartyFiscal? fiscal = null;
if (record.Header.PartyId is { } partyId)
{
fiscal = await uow.Repository<PartyFiscal, long>().FindAsync(Query.For<PartyFiscal>().Where(f => f.PartyId == partyId), cancellationToken).ConfigureAwait(false);
}
if (behavior.Direction == DocumentDirection.Purchase)
{
line.TaxCodeId = PartyTaxCode(fiscal, record.Header.DocumentDate) ?? item.PurchaseTaxCodeId;
var supplier = record.Header.PartyId is { } supplierId
? await uow.Repository<ItemSupplier, long>().FindAsync(Query.For<ItemSupplier>().Where(s => s.ItemId == item.Id && s.PartyId == supplierId), cancellationToken).ConfigureAwait(false)
: null;
line.Price = supplier?.Price ?? item.LastCost ?? item.StandardCost ?? 0m;
line.PriceSource = supplier?.Price is not null ? PriceSource.PartyNet : PriceSource.Item;
line.DiscountFormula = null;
return;
}
line.TaxCodeId = PartyTaxCode(fiscal, record.Header.DocumentDate) ?? item.SalesTaxCodeId;
var (price, discounts) = await PriceListService.QuoteAsync(uow, item.Id, record.Header.PartyId, record.Header.PriceListId, record.Header.DocumentDate, cancellationToken)
.ConfigureAwait(false);
line.Price = price.Price ?? 0m;
line.PriceSource = price.Source;
line.DiscountFormula = discounts.Formula;
if (price.VatIncluded && !record.Header.PricesIncludeTax && line.TaxCodeId is { } taxId
&& await uow.Repository<TaxCode, long>().GetAsync(taxId, cancellationToken).ConfigureAwait(false) is { Rate: > 0m } tax)
{
// A list with VAT on a document without: the net price, to four decimals like the lists.
line.Price = Math.Round(line.Price * 100m / (100m + tax.Rate), 4, MidpointRounding.AwayFromZero);
}
}
/// <summary>
/// Computes the totals of a document being edited, without saving: line amounts and header totals change in place.
/// </summary>
/// <param name="actor">Who edits.</param>
/// <param name="companyCode">The company.</param>
/// <param name="record">The document.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The tax summary and installments the save would write.</returns>
public async Task<DocumentFigures> PreviewAsync(Actor actor, string companyCode, DocumentRecord record, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(record);
var behavior = DocumentBehaviors.Of(record.Header.Kind);
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, behavior.ReadPermission, cancellationToken).ConfigureAwait(false);
var pack = await _packs.PackOfAsync(company, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
return await DocumentCalculation.ApplyAsync(uow, pack.TaxEngine, behavior, record, cancellationToken).ConfigureAwait(false);
}
/// <summary>The documents linked to one: the ones it fulfils, the ones that fulfil it, the invoice a note corrects.</summary>
/// <param name="actor">Who reads.</param>
/// <param name="companyCode">The company.</param>
/// <param name="record">The document.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The linked documents.</returns>
public async Task<IReadOnlyList<LinkedDocument>> LinksAsync(Actor actor, string companyCode, DocumentRecord record, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(record);
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, DocumentBehaviors.Of(record.Header.Kind).ReadPermission, cancellationToken)
.ConfigureAwait(false);
if (record.Header.Id == 0)
{
return [];
}
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
var family = record.Family.ToString();
var id = record.Header.Id;
var links = (await uow.Repository<DocumentLink, long>().ListAsync(
Query.For<DocumentLink>().Where(SqlFragment.Of(
$"((target_family = {family} AND target_document_id = {id}) OR (source_family = {family} AND source_document_id = {id}))")),
cancellationToken).ConfigureAwait(false)).Items;
var wanted = new Dictionary<(DocumentFamily, long), (LinkDirection Direction, decimal Quantity)>();
foreach (var link in links)
{
var (key, direction) = link.TargetFamily == record.Family && link.TargetDocumentId == id
? ((link.SourceFamily, link.SourceDocumentId), LinkDirection.Source)
: ((link.TargetFamily, link.TargetDocumentId), LinkDirection.Target);
wanted[key] = (direction, wanted.GetValueOrDefault(key).Quantity + link.Quantity);
}
if (record.Header.RelatedDocumentId is { } related)
{
wanted.TryAdd((record.Family, related), (LinkDirection.Related, 0m));
}
var notes = await DocumentStores.Of(record.Family).ListAsync(uow, new ListQuery { Limit = 100 },
[SqlFragment.Of($"related_document_id = {id}")], cancellationToken).ConfigureAwait(false);
foreach (var note in notes.Items)
{
wanted.TryAdd((record.Family, note.Id), (LinkDirection.Related, 0m));
}
var result = new List<LinkedDocument>();
foreach (var group in wanted.GroupBy(w => w.Key.Item1))
{
var headers = await DocumentStores.Of(group.Key).ManyAsync(uow, [.. group.Select(g => g.Key.Item2)], cancellationToken).ConfigureAwait(false);
foreach (var header in headers)
{
var (direction, quantity) = wanted[(group.Key, header.Id)];
result.Add(new LinkedDocument(group.Key, header.Id, header.Kind, header.DocumentNumber, header.DocumentDate, header.Status, header.TotalAmount,
direction, quantity));
}
}
return [.. result.OrderBy(r => r.Direction).ThenBy(r => r.Date).ThenBy(r => r.DocumentNumber, StringComparer.Ordinal)];
}
/// <summary>
/// The confirmed documents of some kinds with something left to fulfil, for a party or for all, up to a date: what
/// a new delivery note can take from the orders, or a deferred invoice from the delivery notes.
/// </summary>
/// <param name="actor">Who reads.</param>
/// <param name="companyCode">The company.</param>
/// <param name="family">The family of the sources.</param>
/// <param name="kinds">The kinds of the sources.</param>
/// <param name="partyId">The party; all when empty.</param>
/// <param name="from">The first date; none when empty.</param>
/// <param name="to">The last date; none when empty.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The documents, by party and date.</returns>
public async Task<IReadOnlyList<OpenDocument>> OpenAsync(
Actor actor, string companyCode, DocumentFamily family, IReadOnlyCollection<DocumentKind> kinds, long? partyId, DateOnly? from, DateOnly? to,
CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(kinds);
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, DocumentBehaviors.Of(kinds.First()).ReadPermission, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
var conditions = new List<SqlFragment>
{
SqlFragment.Literal("kind IN (") + SqlFragment.Join(", ", kinds.Select(k => SqlFragment.Parameter(k.ToString()))) + SqlFragment.Literal(")"),
SqlFragment.Of($"status IN ({nameof(DocumentStatus.Confirmed)}, {nameof(DocumentStatus.PartiallyFulfilled)})"),
};
if (partyId is { } party)
{
conditions.Add(SqlFragment.Of($"party_id = {party}"));
}
if (from is { } first)
{
conditions.Add(SqlFragment.Of($"document_date >= {first}"));
}
if (to is { } last)
{
conditions.Add(SqlFragment.Of($"document_date <= {last}"));
}
var store = DocumentStores.Of(family);
var page = await store.ListAsync(uow, new ListQuery { Limit = ListQuery.MaxLimit, Sort = [new ListSort("date"), new ListSort("number")] }, conditions, cancellationToken)
.ConfigureAwait(false);
var rows = await RowsAsync(uow, family, page.Items, cancellationToken).ConfigureAwait(false);
var result = new List<OpenDocument>();
foreach (var row in rows)
{
var lines = (await store.LinesAsync(uow, row.Id, cancellationToken).ConfigureAwait(false)).Where(l => l.Residual > 0m).ToList();
if (lines.Count > 0)
{
result.Add(new OpenDocument(row, lines));
}
}
return [.. result.OrderBy(r => r.Row.PartyName, StringComparer.CurrentCulture).ThenBy(r => r.Row.Date).ThenBy(r => r.Row.DocumentNumber, StringComparer.Ordinal)];
}
private static long? PartyTaxCode(PartyFiscal? fiscal, DateOnly date) =>
fiscal switch
{
{ IntentActive: true, IntentTaxCodeId: { } intent } when (fiscal.IntentFrom is null || fiscal.IntentFrom <= date) && (fiscal.IntentTo is null || fiscal.IntentTo >= date) => intent,
{ TaxCodeId: { } own } => own,
_ => null,
};
private static async Task<IReadOnlyList<DocumentRow>> RowsAsync(IUnitOfWork uow, DocumentFamily family, IReadOnlyList<DocumentHeader> headers, CancellationToken cancellationToken)
{
var partyIds = headers.Where(h => h.PartyId is not null).Select(h => h.PartyId!.Value).Distinct().ToList();
var parties = partyIds.Count == 0
? new Dictionary<long, Party>()
: (await uow.Repository<Party, long>().ListAsync(Query.For<Party>().Where(p => partyIds.Contains(p.Id)), cancellationToken).ConfigureAwait(false)).Items.ToDictionary(p => p.Id);
var typeIds = headers.Select(h => h.DocumentTypeId).Distinct().ToList();
var types = typeIds.Count == 0
? new Dictionary<long, DocumentType>()
: (await uow.Repository<DocumentType, long>().ListAsync(Query.For<DocumentType>().Where(t => typeIds.Contains(t.Id)), cancellationToken).ConfigureAwait(false)).Items.ToDictionary(t => t.Id);
return
[
.. headers.Select(h =>
{
var party = h.PartyId is { } p ? parties.GetValueOrDefault(p) : null;
return new DocumentRow(h.Id, family, h.Kind, types.GetValueOrDefault(h.DocumentTypeId)?.Code ?? string.Empty, h.DocumentNumber, h.DocumentDate, h.PartyId,
party?.Code, party?.Name, h.Status, h.TaxableAmount, h.TotalAmount, h.NetAmount, h.ExternalReference, h.DeliveryDate, h.ValidUntil, h.Revision, h.IsDemo);
}),
];
}
}
@@ -0,0 +1,929 @@
using Khaemhat.Application.Audit;
using Khaemhat.Application.Inventory;
using Khaemhat.Application.Security;
using Khaemhat.Application.Tables;
using Khaemhat.Core.Documents;
using Khaemhat.Data;
using Khaemhat.Data.Querying;
using Microsoft.Extensions.Logging;
namespace Khaemhat.Application.Documents;
/// <summary>A document with its lines, whatever the family.</summary>
public sealed class DocumentRecord
{
/// <summary>The family.</summary>
public DocumentFamily Family { get; init; }
/// <summary>The header.</summary>
public required DocumentHeader Header { get; init; }
/// <summary>The lines, in order.</summary>
public List<DocumentLine> Lines { get; init; } = [];
/// <summary>The tax summary and installments written by the last save.</summary>
public DocumentFigures Figures { get; init; } = DocumentFigures.Empty;
}
/// <summary>The error codes of the document engine; the interface translates them (<c>Documents.json</c>).</summary>
public static class DocumentErrors
{
/// <summary>The document does not exist.</summary>
public const string NotFound = "document.not-found";
/// <summary>A customer or supplier is needed.</summary>
public const string PartyRequired = "document.party.required";
/// <summary>The date is missing.</summary>
public const string DateRequired = "document.date.required";
/// <summary>The date of a numbered document cannot change.</summary>
public const string DateNumbered = "document.date.numbered";
/// <summary>The type belongs to another family of documents.</summary>
public const string TypeFamily = "document.type.family";
/// <summary>The type of a confirmed document cannot change.</summary>
public const string TypeLocked = "document.type.locked";
/// <summary>The document has no lines.</summary>
public const string LinesRequired = "document.lines.required";
/// <summary>The kind of line is not accepted by the document.</summary>
public const string LineKindNotAllowed = "document.line.kind-not-allowed";
/// <summary>A line without description.</summary>
public const string LineDescriptionRequired = "document.line.description-required";
/// <summary>An item line without item.</summary>
public const string LineItemRequired = "document.line.item-required";
/// <summary>A quantity below what later documents already fulfilled.</summary>
public const string LineBelowFulfilled = "document.line.below-fulfilled";
/// <summary>A line fulfilled by later documents cannot be removed.</summary>
public const string LineFulfilledRemoved = "document.line.fulfilled-removed";
/// <summary>The line to fulfil does not exist or belongs to a kind the document does not fulfil.</summary>
public const string LineSourceInvalid = "document.line.source-invalid";
/// <summary>A cancelled invoice needs a reason.</summary>
public const string CancelReasonRequired = "document.cancel.reason-required";
/// <summary>Later documents fulfil this one: cancel them first.</summary>
public const string CancelHasFollowers = "document.cancel.has-followers";
/// <summary>A copy changes direction (sale to purchase).</summary>
public const string CopyDirection = "document.copy.direction";
/// <summary>Nothing is left to fulfil.</summary>
public const string CopyNothingLeft = "document.copy.nothing-left";
/// <summary>A closed or cancelled document cannot be fulfilled.</summary>
public const string CopySourceNotOpen = "document.copy.source-not-open";
/// <summary>Error: documents of different parties cannot go into one document.</summary>
public const string CopyParties = "document.copy.parties";
/// <summary>Error: a discount formula that cannot be read.</summary>
public const string LineDiscountInvalid = "document.line.discount-invalid";
/// <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>
/// The document engine (SPEC §11.3, ADR 0032): one implementation of create, save, confirm or issue, cancel, close,
/// reopen and delete for every family, with the numbering and the fulfilment links. The typed entry points are
/// <see cref="DocumentService{THeader, TLine}"/> and <see cref="DocumentCopyService"/>.
/// </summary>
public sealed partial class DocumentEngine
{
private readonly IUnitOfWorkFactory _factory;
private readonly PermissionService _permissions;
private readonly AuditTrail _audit;
private readonly FiscalYearService _fiscal;
private readonly CompanyFiscalContext _packs;
private readonly TimeProvider _clock;
private readonly ILogger<DocumentEngine> _logger;
/// <summary>Creates the engine.</summary>
/// <param name="factory">The units of work.</param>
/// <param name="permissions">The permissions.</param>
/// <param name="audit">The history.</param>
/// <param name="fiscal">The fiscal calendar (open periods).</param>
/// <param name="packs">The fiscal pack of each company (tax rounding, stamp duty).</param>
/// <param name="clock">The clock.</param>
/// <param name="logger">The log (section Documenti): confirmations, changes of state, deletions.</param>
public DocumentEngine(
IUnitOfWorkFactory factory, PermissionService permissions, AuditTrail audit, FiscalYearService fiscal, CompanyFiscalContext packs, TimeProvider clock,
ILogger<DocumentEngine> logger)
{
ArgumentNullException.ThrowIfNull(logger);
_logger = logger;
ArgumentNullException.ThrowIfNull(packs);
_packs = packs;
ArgumentNullException.ThrowIfNull(factory);
ArgumentNullException.ThrowIfNull(permissions);
ArgumentNullException.ThrowIfNull(audit);
ArgumentNullException.ThrowIfNull(fiscal);
ArgumentNullException.ThrowIfNull(clock);
_factory = factory;
_permissions = permissions;
_audit = audit;
_fiscal = fiscal;
_clock = clock;
}
internal IUnitOfWorkFactory Factory => _factory;
internal AuditTrail Audit => _audit;
/// <summary>The definitions of the usable document types.</summary>
/// <param name="actor">Who asks.</param>
/// <param name="companyCode">The company.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The definitions the actor can see.</returns>
public async Task<IReadOnlyList<DocumentDefinition>> DefinitionsAsync(Actor actor, string companyCode, CancellationToken cancellationToken = default)
{
var company = Company(actor, companyCode);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
var result = new List<DocumentDefinition>();
foreach (var definition in await DocumentDefinitionService.ListAsync(uow, cancellationToken).ConfigureAwait(false))
{
if ((await _permissions.CheckAsync(actor, definition.Behavior.ReadPermission, cancellationToken).ConfigureAwait(false)).Allowed)
{
result.Add(definition);
}
}
return result;
}
/// <summary>A new draft of a type, not saved: today's date and the defaults of the type.</summary>
/// <param name="actor">Who creates.</param>
/// <param name="companyCode">The company.</param>
/// <param name="typeCode">The document type, such as <c>FI</c>.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The draft.</returns>
public async Task<DocumentRecord> NewAsync(Actor actor, string companyCode, string typeCode, CancellationToken cancellationToken = default)
{
var company = Company(actor, companyCode);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
var definition = await DocumentDefinitionService.GetAsync(uow, typeCode, cancellationToken).ConfigureAwait(false);
await _permissions.DemandAsync(actor, definition.Behavior.WritePermission, cancellationToken).ConfigureAwait(false);
var header = DocumentStores.Of(definition.Family).NewHeader();
header.DocumentTypeId = definition.Type.Id;
header.Kind = definition.Kind;
header.Status = DocumentStatus.Draft;
header.DocumentDate = Today();
header.Year = header.DocumentDate.Year;
header.InventoryReasonId = definition.Type.InventoryReasonId;
return new DocumentRecord { Family = definition.Family, Header = header };
}
/// <summary>Reads a document.</summary>
/// <param name="actor">Who reads.</param>
/// <param name="companyCode">The company.</param>
/// <param name="family">The family.</param>
/// <param name="id">The document.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The document, if any.</returns>
public async Task<DocumentRecord?> GetAsync(Actor actor, string companyCode, DocumentFamily family, long id, CancellationToken cancellationToken = default)
{
var company = Company(actor, companyCode);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
var record = await LoadAsync(uow, family, id, cancellationToken).ConfigureAwait(false);
if (record is not null)
{
await _permissions.DemandAsync(actor, DocumentBehaviors.Of(record.Header.Kind).ReadPermission, cancellationToken).ConfigureAwait(false);
}
return record;
}
/// <summary>
/// Saves a draft (or the lines of a confirmed order still open): the engine keeps the number, state and other fields
/// it owns, numbers the lines and recomputes the fulfilment of a confirmed order.
/// </summary>
/// <param name="actor">Who saves.</param>
/// <param name="companyCode">The company.</param>
/// <param name="record">The document.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The document as saved.</returns>
/// <exception cref="ValidationFailedException">The document breaks a rule.</exception>
/// <exception cref="InvalidDocumentActionException">The state does not admit changes.</exception>
public async Task<DocumentRecord> SaveAsync(Actor actor, string companyCode, DocumentRecord record, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(record);
var company = Company(actor, companyCode);
var store = DocumentStores.Of(record.Family);
var pack = await _packs.PackOfAsync(company, cancellationToken).ConfigureAwait(false);
long id;
await using (var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false))
{
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
var header = record.Header;
var before = header.Id == 0 ? null : await LoadAsync(uow, record.Family, header.Id, cancellationToken).ConfigureAwait(false)
?? throw new ValidationFailedException([":" + DocumentErrors.NotFound]);
var definition = await DocumentDefinitionService.GetAsync(uow, before?.Header.DocumentTypeId ?? header.DocumentTypeId, cancellationToken).ConfigureAwait(false);
await _permissions.DemandAsync(actor, definition.Behavior.WritePermission, cancellationToken).ConfigureAwait(false);
if (before is null)
{
header.Kind = definition.Kind;
header.Status = DocumentStatus.Draft;
Release(header);
}
else
{
DocumentStateMachine.Apply(definition.Lifecycle, before.Header.Status, DocumentAction.Edit);
Keep(header, before.Header);
}
var errors = Check(definition, record, before);
await CheckSupplierDocumentAsync(uow, record, confirming: false, errors, cancellationToken).ConfigureAwait(false);
if (errors.Count > 0)
{
throw new ValidationFailedException(errors);
}
if (before is not null && definition.Kind == DocumentKind.Quotation && DocumentStateMachine.IsInForce(header.Status))
{
// A confirmed quotation that changes is a new revision of the same offer.
header.Revision = before.Header.Revision + 1;
}
var figures = await DocumentCalculation.ApplyAsync(uow, pack.TaxEngine, definition.Behavior, record, cancellationToken).ConfigureAwait(false);
id = await WriteAsync(uow, store, record, before, actor.UserName, cancellationToken).ConfigureAwait(false);
await DocumentCalculation.WriteAsync(uow, record.Family, id, figures, cancellationToken).ConfigureAwait(false);
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);
}
return await GetAsync(actor, company, record.Family, id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(DocumentErrors.NotFound);
}
/// <summary>
/// Confirms a document, or issues an invoice: checks it, numbers it, records the fulfilment of the documents its
/// lines come from.
/// </summary>
/// <param name="actor">Who confirms.</param>
/// <param name="companyCode">The company.</param>
/// <param name="family">The family.</param>
/// <param name="id">The document.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The document as confirmed.</returns>
public async Task<DocumentRecord> ConfirmAsync(Actor actor, string companyCode, DocumentFamily family, long id, CancellationToken cancellationToken = default)
{
var company = Company(actor, companyCode);
var store = DocumentStores.Of(family);
await using (var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false))
{
// The open period is read outside the transaction (the calendar has its own cache and connection).
var draft = await LoadAsync(uow, family, id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(DocumentErrors.NotFound);
var definition = await DocumentDefinitionService.GetAsync(uow, draft.Header.DocumentTypeId, cancellationToken).ConfigureAwait(false);
await _permissions.DemandAsync(actor, definition.Behavior.ConfirmPermission, cancellationToken).ConfigureAwait(false);
DocumentStateMachine.Apply(definition.Lifecycle, draft.Header.Status, definition.ConfirmAction);
if (definition.Behavior.Has(DocumentEffects.Ledger))
{
await _fiscal.DemandOpenAsync(company, draft.Header.DocumentDate, PeriodUse.Vat, cancellationToken).ConfigureAwait(false);
}
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
var record = await LoadAsync(uow, family, id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(DocumentErrors.NotFound);
var next = DocumentStateMachine.Apply(definition.Lifecycle, record.Header.Status, definition.ConfirmAction);
var errors = Check(definition, record, record);
if (record.Lines.Count == 0)
{
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.
for (var i = 0; i < record.Lines.Count; i++)
{
if (record.Lines[i] is { Kind: not DocumentLineKind.Description, TaxCodeId: null })
{
errors.Add("Lines." + i.ToString(System.Globalization.CultureInfo.InvariantCulture) + "." + nameof(DocumentLine.TaxCodeId) + ":" + DocumentErrors.LineTaxRequired);
}
}
}
if (errors.Count > 0 || record.Header.DocumentDate != draft.Header.DocumentDate)
{
throw errors.Count > 0 ? new ValidationFailedException(errors) : new Core.Common.ConcurrencyException();
}
var header = record.Header;
var before = header.Clone();
if (definition.Type.NumeratorId is { } numeratorId)
{
var number = await DocumentNumberingService.NextAsync(uow, numeratorId, header.DocumentDate, cancellationToken).ConfigureAwait(false);
header.NumeratorId = number.Numerator.Id;
header.Section = number.Numerator.Section;
header.Number = number.Number;
header.DocumentNumber = number.Text;
}
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);
}
return await GetAsync(actor, company, family, id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(DocumentErrors.NotFound);
}
/// <summary>
/// Cancels a document: the number stays, the fulfilment it recorded is given back. An invoice needs a reason and is
/// cancelled only before its file reaches the exchange system (or after a rejection).
/// </summary>
/// <param name="actor">Who cancels.</param>
/// <param name="companyCode">The company.</param>
/// <param name="family">The family.</param>
/// <param name="id">The document.</param>
/// <param name="reason">Why.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The document as cancelled.</returns>
public Task<DocumentRecord> CancelAsync(Actor actor, string companyCode, DocumentFamily family, long id, string? reason, CancellationToken cancellationToken = default) =>
ChangeStateAsync(actor, companyCode, family, id, DocumentAction.Cancel, async (uow, definition, record, ct) =>
{
var text = reason?.Trim();
if (definition.Lifecycle == DocumentLifecycle.Invoice && string.IsNullOrEmpty(text))
{
throw new ValidationFailedException([nameof(DocumentHeader.CancelReason) + ":" + DocumentErrors.CancelReasonRequired]);
}
if ((await LinksFromAsync(uow, family, id, ct).ConfigureAwait(false)).Count > 0)
{
throw new ValidationFailedException([":" + DocumentErrors.CancelHasFollowers]);
}
record.Header.CancelReason = string.IsNullOrEmpty(text) ? null : text[..Math.Min(text.Length, 200)];
record.Header.CancelledAt = _clock.GetUtcNow().UtcDateTime;
},
(uow, record, user, ct) => UnlinkAsync(uow, family, id, user, ct),
cancellationToken);
/// <summary>Closes what is left to fulfil of an order, quotation, delivery note or pro forma.</summary>
/// <param name="actor">Who closes.</param>
/// <param name="companyCode">The company.</param>
/// <param name="family">The family.</param>
/// <param name="id">The document.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The document as closed.</returns>
public Task<DocumentRecord> CloseAsync(Actor actor, string companyCode, DocumentFamily family, long id, CancellationToken cancellationToken = default) =>
ChangeStateAsync(actor, companyCode, family, id, DocumentAction.Close, null, null, cancellationToken);
/// <summary>Reopens a closed document: its state comes back from the fulfilment of its lines.</summary>
/// <param name="actor">Who reopens.</param>
/// <param name="companyCode">The company.</param>
/// <param name="family">The family.</param>
/// <param name="id">The document.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The document as reopened.</returns>
public Task<DocumentRecord> ReopenAsync(Actor actor, string companyCode, DocumentFamily family, long id, CancellationToken cancellationToken = default) =>
ChangeStateAsync(actor, companyCode, family, id, DocumentAction.Reopen, null,
(uow, record, user, ct) => RefreshFulfillmentAsync(uow, family, id, user, ct), cancellationToken);
/// <summary>
/// Records a step of the electronic invoice (file generated, sent, delivered, rejected, not delivered); the module
/// of the electronic invoice (M8) calls it.
/// </summary>
/// <param name="actor">Who records it.</param>
/// <param name="companyCode">The company.</param>
/// <param name="family">The family.</param>
/// <param name="id">The document.</param>
/// <param name="action">The step.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The document.</returns>
public Task<DocumentRecord> RecordExchangeAsync(Actor actor, string companyCode, DocumentFamily family, long id, DocumentAction action, CancellationToken cancellationToken = default)
{
if (action is not (DocumentAction.GenerateXml or DocumentAction.Send or DocumentAction.MarkDelivered or DocumentAction.MarkRejected or DocumentAction.MarkNotDelivered))
{
throw new ArgumentOutOfRangeException(nameof(action), action, "Not a step of the electronic invoice.");
}
return ChangeStateAsync(actor, companyCode, family, id, action, (uow, definition, record, ct) =>
{
if (action == DocumentAction.GenerateXml)
{
record.Header.XmlGenerated = true;
}
return Task.CompletedTask;
}, null, cancellationToken);
}
/// <summary>Records that the document was printed (its PDF kept among the attachments); the state does not change.</summary>
/// <param name="actor">Who prints: needs to read the document.</param>
/// <param name="companyCode">The company.</param>
/// <param name="family">The family.</param>
/// <param name="id">The document.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
public Task MarkPrintedAsync(Actor actor, string companyCode, DocumentFamily family, long id, CancellationToken cancellationToken = default) =>
MarkAsync(actor, companyCode, family, id, h => h.Printed = true, cancellationToken);
/// <summary>Records that the document was sent by e-mail; the state does not change.</summary>
/// <param name="actor">Who sends: needs to read the document.</param>
/// <param name="companyCode">The company.</param>
/// <param name="family">The family.</param>
/// <param name="id">The document.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
public Task MarkSentAsync(Actor actor, string companyCode, DocumentFamily family, long id, CancellationToken cancellationToken = default) =>
MarkAsync(actor, companyCode, family, id, h => h.Sent = true, cancellationToken);
/// <summary>Deletes a draft.</summary>
/// <param name="actor">Who deletes.</param>
/// <param name="companyCode">The company.</param>
/// <param name="family">The family.</param>
/// <param name="id">The document.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
public async Task DeleteAsync(Actor actor, string companyCode, DocumentFamily family, long id, CancellationToken cancellationToken = default)
{
var company = Company(actor, companyCode);
var store = DocumentStores.Of(family);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
var record = await LoadAsync(uow, family, id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(DocumentErrors.NotFound);
var definition = DocumentBehaviors.Of(record.Header.Kind);
await _permissions.DemandAsync(actor, definition.DeletePermission, cancellationToken).ConfigureAwait(false);
DocumentStateMachine.Apply(definition.Lifecycle, record.Header.Status, DocumentAction.Delete);
await store.DeleteAsync(uow, id, cancellationToken).ConfigureAwait(false);
await store.RecordAsync(_audit, uow, AuditAction.Delete, id, record.Header, null, actor.UserName, cancellationToken).ConfigureAwait(false);
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
LogDeleted(_logger, record.Header.Kind, id, company, actor.UserName);
}
/// <summary>The actions the state of a document admits for an actor.</summary>
/// <param name="actor">Who asks.</param>
/// <param name="record">The document.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The actions.</returns>
public async Task<IReadOnlyList<DocumentAction>> ActionsAsync(Actor actor, DocumentRecord record, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(record);
var behavior = DocumentBehaviors.Of(record.Header.Kind);
var result = new List<DocumentAction>();
foreach (var action in DocumentStateMachine.Actions(behavior.Lifecycle, record.Header.Status))
{
var permission = action switch
{
DocumentAction.Edit or DocumentAction.Copy => behavior.WritePermission,
DocumentAction.Delete => behavior.DeletePermission,
_ => behavior.ConfirmPermission,
};
if ((await _permissions.CheckAsync(actor, permission, cancellationToken).ConfigureAwait(false)).Allowed)
{
result.Add(action);
}
}
return result;
}
internal static async Task<DocumentRecord?> LoadAsync(IUnitOfWork uow, DocumentFamily family, long id, CancellationToken cancellationToken)
{
var store = DocumentStores.Of(family);
if (await store.GetAsync(uow, id, cancellationToken).ConfigureAwait(false) is not { } header)
{
return null;
}
return new DocumentRecord
{
Family = family,
Header = header,
Lines = await store.LinesAsync(uow, id, cancellationToken).ConfigureAwait(false),
Figures = await DocumentCalculation.ReadAsync(uow, family, id, cancellationToken).ConfigureAwait(false),
};
}
/// <summary>Checks a document against its definition; <paramref name="before"/> is the stored one.</summary>
internal static List<string> Check(DocumentDefinition definition, DocumentRecord record, DocumentRecord? before)
{
var errors = new List<string>();
var header = record.Header;
if (definition.Family != record.Family)
{
errors.Add(nameof(DocumentHeader.DocumentTypeId) + ":" + DocumentErrors.TypeFamily);
}
if (before is not null && header.DocumentTypeId != before.Header.DocumentTypeId)
{
errors.Add(nameof(DocumentHeader.DocumentTypeId) + ":" + DocumentErrors.TypeLocked);
}
if (definition.Type.Disabled && before is null)
{
errors.Add(nameof(DocumentHeader.DocumentTypeId) + ":" + DocumentDefinitionService.TypeDisabled);
}
if (definition.Behavior.NeedsParty && header.PartyId is null)
{
errors.Add(nameof(DocumentHeader.PartyId) + ":" + DocumentErrors.PartyRequired);
}
if (header.DocumentDate == default)
{
errors.Add(nameof(DocumentHeader.DocumentDate) + ":" + DocumentErrors.DateRequired);
}
else if (before?.Header.Number is not null && header.DocumentDate != before.Header.DocumentDate)
{
errors.Add(nameof(DocumentHeader.DocumentDate) + ":" + DocumentErrors.DateNumbered);
}
var stored = before?.Lines.ToDictionary(l => l.Id) ?? [];
for (var i = 0; i < record.Lines.Count; i++)
{
var line = record.Lines[i];
var field = "Lines." + i.ToString(System.Globalization.CultureInfo.InvariantCulture) + ".";
if (!definition.Behavior.Lines.Contains(line.Kind))
{
errors.Add(field + nameof(DocumentLine.Kind) + ":" + DocumentErrors.LineKindNotAllowed);
}
if (string.IsNullOrWhiteSpace(line.Description))
{
errors.Add(field + nameof(DocumentLine.Description) + ":" + DocumentErrors.LineDescriptionRequired);
}
if (!string.IsNullOrWhiteSpace(line.DiscountFormula) && !DiscountFormula.TryParse(line.DiscountFormula, out _))
{
errors.Add(field + nameof(DocumentLine.DiscountFormula) + ":" + DocumentErrors.LineDiscountInvalid);
}
if (line.Kind == DocumentLineKind.Item && line.ItemId is null)
{
errors.Add(field + nameof(DocumentLine.ItemId) + ":" + DocumentErrors.LineItemRequired);
}
if (line.Id != 0 && stored.TryGetValue(line.Id, out var old) && old.FulfilledQuantity > 0 && line.Quantity < old.FulfilledQuantity)
{
errors.Add(field + nameof(DocumentLine.Quantity) + ":" + DocumentErrors.LineBelowFulfilled);
}
}
var kept = record.Lines.Where(l => l.Id != 0).Select(l => l.Id).ToHashSet();
if (before is not null && before.Lines.Any(l => !kept.Contains(l.Id) && l.FulfilledQuantity > 0))
{
errors.Add("Lines:" + DocumentErrors.LineFulfilledRemoved);
}
return errors;
}
/// <summary>Writes the header and replaces the lines of a draft or open document.</summary>
internal async Task<long> WriteAsync(IUnitOfWork uow, IDocumentStore store, DocumentRecord record, DocumentRecord? before, string userName, CancellationToken cancellationToken)
{
var header = record.Header;
if (before is null)
{
header.Year = header.DocumentDate.Year;
await store.InsertAsync(uow, header, cancellationToken).ConfigureAwait(false);
await store.RecordAsync(_audit, uow, AuditAction.Insert, header.Id, null, header, userName, cancellationToken).ConfigureAwait(false);
}
else
{
if (header.Number is null)
{
header.Year = header.DocumentDate.Year;
}
header.RowVersion = before.Header.RowVersion;
await store.UpdateAsync(uow, header, cancellationToken).ConfigureAwait(false);
await store.RecordAsync(_audit, uow, AuditAction.Update, header.Id, before.Header, header, userName, cancellationToken).ConfigureAwait(false);
}
var id = header.Id;
var previous = before?.Lines.ToDictionary(l => l.Id) ?? [];
var kept = record.Lines.Where(l => l.Id != 0 && previous.ContainsKey(l.Id)).Select(l => l.Id).ToHashSet();
foreach (var old in previous.Values.Where(l => !kept.Contains(l.Id)))
{
await store.DeleteLineAsync(uow, old.Id, cancellationToken).ConfigureAwait(false);
}
for (var i = 0; i < record.Lines.Count; i++)
{
var line = record.Lines[i];
line.DocumentId = id;
line.LineNumber = i + 1;
line.SortOrder = i + 1;
if (line.Id != 0 && previous.TryGetValue(line.Id, out var old))
{
// The fulfilment is the engine's: what the links say, not what the screen sends.
line.FulfilledQuantity = old.FulfilledQuantity;
line.SourceFamily = old.SourceFamily;
line.SourceLineId = old.SourceLineId;
line.RowVersion = old.RowVersion;
await store.UpdateLineAsync(uow, line, cancellationToken).ConfigureAwait(false);
}
else
{
line.Id = 0;
line.FulfilledQuantity = 0;
if (line.SourceLineId is null || line.SourceFamily is null)
{
line.SourceLineId = null;
line.SourceFamily = null;
}
await store.InsertLineAsync(uow, line, cancellationToken).ConfigureAwait(false);
}
}
return id;
}
private async Task<DocumentRecord> ChangeStateAsync(
Actor actor,
string companyCode,
DocumentFamily family,
long id,
DocumentAction action,
Func<IUnitOfWork, DocumentDefinition, DocumentRecord, CancellationToken, Task>? before,
Func<IUnitOfWork, DocumentRecord, string, CancellationToken, Task>? after,
CancellationToken cancellationToken)
{
var company = Company(actor, companyCode);
var store = DocumentStores.Of(family);
await using (var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false))
{
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
var record = await LoadAsync(uow, family, id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(DocumentErrors.NotFound);
var definition = await DocumentDefinitionService.GetAsync(uow, record.Header.DocumentTypeId, cancellationToken).ConfigureAwait(false);
await _permissions.DemandAsync(actor, definition.Behavior.ConfirmPermission, cancellationToken).ConfigureAwait(false);
var next = DocumentStateMachine.Apply(definition.Lifecycle, record.Header.Status, action);
var old = record.Header.Clone();
if (before is not null)
{
await before(uow, definition, record, cancellationToken).ConfigureAwait(false);
}
record.Header.Status = next;
await store.UpdateAsync(uow, record.Header, cancellationToken).ConfigureAwait(false);
await store.RecordAsync(_audit, uow, AuditAction.Update, id, old, record.Header, actor.UserName, cancellationToken).ConfigureAwait(false);
if (after is not null)
{
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);
}
return await GetAsync(actor, company, family, id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(DocumentErrors.NotFound);
}
// Sets an output flag (printed, sent) with its trace in the history, whatever the state.
private async Task MarkAsync(Actor actor, string companyCode, DocumentFamily family, long id, Action<DocumentHeader> change, CancellationToken cancellationToken)
{
var company = Company(actor, companyCode);
var store = DocumentStores.Of(family);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
var header = await store.GetAsync(uow, id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(DocumentErrors.NotFound);
await _permissions.DemandAsync(actor, DocumentBehaviors.Of(header.Kind).ReadPermission, cancellationToken).ConfigureAwait(false);
var old = header.Clone();
change(header);
if (old.Printed != header.Printed || old.Sent != header.Sent)
{
await store.UpdateAsync(uow, header, cancellationToken).ConfigureAwait(false);
await store.RecordAsync(_audit, uow, AuditAction.Update, id, old, header, actor.UserName, cancellationToken).ConfigureAwait(false);
}
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
}
// Records the links of a confirmed document towards the lines it fulfils, then the fulfilment of those documents.
private async Task LinkAsync(IUnitOfWork uow, DocumentDefinition definition, DocumentRecord record, string userName, CancellationToken cancellationToken)
{
var links = uow.Repository<DocumentLink, long>();
var touched = new HashSet<(DocumentFamily, long)>();
foreach (var line in record.Lines.Where(l => l.SourceLineId is not null && l.SourceFamily is not null))
{
var sourceFamily = line.SourceFamily!.Value;
var source = await DocumentStores.Of(sourceFamily).GetLineAsync(uow, line.SourceLineId!.Value, cancellationToken).ConfigureAwait(false);
var sourceHeader = source is null ? null : await DocumentStores.Of(sourceFamily).GetAsync(uow, source.DocumentId, cancellationToken).ConfigureAwait(false);
if (source is null || sourceHeader is null || !definition.Behavior.Fulfils(sourceHeader.Kind) || !DocumentStateMachine.IsInForce(sourceHeader.Status))
{
throw new ValidationFailedException(["Lines." + (line.LineNumber - 1).ToString(System.Globalization.CultureInfo.InvariantCulture) + ".SourceLineId:" + DocumentErrors.LineSourceInvalid]);
}
await links.InsertAsync(
new DocumentLink
{
TargetFamily = record.Family,
TargetDocumentId = record.Header.Id,
TargetLineId = line.Id,
SourceFamily = sourceFamily,
SourceDocumentId = source.DocumentId,
SourceLineId = source.Id,
Quantity = line.Quantity,
},
cancellationToken).ConfigureAwait(false);
touched.Add((sourceFamily, source.DocumentId));
}
foreach (var (family, documentId) in touched)
{
await RefreshFulfillmentAsync(uow, family, documentId, userName, cancellationToken).ConfigureAwait(false);
}
}
// Removes the links of a cancelled document and gives the quantities back to the documents it fulfilled.
private async Task UnlinkAsync(IUnitOfWork uow, DocumentFamily family, long id, string userName, CancellationToken cancellationToken)
{
var links = uow.Repository<DocumentLink, long>();
var mine = (await links.ListAsync(Query.For<DocumentLink>().Where(l => l.TargetFamily == family && l.TargetDocumentId == id), cancellationToken).ConfigureAwait(false)).Items;
foreach (var link in mine)
{
await links.DeleteAsync(link.Id, cancellationToken).ConfigureAwait(false);
}
foreach (var source in mine.Select(l => (l.SourceFamily, l.SourceDocumentId)).Distinct())
{
await RefreshFulfillmentAsync(uow, source.SourceFamily, source.SourceDocumentId, userName, cancellationToken).ConfigureAwait(false);
}
}
private static async Task<IReadOnlyList<DocumentLink>> LinksFromAsync(IUnitOfWork uow, DocumentFamily family, long id, CancellationToken cancellationToken) =>
(await uow.Repository<DocumentLink, long>().ListAsync(Query.For<DocumentLink>().Where(l => l.SourceFamily == family && l.SourceDocumentId == id), cancellationToken)
.ConfigureAwait(false)).Items;
// The quantities fulfilled of each line from the links, then the state of the document from its lines.
private async Task RefreshFulfillmentAsync(IUnitOfWork uow, DocumentFamily family, long id, string userName, CancellationToken cancellationToken)
{
var store = DocumentStores.Of(family);
var record = await LoadAsync(uow, family, id, cancellationToken).ConfigureAwait(false);
if (record is null)
{
return;
}
var links = await LinksFromAsync(uow, family, id, cancellationToken).ConfigureAwait(false);
foreach (var line in FulfillmentCalculator.Apply(record.Lines, links))
{
await store.UpdateLineAsync(uow, line, cancellationToken).ConfigureAwait(false);
}
var header = record.Header;
var lifecycle = DocumentBehaviors.Of(header.Kind).Lifecycle;
var status = DocumentStateMachine.AfterFulfillment(lifecycle, header.Status, FulfillmentCalculator.StateOf(record.Lines));
if (status != header.Status)
{
var before = header.Clone();
header.Status = status;
await store.UpdateAsync(uow, header, cancellationToken).ConfigureAwait(false);
await store.RecordAsync(_audit, uow, AuditAction.Update, id, before, header, userName, cancellationToken).ConfigureAwait(false);
}
}
// The fields the engine owns keep their stored value whatever the screen sends.
private static void Keep(DocumentHeader header, DocumentHeader stored)
{
header.Kind = stored.Kind;
header.Status = stored.Status;
header.NumeratorId = stored.NumeratorId;
header.Section = stored.Section;
header.Number = stored.Number;
header.DocumentNumber = stored.DocumentNumber;
header.Year = stored.Year;
header.ConfirmedAt = stored.ConfirmedAt;
header.ConfirmedBy = stored.ConfirmedBy;
header.CancelledAt = stored.CancelledAt;
header.CancelReason = stored.CancelReason;
header.XmlGenerated = stored.XmlGenerated;
header.Posted = stored.Posted;
header.GlEntryId = stored.GlEntryId;
header.InstallmentsGenerated = stored.InstallmentsGenerated;
header.Printed = stored.Printed;
header.Sent = stored.Sent;
header.Revision = stored.Revision;
header.IsDemo = stored.IsDemo;
}
// A new draft has no number and no history of states.
private static void Release(DocumentHeader header)
{
header.Id = 0;
header.NumeratorId = null;
header.Number = null;
header.DocumentNumber = null;
header.ConfirmedAt = null;
header.ConfirmedBy = null;
header.CancelledAt = null;
header.CancelReason = null;
header.XmlGenerated = false;
header.Posted = false;
header.GlEntryId = null;
header.InstallmentsGenerated = false;
header.Printed = false;
header.Sent = false;
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);
var company = CompanyCodes.Normalize(companyCode);
if (!actor.IsInstanceAccount && !string.Equals(actor.CompanyCode, company, StringComparison.Ordinal))
{
throw new AccessDeniedException(SecurityErrors.PermissionDenied, "A company user works only in its own company.");
}
return company;
}
private DateOnly Today() => DateOnly.FromDateTime(_clock.GetLocalNow().DateTime);
[LoggerMessage(EventId = 4101, Level = LogLevel.Information, Message = "{Kind} {Number} confirmed ({Status}) in {Company} by {User}")]
private static partial void LogConfirmed(ILogger logger, DocumentKind kind, string number, DocumentStatus status, string company, string user);
[LoggerMessage(EventId = 4102, Level = LogLevel.Information, Message = "{Kind} {Number}: {Action}, now {Status}, in {Company} by {User}")]
private static partial void LogChanged(ILogger logger, DocumentKind kind, string number, DocumentAction action, DocumentStatus status, string company, string user);
[LoggerMessage(EventId = 4103, Level = LogLevel.Information, Message = "Draft {Kind} {Id} deleted in {Company} by {User}")]
private static partial void LogDeleted(ILogger logger, DocumentKind kind, long id, string company, string user);
}
@@ -0,0 +1,178 @@
using System.Text.RegularExpressions;
using Khaemhat.Application.Files;
using Khaemhat.Application.Localization;
using Khaemhat.Application.Security;
using Khaemhat.Core.Documents;
using Khaemhat.Core.Parties;
using Khaemhat.Data;
using Khaemhat.Infrastructure.Mail;
namespace Khaemhat.Application.Documents;
/// <summary>
/// Fills a mail template (SPEC §12.6): <c>{{Name}}</c> becomes the value of the field, unknown fields stay as they are
/// so that a typing error shows in the message instead of disappearing.
/// </summary>
public static partial class MailTemplateRenderer
{
/// <summary>Fills a template.</summary>
/// <param name="template">The template.</param>
/// <param name="fields">The values by name (case does not matter).</param>
/// <returns>The text.</returns>
public static string Render(string template, IReadOnlyDictionary<string, string?> fields)
{
ArgumentNullException.ThrowIfNull(template);
ArgumentNullException.ThrowIfNull(fields);
var lookup = new Dictionary<string, string?>(fields, StringComparer.OrdinalIgnoreCase);
return Field().Replace(template, m => lookup.TryGetValue(m.Groups[1].Value, out var value) ? value ?? string.Empty : m.Value);
}
[GeneratedRegex(@"\{\{\s*([A-Za-z][A-Za-z0-9]*)\s*\}\}", RegexOptions.CultureInvariant, 1000)]
private static partial Regex Field();
}
/// <summary>A message about a document, as the user is about to send it.</summary>
/// <param name="To">The recipients, separated by commas or semicolons.</param>
/// <param name="Subject">The subject.</param>
/// <param name="Body">The text.</param>
public sealed record DocumentMailDraft(string To, string Subject, string Body);
/// <summary>The errors of <see cref="DocumentMailService"/> (text keys).</summary>
public static class DocumentMailErrors
{
/// <summary>No SMTP server is configured.</summary>
public const string NotConfigured = "document.mail.not-configured";
/// <summary>No recipient, or one that is not an e-mail address.</summary>
public const string RecipientInvalid = "document.mail.recipient-invalid";
/// <summary>The subject is empty.</summary>
public const string SubjectRequired = "document.mail.subject-required";
/// <summary>The queue is full.</summary>
public const string QueueFull = "document.mail.queue-full";
}
/// <summary>
/// Sends a document by e-mail (SPEC §9.4, §12.6, issue #52): proposes recipient, subject and text from the templates
/// (<c>Print.Mail.*</c>) and the e-mail of the party; on sending keeps the PDF as a new version among the attachments,
/// attaches it, queues the message and marks the document as sent. The outcome is in the log, section E-mail/PEC.
/// </summary>
/// <param name="prints">The printed form of documents.</param>
/// <param name="engine">The document engine.</param>
/// <param name="generation">The generated files (the PDF).</param>
/// <param name="attachments">The attachments.</param>
/// <param name="queue">The mail queue.</param>
/// <param name="factory">The units of work.</param>
/// <param name="texts">The texts.</param>
public sealed partial class DocumentMailService(
DocumentPrintService prints, DocumentEngine engine, FileGenerationService generation, AttachmentService attachments, IMailQueue queue, IUnitOfWorkFactory factory,
ITexts texts)
{
/// <summary>Whether mail can be sent from this instance.</summary>
public bool IsConfigured => queue.IsConfigured;
/// <summary>The message proposed for a document.</summary>
/// <param name="actor">Who sends.</param>
/// <param name="companyCode">The company.</param>
/// <param name="family">The family.</param>
/// <param name="id">The document.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The draft.</returns>
public async Task<DocumentMailDraft> DraftAsync(Actor actor, string companyCode, DocumentFamily family, long id, CancellationToken cancellationToken = default)
{
var model = await prints.BuildAsync(actor, companyCode, family, id, null, cancellationToken).ConfigureAwait(false);
var record = await engine.GetAsync(actor, companyCode, family, id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(DocumentErrors.NotFound);
string? email = null;
if (record.Header.PartyId is { } partyId)
{
await using var uow = await factory.CreateAsync(DatabaseScope.Company(CompanyCodes.Normalize(companyCode)), cancellationToken).ConfigureAwait(false);
email = (await uow.Repository<Party, long>().GetAsync(partyId, cancellationToken).ConfigureAwait(false))?.Email;
}
var fields = new Dictionary<string, string?>
{
["Documento"] = model.Title,
["Numero"] = model.Number,
["Data"] = model.Date,
["Cliente"] = model.Party.Name,
["Azienda"] = model.Company.Name,
["Totale"] = model.Totals.LastOrDefault(t => t.Strong)?.Value,
};
return new DocumentMailDraft(
email ?? string.Empty,
MailTemplateRenderer.Render(texts["Print.Mail.Subject"], fields),
MailTemplateRenderer.Render(texts["Print.Mail.Body"], fields));
}
/// <summary>Sends a document: the PDF becomes a new attachment version and leaves with the message.</summary>
/// <param name="actor">Who sends.</param>
/// <param name="companyCode">The company.</param>
/// <param name="family">The family.</param>
/// <param name="id">The document.</param>
/// <param name="draft">The message.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The PDF attached.</returns>
/// <exception cref="ValidationFailedException">The message is not complete, or mail is not configured.</exception>
public async Task<AttachmentView> SendAsync(
Actor actor, string companyCode, DocumentFamily family, long id, DocumentMailDraft draft, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(draft);
var recipients = Recipients(draft.To);
var errors = new List<string>();
if (!queue.IsConfigured)
{
errors.Add(":" + DocumentMailErrors.NotConfigured);
}
if (recipients.Count == 0 || !recipients.All(r => Address().IsMatch(r)))
{
errors.Add(nameof(DocumentMailDraft.To) + ":" + DocumentMailErrors.RecipientInvalid);
}
if (string.IsNullOrWhiteSpace(draft.Subject))
{
errors.Add(nameof(DocumentMailDraft.Subject) + ":" + DocumentMailErrors.SubjectRequired);
}
if (errors.Count > 0)
{
throw new ValidationFailedException(errors);
}
var model = await prints.BuildAsync(actor, companyCode, family, id, null, cancellationToken).ConfigureAwait(false);
var pdf = await generation.GenerateAsync(actor, companyCode, DocumentPrintService.EntityOf(family), id, DocumentPdfGenerator.GeneratorCode, cancellationToken)
.ConfigureAwait(false);
byte[] bytes;
await using (var content = await attachments.OpenAsync(actor, companyCode, pdf.Id, cancellationToken).ConfigureAwait(false))
{
using var buffer = new MemoryStream();
await content.Content.CopyToAsync(buffer, cancellationToken).ConfigureAwait(false);
bytes = buffer.ToArray();
}
var mail = new OutgoingMail(recipients, draft.Subject.Trim(), draft.Body)
{
Attachments = [new MailAttachment(pdf.FileName, pdf.Mime, bytes)],
Reference = model.Title + " " + model.Number,
};
if (!queue.Enqueue(mail))
{
throw new ValidationFailedException([":" + DocumentMailErrors.QueueFull]);
}
await engine.MarkSentAsync(actor, companyCode, family, id, cancellationToken).ConfigureAwait(false);
return pdf;
}
/// <summary>The addresses of a recipient field (commas, semicolons or spaces between them).</summary>
/// <param name="text">The field.</param>
/// <returns>The addresses.</returns>
public static IReadOnlyList<string> Recipients(string? text) =>
string.IsNullOrWhiteSpace(text) ? [] : text.Split([',', ';', ' ', '\n'], StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
[GeneratedRegex(@"^[^@\s<>]+@[^@\s<>]+\.[^@\s<>]+$", RegexOptions.CultureInvariant, 1000)]
private static partial Regex Address();
}
@@ -0,0 +1,172 @@
using System.Globalization;
using Khaemhat.Application.Security;
using Khaemhat.Application.Tables;
using Khaemhat.Core.Tables;
using Khaemhat.Data;
using Khaemhat.Data.Querying;
namespace Khaemhat.Application.Documents;
/// <summary>A number given to a document.</summary>
/// <param name="Numerator">The numerator row (code and year) that gave it, already updated.</param>
/// <param name="Number">The progressive number.</param>
/// <param name="Text">The number as printed.</param>
public sealed record AssignedNumber(DocumentNumerator Numerator, long Number, string Text);
/// <summary>
/// Numbers documents (SPEC §11.3, ADR 0032): inside the transaction that confirms the document, under the lock of the
/// numerator and year, so that two confirmations never get the same number and a rollback gives the number back.
/// </summary>
public static class DocumentNumberingService
{
/// <summary>Error: on a numerator without gaps the date precedes the last document numbered.</summary>
public const string DateBeforeLast = "document.number.date-before-last";
/// <summary>Error: the numerator of the document type does not exist.</summary>
public const string NumeratorMissing = "document.number.numerator-missing";
/// <summary>Error: the numerator is disabled.</summary>
public const string NumeratorDisabled = "document.number.numerator-disabled";
/// <summary>Error: the formatted number is longer than the column.</summary>
public const string NumberTooLong = "document.number.too-long";
/// <summary>The longest number as printed.</summary>
public const int MaxLength = 30;
/// <summary>The lock that serializes the numbering of a numerator in a year.</summary>
/// <param name="code">The numerator code.</param>
/// <param name="year">The year.</param>
/// <returns>The lock key.</returns>
public static string LockKey(string code, int year) => "numerator:" + code + ":" + year.ToString(CultureInfo.InvariantCulture);
/// <summary>
/// Gives the next number of a numerator for a date. The numerator row of the document type names the code; the
/// number comes from the row of the same code for the year of the date, created from the latest one when missing.
/// </summary>
/// <param name="uow">A company unit of work inside a transaction.</param>
/// <param name="numeratorId">The numerator of the document type.</param>
/// <param name="date">The date of the document.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The number.</returns>
/// <exception cref="ValidationFailedException">The numerator is missing or disabled, or the date is out of sequence.</exception>
public static async Task<AssignedNumber> NextAsync(IUnitOfWork uow, long numeratorId, DateOnly date, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(uow);
var numerators = uow.Repository<DocumentNumerator, long>();
var template = await numerators.GetAsync(numeratorId, cancellationToken).ConfigureAwait(false)
?? throw new ValidationFailedException([NumeratorMissing]);
await uow.AcquireLockAsync(LockKey(template.Code, date.Year), cancellationToken).ConfigureAwait(false);
// Read again under the lock: another transaction may have numbered (or created the year) meanwhile.
var numerator = await ForYearAsync(uow, template, date.Year, cancellationToken).ConfigureAwait(false);
if (numerator.Disabled)
{
throw new ValidationFailedException([NumeratorDisabled]);
}
if (!numerator.GapsAllowed && numerator.LastDate is { } last && date < last)
{
throw new ValidationFailedException([DateBeforeLast]);
}
var number = numerator.LastNumber + 1;
var text = DocumentNumberFormat.Apply(numerator.Format, number, numerator.Year, numerator.Prefix, numerator.Section);
if (text.Length > MaxLength)
{
throw new ValidationFailedException([NumberTooLong]);
}
numerator.LastNumber = number;
if (numerator.LastDate is null || date > numerator.LastDate)
{
numerator.LastDate = date;
}
await numerators.UpdateAsync(numerator, cancellationToken).ConfigureAwait(false);
return new AssignedNumber(numerator, number, text);
}
/// <summary>What the next number would be, without giving it (the preview of a draft).</summary>
/// <param name="uow">A company unit of work.</param>
/// <param name="numeratorId">The numerator of the document type.</param>
/// <param name="date">The date.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The number as printed, or <see langword="null"/> when the numerator is missing.</returns>
public static async Task<string?> PreviewAsync(IUnitOfWork uow, long numeratorId, DateOnly date, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(uow);
var numerators = uow.Repository<DocumentNumerator, long>();
if (await numerators.GetAsync(numeratorId, cancellationToken).ConfigureAwait(false) is not { } template)
{
return null;
}
var row = template.Year == date.Year
? template
: await numerators.FindAsync(Query.For<DocumentNumerator>().Where(n => n.Code == template.Code && n.Year == date.Year), cancellationToken).ConfigureAwait(false);
var source = row ?? template;
return DocumentNumberFormat.Apply(source.Format, (row?.LastNumber ?? 0) + 1, date.Year, source.Prefix, source.Section);
}
/// <summary>
/// The numbers missing between 1 and the last number given, over every family of documents: on a numerator without
/// gaps the list must be empty.
/// </summary>
/// <param name="uow">A company unit of work.</param>
/// <param name="numeratorId">The numerator row (code and year).</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The missing numbers, in order.</returns>
public static async Task<IReadOnlyList<long>> FindGapsAsync(IUnitOfWork uow, long numeratorId, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(uow);
var numerator = await uow.Repository<DocumentNumerator, long>().GetAsync(numeratorId, cancellationToken).ConfigureAwait(false)
?? throw new ValidationFailedException([NumeratorMissing]);
var used = new HashSet<long>();
foreach (var store in DocumentStores.All)
{
var sql = SqlFragment.Literal("SELECT number FROM " + store.HeaderTable + " WHERE ") + SqlFragment.Of($"numerator_id = {numeratorId} AND number IS NOT NULL");
used.UnionWith(await uow.QueryAsync<long>(sql, cancellationToken).ConfigureAwait(false));
}
var missing = new List<long>();
for (var n = 1L; n <= numerator.LastNumber; n++)
{
if (!used.Contains(n))
{
missing.Add(n);
}
}
return missing;
}
private static async Task<DocumentNumerator> ForYearAsync(IUnitOfWork uow, DocumentNumerator template, int year, CancellationToken cancellationToken)
{
var numerators = uow.Repository<DocumentNumerator, long>();
var code = template.Code;
if (await numerators.FindAsync(Query.For<DocumentNumerator>().Where(n => n.Code == code && n.Year == year), cancellationToken).ConfigureAwait(false) is { } row)
{
return row;
}
// A new year: the same rules as the latest year of the code, starting from one.
var found = (await numerators.ListAsync(Query.For<DocumentNumerator>().Where(n => n.Code == code).OrderByDescending(n => n.Year).Take(1), cancellationToken)
.ConfigureAwait(false)).Items;
var latest = found.Count > 0 ? found[0] : template;
var created = new DocumentNumerator
{
Code = latest.Code,
Description = latest.Description,
Kind = latest.Kind,
Section = latest.Section,
Year = year,
Prefix = latest.Prefix,
Format = latest.Format,
GapsAllowed = latest.GapsAllowed,
Disabled = latest.Disabled,
};
await numerators.InsertAsync(created, cancellationToken).ConfigureAwait(false);
return created;
}
}
@@ -0,0 +1,440 @@
using Khaemhat.Application.Files;
using Khaemhat.Application.Security;
using Khaemhat.Infrastructure.Files;
namespace Khaemhat.Application.Documents;
/// <summary>
/// The PDF of a document (SPEC §9.4, issue #52): A4, letterhead with logo and company data, address box, conditions,
/// lines over as many pages as needed (the headings repeat), VAT summary, totals, installments, transport and signature
/// boxes, notes and footer. Saved as a generated attachment of the document, so every print is a new version and
/// <i>Rigenera</i> writes the current state after a change.
/// </summary>
/// <param name="prints">The printed form of documents.</param>
/// <param name="attachments">The attachments (the logo of the company).</param>
public sealed class DocumentPdfGenerator(DocumentPrintService prints, AttachmentService attachments) : IFileGenerator
{
/// <summary>The code of the generator.</summary>
public const string GeneratorCode = "documents.pdf";
private const double Margin = 42;
private const double Bottom = 60;
private static readonly PdfColor Accent = PdfColor.FromHex("#1F5F8B");
private static readonly PdfColor Muted = PdfColor.Gray(105);
private static readonly PdfColor Rule = PdfColor.Gray(205);
private static readonly PdfColor Band = PdfColor.Gray(238);
private static readonly PdfColor Warning = PdfColor.FromHex("#B54708");
/// <inheritdoc />
public string Code => GeneratorCode;
/// <inheritdoc />
public string TitleKey => "files.generators.document_pdf";
/// <inheritdoc />
public string MediaType => PdfWriter.MediaType;
/// <inheritdoc />
public string Extension => ".pdf";
/// <inheritdoc />
public bool Supports(string entity) => DocumentPrintService.FamilyOf(entity) is not null;
/// <inheritdoc />
public string FileName(FileGenerationContext context)
{
ArgumentNullException.ThrowIfNull(context);
return Stem(context) + Extension;
}
/// <inheritdoc />
public async Task GenerateAsync(FileGenerationContext context, Stream output, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(context);
var model = await ModelAsync(context, cancellationToken).ConfigureAwait(false);
await WriteAsync(model, context, output, cancellationToken).ConfigureAwait(false);
}
// The file name follows the document (number and kind); without the logo, which the name does not need.
private string Stem(FileGenerationContext context)
{
try
{
return prints.BuildAsync(context.Actor, context.CompanyCode, FamilyOf(context), context.EntityId).GetAwaiter().GetResult().FileStem;
}
catch (KeyNotFoundException)
{
return "documento-" + context.EntityId.ToString(System.Globalization.CultureInfo.InvariantCulture);
}
}
private static Core.Documents.DocumentFamily FamilyOf(FileGenerationContext context) =>
DocumentPrintService.FamilyOf(context.Entity) ?? throw new ValidationFailedException([FileGenerationService.UnknownGeneratorError]);
private Task<DocumentPrintModel> ModelAsync(FileGenerationContext context, CancellationToken cancellationToken) =>
prints.BuildAsync(context.Actor, context.CompanyCode, FamilyOf(context), context.EntityId, (id, ct) => LogoAsync(context, id, ct), cancellationToken);
// The logo, when it is a JPEG the actor may read; the PDF writer embeds JPEG only.
private async Task<byte[]?> LogoAsync(FileGenerationContext context, long id, CancellationToken cancellationToken)
{
try
{
await using var content = await attachments.OpenAsync(context.Actor, context.CompanyCode, id, cancellationToken).ConfigureAwait(false);
if (content.Attachment.Mime != "image/jpeg")
{
return null;
}
using var buffer = new MemoryStream();
await content.Content.CopyToAsync(buffer, cancellationToken).ConfigureAwait(false);
return buffer.ToArray();
}
catch (Exception ex) when (ex is KeyNotFoundException or AccessDeniedException)
{
return null;
}
}
private static async Task WriteAsync(DocumentPrintModel model, FileGenerationContext context, Stream output, CancellationToken cancellationToken)
{
var info = new PdfDocumentInfo
{
Title = model.Title + " " + model.Number,
Author = model.Company.Name,
Subject = model.Title + " " + model.Number + " · " + model.Party.Name,
CreationDate = new DateTimeOffset(DateTime.SpecifyKind(context.Now, DateTimeKind.Utc)),
};
await using var pdf = new PdfWriter(output, info, leaveOpen: true);
var sheet = new Sheet(pdf, model, cancellationToken);
await sheet.FirstPageAsync().ConfigureAwait(false);
await sheet.LinesAsync().ConfigureAwait(false);
await sheet.FooterBlocksAsync().ConfigureAwait(false);
sheet.Finish();
await pdf.CloseAsync(cancellationToken).ConfigureAwait(false);
}
// The pen on the pages: where it is, and how to go on to the next page.
private sealed class Sheet(PdfWriter pdf, DocumentPrintModel model, CancellationToken cancellationToken)
{
// Code, description, unit, quantity, price, discounts, VAT, amount: the left edge of each column and the right end.
private double[] _edges = [];
private PdfPage _page = null!;
private int _pages;
private double _y;
private double Right => _page.Width - Margin;
public async Task FirstPageAsync()
{
await NewPageAsync(first: true).ConfigureAwait(false);
}
public async Task LinesAsync()
{
Headings();
foreach (var line in model.Lines)
{
var width = _edges[2] - _edges[1] - 8;
var wrapped = PdfTextLayout.Wrap(line.Description, line.IsDescription ? PdfFont.HelveticaOblique : PdfFont.Helvetica, 8.5, line.IsDescription ? Right - _edges[1] - 8 : width);
var height = Math.Max(1, wrapped.Count) * 11 + 5;
if (_y - height < Bottom + 20)
{
await NewPageAsync(first: false).ConfigureAwait(false);
Headings();
}
var y = _y;
if (!line.IsDescription)
{
_page.DrawText(line.Code, _edges[0] + 3, y, PdfFont.Courier, 8);
_page.DrawText(line.Unit, _edges[2] + 3, y, PdfFont.Helvetica, 8.5);
_page.DrawTextRight(line.Quantity, _edges[4] - 3, y, PdfFont.Helvetica, 8.5);
_page.DrawTextRight(line.Price, _edges[5] - 3, y, PdfFont.Helvetica, 8.5);
_page.DrawTextRight(line.Discount, _edges[6] - 3, y, PdfFont.Helvetica, 8.5);
_page.DrawTextRight(line.Tax, _edges[7] - 3, y, PdfFont.Helvetica, 8.5);
_page.DrawTextRight(line.Amount, _edges[8] - 3, y, PdfFont.Helvetica, 8.5);
}
foreach (var text in wrapped)
{
_page.DrawText(text, _edges[1] + 3, y, line.IsDescription ? PdfFont.HelveticaOblique : PdfFont.Helvetica, 8.5, line.IsDescription ? Muted : null);
y -= 11;
}
_y -= height;
_page.DrawLine(Margin, _y + 8, Right, _y + 8, 0.25, Rule);
}
_y -= 6;
}
public async Task FooterBlocksAsync()
{
foreach (var note in model.Notes)
{
var wrapped = PdfTextLayout.Wrap(note, PdfFont.Helvetica, 8.5, Right - Margin);
await RoomAsync(wrapped.Count * 11 + 4).ConfigureAwait(false);
foreach (var text in wrapped)
{
_page.DrawText(text, Margin, _y, PdfFont.Helvetica, 8.5);
_y -= 11;
}
_y -= 4;
}
// VAT summary on the left, totals on the right, side by side.
var middle = Margin + (Right - Margin) * 0.58;
var summaryHeight = model.Summary is { } s ? 20 + s.Rows.Count * 13 : 0;
var totalsHeight = model.Totals.Count * 14 + 8;
await RoomAsync(Math.Max(summaryHeight, totalsHeight) + 10).ConfigureAwait(false);
var top = _y - 4;
var afterSummary = model.Summary is { } summary ? Table(summary, Margin, middle - 14, top) : top;
var y = top;
_page.DrawRectangle(middle, y - totalsHeight + 10, Right - middle, totalsHeight, fill: Band, stroke: Band);
foreach (var row in model.Totals)
{
var font = row.Strong ? PdfFont.HelveticaBold : PdfFont.Helvetica;
var size = row.Strong ? 11 : 8.5;
if (row.Strong)
{
y -= 3;
}
_page.DrawText(row.Label, middle + 8, y, font, size, row.Strong ? Accent : null);
_page.DrawTextRight(row.Value, Right - 8, y, font, size, row.Strong ? Accent : null);
y -= 14;
}
_y = Math.Min(afterSummary, y) - 12;
if (model.Installments is { } installments)
{
await RoomAsync(22 + installments.Rows.Count * 13).ConfigureAwait(false);
_y = Table(installments, Margin, middle - 14, _y) - 12;
}
if (model.Transport.Count > 0)
{
await RoomAsync(110).ConfigureAwait(false);
_y = Fields(model.Transport, 4) - 10;
var width = (Right - Margin - 24) / Math.Max(1, model.Signatures.Count);
for (var i = 0; i < model.Signatures.Count; i++)
{
var x = Margin + i * (width + 12);
_page.DrawText(model.Signatures[i], x, _y, PdfFont.Helvetica, 7.5, Muted);
_page.DrawLine(x, _y - 28, x + width, _y - 28, 0.5, Rule);
}
_y -= 40;
}
}
public void Finish() => Foot();
private async Task RoomAsync(double height)
{
if (_y - height < Bottom)
{
await NewPageAsync(first: false).ConfigureAwait(false);
}
}
private async Task NewPageAsync(bool first)
{
if (_page is not null)
{
Foot();
}
_page = await pdf.AddPageAsync(cancellationToken: cancellationToken).ConfigureAwait(false);
_pages++;
var right = _page.Width - Margin;
double[] widths = [62, 0, 30, 50, 62, 44, 30, 66];
var description = right - Margin - widths.Sum();
_edges = new double[9];
_edges[0] = Margin;
for (var i = 0; i < widths.Length; i++)
{
_edges[i + 1] = _edges[i] + (i == 1 ? description : widths[i]);
}
_y = _page.Height - Margin;
if (!first)
{
_page.DrawText(model.Company.Name, Margin, _y - 8, PdfFont.HelveticaBold, 9);
_page.DrawTextRight(model.Title + " " + model.Number + " · " + model.Date, right, _y - 8, PdfFont.Helvetica, 9, Muted);
_y -= 18;
_page.DrawLine(Margin, _y, right, _y, 0.75, Accent);
_y -= 16;
return;
}
Letterhead(right);
}
private void Letterhead(double right)
{
var top = _y;
var x = Margin;
if (model.Logo is { } logo)
{
try
{
var info = JpegInfo.Read(logo);
var image = pdf.AddJpeg(logo);
const double height = 44;
var width = Math.Min(130, height * info.Width / Math.Max(1, info.Height));
_page.DrawImage(image, Margin, top - height, width, height);
x = Margin + width + 12;
}
catch (InvalidDataException)
{
// Not a JPEG the writer can embed: the name alone.
}
}
var y = top - 12;
_page.DrawText(model.Company.Name, x, y, PdfFont.HelveticaBold, 13, Accent);
y -= 13;
foreach (var line in model.Company.Lines)
{
_page.DrawText(PdfTextLayout.Fit(line, PdfFont.Helvetica, 7.5, right - x - 190), x, y, PdfFont.Helvetica, 7.5, Muted);
y -= 9.5;
}
// Kind, number and date on the right; a mark for drafts, cancelled and demo documents.
_page.DrawTextRight(model.Title.ToUpperInvariant(), right, top - 10, PdfFont.HelveticaBold, 9, Accent);
_page.DrawTextRight(model.Number, right, top - 28, PdfFont.HelveticaBold, 16);
_page.DrawTextRight(model.Date, right, top - 42, PdfFont.Helvetica, 9, Muted);
if (model.Watermark is { } mark)
{
_page.DrawTextRight(mark.ToUpperInvariant(), right, top - 56, PdfFont.HelveticaBold, 9, Warning);
}
_y = Math.Min(y, top - 62) - 8;
_page.DrawLine(Margin, _y, right, _y, 1, Accent);
_y -= 14;
// The address box on the right half, the conditions on the left.
var boxLeft = Margin + (right - Margin) * 0.52;
var boxTop = _y + 6;
var lines = 2 + model.Party.Lines.Count;
var boxHeight = lines * 11 + 14;
_page.DrawRectangle(boxLeft, boxTop - boxHeight, right - boxLeft, boxHeight, stroke: Rule);
var by = boxTop - 13;
_page.DrawText(model.PartyLabel, boxLeft + 8, by, PdfFont.Helvetica, 7.5, Muted);
if (model.Party.Code is { } code)
{
_page.DrawTextRight(code, right - 8, by, PdfFont.Courier, 7.5, Muted);
}
by -= 13;
_page.DrawText(PdfTextLayout.Fit(model.Party.Name, PdfFont.HelveticaBold, 10, right - boxLeft - 16), boxLeft + 8, by, PdfFont.HelveticaBold, 10);
foreach (var line in model.Party.Lines)
{
by -= 11;
_page.DrawText(PdfTextLayout.Fit(line, PdfFont.Helvetica, 8.5, right - boxLeft - 16), boxLeft + 8, by, PdfFont.Helvetica, 8.5);
}
var fy = _y - 6;
foreach (var field in model.Fields)
{
_page.DrawText(field.Label, Margin, fy, PdfFont.Helvetica, 7.5, Muted);
_page.DrawText(PdfTextLayout.Fit(field.Value, PdfFont.Helvetica, 8.5, boxLeft - Margin - 100), Margin + 92, fy, PdfFont.Helvetica, 8.5);
fy -= 12;
}
_y = Math.Min(boxTop - boxHeight, fy) - 14;
}
private void Headings()
{
_page.DrawRectangle(Margin, _y - 5, Right - Margin, 16, fill: Band, stroke: Band);
for (var i = 0; i < model.LineHeaders.Count; i++)
{
if (i is 0 or 1 or 2)
{
_page.DrawText(model.LineHeaders[i], _edges[i] + 3, _y, PdfFont.HelveticaBold, 7.5);
}
else
{
_page.DrawTextRight(model.LineHeaders[i], _edges[i + 1] - 3, _y, PdfFont.HelveticaBold, 7.5);
}
}
_y -= 17;
}
// A small table; returns the y under it.
private double Table(PrintTable table, double left, double right, double y)
{
_page.DrawText(table.Title, left, y, PdfFont.HelveticaBold, 8.5, Accent);
y -= 13;
var width = (right - left) / table.Headers.Count;
for (var i = 0; i < table.Headers.Count; i++)
{
Cell(table.Headers[i], left + i * width, width, y, table.Numeric[i], PdfFont.HelveticaBold, 7.5);
}
_page.DrawLine(left, y - 4, right, y - 4, 0.5, Rule);
y -= 13;
foreach (var row in table.Rows)
{
for (var i = 0; i < row.Count; i++)
{
Cell(row[i], left + i * width, width, y, table.Numeric[i], PdfFont.Helvetica, 8);
}
y -= 13;
}
return y;
}
private void Cell(string text, double x, double width, double y, bool numeric, PdfFont font, double size)
{
var fitted = PdfTextLayout.Fit(text, font, size, width - 6);
if (numeric)
{
_page.DrawTextRight(fitted, x + width - 3, y, font, size);
}
else
{
_page.DrawText(fitted, x + 3, y, font, size);
}
}
// Label and value pairs in columns; returns the y under them.
private double Fields(IReadOnlyList<PrintField> fields, int columns)
{
var width = (Right - Margin) / columns;
var y = _y;
for (var i = 0; i < fields.Count; i++)
{
var x = Margin + (i % columns) * width;
_page.DrawText(fields[i].Label, x, y, PdfFont.Helvetica, 7.5, Muted);
_page.DrawText(PdfTextLayout.Fit(fields[i].Value, PdfFont.Helvetica, 8.5, width - 8), x, y - 11, PdfFont.Helvetica, 8.5);
if (i % columns == columns - 1 || i == fields.Count - 1)
{
y -= 26;
}
}
return y;
}
private void Foot()
{
var right = _page.Width - Margin;
_page.DrawLine(Margin, 46, right, 46, 0.5, Rule);
if (model.Footer is { } footer)
{
_page.DrawText(PdfTextLayout.Fit(footer, PdfFont.Helvetica, 7, right - Margin - 80), Margin, 34, PdfFont.Helvetica, 7, Muted);
}
_page.DrawTextRight(_pages.ToString(System.Globalization.CultureInfo.InvariantCulture), right, 34, PdfFont.Helvetica, 7, Muted);
}
}
}
@@ -0,0 +1,514 @@
using System.Globalization;
using Khaemhat.Application.Localization;
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.Companies;
using Khaemhat.Data.Querying;
namespace Khaemhat.Application.Documents;
/// <summary>A block of name and lines: the company in the letterhead, the party in the address box.</summary>
/// <param name="Name">The name.</param>
/// <param name="Code">The code of the party, when there is one.</param>
/// <param name="Lines">Address, tax numbers, contacts.</param>
public sealed record PrintParty(string Name, string? Code, IReadOnlyList<string> Lines);
/// <summary>A label and its value.</summary>
/// <param name="Label">The label.</param>
/// <param name="Value">The value, formatted.</param>
public sealed record PrintField(string Label, string Value);
/// <summary>A row of the totals.</summary>
/// <param name="Label">The label.</param>
/// <param name="Value">The amount, formatted.</param>
/// <param name="Strong">Whether it is the amount to pay.</param>
public sealed record PrintRow(string Label, string Value, bool Strong);
/// <summary>A line of the document as printed; every value formatted, empty for a descriptive line.</summary>
/// <param name="Code">The item code.</param>
/// <param name="Description">The description.</param>
/// <param name="Unit">The unit of measure.</param>
/// <param name="Quantity">The quantity.</param>
/// <param name="Price">The unit price.</param>
/// <param name="Discount">The discounts, such as 10+5.</param>
/// <param name="Tax">The VAT code.</param>
/// <param name="Amount">The amount.</param>
/// <param name="IsDescription">Whether the line is only text.</param>
public sealed record PrintLine(
string? Code, string Description, string? Unit, string? Quantity, string? Price, string? Discount, string? Tax, string? Amount, bool IsDescription);
/// <summary>A small table (VAT summary, installments) with its headings and rows.</summary>
/// <param name="Title">The title.</param>
/// <param name="Headers">The headings.</param>
/// <param name="Numeric">Which columns hold numbers (aligned right).</param>
/// <param name="Rows">The rows, formatted.</param>
public sealed record PrintTable(string Title, IReadOnlyList<string> Headers, IReadOnlyList<bool> Numeric, IReadOnlyList<IReadOnlyList<string>> Rows);
/// <summary>
/// A document ready to print (SPEC §9.4, issue #52): every text already formatted and translated, so that the HTML
/// preview and the PDF show exactly the same thing.
/// </summary>
public sealed record DocumentPrintModel
{
/// <summary>The kind, such as Fattura immediata.</summary>
public required string Title { get; init; }
/// <summary>The number, or the draft label.</summary>
public required string Number { get; init; }
/// <summary>The date.</summary>
public required string Date { get; init; }
/// <summary>A mark across the sheet: draft, cancelled, demo; none for a valid document.</summary>
public string? Watermark { get; init; }
/// <summary>The company in the letterhead.</summary>
public required PrintParty Company { get; init; }
/// <summary>The logo of the company, a JPEG, when it has one.</summary>
public byte[]? Logo { get; init; }
/// <summary>The attachment of the logo, for the HTML preview.</summary>
public long? LogoAttachmentId { get; init; }
/// <summary>The heading of the address box (Spett.le, Fornitore).</summary>
public required string PartyLabel { get; init; }
/// <summary>The customer or supplier.</summary>
public required PrintParty Party { get; init; }
/// <summary>Payment, reference, validity, delivery, agent, CIG and CUP.</summary>
public required IReadOnlyList<PrintField> Fields { get; init; }
/// <summary>The headings of the lines.</summary>
public required IReadOnlyList<string> LineHeaders { get; init; }
/// <summary>The lines.</summary>
public required IReadOnlyList<PrintLine> Lines { get; init; }
/// <summary>The VAT summary; empty for documents without VAT.</summary>
public PrintTable? Summary { get; init; }
/// <summary>The installments; empty when the document has none.</summary>
public PrintTable? Installments { get; init; }
/// <summary>The totals, the amount to pay last.</summary>
public required IReadOnlyList<PrintRow> Totals { get; init; }
/// <summary>The transport data of a delivery note or accompanying invoice; empty otherwise.</summary>
public required IReadOnlyList<PrintField> Transport { get; init; }
/// <summary>The signature boxes of a delivery note.</summary>
public required IReadOnlyList<string> Signatures { get; init; }
/// <summary>Notes printed under the lines (document notes, legal notes such as split payment).</summary>
public required IReadOnlyList<string> Notes { get; init; }
/// <summary>The footer of the company.</summary>
public string? Footer { get; init; }
/// <summary>The name of the file without extension, such as fattura-immediata-6-2026.</summary>
public required string FileStem { get; init; }
}
/// <summary>
/// Builds the printed form of a document (SPEC §9.4, §11.3, issue #52; mockup 025): letterhead with logo and data of
/// the company, address box, conditions, lines, VAT summary, installments, totals, transport and notes. The texts come
/// from the resources (<c>Print.*</c>); the same model feeds the HTML preview and the PDF generator.
/// </summary>
/// <param name="engine">The document engine (reads the document with its permission).</param>
/// <param name="factory">The units of work.</param>
/// <param name="companies">The company registry (name of a company without profile).</param>
/// <param name="texts">The texts.</param>
public sealed class DocumentPrintService(DocumentEngine engine, IUnitOfWorkFactory factory, ICompanyRegistry companies, ITexts texts)
{
private static readonly Dictionary<DocumentFamily, string> Entities = new Dictionary<DocumentFamily, string>
{
[DocumentFamily.SaleQuotation] = "sales.salequotation",
[DocumentFamily.SaleOrder] = "sales.saleorder",
[DocumentFamily.SaleDocument] = "sales.saledocument",
[DocumentFamily.PurchaseOrder] = "purchases.purchaseorder",
[DocumentFamily.PurchaseDocument] = "purchases.purchasedocument",
[DocumentFamily.InventoryDocument] = "inventory.inventorydocument",
};
/// <summary>The entity of the attachments of a family, such as <c>sales.saledocument</c>.</summary>
/// <param name="family">The family.</param>
/// <returns>The entity.</returns>
public static string EntityOf(DocumentFamily family) => Entities[family];
/// <summary>The family of an attachment entity.</summary>
/// <param name="entity">The entity.</param>
/// <returns>The family, or none for another entity.</returns>
public static DocumentFamily? FamilyOf(string? entity) =>
Entities.Where(e => string.Equals(e.Value, entity, StringComparison.Ordinal)).Select(e => (DocumentFamily?)e.Key).FirstOrDefault();
/// <summary>The printed form of a document.</summary>
/// <param name="actor">Who prints: needs to read the document.</param>
/// <param name="companyCode">The company.</param>
/// <param name="family">The family.</param>
/// <param name="id">The document.</param>
/// <param name="logo">The logo, read by the caller with its own permission (a JPEG for the PDF).</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The model.</returns>
/// <exception cref="KeyNotFoundException">No such document.</exception>
public async Task<DocumentPrintModel> BuildAsync(
Actor actor, string companyCode, DocumentFamily family, long id, Func<long, CancellationToken, Task<byte[]?>>? logo = null, CancellationToken cancellationToken = default)
{
var record = await engine.GetAsync(actor, companyCode, family, id, cancellationToken).ConfigureAwait(false)
?? throw new KeyNotFoundException(DocumentErrors.NotFound);
var company = CompanyCodes.Normalize(companyCode);
await using var uow = await factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
var h = record.Header;
var definition = await DocumentDefinitionService.GetAsync(uow, h.DocumentTypeId, cancellationToken).ConfigureAwait(false);
var profile = await uow.Repository<CompanyProfile, long>().FindAsync(Query.For<CompanyProfile>(), cancellationToken).ConfigureAwait(false);
var registered = profile is null ? await companies.FindAsync(company, cancellationToken).ConfigureAwait(false) : null;
var party = h.PartyId is { } partyId ? await uow.Repository<Party, long>().GetAsync(partyId, cancellationToken).ConfigureAwait(false) : null;
var lookups = new Lookups(uow, cancellationToken);
var behavior = definition.Behavior;
var lines = new List<PrintLine>();
foreach (var line in record.Lines)
{
if (line.Kind == DocumentLineKind.Description)
{
lines.Add(new PrintLine(null, line.Description, null, null, null, null, null, null, true));
continue;
}
var code = line.ItemId is { } itemId ? (await lookups.GetAsync<Item>(itemId).ConfigureAwait(false))?.Code : null;
lines.Add(new PrintLine(
code,
line.Description,
await lookups.CodeAsync<UnitOfMeasure>(line.UnitOfMeasureId).ConfigureAwait(false),
texts.Number(line.Quantity, 2),
texts.Money(line.Price),
string.IsNullOrWhiteSpace(line.DiscountFormula) ? null : line.DiscountFormula,
await lookups.CodeAsync<TaxCode>(line.TaxCodeId).ConfigureAwait(false),
texts.Money(line.TaxableAmount),
false));
}
var fields = new List<PrintField>();
void Field(string key, string? value)
{
if (!string.IsNullOrWhiteSpace(value))
{
fields.Add(new PrintField(texts["Print.Fields." + key], value));
}
}
Field("Payment", await lookups.DescriptionAsync<PaymentTerm>(h.PaymentTermId).ConfigureAwait(false));
if (h.BankAccountId is { } bankId && await lookups.GetAsync<BankAccount>(bankId).ConfigureAwait(false) is { } bank)
{
Field("Bank", string.Join(" · ", new[] { bank.BankName ?? bank.Description, bank.Iban }.Where(s => !string.IsNullOrWhiteSpace(s))));
}
Field("Reference", h.ExternalReference is { } reference
? reference + (h.ExternalDate is { } externalDate ? " " + texts.Format("Print.Of", texts.Date(externalDate)) : null)
: null);
Field("ValidUntil", h.ValidUntil is { } validUntil ? texts.Date(validUntil) : null);
Field("Delivery", h.DeliveryDate is { } delivery ? texts.Date(delivery) : null);
Field("Salesperson", await lookups.DescriptionAsync<Salesperson>(h.SalespersonId).ConfigureAwait(false));
Field("Revision", h.Revision > 0 ? h.Revision.ToString(texts.Culture) : null);
Field("Cig", h.Cig);
Field("Cup", h.Cup);
Field("Related", h.RelatedNumber is { } related
? related + (h.RelatedDate is { } relatedDate ? " " + texts.Format("Print.Of", texts.Date(relatedDate)) : null)
: null);
var transport = new List<PrintField>();
var signatures = new List<string>();
if (behavior.Has(DocumentEffects.Inventory) && definition.Kind is DocumentKind.DeliveryNote or DocumentKind.AccompanyingInvoice or DocumentKind.PurchaseDeliveryNote)
{
void Transport(string key, string? value)
{
if (!string.IsNullOrWhiteSpace(value))
{
transport.Add(new PrintField(texts["Print.Transport." + key], value));
}
}
Transport("Reason", await lookups.DescriptionAsync<TransportReason>(h.TransportReasonId).ConfigureAwait(false));
Transport("By", h.TransportBy is { } by ? texts["Sales.TransportBy." + by] : null);
Transport("Carrier", await lookups.DescriptionAsync<Carrier>(h.CarrierId).ConfigureAwait(false));
Transport("Port", await lookups.DescriptionAsync<ShippingTerm>(h.ShippingTermId).ConfigureAwait(false));
Transport("Appearance", await lookups.DescriptionAsync<GoodsAppearance>(h.GoodsAppearanceId).ConfigureAwait(false));
Transport("Packages", h.Packages?.ToString(texts.Culture));
Transport("GrossWeight", h.GrossWeight is { } gross ? texts.Number(gross, 3) : null);
Transport("NetWeight", h.NetWeight is { } net ? texts.Number(net, 3) : null);
Transport("Start", h.TransportStart is { } start ? start.ToString("g", texts.Culture) : null);
signatures.AddRange([texts["Print.Transport.SignatureDriver"], texts["Print.Transport.SignatureCarrier"], texts["Print.Transport.SignatureRecipient"]]);
}
PrintTable? summary = null;
if (record.Figures.Summary.Count > 0)
{
var rows = new List<IReadOnlyList<string>>();
foreach (var row in record.Figures.Summary)
{
var tax = row.TaxCodeId is { } taxId ? await lookups.GetAsync<TaxCode>(taxId).ConfigureAwait(false) : null;
rows.Add([
tax is null ? row.Nature ?? string.Empty : tax.Code + " · " + tax.Description,
row.Rate.ToString("0.##", texts.Culture) + "%",
texts.Money(row.Taxable),
texts.Money(row.Tax),
]);
}
summary = new PrintTable(
texts["Print.Summary.Title"],
[texts["Print.Summary.Code"], texts["Print.Summary.Rate"], texts["Print.Summary.Taxable"], texts["Print.Summary.Tax"]],
[false, true, true, true],
rows);
}
PrintTable? installments = null;
if (record.Figures.Installments.Count > 0)
{
var rows = new List<IReadOnlyList<string>>();
foreach (var due in record.Figures.Installments)
{
rows.Add([
due.Number.ToString(texts.Culture),
texts.Date(due.DueDate),
await lookups.DescriptionAsync<PaymentMethod>(due.PaymentMethodId).ConfigureAwait(false) ?? string.Empty,
texts.Money(due.Amount),
]);
}
installments = new PrintTable(
texts["Print.Installments.Title"],
[texts["Print.Installments.Number"], texts["Print.Installments.Due"], texts["Print.Installments.Method"], texts["Print.Installments.Amount"]],
[true, false, false, true],
rows);
}
var notes = new List<string>();
if (!string.IsNullOrWhiteSpace(h.Notes))
{
notes.Add(h.Notes.Trim());
}
if (h.SplitPayment)
{
notes.Add(texts["Print.Notes.SplitPayment"]);
}
if (definition.Kind == DocumentKind.ProForma)
{
notes.Add(texts["Print.Notes.ProForma"]);
}
if (definition.Kind is DocumentKind.DeferredInvoice)
{
notes.Add(texts["Print.Notes.Deferred"]);
}
var title = definition.Type.Description;
var number = h.DocumentNumber ?? texts["Print.Draft"];
var stem = Slug(title + (h.DocumentNumber is { } n ? " " + n : " " + texts["Print.Draft"]));
return new DocumentPrintModel
{
Title = title,
Number = number,
Date = texts.Date(h.DocumentDate),
Watermark = h.Status switch
{
DocumentStatus.Draft => texts["Print.Watermarks.Draft"],
DocumentStatus.Cancelled => texts["Print.Watermarks.Cancelled"],
_ => h.IsDemo ? texts["Print.Watermarks.Demo"] : null,
},
Company = CompanyBlock(profile, registered?.Name ?? company),
Logo = profile?.LogoAttachmentId is { } logoId && logo is not null ? await logo(logoId, cancellationToken).ConfigureAwait(false) : null,
LogoAttachmentId = profile?.LogoAttachmentId,
PartyLabel = texts[behavior.Direction == DocumentDirection.Purchase ? "Print.Supplier" : "Print.Customer"],
Party = PartyBlock(party),
Fields = fields,
LineHeaders =
[
texts["Print.Lines.Code"], texts["Print.Lines.Description"], texts["Print.Lines.Unit"], texts["Print.Lines.Quantity"],
texts["Print.Lines.Price"], texts["Print.Lines.Discount"], texts["Print.Lines.Tax"], texts["Print.Lines.Amount"],
],
Lines = lines,
Summary = summary,
Installments = installments,
Totals = TotalsOf(record, definition),
Transport = transport,
Signatures = signatures,
Notes = notes,
Footer = profile?.FooterNotes,
FileStem = stem,
};
}
// A name for files: lower case letters and digits joined by dashes, such as fattura-immediata-6-2026.
private static string Slug(string text)
{
var builder = new System.Text.StringBuilder();
foreach (var c in text.Normalize(System.Text.NormalizationForm.FormD))
{
if (char.IsLetterOrDigit(c) && c < 128)
{
builder.Append(char.ToLowerInvariant(c));
}
else if (CharUnicodeInfo.GetUnicodeCategory(c) != UnicodeCategory.NonSpacingMark && builder.Length > 0 && builder[^1] != '-')
{
builder.Append('-');
}
}
return builder.ToString().Trim('-');
}
private PrintParty CompanyBlock(CompanyProfile? profile, string fallbackName)
{
if (profile is null)
{
return new PrintParty(fallbackName, null, []);
}
var lines = new List<string>();
Add(lines, Address(profile.Address, profile.StreetNumber, profile.PostalCode, profile.City, profile.ProvinceCode, profile.AddressCountry));
Add(lines, Join(
profile.VatNumber is { Length: > 0 } vat ? texts.Format("Print.VatNumber", vat) : null,
profile.TaxCode is { Length: > 0 } taxCode && taxCode != profile.VatNumber ? texts.Format("Print.TaxCode", taxCode) : null));
Add(lines, Join(
profile.ReaNumber is { Length: > 0 } rea ? texts.Format("Print.Rea", profile.ReaOffice ?? string.Empty, rea) : null,
profile.ShareCapital is { } capital ? texts.Format("Print.ShareCapital", texts.Money(capital)) : null));
Add(lines, Join(
profile.Phone is { Length: > 0 } phone ? texts.Format("Print.Phone", phone) : null,
profile.Email,
profile.Pec is { Length: > 0 } pec ? texts.Format("Print.Pec", pec) : null,
profile.Website));
return new PrintParty(profile.LegalName, null, lines);
}
private PrintParty PartyBlock(Party? party)
{
if (party is null)
{
return new PrintParty(texts["Print.NoParty"], null, []);
}
var lines = new List<string>();
Add(lines, Join(party.Address, party.StreetNumber));
Add(lines, Join(party.PostalCode, party.City, party.Province is { Length: > 0 } province ? "(" + province + ")" : null)
+ (party.CountryCode is { Length: > 0 } country && country != "IT" ? " · " + country : null));
Add(lines, Join(
party.VatNumber is { Length: > 0 } vat ? texts.Format("Print.VatNumber", vat) : null,
party.TaxCode is { Length: > 0 } taxCode && taxCode != party.VatNumber ? texts.Format("Print.TaxCode", taxCode) : null));
Add(lines, party.Pec is { Length: > 0 } pec ? texts.Format("Print.Pec", pec) : null);
return new PrintParty(party.Name, party.Code, lines);
}
private List<PrintRow> TotalsOf(DocumentRecord record, DocumentDefinition definition)
{
var h = record.Header;
var rows = new List<PrintRow>();
void Row(string key, decimal value, bool strong = false, string? suffix = null) =>
rows.Add(new PrintRow(texts["Print.Totals." + key] + suffix, texts.Money(value), strong));
var goods = record.Lines.Where(l => l.Kind is DocumentLineKind.Item or DocumentLineKind.Free or DocumentLineKind.Discount).Sum(l => l.TaxableAmount);
Row("Goods", goods);
if (h.FooterDiscountAmount != 0m)
{
Row("FooterDiscount", -h.FooterDiscountAmount, suffix: h.FooterDiscount is { } f ? " " + f + "%" : null);
}
if (h.ExpensesAmount != 0m)
{
Row("Expenses", h.ExpensesAmount);
}
if (h.SocialSecurityAmount != 0m)
{
Row("SocialSecurity", h.SocialSecurityAmount);
}
var ledger = definition.Behavior.Has(DocumentEffects.Ledger) || h.TaxAmount != 0m;
if (ledger)
{
Row("Taxable", h.TaxableAmount);
Row("Tax", h.TaxAmount);
}
if (h.StampDuty != 0m)
{
Row("StampDuty", h.StampDuty);
}
var showsNet = h.NetAmount != h.TotalAmount && h.NetAmount != 0m;
Row("Total", h.TotalAmount, strong: !showsNet);
if (h.WithholdingAmount != 0m)
{
Row("Withholding", -h.WithholdingAmount);
}
if (h.EnasarcoAmount != 0m)
{
Row("Enasarco", -h.EnasarcoAmount);
}
if (h.SplitPayment && h.TaxAmount != 0m)
{
Row("SplitPayment", -h.TaxAmount);
}
if (showsNet)
{
Row("Net", h.NetAmount, strong: true);
}
return rows;
}
private static string? Address(string? street, string? number, string? postalCode, string? city, string? province, string? country) =>
Join(Join(street, number), Join(postalCode, city, province is { Length: > 0 } p ? "(" + p + ")" : null), country is { Length: > 0 } c && c != "IT" ? c : null) is { } text
? text.Replace(" · ", " - ", StringComparison.Ordinal)
: null;
private static string? Join(params string?[] parts)
{
var present = parts.Where(p => !string.IsNullOrWhiteSpace(p)).ToList();
return present.Count == 0 ? null : string.Join(" · ", present);
}
private static void Add(List<string> lines, string? line)
{
if (!string.IsNullOrWhiteSpace(line))
{
lines.Add(line);
}
}
// The coded rows the printout names, read once each.
private sealed class Lookups(IUnitOfWork uow, CancellationToken cancellationToken)
{
private readonly Dictionary<(Type, long), object?> _cache = [];
public async Task<T?> GetAsync<T>(long id)
where T : Core.Entities.Entity<long>, new()
{
if (!_cache.TryGetValue((typeof(T), id), out var found))
{
found = await uow.Repository<T, long>().GetAsync(id, cancellationToken).ConfigureAwait(false);
_cache[(typeof(T), id)] = found;
}
return (T?)found;
}
public async Task<string?> CodeAsync<T>(long? id)
where T : CodedEntity, new() =>
id is { } value ? (await GetAsync<T>(value).ConfigureAwait(false))?.Code : null;
public async Task<string?> DescriptionAsync<T>(long? id)
where T : CodedEntity, new() =>
id is { } value ? (await GetAsync<T>(value).ConfigureAwait(false))?.Description : null;
}
}
@@ -0,0 +1,149 @@
using Khaemhat.Application.Security;
using Khaemhat.Core.Documents;
namespace Khaemhat.Application.Documents;
/// <summary>A document of one family, with its lines.</summary>
/// <typeparam name="THeader">The header.</typeparam>
/// <typeparam name="TLine">The line.</typeparam>
public sealed class DocumentRecord<THeader, TLine>
where THeader : DocumentHeader, new()
where TLine : DocumentLine, new()
{
/// <summary>The header.</summary>
public THeader Header { get; set; } = new();
/// <summary>The lines, in order.</summary>
public List<TLine> Lines { get; set; } = [];
}
/// <summary>
/// The document engine for one family (SPEC §11.3): create, read, save, confirm or issue, cancel, close, reopen,
/// delete and copy, with the types of that family. The screens of quotations, orders, invoices use one each.
/// </summary>
/// <typeparam name="THeader">The header.</typeparam>
/// <typeparam name="TLine">The line.</typeparam>
public sealed class DocumentService<THeader, TLine>
where THeader : DocumentHeader, new()
where TLine : DocumentLine, new()
{
private readonly DocumentEngine _engine;
private readonly DocumentCopyService _copies;
/// <summary>Creates the service.</summary>
/// <param name="engine">The engine.</param>
/// <param name="copies">The copies.</param>
public DocumentService(DocumentEngine engine, DocumentCopyService copies)
{
ArgumentNullException.ThrowIfNull(engine);
ArgumentNullException.ThrowIfNull(copies);
_engine = engine;
_copies = copies;
}
/// <summary>The family.</summary>
public DocumentFamily Family => FamilyOfHeader;
private static readonly DocumentFamily FamilyOfHeader = DocumentStores.FamilyOf<THeader>();
/// <summary>A new draft of a type of this family, not saved.</summary>
/// <param name="actor">Who creates.</param>
/// <param name="companyCode">The company.</param>
/// <param name="typeCode">The document type.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The draft.</returns>
public async Task<DocumentRecord<THeader, TLine>> NewAsync(Actor actor, string companyCode, string typeCode, CancellationToken cancellationToken = default)
{
var record = await _engine.NewAsync(actor, companyCode, typeCode, cancellationToken).ConfigureAwait(false);
if (record.Family != Family)
{
throw new ValidationFailedException([nameof(DocumentHeader.DocumentTypeId) + ":" + DocumentErrors.TypeFamily]);
}
return Typed(record);
}
/// <summary>Reads a document.</summary>
/// <param name="actor">Who reads.</param>
/// <param name="companyCode">The company.</param>
/// <param name="id">The document.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The document, if any.</returns>
public async Task<DocumentRecord<THeader, TLine>?> GetAsync(Actor actor, string companyCode, long id, CancellationToken cancellationToken = default) =>
await _engine.GetAsync(actor, companyCode, Family, id, cancellationToken).ConfigureAwait(false) is { } record ? Typed(record) : null;
/// <summary>Saves a draft, or an order still open.</summary>
/// <param name="actor">Who saves.</param>
/// <param name="companyCode">The company.</param>
/// <param name="record">The document.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The document as saved.</returns>
public async Task<DocumentRecord<THeader, TLine>> SaveAsync(Actor actor, string companyCode, DocumentRecord<THeader, TLine> record, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(record);
var saved = await _engine.SaveAsync(actor, companyCode, new DocumentRecord { Family = Family, Header = record.Header, Lines = [.. record.Lines] }, cancellationToken)
.ConfigureAwait(false);
return Typed(saved);
}
/// <summary>Confirms a document, or issues an invoice.</summary>
/// <param name="actor">Who confirms.</param>
/// <param name="companyCode">The company.</param>
/// <param name="id">The document.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The document.</returns>
public async Task<DocumentRecord<THeader, TLine>> ConfirmAsync(Actor actor, string companyCode, long id, CancellationToken cancellationToken = default) =>
Typed(await _engine.ConfirmAsync(actor, companyCode, Family, id, cancellationToken).ConfigureAwait(false));
/// <summary>Cancels a document.</summary>
/// <param name="actor">Who cancels.</param>
/// <param name="companyCode">The company.</param>
/// <param name="id">The document.</param>
/// <param name="reason">Why (required for invoices).</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The document.</returns>
public async Task<DocumentRecord<THeader, TLine>> CancelAsync(Actor actor, string companyCode, long id, string? reason, CancellationToken cancellationToken = default) =>
Typed(await _engine.CancelAsync(actor, companyCode, Family, id, reason, cancellationToken).ConfigureAwait(false));
/// <summary>Closes what is left to fulfil.</summary>
/// <param name="actor">Who closes.</param>
/// <param name="companyCode">The company.</param>
/// <param name="id">The document.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The document.</returns>
public async Task<DocumentRecord<THeader, TLine>> CloseAsync(Actor actor, string companyCode, long id, CancellationToken cancellationToken = default) =>
Typed(await _engine.CloseAsync(actor, companyCode, Family, id, cancellationToken).ConfigureAwait(false));
/// <summary>Reopens a closed document.</summary>
/// <param name="actor">Who reopens.</param>
/// <param name="companyCode">The company.</param>
/// <param name="id">The document.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The document.</returns>
public async Task<DocumentRecord<THeader, TLine>> ReopenAsync(Actor actor, string companyCode, long id, CancellationToken cancellationToken = default) =>
Typed(await _engine.ReopenAsync(actor, companyCode, Family, id, cancellationToken).ConfigureAwait(false));
/// <summary>Deletes a draft.</summary>
/// <param name="actor">Who deletes.</param>
/// <param name="companyCode">The company.</param>
/// <param name="id">The document.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
public Task DeleteAsync(Actor actor, string companyCode, long id, CancellationToken cancellationToken = default) =>
_engine.DeleteAsync(actor, companyCode, Family, id, cancellationToken);
/// <summary>Copies a document of this family into a new draft of any type of the same direction.</summary>
/// <param name="actor">Who copies.</param>
/// <param name="companyCode">The company.</param>
/// <param name="id">The source.</param>
/// <param name="targetTypeCode">The type of the new document.</param>
/// <param name="lineIds">The lines to copy; all when empty.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The new draft, in its own family.</returns>
public Task<DocumentRecord> CopyAsync(
Actor actor, string companyCode, long id, string targetTypeCode, IReadOnlyCollection<long>? lineIds = null, CancellationToken cancellationToken = default) =>
_copies.CopyAsync(actor, companyCode, Family, id, targetTypeCode, lineIds, cancellationToken);
private static DocumentRecord<THeader, TLine> Typed(DocumentRecord record) =>
new() { Header = (THeader)record.Header, Lines = [.. record.Lines.Cast<TLine>()] };
}
@@ -0,0 +1,291 @@
using Khaemhat.Application.Audit;
using Khaemhat.Application.Querying;
using Khaemhat.Core.Documents;
using Khaemhat.Data;
using Khaemhat.Data.Querying;
namespace Khaemhat.Application.Documents;
/// <summary>
/// Reads and writes the headers and lines of one family through the base classes, so that the engine can follow
/// fulfilment links and copies from one family to another (ADR 0032).
/// </summary>
internal interface IDocumentStore
{
/// <summary>The family.</summary>
DocumentFamily Family { get; }
/// <summary>The header table.</summary>
string HeaderTable { get; }
/// <summary>A new header of the family.</summary>
/// <returns>The header.</returns>
DocumentHeader NewHeader();
/// <summary>A new line of the family.</summary>
/// <returns>The line.</returns>
DocumentLine NewLine();
/// <summary>Reads a header.</summary>
/// <param name="uow">The unit of work.</param>
/// <param name="id">The document.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The header, if any.</returns>
Task<DocumentHeader?> GetAsync(IUnitOfWork uow, long id, CancellationToken cancellationToken);
/// <summary>Reads the lines of a document in their order.</summary>
/// <param name="uow">The unit of work.</param>
/// <param name="documentId">The document.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <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>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The line, if any.</returns>
Task<DocumentLine?> GetLineAsync(IUnitOfWork uow, long id, CancellationToken cancellationToken);
/// <summary>Inserts a header.</summary>
/// <param name="uow">The unit of work.</param>
/// <param name="header">The header.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
Task InsertAsync(IUnitOfWork uow, DocumentHeader header, CancellationToken cancellationToken);
/// <summary>Updates a header.</summary>
/// <param name="uow">The unit of work.</param>
/// <param name="header">The header.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
Task UpdateAsync(IUnitOfWork uow, DocumentHeader header, CancellationToken cancellationToken);
/// <summary>Deletes a header and, by cascade, its lines.</summary>
/// <param name="uow">The unit of work.</param>
/// <param name="id">The document.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
Task DeleteAsync(IUnitOfWork uow, long id, CancellationToken cancellationToken);
/// <summary>Inserts a line.</summary>
/// <param name="uow">The unit of work.</param>
/// <param name="line">The line.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
Task InsertLineAsync(IUnitOfWork uow, DocumentLine line, CancellationToken cancellationToken);
/// <summary>Updates a line.</summary>
/// <param name="uow">The unit of work.</param>
/// <param name="line">The line.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
Task UpdateLineAsync(IUnitOfWork uow, DocumentLine line, CancellationToken cancellationToken);
/// <summary>Deletes a line.</summary>
/// <param name="uow">The unit of work.</param>
/// <param name="id">The line.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
Task DeleteLineAsync(IUnitOfWork uow, long id, CancellationToken cancellationToken);
/// <summary>Writes a change of a header in the history, under the name of its class.</summary>
/// <param name="audit">The history.</param>
/// <param name="uow">The unit of work.</param>
/// <param name="action">What happened.</param>
/// <param name="id">The document.</param>
/// <param name="before">The header before.</param>
/// <param name="after">The header after.</param>
/// <param name="userName">Who did it.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
Task RecordAsync(
AuditTrail audit, IUnitOfWork uow, AuditAction action, long id, DocumentHeader? before, DocumentHeader? after, string? userName,
CancellationToken cancellationToken);
/// <summary>A page of headers: the list request, plus the conditions the caller adds (kinds, search on parties).</summary>
Task<ListPage<DocumentHeader>> ListAsync(IUnitOfWork uow, ListQuery list, IReadOnlyList<SqlFragment> conditions, CancellationToken cancellationToken);
/// <summary>Headers by id.</summary>
Task<IReadOnlyList<DocumentHeader>> ManyAsync(IUnitOfWork uow, IReadOnlyCollection<long> ids, CancellationToken cancellationToken);
/// <summary>Lines by id.</summary>
Task<IReadOnlyList<DocumentLine>> LinesByIdAsync(IUnitOfWork uow, IReadOnlyCollection<long> ids, CancellationToken cancellationToken);
}
/// <summary>The store of one family.</summary>
/// <typeparam name="THeader">The header.</typeparam>
/// <typeparam name="TLine">The line.</typeparam>
internal sealed class DocumentStore<THeader, TLine>(DocumentFamily family, string headerTable) : IDocumentStore
where THeader : DocumentHeader, new()
where TLine : DocumentLine, new()
{
/// <inheritdoc />
public DocumentFamily Family => family;
/// <inheritdoc />
public string HeaderTable => headerTable;
/// <inheritdoc />
public DocumentHeader NewHeader() => new THeader();
/// <inheritdoc />
public DocumentLine NewLine() => new TLine();
/// <inheritdoc />
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)
{
// A SQL condition: the expression of a generic parameter may reach the base property through a conversion.
var rows = await uow.Repository<TLine, long>().ListAsync(Query.For<TLine>().Where(SqlFragment.Of($"document_id = {documentId}")), cancellationToken)
.ConfigureAwait(false);
return [.. rows.Items.OrderBy(l => l.SortOrder).ThenBy(l => l.LineNumber).ThenBy(l => l.Id).Cast<DocumentLine>()];
}
/// <inheritdoc />
public async Task<DocumentLine?> GetLineAsync(IUnitOfWork uow, long id, CancellationToken cancellationToken) =>
await uow.Repository<TLine, long>().GetAsync(id, cancellationToken).ConfigureAwait(false);
/// <inheritdoc />
public async Task InsertAsync(IUnitOfWork uow, DocumentHeader header, CancellationToken cancellationToken) =>
header.Id = await uow.Repository<THeader, long>().InsertAsync((THeader)header, cancellationToken).ConfigureAwait(false);
/// <inheritdoc />
public Task UpdateAsync(IUnitOfWork uow, DocumentHeader header, CancellationToken cancellationToken) =>
uow.Repository<THeader, long>().UpdateAsync((THeader)header, cancellationToken);
/// <inheritdoc />
public Task DeleteAsync(IUnitOfWork uow, long id, CancellationToken cancellationToken) =>
uow.Repository<THeader, long>().DeleteAsync(id, cancellationToken);
/// <inheritdoc />
public async Task InsertLineAsync(IUnitOfWork uow, DocumentLine line, CancellationToken cancellationToken) =>
line.Id = await uow.Repository<TLine, long>().InsertAsync((TLine)line, cancellationToken).ConfigureAwait(false);
/// <inheritdoc />
public Task UpdateLineAsync(IUnitOfWork uow, DocumentLine line, CancellationToken cancellationToken) =>
uow.Repository<TLine, long>().UpdateAsync((TLine)line, cancellationToken);
/// <inheritdoc />
public Task DeleteLineAsync(IUnitOfWork uow, long id, CancellationToken cancellationToken) =>
uow.Repository<TLine, long>().DeleteAsync(id, cancellationToken);
/// <inheritdoc />
public Task RecordAsync(
AuditTrail audit, IUnitOfWork uow, AuditAction action, long id, DocumentHeader? before, DocumentHeader? after, string? userName,
CancellationToken cancellationToken) =>
audit.RecordAsync(uow, action, id, (THeader?)before, (THeader?)after, userName, cancellationToken);
/// <inheritdoc />
public async Task<ListPage<DocumentHeader>> ListAsync(IUnitOfWork uow, ListQuery list, IReadOnlyList<SqlFragment> conditions, CancellationToken cancellationToken)
{
var query = Query.For<THeader>();
foreach (var condition in conditions)
{
query = query.Where(condition);
}
var fields = DocumentListFields<THeader>.Fields;
var page = await uow.Repository<THeader, long>().ListAsync(fields.Apply(query, list), cancellationToken).ConfigureAwait(false);
return new ListPage<DocumentHeader>([.. page.Items], page.TotalCount, new Dictionary<string, decimal>());
}
/// <inheritdoc />
public async Task<IReadOnlyList<DocumentHeader>> ManyAsync(IUnitOfWork uow, IReadOnlyCollection<long> ids, CancellationToken cancellationToken)
{
if (ids.Count == 0)
{
return [];
}
var list = ids.ToList();
var rows = await uow.Repository<THeader, long>().ListAsync(Query.For<THeader>().Where(h => list.Contains(h.Id)), cancellationToken).ConfigureAwait(false);
return [.. rows.Items];
}
/// <inheritdoc />
public async Task<IReadOnlyList<DocumentLine>> LinesByIdAsync(IUnitOfWork uow, IReadOnlyCollection<long> ids, CancellationToken cancellationToken)
{
if (ids.Count == 0)
{
return [];
}
var list = ids.ToList();
var rows = await uow.Repository<TLine, long>().ListAsync(Query.For<TLine>().Where(l => list.Contains(l.Id)), cancellationToken).ConfigureAwait(false);
return [.. rows.Items];
}
}
/// <summary>The fields of the document radars (ADR 0032): the same for every family.</summary>
/// <typeparam name="THeader">The header.</typeparam>
internal static class DocumentListFields<THeader>
where THeader : DocumentHeader
{
/// <summary>The fields.</summary>
public static ListFields<THeader> Fields { get; } = new ListFields<THeader>()
.Add("number", h => h.Number)
.Add("documentNumber", h => h.DocumentNumber, searchable: true)
.Add("date", h => h.DocumentDate)
.Add("year", h => h.Year)
.Add("kind", h => h.Kind)
.Add("type", h => h.DocumentTypeId)
.Add("status", h => h.Status)
.Add("party", h => h.PartyId)
.Add("reference", h => h.ExternalReference, searchable: true)
.Add("salesperson", h => h.SalespersonId)
.Add("taxable", h => h.TaxableAmount, total: true)
.Add("tax", h => h.TaxAmount, total: true)
.Add("total", h => h.TotalAmount, total: true)
.Add("net", h => h.NetAmount, total: true)
.Add("delivery", h => h.DeliveryDate)
.Add("validUntil", h => h.ValidUntil)
.Add("demo", h => h.IsDemo)
.OrderByDefault(new ListSort("date", Descending: true), new ListSort("number", Descending: true));
}
/// <summary>The stores of the six families.</summary>
internal static class DocumentStores
{
private static readonly Dictionary<DocumentFamily, IDocumentStore> ByFamily = new IDocumentStore[]
{
new DocumentStore<SaleQuotation, SaleQuotationLine>(DocumentFamily.SaleQuotation, "sale_quotations"),
new DocumentStore<SaleOrder, SaleOrderLine>(DocumentFamily.SaleOrder, "sale_orders"),
new DocumentStore<SaleDocument, SaleDocumentLine>(DocumentFamily.SaleDocument, "sale_documents"),
new DocumentStore<PurchaseOrder, PurchaseOrderLine>(DocumentFamily.PurchaseOrder, "purchase_orders"),
new DocumentStore<PurchaseDocument, PurchaseDocumentLine>(DocumentFamily.PurchaseDocument, "purchase_documents"),
new DocumentStore<InventoryDocument, InventoryDocumentLine>(DocumentFamily.InventoryDocument, "inventory_documents"),
}.ToDictionary(s => s.Family);
/// <summary>Every store.</summary>
public static IEnumerable<IDocumentStore> All => ByFamily.Values;
/// <summary>The store of a family.</summary>
/// <param name="family">The family.</param>
/// <returns>The store.</returns>
public static IDocumentStore Of(DocumentFamily family) => ByFamily[family];
/// <summary>The family of a header class.</summary>
/// <typeparam name="THeader">The header.</typeparam>
/// <returns>The family.</returns>
public static DocumentFamily FamilyOf<THeader>()
where THeader : DocumentHeader, new()
{
var type = typeof(THeader);
return All.Single(s => s.NewHeader().GetType() == type).Family;
}
}
@@ -0,0 +1,257 @@
using Khaemhat.Application.Tables;
using Khaemhat.Core.Documents;
using Khaemhat.Core.Tax;
using Khaemhat.Fiscal.Abstractions;
namespace Khaemhat.Application.Documents;
/// <summary>The VAT of a line, from its tax code.</summary>
/// <param name="TaxCodeId">The tax code.</param>
/// <param name="Rate">The rate in percent.</param>
/// <param name="Nature">The nature of operations without VAT.</param>
/// <param name="Exigibility">When the VAT becomes due.</param>
/// <param name="NonDeductiblePercent">The non-deductible share (purchases).</param>
/// <param name="LegalReference">The law printed for operations without VAT.</param>
public sealed record TotalsTax(
long? TaxCodeId,
decimal Rate,
string? Nature = null,
TaxExigibility Exigibility = TaxExigibility.Immediate,
decimal NonDeductiblePercent = 0m,
string? LegalReference = null);
/// <summary>A line as the calculator sees it.</summary>
/// <param name="Kind">The kind of line.</param>
/// <param name="Quantity">The quantity (expenses and discounts without quantity count as one).</param>
/// <param name="Price">The unit price, with VAT when the document's prices include it.</param>
/// <param name="DiscountFormula">The discounts, such as <c>10+5</c>.</param>
/// <param name="Tax">The VAT; lines without it are left out of the summary.</param>
/// <param name="WithholdingExcluded">The line is out of the withholding and of the social security contribution.</param>
public sealed record TotalsLine(
DocumentLineKind Kind,
decimal Quantity,
decimal Price,
string? DiscountFormula,
TotalsTax? Tax,
bool WithholdingExcluded = false);
/// <summary>The settings of the document that change its totals.</summary>
public sealed record TotalsOptions
{
/// <summary>The prices include VAT: the taxable amount is computed back from each VAT group.</summary>
public bool PricesIncludeTax { get; init; }
/// <summary>The discount on the goods (not on expenses), such as <c>5</c> or <c>10+5</c>.</summary>
public string? FooterDiscount { get; init; }
/// <summary>The exigibility of the whole document (cash basis, deferred), when not the one of the tax codes.</summary>
public TaxExigibility? Exigibility { get; init; }
/// <summary>Split payment: the VAT is paid by the customer to the State.</summary>
public bool SplitPayment { get; init; }
/// <summary>The document can carry the stamp duty (invoices and notes).</summary>
public bool StampDutyApplies { get; init; }
/// <summary>The stamp duty is added to the total.</summary>
public bool StampDutyCharged { get; init; }
/// <summary>The withholding rate, percent.</summary>
public decimal? WithholdingRate { get; init; }
/// <summary>The share of the amount the withholding applies to, percent.</summary>
public decimal WithholdingBasePercent { get; init; } = 100m;
/// <summary>The social security contribution rate, percent.</summary>
public decimal? SocialSecurityRate { get; init; }
/// <summary>The VAT of the contribution; the one of the first taxed line when empty.</summary>
public TotalsTax? SocialSecurityTax { get; init; }
/// <summary>The contribution is part of the withholding base.</summary>
public bool SocialSecurityWithheld { get; init; }
/// <summary>The ENASARCO rate withheld, percent.</summary>
public decimal? EnasarcoRate { get; init; }
}
/// <summary>A line of the computed tax summary.</summary>
/// <param name="Tax">The VAT of the group, with the exigibility of the document.</param>
/// <param name="Taxable">The taxable amount.</param>
/// <param name="TaxAmount">The VAT.</param>
/// <param name="NonDeductibleTax">The non-deductible part of the VAT.</param>
public sealed record TotalsSummaryLine(TotalsTax Tax, decimal Taxable, decimal TaxAmount, decimal NonDeductibleTax);
/// <summary>The totals of a document.</summary>
/// <param name="LineAmounts">The amount of each line (quantity × price less its discounts), in the order given.</param>
/// <param name="Summary">The tax summary, by rate (highest first).</param>
/// <param name="Expenses">The total of the expense lines.</param>
/// <param name="FooterDiscountAmount">What the footer discount took off.</param>
/// <param name="SocialSecurity">The social security contribution.</param>
/// <param name="Taxable">The taxable amount.</param>
/// <param name="Tax">The VAT.</param>
/// <param name="StampDuty">The stamp duty due (charged or not).</param>
/// <param name="Total">The total of the document.</param>
/// <param name="Withholding">The withholding tax.</param>
/// <param name="Enasarco">The ENASARCO contribution withheld.</param>
/// <param name="SplitPaymentTax">The VAT the customer pays to the State.</param>
/// <param name="Net">The amount to pay.</param>
public sealed record DocumentTotals(
IReadOnlyList<decimal> LineAmounts,
IReadOnlyList<TotalsSummaryLine> Summary,
decimal Expenses,
decimal FooterDiscountAmount,
decimal SocialSecurity,
decimal Taxable,
decimal Tax,
decimal StampDuty,
decimal Total,
decimal Withholding,
decimal Enasarco,
decimal SplitPaymentTax,
decimal Net);
/// <summary>
/// The totals of a document (SPEC §11.3, issue #48): line amount = quantity × price × (1 − d1)(1 − d2)… rounded to the
/// cent; footer discount on the goods; tax summary per VAT code with the tax computed on the total of each group
/// (FatturaPA <c>DatiRiepilogo</c>); social security contribution with its own VAT; stamp duty; withholding, ENASARCO
/// and split payment taken off the amount to pay.
/// </summary>
public static class DocumentTotalsCalculator
{
/// <summary>Computes the totals.</summary>
/// <param name="lines">The lines.</param>
/// <param name="options">The settings of the document.</param>
/// <param name="engine">The country's rounding and stamp duty rules.</param>
/// <returns>The totals.</returns>
public static DocumentTotals Compute(IReadOnlyList<TotalsLine> lines, TotalsOptions options, ITaxEngine engine)
{
ArgumentNullException.ThrowIfNull(lines);
ArgumentNullException.ThrowIfNull(options);
ArgumentNullException.ThrowIfNull(engine);
var footer = Factor(options.FooterDiscount);
var amounts = new decimal[lines.Count];
var groups = new List<Group>();
decimal beforeFooter = 0m, afterFooter = 0m, expenses = 0m, withholdingBase = 0m;
TotalsTax? firstTax = null;
for (var i = 0; i < lines.Count; i++)
{
var line = lines[i];
if (line.Kind == DocumentLineKind.Description)
{
continue;
}
var quantity = line.Kind is DocumentLineKind.Expense or DocumentLineKind.Discount && line.Quantity == 0m ? 1m : line.Quantity;
var raw = quantity * line.Price * Factor(line.DiscountFormula);
if (line.Kind == DocumentLineKind.Discount)
{
raw = -Math.Abs(raw);
}
amounts[i] = engine.Round(raw);
var net = amounts[i];
if (line.Kind == DocumentLineKind.Expense)
{
expenses += net;
}
else if (footer != 1m)
{
net = engine.Round(raw * footer);
beforeFooter += amounts[i];
afterFooter += net;
}
if (!line.WithholdingExcluded)
{
withholdingBase += net;
}
if (line.Tax is { } tax)
{
firstTax ??= tax.Rate > 0m ? tax : null;
var group = GroupOf(groups, tax);
if (options.PricesIncludeTax)
{
group.Gross += net;
}
else
{
group.Net += net;
}
}
}
var socialSecurity = 0m;
if (options.SocialSecurityRate is > 0m and var rate)
{
socialSecurity = engine.Round(withholdingBase * rate / 100m);
if ((options.SocialSecurityTax ?? firstTax ?? groups.FirstOrDefault()?.Tax) is { } tax)
{
GroupOf(groups, tax).Net += socialSecurity;
}
}
var summary = groups
.Select(g => Summarize(g, options, engine))
.OrderByDescending(s => s.Tax.Rate)
.ThenBy(s => s.Tax.Nature, StringComparer.Ordinal)
.ToList();
var taxable = summary.Sum(s => s.Taxable);
var taxAmount = summary.Sum(s => s.TaxAmount);
var stamp = 0m;
if (options.StampDutyApplies)
{
stamp = engine.AssessStampDuty(summary.Select(s => new TaxSummaryLine(s.Tax.Rate, s.Tax.Nature, s.Tax.Exigibility,
s.Tax.NonDeductiblePercent, s.Taxable, s.TaxAmount, s.NonDeductibleTax))).Amount;
}
var total = taxable + taxAmount + (options.StampDutyCharged ? stamp : 0m);
var withholding = options.WithholdingRate is > 0m and var withholdingRate
? engine.Round((withholdingBase + (options.SocialSecurityWithheld ? socialSecurity : 0m)) * options.WithholdingBasePercent / 100m * withholdingRate / 100m)
: 0m;
var enasarco = options.EnasarcoRate is > 0m and var enasarcoRate ? engine.Round(withholdingBase * enasarcoRate / 100m) : 0m;
var split = summary.Where(s => s.Tax.Exigibility == TaxExigibility.SplitPayment).Sum(s => s.TaxAmount);
return new DocumentTotals(amounts, summary, expenses, beforeFooter - afterFooter, socialSecurity, taxable, taxAmount, stamp, total,
withholding, enasarco, split, total - withholding - enasarco - split);
}
/// <summary>The factor of a discount formula: 10+5 is 0.855; an empty or invalid formula is 1.</summary>
/// <param name="formula">The formula.</param>
/// <returns>The factor.</returns>
public static decimal Factor(string? formula) =>
DiscountFormula.TryParse(formula, out var steps) ? steps.Aggregate(1m, (left, step) => left * (1m - (step / 100m))) : 1m;
private static Group GroupOf(List<Group> groups, TotalsTax tax)
{
var group = groups.Find(g => g.Tax.TaxCodeId == tax.TaxCodeId && g.Tax.Rate == tax.Rate && g.Tax.Nature == tax.Nature);
if (group is null)
{
group = new Group(tax);
groups.Add(group);
}
return group;
}
private static TotalsSummaryLine Summarize(Group group, TotalsOptions options, ITaxEngine engine)
{
var tax = group.Tax;
var exigibility = tax.Rate == 0m ? tax.Exigibility
: options.SplitPayment ? TaxExigibility.SplitPayment
: options.Exigibility ?? tax.Exigibility;
var grossTaxable = group.Gross == 0m ? 0m : engine.Round(group.Gross * 100m / (100m + tax.Rate));
var taxable = grossTaxable + group.Net;
var amount = group.Gross - grossTaxable + engine.ComputeTax(group.Net, tax.Rate);
return new TotalsSummaryLine(tax with { Exigibility = exigibility }, taxable, amount, engine.Round(amount * tax.NonDeductiblePercent / 100m));
}
private sealed class Group(TotalsTax tax)
{
public TotalsTax Tax { get; } = tax;
public decimal Net { get; set; }
public decimal Gross { get; set; }
}
}
@@ -0,0 +1,110 @@
namespace Khaemhat.Application.Documents;
/// <summary>An installment of payment terms.</summary>
/// <param name="Days">Days from the document date.</param>
/// <param name="EndOfMonth">Move to the end of that month.</param>
/// <param name="FixedDay">A fixed day: of the next month after the end-of-month move, else the next such day.</param>
/// <param name="Percent">The share of the amount, percent.</param>
public sealed record InstallmentRule(int Days, bool EndOfMonth, int? FixedDay, decimal Percent);
/// <summary>Months without due dates (mesi esclusi): a due date in them moves to a day of the next month.</summary>
/// <param name="First">The first month (1-12).</param>
/// <param name="Second">The second month.</param>
/// <param name="Day">The day of the next month.</param>
public sealed record ExcludedMonths(int? First, int? Second, int Day = 10)
{
/// <summary>Whether a month is excluded.</summary>
/// <param name="month">The month.</param>
/// <returns>Whether it is.</returns>
public bool Contains(int month) => First == month || Second == month;
}
/// <summary>A computed installment.</summary>
/// <param name="Number">The order, from 1.</param>
/// <param name="DueDate">The due date.</param>
/// <param name="Amount">The amount.</param>
public sealed record InstallmentDue(int Number, DateOnly DueDate, decimal Amount);
/// <summary>
/// The installments of a document from its payment terms (SPEC §11.3, issue #48): days, end of month, fixed day,
/// excluded months, percentages, all the VAT on the first installment; the rounding goes on the last one.
/// </summary>
public static class InstallmentGenerator
{
/// <summary>Computes the installments.</summary>
/// <param name="date">The document date.</param>
/// <param name="amount">The amount to pay.</param>
/// <param name="tax">The VAT included in <paramref name="amount"/> (for <paramref name="vatOnFirst"/>).</param>
/// <param name="rules">The installments of the terms; none means one installment on the document date.</param>
/// <param name="vatOnFirst">All the VAT is paid with the first installment.</param>
/// <param name="excluded">The months without due dates.</param>
/// <param name="round">Rounding to the cent.</param>
/// <returns>The installments, empty for a zero amount.</returns>
public static IReadOnlyList<InstallmentDue> Generate(
DateOnly date, decimal amount, decimal tax, IReadOnlyList<InstallmentRule> rules, bool vatOnFirst, ExcludedMonths? excluded, Func<decimal, decimal> round)
{
ArgumentNullException.ThrowIfNull(rules);
ArgumentNullException.ThrowIfNull(round);
if (amount == 0m)
{
return [];
}
if (rules.Count == 0)
{
return [new InstallmentDue(1, Move(date, excluded), amount)];
}
var share = vatOnFirst && rules.Count > 1 ? tax : 0m;
var spread = amount - share;
var percents = rules.Sum(r => r.Percent);
var result = new List<InstallmentDue>(rules.Count);
var assigned = 0m;
for (var i = 0; i < rules.Count; i++)
{
var rule = rules[i];
var part = i == rules.Count - 1
? spread - assigned
: round(spread * (percents == 0m ? 1m / rules.Count : rule.Percent / percents));
assigned += part;
result.Add(new InstallmentDue(i + 1, DueDate(date, rule, excluded), part + (i == 0 ? share : 0m)));
}
return result;
}
/// <summary>The due date of an installment.</summary>
/// <param name="date">The document date.</param>
/// <param name="rule">The installment.</param>
/// <param name="excluded">The months without due dates.</param>
/// <returns>The due date.</returns>
public static DateOnly DueDate(DateOnly date, InstallmentRule rule, ExcludedMonths? excluded)
{
ArgumentNullException.ThrowIfNull(rule);
var due = date.AddDays(rule.Days);
if (rule.EndOfMonth)
{
due = new DateOnly(due.Year, due.Month, DateTime.DaysInMonth(due.Year, due.Month));
}
if (rule.FixedDay is { } day and >= 1 and <= 31)
{
due = rule.EndOfMonth || due.Day > day ? Day(due.AddMonths(1), day) : Day(due, day);
}
return Move(due, excluded);
}
private static DateOnly Move(DateOnly due, ExcludedMonths? excluded)
{
for (var guard = 0; excluded is not null && excluded.Contains(due.Month) && guard < 12; guard++)
{
due = Day(due.AddMonths(1), excluded.Day);
}
return due;
}
private static DateOnly Day(DateOnly month, int day) =>
new(month.Year, month.Month, Math.Min(day, DateTime.DaysInMonth(month.Year, month.Month)));
}
@@ -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));
}
}
@@ -123,6 +123,7 @@ public sealed class BaseTablesSeeder(FiscalYearService years) : ISeeder
Code = d.Code,
Description = d.Description,
Kind = d.Kind,
DocumentKind = d.DocumentKind,
NumeratorId = d.NumeratorCode is { } n && numerators.TryGetValue(n, out var numerator) ? numerator.Id : null,
InventoryReasonId = d.InventoryReasonCode is { } r && reasons.TryGetValue(r, out var reason) ? reason.Id : null,
EInvoiceType = d.EInvoiceType,
@@ -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);
}
}
@@ -0,0 +1,215 @@
using Khaemhat.Application.Documents;
using Khaemhat.Application.Instance;
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.Seeding;
/// <summary>
/// The sales of the demo company (SPEC §14, issue #53): the profile of the company, then a year of documents made the
/// way a user makes them, through the document engine: quotations sent, accepted, refused and expired; orders from
/// quotations and direct, delivered in full or in part; delivery notes still to invoice (for the deferred invoicing);
/// immediate and deferred invoices, a credit note, a pro forma and a few drafts. Dates fall between the first of
/// January and today, in order for each numerator. Runs only when the demo data are asked and the company has no sales
/// documents yet; every document is marked as demo.
/// </summary>
/// <param name="engine">The document engine.</param>
/// <param name="editor">The document editor (party terms, item prices).</param>
/// <param name="copies">The transformations between documents.</param>
/// <param name="profiles">The company profiles.</param>
/// <param name="factory">The units of work.</param>
/// <param name="clock">The clock.</param>
public sealed class DemoSalesSeeder(
DocumentEngine engine, DocumentEditor editor, DocumentCopyService copies, CompanyProfileService profiles, IUnitOfWorkFactory factory, TimeProvider clock)
: ICompanySeeder
{
/// <summary>The fictitious VAT number of the demo company (valid check digit).</summary>
public const string CompanyVatNumber = "03579135793";
private static readonly Actor Seed = Actor.System;
private DocumentEngine Engine { get; } = engine;
private DocumentEditor Editor { get; } = editor;
private DocumentCopyService Copies { get; } = copies;
/// <inheritdoc />
public int Order => 20;
/// <inheritdoc />
public async Task SeedAsync(string companyCode, CompanySeedContext context, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(context);
if (!context.Demo)
{
return;
}
await ProfileAsync(companyCode, cancellationToken).ConfigureAwait(false);
var data = await ReadAsync(companyCode, cancellationToken).ConfigureAwait(false);
if (data is null)
{
return;
}
var today = DateOnly.FromDateTime(TimeZoneInfo.ConvertTime(clock.GetUtcNow(), TimeZoneInfo.Local).DateTime);
await new Run(this, companyCode, data, today, cancellationToken).ExecuteAsync().ConfigureAwait(false);
}
// The letterhead of the demo company, when nobody wrote it yet.
private async Task ProfileAsync(string companyCode, CancellationToken cancellationToken)
{
var profile = await profiles.GetAsync(Seed, companyCode, cancellationToken).ConfigureAwait(false);
if (profile.Id != 0 || !string.IsNullOrEmpty(profile.VatNumber))
{
return;
}
profile.FiscalName = profile.LegalName;
profile.VatNumber = CompanyVatNumber;
profile.TaxCode = CompanyVatNumber;
profile.ReaOffice = "CN";
profile.ReaNumber = "123456";
profile.ShareCapital = 50000m;
profile.Shareholders = "SM";
profile.LiquidationStatus = "LN";
profile.Address = "Via dei Granai";
profile.StreetNumber = "57";
profile.PostalCode = "12100";
profile.City = "Cuneo";
profile.ProvinceCode = "CN";
profile.AddressCountry = "IT";
profile.Phone = "+39 0171 000000";
profile.Email = "info@demo.example";
profile.Pec = "demo@pec.demo.example";
profile.Website = "https://demo.example";
profile.FooterNotes = "Dati dimostrativi: nomi, numeri e conti sono fittizi.";
await profiles.SaveAsync(Seed, companyCode, profile, cancellationToken).ConfigureAwait(false);
}
// The parties and items the documents use; null when the company already has sales or lacks the demo masters.
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<SaleQuotation, long>().CountAsync(Query.For<SaleQuotation>(), cancellationToken).ConfigureAwait(false) > 0
|| await uow.Repository<SaleDocument, long>().CountAsync(Query.For<SaleDocument>(), 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 items = (await uow.Repository<Item, long>().ListAsync(Query.For<Item>().Where(i => i.IsDemo), cancellationToken).ConfigureAwait(false)).Items
.OrderBy(i => i.Id).ToList();
var goods = items.Where(i => i.Kind == ItemKind.Goods).Select(i => i.Id).ToList();
var services = items.Where(i => i.Kind == ItemKind.Service).Select(i => i.Id).ToList();
string[] names = ["Rossi Impianti S.r.l.", "Bianchi & Figli S.n.c.", "Idrotermica Piemonte S.r.l.", "Edilizia Moderna S.p.A.", "Hotel Belvedere S.r.l.", "Esposito Mario"];
return goods.Count >= 12 && services.Count > 0 && names.All(parties.ContainsKey) ? new DemoData(parties, goods, services) : null;
}
private sealed record DemoData(IReadOnlyDictionary<string, long> Parties, IReadOnlyList<long> Goods, IReadOnlyList<long> Services);
// One seeding, with its company and dates.
private sealed class Run(DemoSalesSeeder 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 so that every document falls
// in the current year and the numbering stays in date order.
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;
}
public async Task ExecuteAsync()
{
// Quotations (numerator PRE), in date order.
var q1 = await NewAsync("PRE", "Rossi Impianti S.r.l.", D(5, 10), [(0, 4m), (1, 10m), (2, 24m)], validDays: 30).ConfigureAwait(false);
var q2 = await NewAsync("PRE", "Hotel Belvedere S.r.l.", D(4, 3), [(3, 6m), (4, 6m)], validDays: 30).ConfigureAwait(false);
await NewAsync("PRE", "Edilizia Moderna S.p.A.", D(3, 1), [(5, 20m), (6, 40m)], validDays: 30).ConfigureAwait(false);
var q4 = await NewAsync("PRE", "Bianchi & Figli S.n.c.", D(2, 5), [(7, 12m), (8, 3m)], validDays: 60, service: 8m).ConfigureAwait(false);
await NewAsync("PRE", "Idrotermica Piemonte S.r.l.", D(0, 2), [(9, 2m), (10, 5m)], validDays: 30).ConfigureAwait(false);
await owner.Engine.CloseAsync(Seed, company, q2.Family, q2.Header.Id, cancellationToken).ConfigureAwait(false);
await NewAsync("PRE", "Esposito Mario", today, [(11, 1m)], validDays: 15, confirm: false).ConfigureAwait(false);
// Orders (numerator ORD): from the accepted quotations and direct.
var o1 = await ConfirmAsync(await CopyAsync(q1, "OC", D(5, 20)).ConfigureAwait(false)).ConfigureAwait(false);
var o3 = await NewAsync("OC", "Edilizia Moderna S.p.A.", D(3, 10), [(0, 10m), (2, 30m), (5, 50m)], reference: "ORD-EM-0412").ConfigureAwait(false);
var o2 = await ConfirmAsync(await CopyAsync(q4, "OC", D(2, 12)).ConfigureAwait(false)).ConfigureAwait(false);
await NewAsync("OC", "Hotel Belvedere S.r.l.", D(1, 8), [(3, 4m), (4, 4m), (11, 2m)], reference: "Ristrutturazione bagni").ConfigureAwait(false);
// Delivery notes (numerator DDT): one per order, the second order in two goes; the last three stay to invoice.
var d1 = await ConfirmAsync(await CopyAsync(o1, "DDT", D(4, 2)).ConfigureAwait(false)).ConfigureAwait(false);
var d2 = await ConfirmAsync(await CopyAsync(o3, "DDT", D(3, 15), [o3.Lines[0].Id, o3.Lines[1].Id]).ConfigureAwait(false)).ConfigureAwait(false);
await ConfirmAsync(await CopyAsync(o2, "DDT", D(1, 5)).ConfigureAwait(false)).ConfigureAwait(false);
await ConfirmAsync(await CopyAsync(o3, "DDT", D(1, 12)).ConfigureAwait(false)).ConfigureAwait(false);
await NewAsync("DDT", "Rossi Impianti S.r.l.", D(1, 20), [(6, 15m), (1, 6m)]).ConfigureAwait(false);
// Invoices and notes (numerator FAT, shared), in date order.
await NewAsync("FI", "Bianchi & Figli S.n.c.", D(5, 28), [(2, 12m), (9, 1m)], service: 4m).ConfigureAwait(false);
var f2 = await NewAsync("FI", "Hotel Belvedere S.r.l.", D(4, 10), [(3, 2m), (4, 2m), (10, 3m)]).ConfigureAwait(false);
await ConfirmAsync(await CopyAsync(d1, "FD", D(4, 30)).ConfigureAwait(false)).ConfigureAwait(false);
await ConfirmAsync(await CopyAsync(d2, "FD", D(3, 31)).ConfigureAwait(false)).ConfigureAwait(false);
var note = await CopyAsync(f2, "NC", D(2, 15), [f2.Lines[0].Id]).ConfigureAwait(false);
note.Lines[^1].Quantity = 1m;
note.Header.Notes = "Reso di un articolo difettoso.";
await ConfirmAsync(await owner.Engine.SaveAsync(Seed, company, note, cancellationToken).ConfigureAwait(false)).ConfigureAwait(false);
await NewAsync("FI", "Edilizia Moderna S.p.A.", D(1, 25), [(7, 30m), (8, 10m)], service: 16m).ConfigureAwait(false);
await NewAsync("FI", "Rossi Impianti S.r.l.", D(0, 5), [(0, 2m), (11, 1m)]).ConfigureAwait(false);
await NewAsync("FI", "Idrotermica Piemonte S.r.l.", today, [(5, 8m)], confirm: false).ConfigureAwait(false);
await NewAsync("PF", "Esposito Mario", today, [(9, 1m)], service: 3m).ConfigureAwait(false);
}
// A new document of the customer with goods (index in the demo goods, quantity) and optional hours of work.
private async Task<DocumentRecord> NewAsync(
string type, string customer, DateOnly date, IReadOnlyList<(int Good, decimal Quantity)> lines, int? validDays = null, decimal? service = null,
string? reference = null, bool confirm = true)
{
var record = await owner.Engine.NewAsync(Seed, company, type, cancellationToken).ConfigureAwait(false);
record.Header.IsDemo = true;
record.Header.DocumentDate = date;
record.Header.ExternalReference = reference;
await owner.Editor.ApplyPartyAsync(Seed, company, record, Party(customer), cancellationToken).ConfigureAwait(false);
if (validDays is { } days)
{
record.Header.ValidUntil = date.AddDays(days);
}
foreach (var (good, quantity) in lines)
{
await AddAsync(record, data.Goods[good % data.Goods.Count], quantity).ConfigureAwait(false);
}
if (service is { } hours)
{
await AddAsync(record, data.Services[0], hours).ConfigureAwait(false);
}
record = await owner.Engine.SaveAsync(Seed, company, record, cancellationToken).ConfigureAwait(false);
return confirm ? await ConfirmAsync(record).ConfigureAwait(false) : record;
}
private async Task AddAsync(DocumentRecord record, long itemId, decimal quantity)
{
var line = DocumentStores.Of(record.Family).NewLine();
line.Quantity = quantity;
await owner.Editor.FillLineAsync(Seed, company, record, line, itemId, cancellationToken).ConfigureAwait(false);
record.Lines.Add(line);
}
private Task<DocumentRecord> CopyAsync(DocumentRecord source, string type, DateOnly date, IReadOnlyCollection<long>? lines = null) =>
owner.Copies.MergeAsync(Seed, company, source.Family, [source.Header.Id], type, date, lines, cancellationToken);
private Task<DocumentRecord> ConfirmAsync(DocumentRecord record) =>
owner.Engine.ConfirmAsync(Seed, company, record.Family, record.Header.Id, cancellationToken);
}
}
@@ -66,6 +66,9 @@ public sealed partial class TableCatalog
/// <summary>Error: another price list is already the base one.</summary>
public const string BaseDuplicate = "tables.price-list.base-duplicate";
/// <summary>A document type without a kind.</summary>
public const string DocumentKindRequired = "tables.document-type.kind-required";
/// <summary>The maximum depth of item categories.</summary>
public const int MaxCategoryLevel = 3;
@@ -303,6 +306,11 @@ public sealed partial class TableCatalog
.Field("einvoice", x => x.EInvoiceType)
.Rule(async (x, c, ct) =>
{
if (x.DocumentKind is null)
{
c.Error(nameof(DocumentType.DocumentKind), DocumentKindRequired);
}
if (!string.IsNullOrWhiteSpace(x.EInvoiceType))
{
x.EInvoiceType = x.EInvoiceType.Trim().ToUpperInvariant();
@@ -0,0 +1,113 @@
namespace Khaemhat.Core.Documents;
/// <summary>How the documents of a kind behave (ADR 0032).</summary>
/// <param name="Kind">The kind.</param>
/// <param name="Family">The tables that hold them.</param>
/// <param name="Direction">Customer, supplier or internal.</param>
/// <param name="Lifecycle">The states they go through.</param>
/// <param name="Effects">What confirming them does.</param>
/// <param name="Lines">The line kinds they accept.</param>
/// <param name="Sources">The kinds whose lines they fulfil (order to delivery note, delivery note to invoice...).</param>
/// <param name="ReadPermission">The permission to see them.</param>
/// <param name="WritePermission">The permission to create and change drafts.</param>
/// <param name="ConfirmPermission">The permission to confirm or issue, cancel, close and reopen.</param>
/// <param name="DeletePermission">The permission to delete drafts.</param>
public sealed record DocumentBehavior(
DocumentKind Kind,
DocumentFamily Family,
DocumentDirection Direction,
DocumentLifecycle Lifecycle,
DocumentEffects Effects,
IReadOnlyList<DocumentLineKind> Lines,
IReadOnlyList<DocumentKind> Sources,
string ReadPermission,
string WritePermission,
string ConfirmPermission,
string DeletePermission)
{
/// <summary>Whether the documents need a customer or supplier.</summary>
public bool NeedsParty => Direction != DocumentDirection.Internal;
/// <summary>Whether the documents have the given effect.</summary>
/// <param name="effect">The effect.</param>
/// <returns>Whether they have it.</returns>
public bool Has(DocumentEffects effect) => (Effects & effect) == effect;
/// <summary>Whether the documents fulfil the lines of documents of another kind.</summary>
/// <param name="source">The kind of the source.</param>
/// <returns>Whether a copy from it creates fulfilment links.</returns>
public bool Fulfils(DocumentKind source) => Sources.Contains(source);
}
/// <summary>The behaviour of every <see cref="DocumentKind"/>.</summary>
public static class DocumentBehaviors
{
private static readonly DocumentLineKind[] Commercial =
[DocumentLineKind.Item, DocumentLineKind.Free, DocumentLineKind.Description, DocumentLineKind.Expense, DocumentLineKind.Discount];
private static readonly DocumentLineKind[] Goods = [DocumentLineKind.Item, DocumentLineKind.Free, DocumentLineKind.Description];
private static readonly DocumentLineKind[] Stock = [DocumentLineKind.Item, DocumentLineKind.Description];
private static readonly DocumentKind[] SaleInvoices =
[
DocumentKind.ImmediateInvoice, DocumentKind.AccompanyingInvoice, DocumentKind.DeferredInvoice, DocumentKind.DownPaymentInvoice,
DocumentKind.Fee,
];
private static readonly Dictionary<DocumentKind, DocumentBehavior> ByKind = Build().ToDictionary(b => b.Kind);
/// <summary>Every behaviour, in the order of <see cref="DocumentKind"/>.</summary>
public static IReadOnlyList<DocumentBehavior> All { get; } = [.. ByKind.Values.OrderBy(b => b.Kind)];
/// <summary>The behaviour of a kind.</summary>
/// <param name="kind">The kind.</param>
/// <returns>The behaviour.</returns>
public static DocumentBehavior Of(DocumentKind kind) =>
ByKind.TryGetValue(kind, out var behavior) ? behavior : throw new ArgumentOutOfRangeException(nameof(kind), kind, "Unknown document kind.");
/// <summary>The kinds kept in a family.</summary>
/// <param name="family">The family.</param>
/// <returns>The kinds.</returns>
public static IReadOnlyList<DocumentKind> KindsOf(DocumentFamily family) => [.. All.Where(b => b.Family == family).Select(b => b.Kind)];
private static IEnumerable<DocumentBehavior> Build()
{
const DocumentEffects Invoice = DocumentEffects.Ledger | DocumentEffects.Installments | DocumentEffects.EInvoice;
var quote = Permissions("sales.quote");
var order = Permissions("sales.order");
var delivery = Permissions("sales.delivery");
var invoice = new Perms("sales.invoice.read", "sales.invoice.write", "sales.invoice.issue", "sales.invoice.delete");
var proForma = new Perms("sales.invoice.read", "sales.invoice.write", "sales.invoice.write", "sales.invoice.delete");
var purchaseOrder = Permissions("purchases.order");
var purchaseInvoice = Permissions("purchases.invoice");
var entry = new Perms("inventory.entry.read", "inventory.entry.write", "inventory.entry.post", "inventory.entry.write");
yield return Make(DocumentKind.Quotation, DocumentFamily.SaleQuotation, DocumentDirection.Sale, DocumentLifecycle.Order, DocumentEffects.None, Commercial, [], quote);
yield return Make(DocumentKind.SalesOrder, DocumentFamily.SaleOrder, DocumentDirection.Sale, DocumentLifecycle.Order, DocumentEffects.Commitment, Commercial, [DocumentKind.Quotation], order);
yield return Make(DocumentKind.DeliveryNote, DocumentFamily.SaleDocument, DocumentDirection.Sale, DocumentLifecycle.Order, DocumentEffects.Inventory, Goods, [DocumentKind.SalesOrder], delivery);
yield return Make(DocumentKind.ImmediateInvoice, DocumentFamily.SaleDocument, DocumentDirection.Sale, DocumentLifecycle.Invoice, Invoice, Commercial, [DocumentKind.SalesOrder, DocumentKind.ProForma], invoice);
yield return Make(DocumentKind.AccompanyingInvoice, DocumentFamily.SaleDocument, DocumentDirection.Sale, DocumentLifecycle.Invoice, Invoice | DocumentEffects.Inventory, Commercial, [DocumentKind.SalesOrder, DocumentKind.ProForma], invoice);
yield return Make(DocumentKind.DeferredInvoice, DocumentFamily.SaleDocument, DocumentDirection.Sale, DocumentLifecycle.Invoice, Invoice, Commercial, [DocumentKind.DeliveryNote], invoice);
yield return Make(DocumentKind.DownPaymentInvoice, DocumentFamily.SaleDocument, DocumentDirection.Sale, DocumentLifecycle.Invoice, Invoice, Commercial, [DocumentKind.SalesOrder], invoice);
yield return Make(DocumentKind.CreditNote, DocumentFamily.SaleDocument, DocumentDirection.Sale, DocumentLifecycle.Invoice, Invoice, Commercial, SaleInvoices, invoice);
yield return Make(DocumentKind.DebitNote, DocumentFamily.SaleDocument, DocumentDirection.Sale, DocumentLifecycle.Invoice, Invoice, Commercial, SaleInvoices, invoice);
yield return Make(DocumentKind.Fee, DocumentFamily.SaleDocument, DocumentDirection.Sale, DocumentLifecycle.Invoice, Invoice, Commercial, [DocumentKind.SalesOrder, DocumentKind.ProForma], invoice);
yield return Make(DocumentKind.ProForma, DocumentFamily.SaleDocument, DocumentDirection.Sale, DocumentLifecycle.Order, DocumentEffects.None, Commercial, [DocumentKind.SalesOrder], proForma);
yield return Make(DocumentKind.SelfInvoice, DocumentFamily.SaleDocument, DocumentDirection.Purchase, DocumentLifecycle.Invoice, DocumentEffects.Ledger | DocumentEffects.EInvoice, Commercial, [DocumentKind.PurchaseInvoice], purchaseInvoice);
yield return Make(DocumentKind.PurchaseOrder, DocumentFamily.PurchaseOrder, DocumentDirection.Purchase, DocumentLifecycle.Order, DocumentEffects.Ordered, Commercial, [], purchaseOrder);
yield return Make(DocumentKind.PurchaseDeliveryNote, DocumentFamily.PurchaseDocument, DocumentDirection.Purchase, DocumentLifecycle.Order, DocumentEffects.Inventory, Goods, [DocumentKind.PurchaseOrder], entry);
yield return Make(DocumentKind.PurchaseInvoice, DocumentFamily.PurchaseDocument, DocumentDirection.Purchase, DocumentLifecycle.Simple, DocumentEffects.Ledger | DocumentEffects.Installments, Commercial, [DocumentKind.PurchaseOrder, DocumentKind.PurchaseDeliveryNote], purchaseInvoice);
yield return Make(DocumentKind.PurchaseCreditNote, DocumentFamily.PurchaseDocument, DocumentDirection.Purchase, DocumentLifecycle.Simple, DocumentEffects.Ledger | DocumentEffects.Installments, Commercial, [DocumentKind.PurchaseInvoice], purchaseInvoice);
yield return Make(DocumentKind.InventoryEntry, DocumentFamily.InventoryDocument, DocumentDirection.Internal, DocumentLifecycle.Simple, DocumentEffects.Inventory, Stock, [], entry);
}
private static Perms Permissions(string area) => new(area + ".read", area + ".write", area + ".write", area + ".write");
private static DocumentBehavior Make(
DocumentKind kind, DocumentFamily family, DocumentDirection direction, DocumentLifecycle lifecycle, DocumentEffects effects,
DocumentLineKind[] lines, DocumentKind[] sources, Perms perms) =>
new(kind, family, direction, lifecycle, effects, lines, sources, perms.Read, perms.Write, perms.Confirm, perms.Delete);
private sealed record Perms(string Read, string Write, string Confirm, string Delete);
}
@@ -0,0 +1,248 @@
namespace Khaemhat.Core.Documents;
/// <summary>The family of a document: the pair of tables that holds it (SPEC §11.3).</summary>
public enum DocumentFamily
{
/// <summary>Quotations (<c>sale_quotations</c>).</summary>
SaleQuotation = 0,
/// <summary>Customer orders (<c>sale_orders</c>).</summary>
SaleOrder = 1,
/// <summary>Delivery notes, invoices, credit and debit notes, pro forma, fees, self-invoices (<c>sale_documents</c>).</summary>
SaleDocument = 2,
/// <summary>Supplier orders (<c>purchase_orders</c>).</summary>
PurchaseOrder = 3,
/// <summary>Supplier delivery notes, invoices and credit notes (<c>purchase_documents</c>).</summary>
PurchaseDocument = 4,
/// <summary>Warehouse entries (<c>inventory_documents</c>).</summary>
InventoryDocument = 5,
}
/// <summary>Who the document is with.</summary>
public enum DocumentDirection
{
/// <summary>A customer: the company sells.</summary>
Sale = 0,
/// <summary>A supplier: the company buys.</summary>
Purchase = 1,
/// <summary>Nobody: an internal document.</summary>
Internal = 2,
}
/// <summary>
/// What a document is, which decides how it behaves (ADR 0032). A document type of the company chooses a kind and adds
/// its numerator, reasons and templates.
/// </summary>
public enum DocumentKind
{
/// <summary>A quotation to a customer.</summary>
Quotation = 0,
/// <summary>A customer order.</summary>
SalesOrder = 1,
/// <summary>A delivery note (DDT) to a customer.</summary>
DeliveryNote = 2,
/// <summary>An immediate invoice.</summary>
ImmediateInvoice = 3,
/// <summary>An accompanying invoice: an invoice that is also the delivery note.</summary>
AccompanyingInvoice = 4,
/// <summary>A deferred invoice of one or more delivery notes.</summary>
DeferredInvoice = 5,
/// <summary>A down payment invoice.</summary>
DownPaymentInvoice = 6,
/// <summary>A credit note to a customer.</summary>
CreditNote = 7,
/// <summary>A debit note to a customer.</summary>
DebitNote = 8,
/// <summary>A professional fee invoice (parcella).</summary>
Fee = 9,
/// <summary>A pro forma invoice, without fiscal effects.</summary>
ProForma = 10,
/// <summary>A self-invoice or integration of a purchase (reverse charge, purchases from abroad).</summary>
SelfInvoice = 11,
/// <summary>An order to a supplier.</summary>
PurchaseOrder = 12,
/// <summary>A delivery note of a supplier (goods received).</summary>
PurchaseDeliveryNote = 13,
/// <summary>An invoice of a supplier.</summary>
PurchaseInvoice = 14,
/// <summary>A credit note of a supplier.</summary>
PurchaseCreditNote = 15,
/// <summary>A warehouse entry: loads, unloads, transfers.</summary>
InventoryEntry = 16,
}
/// <summary>The life cycle a document follows (ADR 0032).</summary>
public enum DocumentLifecycle
{
/// <summary>Draft, confirmed, partially fulfilled, fulfilled, closed, cancelled: quotations, orders, delivery notes, pro forma.</summary>
Order = 0,
/// <summary>Draft, issued, then the states of the exchange system: sale invoices and self-invoices.</summary>
Invoice = 1,
/// <summary>Draft, confirmed, cancelled: supplier invoices, warehouse entries.</summary>
Simple = 2,
}
/// <summary>The state of a document (SPEC §11.3).</summary>
public enum DocumentStatus
{
/// <summary>Being written: no number, no effects.</summary>
Draft = 0,
/// <summary>Confirmed: numbered, effects applied.</summary>
Confirmed = 1,
/// <summary>Some lines fulfilled by later documents.</summary>
PartiallyFulfilled = 2,
/// <summary>Every line fulfilled.</summary>
Fulfilled = 3,
/// <summary>Closed by hand: what is left will not be fulfilled.</summary>
Closed = 4,
/// <summary>Cancelled: the number stays, the effects are removed.</summary>
Cancelled = 5,
/// <summary>An invoice issued: numbered and no longer changeable.</summary>
Issued = 6,
/// <summary>The electronic invoice file has been generated.</summary>
SdiGenerated = 7,
/// <summary>The electronic invoice has been sent to the exchange system.</summary>
SdiSent = 8,
/// <summary>The exchange system delivered the invoice.</summary>
SdiDelivered = 9,
/// <summary>The exchange system rejected the invoice.</summary>
SdiRejected = 10,
/// <summary>The exchange system could not deliver the invoice (made available to the customer).</summary>
SdiNotDelivered = 11,
}
/// <summary>What a user or a procedure can do with a document; the state machine says when.</summary>
public enum DocumentAction
{
/// <summary>Change the header or the lines.</summary>
Edit = 0,
/// <summary>Delete a draft that was never numbered.</summary>
Delete = 1,
/// <summary>Confirm: number and apply the effects (orders, delivery notes, simple documents).</summary>
Confirm = 2,
/// <summary>Issue an invoice: number it and make it unchangeable.</summary>
Issue = 3,
/// <summary>Cancel: keep the number, remove the effects.</summary>
Cancel = 4,
/// <summary>Close what is left to fulfil.</summary>
Close = 5,
/// <summary>Reopen a closed document.</summary>
Reopen = 6,
/// <summary>Make a new draft from the document (duplicate or transform).</summary>
Copy = 7,
/// <summary>Record that the electronic invoice file was generated.</summary>
GenerateXml = 8,
/// <summary>Record that the electronic invoice was sent.</summary>
Send = 9,
/// <summary>Record the delivery receipt.</summary>
MarkDelivered = 10,
/// <summary>Record the rejection.</summary>
MarkRejected = 11,
/// <summary>Record that the invoice could not be delivered.</summary>
MarkNotDelivered = 12,
}
/// <summary>What confirming a document does to the rest of the company's data (applied by the modules: M6, M7, M8).</summary>
[Flags]
public enum DocumentEffects
{
/// <summary>No effect.</summary>
None = 0,
/// <summary>Moves stock (load or unload by the warehouse reason).</summary>
Inventory = 1,
/// <summary>Commits stock to customers (orders).</summary>
Commitment = 2,
/// <summary>Records quantities ordered from suppliers.</summary>
Ordered = 4,
/// <summary>Posts to the general ledger and the VAT registers.</summary>
Ledger = 8,
/// <summary>Generates the installments of the payment schedule.</summary>
Installments = 16,
/// <summary>Produces an electronic invoice.</summary>
EInvoice = 32,
}
/// <summary>The kind of a document line.</summary>
public enum DocumentLineKind
{
/// <summary>An item of the catalogue, with quantity and price.</summary>
Item = 0,
/// <summary>A line with quantity and price but no item.</summary>
Free = 1,
/// <summary>Text only.</summary>
Description = 2,
/// <summary>An ancillary expense (transport, collection).</summary>
Expense = 3,
/// <summary>A discount, premium or allowance.</summary>
Discount = 4,
}
/// <summary>Who carries the goods (delivery note: trasporto a cura del).</summary>
public enum TransportResponsibility
{
/// <summary>The sender (mittente).</summary>
Sender = 0,
/// <summary>The recipient (destinatario).</summary>
Recipient = 1,
/// <summary>A carrier (vettore).</summary>
Carrier = 2,
}
@@ -0,0 +1,157 @@
namespace Khaemhat.Core.Documents;
/// <summary>
/// The states of the three life cycles and the actions each state admits (SPEC §11.3, ADR 0032). The fulfilment states
/// are not reached by actions: <see cref="FulfillmentCalculator"/> computes them.
/// </summary>
public static class DocumentStateMachine
{
private static readonly Dictionary<(DocumentLifecycle, DocumentStatus), Dictionary<DocumentAction, DocumentStatus>> Rules = Build();
/// <summary>The states a life cycle uses, in order.</summary>
/// <param name="lifecycle">The life cycle.</param>
/// <returns>The states.</returns>
public static IReadOnlyList<DocumentStatus> States(DocumentLifecycle lifecycle) =>
[.. Rules.Keys.Where(k => k.Item1 == lifecycle).Select(k => k.Item2).OrderBy(s => s)];
/// <summary>The actions a state admits.</summary>
/// <param name="lifecycle">The life cycle.</param>
/// <param name="status">The state.</param>
/// <returns>The actions, in the order of <see cref="DocumentAction"/>.</returns>
public static IReadOnlyList<DocumentAction> Actions(DocumentLifecycle lifecycle, DocumentStatus status) =>
Rules.TryGetValue((lifecycle, status), out var actions) ? [.. actions.Keys.OrderBy(a => a)] : [];
/// <summary>Whether a state admits an action.</summary>
/// <param name="lifecycle">The life cycle.</param>
/// <param name="status">The state.</param>
/// <param name="action">The action.</param>
/// <returns>Whether it is admitted.</returns>
public static bool Allows(DocumentLifecycle lifecycle, DocumentStatus status, DocumentAction action) =>
Rules.TryGetValue((lifecycle, status), out var actions) && actions.ContainsKey(action);
/// <summary>The state after an action.</summary>
/// <param name="lifecycle">The life cycle.</param>
/// <param name="status">The state.</param>
/// <param name="action">The action.</param>
/// <returns>The new state (the same one for actions that do not move it, such as edit and copy).</returns>
/// <exception cref="InvalidDocumentActionException">The state does not admit the action.</exception>
public static DocumentStatus Apply(DocumentLifecycle lifecycle, DocumentStatus status, DocumentAction action) =>
Rules.TryGetValue((lifecycle, status), out var actions) && actions.TryGetValue(action, out var next)
? next
: throw new InvalidDocumentActionException(lifecycle, status, action);
/// <summary>Whether the header and lines can change in a state.</summary>
/// <param name="lifecycle">The life cycle.</param>
/// <param name="status">The state.</param>
/// <returns>Whether they can.</returns>
public static bool IsEditable(DocumentLifecycle lifecycle, DocumentStatus status) => Allows(lifecycle, status, DocumentAction.Edit);
/// <summary>Whether a document in this state counts: confirmed or issued, and not cancelled.</summary>
/// <param name="status">The state.</param>
/// <returns>Whether its effects and links are in force.</returns>
public static bool IsInForce(DocumentStatus status) => status is not (DocumentStatus.Draft or DocumentStatus.Cancelled);
/// <summary>
/// The state of a document after its lines were fulfilled: only confirmed, partially fulfilled and fulfilled
/// documents of the order life cycle move; the others keep their state.
/// </summary>
/// <param name="lifecycle">The life cycle.</param>
/// <param name="status">The state.</param>
/// <param name="fulfillment">What the lines say.</param>
/// <returns>The new state.</returns>
public static DocumentStatus AfterFulfillment(DocumentLifecycle lifecycle, DocumentStatus status, FulfillmentState fulfillment) =>
lifecycle == DocumentLifecycle.Order && status is DocumentStatus.Confirmed or DocumentStatus.PartiallyFulfilled or DocumentStatus.Fulfilled
? fulfillment switch
{
FulfillmentState.Fulfilled => DocumentStatus.Fulfilled,
FulfillmentState.Partial => DocumentStatus.PartiallyFulfilled,
_ => DocumentStatus.Confirmed,
}
: status;
private static Dictionary<(DocumentLifecycle, DocumentStatus), Dictionary<DocumentAction, DocumentStatus>> Build()
{
var rules = new Dictionary<(DocumentLifecycle, DocumentStatus), Dictionary<DocumentAction, DocumentStatus>>();
void Add(DocumentLifecycle lifecycle, DocumentStatus status, params (DocumentAction Action, DocumentStatus? Next)[] actions) =>
rules[(lifecycle, status)] = actions.ToDictionary(a => a.Action, a => a.Next ?? status);
const DocumentAction Copy = DocumentAction.Copy;
const DocumentAction Edit = DocumentAction.Edit;
// Orders, quotations, delivery notes, pro forma: changeable until something is fulfilled.
Add(DocumentLifecycle.Order, DocumentStatus.Draft, (Edit, null), (DocumentAction.Delete, null), (DocumentAction.Confirm, DocumentStatus.Confirmed), (Copy, null));
Add(DocumentLifecycle.Order, DocumentStatus.Confirmed, (Edit, null), (Copy, null), (DocumentAction.Cancel, DocumentStatus.Cancelled), (DocumentAction.Close, DocumentStatus.Closed));
Add(DocumentLifecycle.Order, DocumentStatus.PartiallyFulfilled, (Edit, null), (Copy, null), (DocumentAction.Close, DocumentStatus.Closed));
Add(DocumentLifecycle.Order, DocumentStatus.Fulfilled, (Copy, null), (DocumentAction.Close, DocumentStatus.Closed));
Add(DocumentLifecycle.Order, DocumentStatus.Closed, (Copy, null), (DocumentAction.Reopen, DocumentStatus.Confirmed));
Add(DocumentLifecycle.Order, DocumentStatus.Cancelled, (Copy, null));
// Invoices: unchangeable once issued; cancelled (with a reason) only while the file has not reached the
// exchange system or after a rejection, otherwise a credit note.
Add(DocumentLifecycle.Invoice, DocumentStatus.Draft, (Edit, null), (DocumentAction.Delete, null), (DocumentAction.Issue, DocumentStatus.Issued), (Copy, null));
Add(DocumentLifecycle.Invoice, DocumentStatus.Issued, (Copy, null), (DocumentAction.GenerateXml, DocumentStatus.SdiGenerated), (DocumentAction.Cancel, DocumentStatus.Cancelled));
Add(DocumentLifecycle.Invoice, DocumentStatus.SdiGenerated, (Copy, null), (DocumentAction.GenerateXml, null), (DocumentAction.Send, DocumentStatus.SdiSent), (DocumentAction.Cancel, DocumentStatus.Cancelled));
Add(DocumentLifecycle.Invoice, DocumentStatus.SdiSent, (Copy, null), (DocumentAction.MarkDelivered, DocumentStatus.SdiDelivered),
(DocumentAction.MarkRejected, DocumentStatus.SdiRejected), (DocumentAction.MarkNotDelivered, DocumentStatus.SdiNotDelivered));
Add(DocumentLifecycle.Invoice, DocumentStatus.SdiRejected, (Copy, null), (DocumentAction.GenerateXml, DocumentStatus.SdiGenerated), (DocumentAction.Cancel, DocumentStatus.Cancelled));
Add(DocumentLifecycle.Invoice, DocumentStatus.SdiDelivered, (Copy, null));
Add(DocumentLifecycle.Invoice, DocumentStatus.SdiNotDelivered, (Copy, null));
Add(DocumentLifecycle.Invoice, DocumentStatus.Cancelled, (Copy, null));
// Supplier invoices and warehouse entries.
Add(DocumentLifecycle.Simple, DocumentStatus.Draft, (Edit, null), (DocumentAction.Delete, null), (DocumentAction.Confirm, DocumentStatus.Confirmed), (Copy, null));
Add(DocumentLifecycle.Simple, DocumentStatus.Confirmed, (Copy, null), (DocumentAction.Cancel, DocumentStatus.Cancelled));
Add(DocumentLifecycle.Simple, DocumentStatus.Cancelled, (Copy, null));
return rules;
}
}
/// <summary>An action the state of the document does not admit.</summary>
public sealed class InvalidDocumentActionException : InvalidOperationException
{
/// <summary>The error code for the interface.</summary>
public const string Code = "document.action.not-allowed";
/// <summary>Creates the exception.</summary>
public InvalidDocumentActionException()
: base(Code)
{
}
/// <summary>Creates the exception.</summary>
/// <param name="message">The message.</param>
public InvalidDocumentActionException(string message)
: base(message)
{
}
/// <summary>Creates the exception.</summary>
/// <param name="message">The message.</param>
/// <param name="innerException">The cause.</param>
public InvalidDocumentActionException(string message, Exception innerException)
: base(message, innerException)
{
}
/// <summary>Creates the exception.</summary>
/// <param name="lifecycle">The life cycle.</param>
/// <param name="status">The state.</param>
/// <param name="action">The refused action.</param>
public InvalidDocumentActionException(DocumentLifecycle lifecycle, DocumentStatus status, DocumentAction action)
: base($"A {lifecycle} document in state {status} does not admit {action}.")
{
Lifecycle = lifecycle;
Status = status;
Action = action;
}
/// <summary>The life cycle.</summary>
public DocumentLifecycle Lifecycle { get; }
/// <summary>The state.</summary>
public DocumentStatus Status { get; }
/// <summary>The refused action.</summary>
public DocumentAction Action { get; }
}
+467
View File
@@ -0,0 +1,467 @@
using Khaemhat.Core.Entities;
using Khaemhat.Core.Items;
using Khaemhat.Core.Tax;
namespace Khaemhat.Core.Documents;
/// <summary>
/// The header of a document (SPEC §11.3): the same columns in the six families of tables. The totals are written by the
/// totals calculator (#48); the flags by printing, sending, posting and the electronic invoice.
/// </summary>
public abstract class DocumentHeader : Entity<long>, IDemoMarkable
{
/// <summary>The document type of the company.</summary>
public long DocumentTypeId { get; set; }
/// <summary>The kind, copied from the type when the document is created.</summary>
public DocumentKind Kind { get; set; }
/// <summary>The state.</summary>
public DocumentStatus Status { get; set; }
/// <summary>The numerator row (code and year) that gave the number.</summary>
public long? NumeratorId { get; set; }
/// <summary>The section (sezionale) of the numerator.</summary>
public string? Section { get; set; }
/// <summary>The progressive number; empty until confirmation.</summary>
public long? Number { get; set; }
/// <summary>The number as printed, such as <c>12/2026</c>.</summary>
public string? DocumentNumber { get; set; }
/// <summary>The date of the document.</summary>
public DateOnly DocumentDate { get; set; }
/// <summary>The year of the numbering.</summary>
public int Year { get; set; }
/// <summary>The customer or supplier.</summary>
public long? PartyId { get; set; }
/// <summary>The destination (an address of the party).</summary>
public long? DestinationId { get; set; }
/// <summary>The reference of the other side: customer order number, supplier invoice or delivery note number.</summary>
public string? ExternalReference { get; set; }
/// <summary>The date of the reference.</summary>
public DateOnly? ExternalDate { get; set; }
/// <summary>The currency.</summary>
public string CurrencyCode { get; set; } = "EUR";
/// <summary>The exchange rate to euro.</summary>
public decimal ExchangeRate { get; set; } = 1m;
/// <summary>The price list.</summary>
public long? PriceListId { get; set; }
/// <summary>The payment terms.</summary>
public long? PaymentTermId { get; set; }
/// <summary>The payment method.</summary>
public long? PaymentMethodId { get; set; }
/// <summary>The bank account of the company that collects or pays.</summary>
public long? BankAccountId { get; set; }
/// <summary>The agent.</summary>
public long? SalespersonId { get; set; }
/// <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; }
/// <summary>The reason of the transport.</summary>
public long? TransportReasonId { get; set; }
/// <summary>The shipping terms (porto).</summary>
public long? ShippingTermId { get; set; }
/// <summary>The carrier.</summary>
public long? CarrierId { get; set; }
/// <summary>The appearance of the goods.</summary>
public long? GoodsAppearanceId { get; set; }
/// <summary>The number of packages.</summary>
public int? Packages { get; set; }
/// <summary>The gross weight in kg.</summary>
public decimal? GrossWeight { get; set; }
/// <summary>The net weight in kg.</summary>
public decimal? NetWeight { get; set; }
/// <summary>When the transport starts.</summary>
public DateTime? TransportStart { get; set; }
/// <summary>Until when a quotation is valid.</summary>
public DateOnly? ValidUntil { get; set; }
/// <summary>The delivery date requested or promised.</summary>
public DateOnly? DeliveryDate { get; set; }
/// <summary>The revision of a quotation.</summary>
public int Revision { get; set; }
/// <summary>Printed at least once.</summary>
public bool Printed { get; set; }
/// <summary>Sent by e-mail at least once.</summary>
public bool Sent { get; set; }
/// <summary>Posted to the ledger.</summary>
public bool Posted { get; set; }
/// <summary>Installments generated in the payment schedule.</summary>
public bool InstallmentsGenerated { get; set; }
/// <summary>Electronic invoice file generated.</summary>
public bool XmlGenerated { get; set; }
/// <summary>The taxable amount.</summary>
public decimal TaxableAmount { get; set; }
/// <summary>The tax.</summary>
public decimal TaxAmount { get; set; }
/// <summary>The total of the document.</summary>
public decimal TotalAmount { get; set; }
/// <summary>The discount on the total (percent formula, such as <c>5</c> or <c>10+5</c>).</summary>
public string? FooterDiscount { get; set; }
/// <summary>The ancillary expenses.</summary>
public decimal ExpensesAmount { get; set; }
/// <summary>The stamp duty.</summary>
public decimal StampDuty { get; set; }
/// <summary>The withholding tax.</summary>
public decimal WithholdingAmount { get; set; }
/// <summary>The social security contribution (cassa previdenza).</summary>
public decimal SocialSecurityAmount { get; set; }
/// <summary>The amount to pay.</summary>
public decimal NetAmount { get; set; }
/// <summary>The prices of the lines include VAT: the taxable amount is computed back from them.</summary>
public bool PricesIncludeTax { get; set; }
/// <summary>The amount taken off the lines by <see cref="FooterDiscount"/>.</summary>
public decimal FooterDiscountAmount { get; set; }
/// <summary>When the VAT of the document becomes due, when not the one of its tax codes (split payment, cash basis).</summary>
public TaxExigibility? Exigibility { get; set; }
/// <summary>Split payment: the public administration pays the VAT to the State, not to the company.</summary>
public bool SplitPayment { get; set; }
/// <summary>The stamp duty is charged to the customer (added to the total).</summary>
public bool StampDutyCharged { get; set; }
/// <summary>The withholding tax rate, percent; none when the document has no withholding.</summary>
public decimal? WithholdingRate { get; set; }
/// <summary>The share of the amount the withholding is computed on, percent (100 for fees, 50 or 20 for agents).</summary>
public decimal WithholdingBasePercent { get; set; } = 100m;
/// <summary>The withholding type of the e-invoice, such as <c>RT01</c>.</summary>
public string? WithholdingType { get; set; }
/// <summary>The payment reason of the withholding (e-invoice), such as <c>A</c>.</summary>
public string? WithholdingReason { get; set; }
/// <summary>The social security fund (cassa previdenza) of the e-invoice, such as <c>TC22</c>.</summary>
public string? SocialSecurityFund { get; set; }
/// <summary>The contribution rate of the fund, percent.</summary>
public decimal? SocialSecurityRate { get; set; }
/// <summary>The VAT code of the contribution; the one of the first line when empty.</summary>
public long? SocialSecurityTaxCodeId { get; set; }
/// <summary>The contribution is subject to the withholding tax (INPS 4%).</summary>
public bool SocialSecurityWithheld { get; set; }
/// <summary>The ENASARCO rate withheld from the commissions of an agent, percent.</summary>
public decimal? EnasarcoRate { get; set; }
/// <summary>The ENASARCO contribution withheld.</summary>
public decimal EnasarcoAmount { get; set; }
/// <summary>The tender code (CIG) of a public contract.</summary>
public string? Cig { get; set; }
/// <summary>The project code (CUP) of a public contract.</summary>
public string? Cup { get; set; }
/// <summary>Who carries the goods (delivery notes, accompanying invoices).</summary>
public TransportResponsibility? TransportBy { get; set; }
/// <summary>The document a credit or debit note corrects, in the same family.</summary>
public long? RelatedDocumentId { get; set; }
/// <summary>The number of the corrected document, also for documents outside Khaemhat.</summary>
public string? RelatedNumber { get; set; }
/// <summary>The date of the corrected document.</summary>
public DateOnly? RelatedDate { get; set; }
/// <summary>The notes printed on the document.</summary>
public string? Notes { get; set; }
/// <summary>The ledger entry, once posted (M7).</summary>
public long? GlEntryId { get; set; }
/// <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; }
/// <summary>Who confirmed or issued it.</summary>
public string? ConfirmedBy { get; set; }
/// <summary>When it was cancelled.</summary>
public DateTime? CancelledAt { get; set; }
/// <summary>Why it was cancelled.</summary>
public string? CancelReason { get; set; }
/// <inheritdoc />
public bool IsDemo { get; set; }
/// <summary>A shallow copy of the same class (the state before a change, for the history).</summary>
/// <returns>The copy.</returns>
public DocumentHeader Clone() => (DocumentHeader)MemberwiseClone();
}
/// <summary>A line of a document (SPEC §11.3).</summary>
public abstract class DocumentLine : Entity<long>
{
/// <summary>The document.</summary>
public long DocumentId { get; set; }
/// <summary>The progressive number of the line (1, 2...), the one printed and sent.</summary>
public int LineNumber { get; set; }
/// <summary>The kind of line.</summary>
public DocumentLineKind Kind { get; set; }
/// <summary>The item.</summary>
public long? ItemId { get; set; }
/// <summary>The description.</summary>
public string Description { get; set; } = string.Empty;
/// <summary>The unit of measure.</summary>
public long? UnitOfMeasureId { get; set; }
/// <summary>The quantity.</summary>
public decimal Quantity { get; set; }
/// <summary>The unit price.</summary>
public decimal Price { get; set; }
/// <summary>Where the price comes from.</summary>
public PriceSource PriceSource { get; set; }
/// <summary>The discounts, such as <c>10+5</c>.</summary>
public string? DiscountFormula { get; set; }
/// <summary>The VAT code.</summary>
public long? TaxCodeId { get; set; }
/// <summary>The taxable amount of the line.</summary>
public decimal TaxableAmount { get; set; }
/// <summary>The warehouse of the line, when different from the header.</summary>
public long? WarehouseId { get; set; }
/// <summary>The delivery date of the line.</summary>
public DateOnly? DeliveryDate { get; set; }
/// <summary>How much later documents fulfilled.</summary>
public decimal FulfilledQuantity { get; set; }
/// <summary>The rest will not be fulfilled (line closed by hand).</summary>
public bool FulfillmentClosed { get; set; }
/// <summary>The family of the line this one was copied from to fulfil it.</summary>
public DocumentFamily? SourceFamily { get; set; }
/// <summary>The line this one fulfils.</summary>
public long? SourceLineId { get; set; }
/// <summary>The line is left out of the withholding tax and of the social security contribution (expenses paid on behalf).</summary>
public bool WithholdingExcluded { get; set; }
/// <summary>The ledger account (M7).</summary>
public string? AccountCode { get; set; }
/// <summary>The cost centre.</summary>
public long? CostCenterId { get; set; }
/// <summary>The job (commessa).</summary>
public long? JobId { get; set; }
/// <summary>Notes of the line.</summary>
public string? Notes { get; set; }
/// <summary>The order on screen and in print.</summary>
public int SortOrder { get; set; }
/// <summary>What is left to fulfil: zero for closed lines and lines without quantity.</summary>
public decimal Residual => FulfillmentClosed || !CarriesQuantity(Kind) ? 0m : Math.Max(0m, Quantity - FulfilledQuantity);
/// <summary>A shallow copy of the same class.</summary>
/// <returns>The copy.</returns>
public DocumentLine Clone() => (DocumentLine)MemberwiseClone();
/// <summary>Whether lines of a kind carry a quantity that later documents can fulfil.</summary>
/// <param name="kind">The kind.</param>
/// <returns>Whether they do.</returns>
public static bool CarriesQuantity(DocumentLineKind kind) => kind is DocumentLineKind.Item or DocumentLineKind.Free;
}
/// <summary>A quotation (<c>sale_quotations</c>).</summary>
public sealed class SaleQuotation : DocumentHeader;
/// <summary>A line of a quotation.</summary>
public sealed class SaleQuotationLine : DocumentLine;
/// <summary>A customer order (<c>sale_orders</c>).</summary>
public sealed class SaleOrder : DocumentHeader;
/// <summary>A line of a customer order.</summary>
public sealed class SaleOrderLine : DocumentLine;
/// <summary>A delivery note, invoice, credit or debit note, pro forma, fee or self-invoice (<c>sale_documents</c>).</summary>
public sealed class SaleDocument : DocumentHeader;
/// <summary>A line of a sale document.</summary>
public sealed class SaleDocumentLine : DocumentLine;
/// <summary>A supplier order (<c>purchase_orders</c>).</summary>
public sealed class PurchaseOrder : DocumentHeader;
/// <summary>A line of a supplier order.</summary>
public sealed class PurchaseOrderLine : DocumentLine;
/// <summary>A supplier delivery note, invoice or credit note (<c>purchase_documents</c>).</summary>
public sealed class PurchaseDocument : DocumentHeader;
/// <summary>A line of a purchase document.</summary>
public sealed class PurchaseDocumentLine : DocumentLine;
/// <summary>A warehouse entry (<c>inventory_documents</c>).</summary>
public sealed class InventoryDocument : DocumentHeader;
/// <summary>A line of a warehouse entry.</summary>
public sealed class InventoryDocumentLine : DocumentLine;
/// <summary>
/// A fulfilment link (<c>document_links</c>): a line of a confirmed document fulfils a quantity of a line of an earlier
/// one (order to delivery note, delivery note to deferred invoice, supplier delivery note to supplier invoice).
/// </summary>
public sealed class DocumentLink : Entity<long>
{
/// <summary>The family of the fulfilling document.</summary>
public DocumentFamily TargetFamily { get; set; }
/// <summary>The fulfilling document.</summary>
public long TargetDocumentId { get; set; }
/// <summary>The fulfilling line.</summary>
public long TargetLineId { get; set; }
/// <summary>The family of the fulfilled document.</summary>
public DocumentFamily SourceFamily { get; set; }
/// <summary>The fulfilled document.</summary>
public long SourceDocumentId { get; set; }
/// <summary>The fulfilled line.</summary>
public long SourceLineId { get; set; }
/// <summary>The quantity fulfilled.</summary>
public decimal Quantity { get; set; }
}
/// <summary>
/// A line of the tax summary of a document (castelletto IVA, <c>document_tax_summaries</c>): one per VAT code,
/// written by the totals calculator each time the document is saved.
/// </summary>
public sealed class DocumentTaxSummary : Entity<long>
{
/// <summary>The family of the document.</summary>
public DocumentFamily Family { get; set; }
/// <summary>The document.</summary>
public long DocumentId { get; set; }
/// <summary>The VAT code.</summary>
public long? TaxCodeId { get; set; }
/// <summary>The rate in percent.</summary>
public decimal Rate { get; set; }
/// <summary>The nature of operations without VAT.</summary>
public string? Nature { get; set; }
/// <summary>When the VAT becomes due.</summary>
public TaxExigibility Exigibility { get; set; }
/// <summary>The non-deductible share, percent.</summary>
public decimal NonDeductiblePercent { get; set; }
/// <summary>The law printed for operations without VAT.</summary>
public string? LegalReference { get; set; }
/// <summary>The taxable amount.</summary>
public decimal Taxable { get; set; }
/// <summary>The VAT.</summary>
public decimal Tax { get; set; }
/// <summary>The non-deductible part of the VAT.</summary>
public decimal NonDeductibleTax { get; set; }
}
/// <summary>An installment of a document (<c>document_installments</c>), from its payment terms.</summary>
public sealed class DocumentInstallment : Entity<long>
{
/// <summary>The family of the document.</summary>
public DocumentFamily Family { get; set; }
/// <summary>The document.</summary>
public long DocumentId { get; set; }
/// <summary>The order, from 1.</summary>
public int Number { get; set; }
/// <summary>The due date.</summary>
public DateOnly DueDate { get; set; }
/// <summary>The amount.</summary>
public decimal Amount { get; set; }
/// <summary>The payment method.</summary>
public long? PaymentMethodId { get; set; }
}
@@ -0,0 +1,61 @@
namespace Khaemhat.Core.Documents;
/// <summary>What the lines of a document say about its fulfilment.</summary>
public enum FulfillmentState
{
/// <summary>Nothing fulfilled.</summary>
None = 0,
/// <summary>Something fulfilled, something left.</summary>
Partial = 1,
/// <summary>Every line fulfilled or closed.</summary>
Fulfilled = 2,
}
/// <summary>Line-by-line fulfilment (SPEC §11.3, ADR 0032): quantities from the links, state of the document from the lines.</summary>
public static class FulfillmentCalculator
{
/// <summary>Writes on each line the quantity fulfilled by the links that point to it.</summary>
/// <param name="lines">The lines of the fulfilled document.</param>
/// <param name="links">The links in force (of confirmed documents) towards those lines.</param>
/// <returns>The lines whose quantity changed.</returns>
public static IReadOnlyList<DocumentLine> Apply(IEnumerable<DocumentLine> lines, IEnumerable<DocumentLink> links)
{
ArgumentNullException.ThrowIfNull(lines);
ArgumentNullException.ThrowIfNull(links);
var byLine = links.GroupBy(l => l.SourceLineId).ToDictionary(g => g.Key, g => g.Sum(l => l.Quantity));
var changed = new List<DocumentLine>();
foreach (var line in lines)
{
var fulfilled = byLine.GetValueOrDefault(line.Id);
if (line.FulfilledQuantity != fulfilled)
{
line.FulfilledQuantity = fulfilled;
changed.Add(line);
}
}
return changed;
}
/// <summary>The fulfilment of a document from its lines; lines without quantity do not count.</summary>
/// <param name="lines">The lines.</param>
/// <returns>The state.</returns>
public static FulfillmentState StateOf(IEnumerable<DocumentLine> lines)
{
ArgumentNullException.ThrowIfNull(lines);
var counted = lines.Where(l => DocumentLine.CarriesQuantity(l.Kind) && l.Quantity > 0).ToList();
if (counted.Count == 0)
{
return FulfillmentState.None;
}
if (counted.All(l => l.Residual == 0))
{
return FulfillmentState.Fulfilled;
}
return counted.Any(l => l.FulfilledQuantity > 0 || l.FulfillmentClosed) ? FulfillmentState.Partial : FulfillmentState.None;
}
}
+209
View File
@@ -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;
}
}
+2
View File
@@ -124,6 +124,8 @@ public static class LogSections
_ when category.Contains("Migration", StringComparison.Ordinal) => LogSection.Migrations,
_ when category.StartsWith("Khaemhat.Data", StringComparison.Ordinal) => LogSection.Database,
_ when category.Contains(".Jobs", StringComparison.Ordinal) => LogSection.ScheduledJobs,
_ when category.Contains(".Mail", StringComparison.Ordinal) => LogSection.Email,
_ when category.Contains(".Documents", StringComparison.Ordinal) => LogSection.Documents,
_ when category.StartsWith("Microsoft.AspNetCore.Components", StringComparison.Ordinal) => LogSection.Ui,
_ when category.Contains("SlowQuer", StringComparison.Ordinal) || category.Contains("Performance", StringComparison.Ordinal) => LogSection.Performance,
_ => LogSection.System,
+9
View File
@@ -339,6 +339,15 @@ public sealed class PartySalesTerms : Entity<long>
/// <summary>The day of the month the deferred invoices are issued, if fixed.</summary>
public int? InvoiceDay { get; set; }
/// <summary>A month without due dates (1-12), such as August: they move to the next month.</summary>
public int? ExcludedMonth1 { get; set; }
/// <summary>A second month without due dates, such as December.</summary>
public int? ExcludedMonth2 { get; set; }
/// <summary>The day of the next month a due date in an excluded month moves to (10 when empty).</summary>
public int? ExcludedMonthsDay { get; set; }
/// <summary>How the documents are sent.</summary>
public DocumentDelivery SendDocuments { get; set; }
+6
View File
@@ -408,6 +408,9 @@ public sealed class DocumentNumerator : CodedEntity
/// <summary>Whether gaps are allowed (never for invoices, credit notes and final entries).</summary>
public bool GapsAllowed { get; set; }
/// <summary>The date of the last document numbered: without gaps, no later document may have an earlier date.</summary>
public DateOnly? LastDate { get; set; }
}
/// <summary>A type of document: the links between a document and its numerator, warehouse reason and SDI type.</summary>
@@ -416,6 +419,9 @@ public sealed class DocumentType : CodedEntity
/// <summary>The family of document.</summary>
public NumeratorKind Kind { get; set; }
/// <summary>What the documents of this type are, which decides how they behave (ADR 0032); empty for types not yet usable.</summary>
public Documents.DocumentKind? DocumentKind { get; set; }
/// <summary>The numerator.</summary>
public long? NumeratorId { get; set; }
@@ -0,0 +1,108 @@
using Khaemhat.Core.Documents;
using Khaemhat.Data.Mapping;
namespace Khaemhat.Data.CompanyDatabase;
/// <summary>The columns shared by the six document headers (ADR 0032).</summary>
/// <typeparam name="T">The header.</typeparam>
public abstract class DocumentHeaderMap<T> : EntityMap<T>
where T : DocumentHeader, new()
{
/// <summary>Creates the map.</summary>
/// <param name="table">The table of the family.</param>
protected DocumentHeaderMap(string table)
{
ToTable(table);
Map(x => x.Section).MaxLength(10);
Map(x => x.DocumentNumber).MaxLength(30);
Map(x => x.ExternalReference).MaxLength(40);
Map(x => x.CurrencyCode).MaxLength(3);
Map(x => x.FooterDiscount).MaxLength(30);
Map(x => x.ConfirmedBy).MaxLength(100);
Map(x => x.CancelReason).MaxLength(200);
Map(x => x.WithholdingType).MaxLength(4);
Map(x => x.WithholdingReason).MaxLength(2);
Map(x => x.SocialSecurityFund).MaxLength(4);
Map(x => x.Cig).MaxLength(15);
Map(x => x.Cup).MaxLength(15);
Map(x => x.RelatedNumber).MaxLength(30);
}
}
/// <summary>The columns shared by the six tables of lines.</summary>
/// <typeparam name="T">The line.</typeparam>
public abstract class DocumentLineMap<T> : EntityMap<T>
where T : DocumentLine, new()
{
/// <summary>Creates the map.</summary>
/// <param name="table">The table of the lines.</param>
protected DocumentLineMap(string table)
{
ToTable(table);
Map(x => x.Description).MaxLength(1000);
Map(x => x.DiscountFormula).MaxLength(30);
Map(x => x.AccountCode).MaxLength(20);
}
}
/// <summary>Map of <see cref="SaleQuotation"/> to <c>sale_quotations</c>.</summary>
public sealed class SaleQuotationMap() : DocumentHeaderMap<SaleQuotation>("sale_quotations");
/// <summary>Map of <see cref="SaleQuotationLine"/> to <c>sale_quotation_lines</c>.</summary>
public sealed class SaleQuotationLineMap() : DocumentLineMap<SaleQuotationLine>("sale_quotation_lines");
/// <summary>Map of <see cref="SaleOrder"/> to <c>sale_orders</c>.</summary>
public sealed class SaleOrderMap() : DocumentHeaderMap<SaleOrder>("sale_orders");
/// <summary>Map of <see cref="SaleOrderLine"/> to <c>sale_order_lines</c>.</summary>
public sealed class SaleOrderLineMap() : DocumentLineMap<SaleOrderLine>("sale_order_lines");
/// <summary>Map of <see cref="SaleDocument"/> to <c>sale_documents</c>.</summary>
public sealed class SaleDocumentMap() : DocumentHeaderMap<SaleDocument>("sale_documents");
/// <summary>Map of <see cref="SaleDocumentLine"/> to <c>sale_document_lines</c>.</summary>
public sealed class SaleDocumentLineMap() : DocumentLineMap<SaleDocumentLine>("sale_document_lines");
/// <summary>Map of <see cref="PurchaseOrder"/> to <c>purchase_orders</c>.</summary>
public sealed class PurchaseOrderMap() : DocumentHeaderMap<PurchaseOrder>("purchase_orders");
/// <summary>Map of <see cref="PurchaseOrderLine"/> to <c>purchase_order_lines</c>.</summary>
public sealed class PurchaseOrderLineMap() : DocumentLineMap<PurchaseOrderLine>("purchase_order_lines");
/// <summary>Map of <see cref="PurchaseDocument"/> to <c>purchase_documents</c>.</summary>
public sealed class PurchaseDocumentMap() : DocumentHeaderMap<PurchaseDocument>("purchase_documents");
/// <summary>Map of <see cref="PurchaseDocumentLine"/> to <c>purchase_document_lines</c>.</summary>
public sealed class PurchaseDocumentLineMap() : DocumentLineMap<PurchaseDocumentLine>("purchase_document_lines");
/// <summary>Map of <see cref="InventoryDocument"/> to <c>inventory_documents</c>.</summary>
public sealed class InventoryDocumentMap() : DocumentHeaderMap<InventoryDocument>("inventory_documents");
/// <summary>Map of <see cref="InventoryDocumentLine"/> to <c>inventory_document_lines</c>.</summary>
public sealed class InventoryDocumentLineMap() : DocumentLineMap<InventoryDocumentLine>("inventory_document_lines");
/// <summary>Map of <see cref="DocumentLink"/> to <c>document_links</c>.</summary>
public sealed class DocumentLinkMap : EntityMap<DocumentLink>
{
/// <summary>Creates the map.</summary>
public DocumentLinkMap() => ToTable("document_links");
}
/// <summary>Map of <see cref="DocumentTaxSummary"/> to <c>document_tax_summaries</c>.</summary>
public sealed class DocumentTaxSummaryMap : EntityMap<DocumentTaxSummary>
{
/// <summary>Creates the map.</summary>
public DocumentTaxSummaryMap()
{
ToTable("document_tax_summaries");
Map(x => x.Nature).MaxLength(10);
Map(x => x.LegalReference).MaxLength(100);
}
}
/// <summary>Map of <see cref="DocumentInstallment"/> to <c>document_installments</c>.</summary>
public sealed class DocumentInstallmentMap : EntityMap<DocumentInstallment>
{
/// <summary>Creates the map.</summary>
public DocumentInstallmentMap() => ToTable("document_installments");
}
@@ -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,243 @@
using Khaemhat.Data.Migrations;
using Khaemhat.Data.Schema;
namespace Khaemhat.Data.CompanyDatabase.Migrations;
/// <summary>
/// The document engine (SPEC §11.3, ADR 0032, issue #47): six families of headers with their lines, the fulfilment
/// links, the tax summaries and installments (#48), the kind of each document type and the date of the last number of each numerator.
/// </summary>
[Migration(20261112_003, "create_documents")]
public sealed class M20261112_003_CreateDocuments : IMigration
{
// The kinds of the document types seeded by M20261111_014 (ItalianBaseTables): the code decides the behaviour.
private static readonly (string Code, string Kind)[] SeededKinds =
[
("PRE", "Quotation"), ("OC", "SalesOrder"), ("DDT", "DeliveryNote"), ("FI", "ImmediateInvoice"), ("FA", "AccompanyingInvoice"),
("FD", "DeferredInvoice"), ("FACC", "DownPaymentInvoice"), ("NC", "CreditNote"), ("ND", "DebitNote"), ("PAR", "Fee"), ("PF", "ProForma"),
("AF16", "SelfInvoice"), ("AF17", "SelfInvoice"), ("AF18", "SelfInvoice"), ("AF19", "SelfInvoice"), ("OF", "PurchaseOrder"),
("DDTF", "PurchaseDeliveryNote"), ("FF", "PurchaseInvoice"), ("NCF", "PurchaseCreditNote"), ("MM", "InventoryEntry"),
];
/// <inheritdoc />
public void Up(ISchemaBuilder schema)
{
ArgumentNullException.ThrowIfNull(schema);
schema.AlterTable("document_types", t => t.String("document_kind", 40));
foreach (var (code, kind) in SeededKinds)
{
schema.Sql(_ => "UPDATE document_types SET document_kind = '" + kind + "' WHERE code = '" + code + "'");
}
schema.AlterTable("document_numerators", t => t.Date("last_date"));
schema.AlterTable("party_sales_terms", t =>
{
t.Int32("excluded_month1");
t.Int32("excluded_month2");
t.Int32("excluded_months_day");
});
Family(schema, "sale_quotations", "sale_quotation_lines");
Family(schema, "sale_orders", "sale_order_lines");
Family(schema, "sale_documents", "sale_document_lines");
Family(schema, "purchase_orders", "purchase_order_lines");
Family(schema, "purchase_documents", "purchase_document_lines");
Family(schema, "inventory_documents", "inventory_document_lines");
schema.CreateTable("document_links", t =>
{
t.Id();
t.String("target_family", 40).NotNull();
t.Int64("target_document_id").NotNull();
t.Int64("target_line_id").NotNull();
t.String("source_family", 40).NotNull();
t.Int64("source_document_id").NotNull();
t.Int64("source_line_id").NotNull();
t.Decimal("quantity").NotNull();
t.AuditColumns();
t.Index("ix_document_links_source", "source_family", "source_line_id");
t.Index("ix_document_links_source_document", "source_family", "source_document_id");
t.Index("ix_document_links_target", "target_family", "target_document_id");
});
schema.CreateTable("document_tax_summaries", t =>
{
t.Id();
t.String("family", 40).NotNull();
t.Int64("document_id").NotNull();
t.Int64("tax_code_id");
t.Decimal("rate").NotNull();
t.String("nature", 10);
t.String("exigibility", 40).NotNull();
t.Decimal("non_deductible_percent").NotNull().Default(0m);
t.String("legal_reference", 100);
t.Decimal("taxable").NotNull();
t.Decimal("tax").NotNull();
t.Decimal("non_deductible_tax").NotNull().Default(0m);
t.AuditColumns();
t.Index("ix_document_tax_summaries_document", "family", "document_id");
t.ForeignKey("fk_document_tax_summaries_tax_code", "tax_code_id", "tax_codes", ReferentialAction.Restrict);
});
schema.CreateTable("document_installments", t =>
{
t.Id();
t.String("family", 40).NotNull();
t.Int64("document_id").NotNull();
t.Int32("number").NotNull();
t.Date("due_date").NotNull();
t.Decimal("amount").NotNull();
t.Int64("payment_method_id");
t.AuditColumns();
t.Index("ix_document_installments_document", "family", "document_id");
t.Index("ix_document_installments_due", "due_date");
t.ForeignKey("fk_document_installments_payment_method", "payment_method_id", "payment_methods", ReferentialAction.Restrict);
});
}
private static void Family(ISchemaBuilder schema, string headers, string lines)
{
schema.CreateTable(headers, t =>
{
t.Id();
t.Int64("document_type_id").NotNull();
t.String("kind", 40).NotNull();
t.String("status", 40).NotNull();
t.Int64("numerator_id");
t.String("section", 10);
t.Int64("number");
t.String("document_number", 30);
t.Date("document_date").NotNull();
t.Int32("year").NotNull();
t.Int64("party_id");
t.Int64("destination_id");
t.String("external_reference", 40);
t.Date("external_date");
t.String("currency_code", 3).NotNull();
t.Decimal("exchange_rate").NotNull().Default(1m);
t.Int64("price_list_id");
t.Int64("payment_term_id");
t.Int64("payment_method_id");
t.Int64("bank_account_id");
t.Int64("salesperson_id");
t.Int64("warehouse_id");
t.Int64("inventory_reason_id");
t.Int64("transport_reason_id");
t.Int64("shipping_term_id");
t.Int64("carrier_id");
t.Int64("goods_appearance_id");
t.Int32("packages");
t.Decimal("gross_weight");
t.Decimal("net_weight");
t.DateTimeUtc("transport_start");
t.Date("valid_until");
t.Date("delivery_date");
t.Int32("revision").NotNull().Default(0);
t.Bool("printed").NotNull().Default(false);
t.Bool("sent").NotNull().Default(false);
t.Bool("posted").NotNull().Default(false);
t.Bool("installments_generated").NotNull().Default(false);
t.Bool("xml_generated").NotNull().Default(false);
t.Decimal("taxable_amount").NotNull().Default(0m);
t.Decimal("tax_amount").NotNull().Default(0m);
t.Decimal("total_amount").NotNull().Default(0m);
t.String("footer_discount", 30);
t.Decimal("expenses_amount").NotNull().Default(0m);
t.Decimal("stamp_duty").NotNull().Default(0m);
t.Decimal("withholding_amount").NotNull().Default(0m);
t.Decimal("social_security_amount").NotNull().Default(0m);
t.Decimal("net_amount").NotNull().Default(0m);
t.Bool("prices_include_tax").NotNull().Default(false);
t.Decimal("footer_discount_amount").NotNull().Default(0m);
t.String("exigibility", 40);
t.Bool("split_payment").NotNull().Default(false);
t.Bool("stamp_duty_charged").NotNull().Default(false);
t.Decimal("withholding_rate");
t.Decimal("withholding_base_percent").NotNull().Default(100m);
t.String("withholding_type", 4);
t.String("withholding_reason", 2);
t.String("social_security_fund", 4);
t.Decimal("social_security_rate");
t.Int64("social_security_tax_code_id");
t.Bool("social_security_withheld").NotNull().Default(false);
t.Decimal("enasarco_rate");
t.Decimal("enasarco_amount").NotNull().Default(0m);
t.String("cig", 15);
t.String("cup", 15);
t.String("transport_by", 40);
t.Int64("related_document_id");
t.String("related_number", 30);
t.Date("related_date");
t.Text("notes");
t.Int64("gl_entry_id");
t.Int64("vat_protocol");
t.DateTimeUtc("confirmed_at");
t.String("confirmed_by", 100);
t.DateTimeUtc("cancelled_at");
t.String("cancel_reason", 200);
t.DemoColumn();
t.AuditColumns();
t.Unique("ux_" + headers + "_number", "numerator_id", "number");
t.Index("ix_" + headers + "_date", "document_date");
t.Index("ix_" + headers + "_party", "party_id");
t.Index("ix_" + headers + "_status", "status");
t.ForeignKey("fk_" + headers + "_type", "document_type_id", "document_types", ReferentialAction.Restrict);
t.ForeignKey("fk_" + headers + "_numerator", "numerator_id", "document_numerators", ReferentialAction.Restrict);
t.ForeignKey("fk_" + headers + "_party", "party_id", "parties", ReferentialAction.Restrict);
t.ForeignKey("fk_" + headers + "_destination", "destination_id", "party_addresses", ReferentialAction.Restrict);
t.ForeignKey("fk_" + headers + "_price_list", "price_list_id", "price_lists", ReferentialAction.Restrict);
t.ForeignKey("fk_" + headers + "_payment_term", "payment_term_id", "payment_terms", ReferentialAction.Restrict);
t.ForeignKey("fk_" + headers + "_payment_method", "payment_method_id", "payment_methods", ReferentialAction.Restrict);
t.ForeignKey("fk_" + headers + "_bank_account", "bank_account_id", "bank_accounts", ReferentialAction.Restrict);
t.ForeignKey("fk_" + headers + "_salesperson", "salesperson_id", "salespeople", ReferentialAction.Restrict);
t.ForeignKey("fk_" + headers + "_warehouse", "warehouse_id", "warehouses", ReferentialAction.Restrict);
t.ForeignKey("fk_" + headers + "_inventory_reason", "inventory_reason_id", "inventory_reasons", ReferentialAction.Restrict);
t.ForeignKey("fk_" + headers + "_transport_reason", "transport_reason_id", "transport_reasons", ReferentialAction.Restrict);
t.ForeignKey("fk_" + headers + "_shipping_term", "shipping_term_id", "shipping_terms", ReferentialAction.Restrict);
t.ForeignKey("fk_" + headers + "_carrier", "carrier_id", "carriers", ReferentialAction.Restrict);
t.ForeignKey("fk_" + headers + "_goods_appearance", "goods_appearance_id", "goods_appearances", ReferentialAction.Restrict);
t.ForeignKey("fk_" + headers + "_social_security_tax_code", "social_security_tax_code_id", "tax_codes", ReferentialAction.Restrict);
t.ForeignKey("fk_" + headers + "_related", "related_document_id", headers, ReferentialAction.Restrict);
});
schema.CreateTable(lines, t =>
{
t.Id();
t.Int64("document_id").NotNull();
t.Int32("line_number").NotNull();
t.String("kind", 40).NotNull();
t.Int64("item_id");
t.String("description", 1000).NotNull();
t.Int64("unit_of_measure_id");
t.Decimal("quantity").NotNull().Default(0m);
t.Decimal("price").NotNull().Default(0m);
t.String("price_source", 40).NotNull();
t.String("discount_formula", 30);
t.Int64("tax_code_id");
t.Decimal("taxable_amount").NotNull().Default(0m);
t.Int64("warehouse_id");
t.Date("delivery_date");
t.Decimal("fulfilled_quantity").NotNull().Default(0m);
t.Bool("fulfillment_closed").NotNull().Default(false);
t.String("source_family", 40);
t.Int64("source_line_id");
t.Bool("withholding_excluded").NotNull().Default(false);
t.String("account_code", 20);
t.Int64("cost_center_id");
t.Int64("job_id");
t.Text("notes");
t.Int32("sort_order").NotNull().Default(0);
t.AuditColumns();
t.Index("ix_" + lines + "_document", "document_id");
t.Index("ix_" + lines + "_item", "item_id");
t.Index("ix_" + lines + "_source", "source_family", "source_line_id");
t.ForeignKey("fk_" + lines + "_document", "document_id", headers, ReferentialAction.Cascade);
t.ForeignKey("fk_" + lines + "_item", "item_id", "items", ReferentialAction.Restrict);
t.ForeignKey("fk_" + lines + "_unit", "unit_of_measure_id", "units_of_measure", ReferentialAction.Restrict);
t.ForeignKey("fk_" + lines + "_tax_code", "tax_code_id", "tax_codes", ReferentialAction.Restrict);
t.ForeignKey("fk_" + lines + "_warehouse", "warehouse_id", "warehouses", ReferentialAction.Restrict);
t.ForeignKey("fk_" + lines + "_cost_center", "cost_center_id", "cost_centers", ReferentialAction.Restrict);
t.ForeignKey("fk_" + lines + "_job", "job_id", "jobs", ReferentialAction.Restrict);
});
}
}
@@ -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);
});
}
}
@@ -223,7 +223,9 @@ public sealed class ExpressionTranslator(IEntityMap map, ISqlDialect dialect)
node = convert.Operand;
}
return node is MemberExpression { Member: PropertyInfo property } member && member.Expression == entity
// In generic code (T : DocumentHeader) the compiler casts the parameter to the base class before the member.
return node is MemberExpression { Member: PropertyInfo property } member
&& (member.Expression == entity || member.Expression is UnaryExpression { NodeType: ExpressionType.Convert, Operand: var operand } && operand == entity)
? map.FindByProperty(property.Name) ?? throw new NotSupportedException($"{map.EntityType.Name}.{property.Name} is not mapped.")
: null;
}
+41 -1
View File
@@ -221,8 +221,10 @@ public sealed record PaymentTermTemplate(string Code, string Description, string
/// <param name="NumeratorCode">The numerator of the base data (<c>FAT</c>, <c>DDT</c>...), if the document is numbered by the company.</param>
/// <param name="InventoryReasonCode">The warehouse reason of the base data (<c>SCA</c>, <c>CAR</c>...), if the document moves goods.</param>
/// <param name="EInvoiceType">The type of the e-invoice format, if the document is sent electronically.</param>
/// <param name="DocumentKind">What the documents are, which decides how they behave (ADR 0032).</param>
public sealed record DocumentTypeTemplate(
string Code, string Description, Khaemhat.Core.Tables.NumeratorKind Kind, string? NumeratorCode, string? InventoryReasonCode, string? EInvoiceType);
string Code, string Description, Khaemhat.Core.Tables.NumeratorKind Kind, string? NumeratorCode, string? InventoryReasonCode, string? EInvoiceType,
Khaemhat.Core.Documents.DocumentKind DocumentKind);
/// <summary>
/// The rows of the base tables that depend on the country's rules (SPEC §14): payment methods and terms with the codes
@@ -271,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);
}
Loaded 100 of 160 files, more files were not shown because too many files have changed in this diff. Show more