Compare commits

..
Author SHA1 Message Date
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
96 changed files with 12360 additions and 305 deletions

No files matched your search

+64
View File
@@ -7,6 +7,70 @@ un'immagine `gitea.encke-hake.ts.net/balbosoft/khaemhat:X.Y.Z`.
## [Unreleased]
## [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).
+858
View File
@@ -729,6 +729,7 @@ Migrazioni applicate in ordine:
- `core` 20261111015 `create_code_sequences` (M20261111_015_CreateCodeSequences)
- `core` 20261112001 `create_parties` (M20261112_001_CreateParties)
- `core` 20261112002 `create_items` (M20261112_002_CreateItems)
- `core` 20261112003 `create_documents` (M20261112_003_CreateDocuments)
#### `attachments`
@@ -990,6 +991,48 @@ Migrazioni applicate in ordine:
- indice unico `ux_discount_policies_code` su `code`
#### `document_installments`
| Colonna | Tipo | Null | Default | Note |
|---|---|---|---|---|
| `id` | Int64 | no | | chiave primaria, identity |
| `family` | String(40) | no | | |
| `document_id` | Int64 | no | | |
| `number` | Int32 | no | | |
| `due_date` | Date | no | | |
| `amount` | Decimal(19,6) | no | | |
| `payment_method_id` | Int64 | sì | | -> `payment_methods` (Restrict) |
| `created_at` | DateTimeUtc | no | | |
| `created_by` | String(100) | sì | | |
| `updated_at` | DateTimeUtc | sì | | |
| `updated_by` | String(100) | sì | | |
| `row_version` | Int64 | no | `1` | |
- indice `ix_document_installments_document` su `family`, `document_id`
- indice `ix_document_installments_due` su `due_date`
#### `document_links`
| Colonna | Tipo | Null | Default | Note |
|---|---|---|---|---|
| `id` | Int64 | no | | chiave primaria, identity |
| `target_family` | String(40) | no | | |
| `target_document_id` | Int64 | no | | |
| `target_line_id` | Int64 | no | | |
| `source_family` | String(40) | no | | |
| `source_document_id` | Int64 | no | | |
| `source_line_id` | Int64 | no | | |
| `quantity` | Decimal(19,6) | no | | |
| `created_at` | DateTimeUtc | no | | |
| `created_by` | String(100) | sì | | |
| `updated_at` | DateTimeUtc | sì | | |
| `updated_by` | String(100) | sì | | |
| `row_version` | Int64 | no | `1` | |
- indice `ix_document_links_source` su `source_family`, `source_line_id`
- indice `ix_document_links_source_document` su `source_family`, `source_document_id`
- indice `ix_document_links_target` su `target_family`, `target_document_id`
#### `document_numerators`
| Colonna | Tipo | Null | Default | Note |
@@ -1011,9 +1054,34 @@ Migrazioni applicate in ordine:
| `updated_at` | DateTimeUtc | sì | | |
| `updated_by` | String(100) | sì | | |
| `row_version` | Int64 | no | `1` | |
| `last_date` | Date | sì | | |
- indice unico `ux_document_numerators_code_year` su `code`, `year`
#### `document_tax_summaries`
| Colonna | Tipo | Null | Default | Note |
|---|---|---|---|---|
| `id` | Int64 | no | | chiave primaria, identity |
| `family` | String(40) | no | | |
| `document_id` | Int64 | no | | |
| `tax_code_id` | Int64 | sì | | -> `tax_codes` (Restrict) |
| `rate` | Decimal(19,6) | no | | |
| `nature` | String(10) | sì | | |
| `exigibility` | String(40) | no | | |
| `non_deductible_percent` | Decimal(19,6) | no | `0` | |
| `legal_reference` | String(100) | sì | | |
| `taxable` | Decimal(19,6) | no | | |
| `tax` | Decimal(19,6) | no | | |
| `non_deductible_tax` | Decimal(19,6) | no | `0` | |
| `created_at` | DateTimeUtc | no | | |
| `created_by` | String(100) | sì | | |
| `updated_at` | DateTimeUtc | sì | | |
| `updated_by` | String(100) | sì | | |
| `row_version` | Int64 | no | `1` | |
- indice `ix_document_tax_summaries_document` su `family`, `document_id`
#### `document_types`
| Colonna | Tipo | Null | Default | Note |
@@ -1035,6 +1103,7 @@ Migrazioni applicate in ordine:
| `updated_at` | DateTimeUtc | sì | | |
| `updated_by` | String(100) | sì | | |
| `row_version` | Int64 | no | `1` | |
| `document_kind` | String(40) | sì | | |
- indice unico `ux_document_types_code` su `code`
@@ -1112,6 +1181,137 @@ Migrazioni applicate in ordine:
- indice unico `ux_goods_appearances_code` su `code`
#### `inventory_document_lines`
| Colonna | Tipo | Null | Default | Note |
|---|---|---|---|---|
| `id` | Int64 | no | | chiave primaria, identity |
| `document_id` | Int64 | no | | -> `inventory_documents` (Cascade) |
| `line_number` | Int32 | no | | |
| `kind` | String(40) | no | | |
| `item_id` | Int64 | sì | | -> `items` (Restrict) |
| `description` | String(1000) | no | | |
| `unit_of_measure_id` | Int64 | sì | | -> `units_of_measure` (Restrict) |
| `quantity` | Decimal(19,6) | no | `0` | |
| `price` | Decimal(19,6) | no | `0` | |
| `price_source` | String(40) | no | | |
| `discount_formula` | String(30) | sì | | |
| `tax_code_id` | Int64 | sì | | -> `tax_codes` (Restrict) |
| `taxable_amount` | Decimal(19,6) | no | `0` | |
| `warehouse_id` | Int64 | sì | | -> `warehouses` (Restrict) |
| `delivery_date` | Date | sì | | |
| `fulfilled_quantity` | Decimal(19,6) | no | `0` | |
| `fulfillment_closed` | Bool | no | `false` | |
| `source_family` | String(40) | sì | | |
| `source_line_id` | Int64 | sì | | |
| `withholding_excluded` | Bool | no | `false` | |
| `account_code` | String(20) | sì | | |
| `cost_center_id` | Int64 | sì | | -> `cost_centers` (Restrict) |
| `job_id` | Int64 | sì | | -> `jobs` (Restrict) |
| `notes` | Text | sì | | |
| `sort_order` | Int32 | no | `0` | |
| `created_at` | DateTimeUtc | no | | |
| `created_by` | String(100) | sì | | |
| `updated_at` | DateTimeUtc | sì | | |
| `updated_by` | String(100) | sì | | |
| `row_version` | Int64 | no | `1` | |
- indice `ix_inventory_document_lines_document` su `document_id`
- indice `ix_inventory_document_lines_item` su `item_id`
- indice `ix_inventory_document_lines_source` su `source_family`, `source_line_id`
#### `inventory_documents`
| Colonna | Tipo | Null | Default | Note |
|---|---|---|---|---|
| `id` | Int64 | no | | chiave primaria, identity |
| `document_type_id` | Int64 | no | | -> `document_types` (Restrict) |
| `kind` | String(40) | no | | |
| `status` | String(40) | no | | |
| `numerator_id` | Int64 | sì | | -> `document_numerators` (Restrict) |
| `section` | String(10) | sì | | |
| `number` | Int64 | sì | | |
| `document_number` | String(30) | sì | | |
| `document_date` | Date | no | | |
| `year` | Int32 | no | | |
| `party_id` | Int64 | sì | | -> `parties` (Restrict) |
| `destination_id` | Int64 | sì | | -> `party_addresses` (Restrict) |
| `external_reference` | String(40) | sì | | |
| `external_date` | Date | sì | | |
| `currency_code` | String(3) | no | | |
| `exchange_rate` | Decimal(19,6) | no | `1` | |
| `price_list_id` | Int64 | sì | | -> `price_lists` (Restrict) |
| `payment_term_id` | Int64 | sì | | -> `payment_terms` (Restrict) |
| `payment_method_id` | Int64 | sì | | -> `payment_methods` (Restrict) |
| `bank_account_id` | Int64 | sì | | -> `bank_accounts` (Restrict) |
| `salesperson_id` | Int64 | sì | | -> `salespeople` (Restrict) |
| `warehouse_id` | Int64 | sì | | -> `warehouses` (Restrict) |
| `inventory_reason_id` | Int64 | sì | | -> `inventory_reasons` (Restrict) |
| `transport_reason_id` | Int64 | sì | | -> `transport_reasons` (Restrict) |
| `shipping_term_id` | Int64 | sì | | -> `shipping_terms` (Restrict) |
| `carrier_id` | Int64 | sì | | -> `carriers` (Restrict) |
| `goods_appearance_id` | Int64 | sì | | -> `goods_appearances` (Restrict) |
| `packages` | Int32 | sì | | |
| `gross_weight` | Decimal(19,6) | sì | | |
| `net_weight` | Decimal(19,6) | sì | | |
| `transport_start` | DateTimeUtc | sì | | |
| `valid_until` | Date | sì | | |
| `delivery_date` | Date | sì | | |
| `revision` | Int32 | no | `0` | |
| `printed` | Bool | no | `false` | |
| `sent` | Bool | no | `false` | |
| `posted` | Bool | no | `false` | |
| `installments_generated` | Bool | no | `false` | |
| `xml_generated` | Bool | no | `false` | |
| `taxable_amount` | Decimal(19,6) | no | `0` | |
| `tax_amount` | Decimal(19,6) | no | `0` | |
| `total_amount` | Decimal(19,6) | no | `0` | |
| `footer_discount` | String(30) | sì | | |
| `expenses_amount` | Decimal(19,6) | no | `0` | |
| `stamp_duty` | Decimal(19,6) | no | `0` | |
| `withholding_amount` | Decimal(19,6) | no | `0` | |
| `social_security_amount` | Decimal(19,6) | no | `0` | |
| `net_amount` | Decimal(19,6) | no | `0` | |
| `prices_include_tax` | Bool | no | `false` | |
| `footer_discount_amount` | Decimal(19,6) | no | `0` | |
| `exigibility` | String(40) | sì | | |
| `split_payment` | Bool | no | `false` | |
| `stamp_duty_charged` | Bool | no | `false` | |
| `withholding_rate` | Decimal(19,6) | sì | | |
| `withholding_base_percent` | Decimal(19,6) | no | `100` | |
| `withholding_type` | String(4) | sì | | |
| `withholding_reason` | String(2) | sì | | |
| `social_security_fund` | String(4) | sì | | |
| `social_security_rate` | Decimal(19,6) | sì | | |
| `social_security_tax_code_id` | Int64 | sì | | -> `tax_codes` (Restrict) |
| `social_security_withheld` | Bool | no | `false` | |
| `enasarco_rate` | Decimal(19,6) | sì | | |
| `enasarco_amount` | Decimal(19,6) | no | `0` | |
| `cig` | String(15) | sì | | |
| `cup` | String(15) | sì | | |
| `transport_by` | String(40) | sì | | |
| `related_document_id` | Int64 | sì | | -> `inventory_documents` (Restrict) |
| `related_number` | String(30) | sì | | |
| `related_date` | Date | sì | | |
| `notes` | Text | sì | | |
| `gl_entry_id` | Int64 | sì | | |
| `vat_protocol` | Int64 | sì | | |
| `confirmed_at` | DateTimeUtc | sì | | |
| `confirmed_by` | String(100) | sì | | |
| `cancelled_at` | DateTimeUtc | sì | | |
| `cancel_reason` | String(200) | sì | | |
| `is_demo` | Bool | no | `false` | |
| `created_at` | DateTimeUtc | no | | |
| `created_by` | String(100) | sì | | |
| `updated_at` | DateTimeUtc | sì | | |
| `updated_by` | String(100) | sì | | |
| `row_version` | Int64 | no | `1` | |
- indice `ix_inventory_documents_date` su `document_date`
- indice `ix_inventory_documents_party` su `party_id`
- indice `ix_inventory_documents_status` su `status`
- indice unico `ux_inventory_documents_number` su `numerator_id`, `number`
#### `inventory_reasons`
| Colonna | Tipo | Null | Default | Note |
@@ -1606,6 +1806,9 @@ Migrazioni applicate in ordine:
| `updated_at` | DateTimeUtc | sì | | |
| `updated_by` | String(100) | sì | | |
| `row_version` | Int64 | no | `1` | |
| `excluded_month1` | Int32 | sì | | |
| `excluded_month2` | Int32 | sì | | |
| `excluded_months_day` | Int32 | sì | | |
- indice unico `ux_party_sales_terms_party` su `party_id`
@@ -1710,6 +1913,268 @@ Migrazioni applicate in ordine:
- indice unico `ux_provinces_code` su `code`
#### `purchase_document_lines`
| Colonna | Tipo | Null | Default | Note |
|---|---|---|---|---|
| `id` | Int64 | no | | chiave primaria, identity |
| `document_id` | Int64 | no | | -> `purchase_documents` (Cascade) |
| `line_number` | Int32 | no | | |
| `kind` | String(40) | no | | |
| `item_id` | Int64 | sì | | -> `items` (Restrict) |
| `description` | String(1000) | no | | |
| `unit_of_measure_id` | Int64 | sì | | -> `units_of_measure` (Restrict) |
| `quantity` | Decimal(19,6) | no | `0` | |
| `price` | Decimal(19,6) | no | `0` | |
| `price_source` | String(40) | no | | |
| `discount_formula` | String(30) | sì | | |
| `tax_code_id` | Int64 | sì | | -> `tax_codes` (Restrict) |
| `taxable_amount` | Decimal(19,6) | no | `0` | |
| `warehouse_id` | Int64 | sì | | -> `warehouses` (Restrict) |
| `delivery_date` | Date | sì | | |
| `fulfilled_quantity` | Decimal(19,6) | no | `0` | |
| `fulfillment_closed` | Bool | no | `false` | |
| `source_family` | String(40) | sì | | |
| `source_line_id` | Int64 | sì | | |
| `withholding_excluded` | Bool | no | `false` | |
| `account_code` | String(20) | sì | | |
| `cost_center_id` | Int64 | sì | | -> `cost_centers` (Restrict) |
| `job_id` | Int64 | sì | | -> `jobs` (Restrict) |
| `notes` | Text | sì | | |
| `sort_order` | Int32 | no | `0` | |
| `created_at` | DateTimeUtc | no | | |
| `created_by` | String(100) | sì | | |
| `updated_at` | DateTimeUtc | sì | | |
| `updated_by` | String(100) | sì | | |
| `row_version` | Int64 | no | `1` | |
- indice `ix_purchase_document_lines_document` su `document_id`
- indice `ix_purchase_document_lines_item` su `item_id`
- indice `ix_purchase_document_lines_source` su `source_family`, `source_line_id`
#### `purchase_documents`
| Colonna | Tipo | Null | Default | Note |
|---|---|---|---|---|
| `id` | Int64 | no | | chiave primaria, identity |
| `document_type_id` | Int64 | no | | -> `document_types` (Restrict) |
| `kind` | String(40) | no | | |
| `status` | String(40) | no | | |
| `numerator_id` | Int64 | sì | | -> `document_numerators` (Restrict) |
| `section` | String(10) | sì | | |
| `number` | Int64 | sì | | |
| `document_number` | String(30) | sì | | |
| `document_date` | Date | no | | |
| `year` | Int32 | no | | |
| `party_id` | Int64 | sì | | -> `parties` (Restrict) |
| `destination_id` | Int64 | sì | | -> `party_addresses` (Restrict) |
| `external_reference` | String(40) | sì | | |
| `external_date` | Date | sì | | |
| `currency_code` | String(3) | no | | |
| `exchange_rate` | Decimal(19,6) | no | `1` | |
| `price_list_id` | Int64 | sì | | -> `price_lists` (Restrict) |
| `payment_term_id` | Int64 | sì | | -> `payment_terms` (Restrict) |
| `payment_method_id` | Int64 | sì | | -> `payment_methods` (Restrict) |
| `bank_account_id` | Int64 | sì | | -> `bank_accounts` (Restrict) |
| `salesperson_id` | Int64 | sì | | -> `salespeople` (Restrict) |
| `warehouse_id` | Int64 | sì | | -> `warehouses` (Restrict) |
| `inventory_reason_id` | Int64 | sì | | -> `inventory_reasons` (Restrict) |
| `transport_reason_id` | Int64 | sì | | -> `transport_reasons` (Restrict) |
| `shipping_term_id` | Int64 | sì | | -> `shipping_terms` (Restrict) |
| `carrier_id` | Int64 | sì | | -> `carriers` (Restrict) |
| `goods_appearance_id` | Int64 | sì | | -> `goods_appearances` (Restrict) |
| `packages` | Int32 | sì | | |
| `gross_weight` | Decimal(19,6) | sì | | |
| `net_weight` | Decimal(19,6) | sì | | |
| `transport_start` | DateTimeUtc | sì | | |
| `valid_until` | Date | sì | | |
| `delivery_date` | Date | sì | | |
| `revision` | Int32 | no | `0` | |
| `printed` | Bool | no | `false` | |
| `sent` | Bool | no | `false` | |
| `posted` | Bool | no | `false` | |
| `installments_generated` | Bool | no | `false` | |
| `xml_generated` | Bool | no | `false` | |
| `taxable_amount` | Decimal(19,6) | no | `0` | |
| `tax_amount` | Decimal(19,6) | no | `0` | |
| `total_amount` | Decimal(19,6) | no | `0` | |
| `footer_discount` | String(30) | sì | | |
| `expenses_amount` | Decimal(19,6) | no | `0` | |
| `stamp_duty` | Decimal(19,6) | no | `0` | |
| `withholding_amount` | Decimal(19,6) | no | `0` | |
| `social_security_amount` | Decimal(19,6) | no | `0` | |
| `net_amount` | Decimal(19,6) | no | `0` | |
| `prices_include_tax` | Bool | no | `false` | |
| `footer_discount_amount` | Decimal(19,6) | no | `0` | |
| `exigibility` | String(40) | sì | | |
| `split_payment` | Bool | no | `false` | |
| `stamp_duty_charged` | Bool | no | `false` | |
| `withholding_rate` | Decimal(19,6) | sì | | |
| `withholding_base_percent` | Decimal(19,6) | no | `100` | |
| `withholding_type` | String(4) | sì | | |
| `withholding_reason` | String(2) | sì | | |
| `social_security_fund` | String(4) | sì | | |
| `social_security_rate` | Decimal(19,6) | sì | | |
| `social_security_tax_code_id` | Int64 | sì | | -> `tax_codes` (Restrict) |
| `social_security_withheld` | Bool | no | `false` | |
| `enasarco_rate` | Decimal(19,6) | sì | | |
| `enasarco_amount` | Decimal(19,6) | no | `0` | |
| `cig` | String(15) | sì | | |
| `cup` | String(15) | sì | | |
| `transport_by` | String(40) | sì | | |
| `related_document_id` | Int64 | sì | | -> `purchase_documents` (Restrict) |
| `related_number` | String(30) | sì | | |
| `related_date` | Date | sì | | |
| `notes` | Text | sì | | |
| `gl_entry_id` | Int64 | sì | | |
| `vat_protocol` | Int64 | sì | | |
| `confirmed_at` | DateTimeUtc | sì | | |
| `confirmed_by` | String(100) | sì | | |
| `cancelled_at` | DateTimeUtc | sì | | |
| `cancel_reason` | String(200) | sì | | |
| `is_demo` | Bool | no | `false` | |
| `created_at` | DateTimeUtc | no | | |
| `created_by` | String(100) | sì | | |
| `updated_at` | DateTimeUtc | sì | | |
| `updated_by` | String(100) | sì | | |
| `row_version` | Int64 | no | `1` | |
- indice `ix_purchase_documents_date` su `document_date`
- indice `ix_purchase_documents_party` su `party_id`
- indice `ix_purchase_documents_status` su `status`
- indice unico `ux_purchase_documents_number` su `numerator_id`, `number`
#### `purchase_order_lines`
| Colonna | Tipo | Null | Default | Note |
|---|---|---|---|---|
| `id` | Int64 | no | | chiave primaria, identity |
| `document_id` | Int64 | no | | -> `purchase_orders` (Cascade) |
| `line_number` | Int32 | no | | |
| `kind` | String(40) | no | | |
| `item_id` | Int64 | sì | | -> `items` (Restrict) |
| `description` | String(1000) | no | | |
| `unit_of_measure_id` | Int64 | sì | | -> `units_of_measure` (Restrict) |
| `quantity` | Decimal(19,6) | no | `0` | |
| `price` | Decimal(19,6) | no | `0` | |
| `price_source` | String(40) | no | | |
| `discount_formula` | String(30) | sì | | |
| `tax_code_id` | Int64 | sì | | -> `tax_codes` (Restrict) |
| `taxable_amount` | Decimal(19,6) | no | `0` | |
| `warehouse_id` | Int64 | sì | | -> `warehouses` (Restrict) |
| `delivery_date` | Date | sì | | |
| `fulfilled_quantity` | Decimal(19,6) | no | `0` | |
| `fulfillment_closed` | Bool | no | `false` | |
| `source_family` | String(40) | sì | | |
| `source_line_id` | Int64 | sì | | |
| `withholding_excluded` | Bool | no | `false` | |
| `account_code` | String(20) | sì | | |
| `cost_center_id` | Int64 | sì | | -> `cost_centers` (Restrict) |
| `job_id` | Int64 | sì | | -> `jobs` (Restrict) |
| `notes` | Text | sì | | |
| `sort_order` | Int32 | no | `0` | |
| `created_at` | DateTimeUtc | no | | |
| `created_by` | String(100) | sì | | |
| `updated_at` | DateTimeUtc | sì | | |
| `updated_by` | String(100) | sì | | |
| `row_version` | Int64 | no | `1` | |
- indice `ix_purchase_order_lines_document` su `document_id`
- indice `ix_purchase_order_lines_item` su `item_id`
- indice `ix_purchase_order_lines_source` su `source_family`, `source_line_id`
#### `purchase_orders`
| Colonna | Tipo | Null | Default | Note |
|---|---|---|---|---|
| `id` | Int64 | no | | chiave primaria, identity |
| `document_type_id` | Int64 | no | | -> `document_types` (Restrict) |
| `kind` | String(40) | no | | |
| `status` | String(40) | no | | |
| `numerator_id` | Int64 | sì | | -> `document_numerators` (Restrict) |
| `section` | String(10) | sì | | |
| `number` | Int64 | sì | | |
| `document_number` | String(30) | sì | | |
| `document_date` | Date | no | | |
| `year` | Int32 | no | | |
| `party_id` | Int64 | sì | | -> `parties` (Restrict) |
| `destination_id` | Int64 | sì | | -> `party_addresses` (Restrict) |
| `external_reference` | String(40) | sì | | |
| `external_date` | Date | sì | | |
| `currency_code` | String(3) | no | | |
| `exchange_rate` | Decimal(19,6) | no | `1` | |
| `price_list_id` | Int64 | sì | | -> `price_lists` (Restrict) |
| `payment_term_id` | Int64 | sì | | -> `payment_terms` (Restrict) |
| `payment_method_id` | Int64 | sì | | -> `payment_methods` (Restrict) |
| `bank_account_id` | Int64 | sì | | -> `bank_accounts` (Restrict) |
| `salesperson_id` | Int64 | sì | | -> `salespeople` (Restrict) |
| `warehouse_id` | Int64 | sì | | -> `warehouses` (Restrict) |
| `inventory_reason_id` | Int64 | sì | | -> `inventory_reasons` (Restrict) |
| `transport_reason_id` | Int64 | sì | | -> `transport_reasons` (Restrict) |
| `shipping_term_id` | Int64 | sì | | -> `shipping_terms` (Restrict) |
| `carrier_id` | Int64 | sì | | -> `carriers` (Restrict) |
| `goods_appearance_id` | Int64 | sì | | -> `goods_appearances` (Restrict) |
| `packages` | Int32 | sì | | |
| `gross_weight` | Decimal(19,6) | sì | | |
| `net_weight` | Decimal(19,6) | sì | | |
| `transport_start` | DateTimeUtc | sì | | |
| `valid_until` | Date | sì | | |
| `delivery_date` | Date | sì | | |
| `revision` | Int32 | no | `0` | |
| `printed` | Bool | no | `false` | |
| `sent` | Bool | no | `false` | |
| `posted` | Bool | no | `false` | |
| `installments_generated` | Bool | no | `false` | |
| `xml_generated` | Bool | no | `false` | |
| `taxable_amount` | Decimal(19,6) | no | `0` | |
| `tax_amount` | Decimal(19,6) | no | `0` | |
| `total_amount` | Decimal(19,6) | no | `0` | |
| `footer_discount` | String(30) | sì | | |
| `expenses_amount` | Decimal(19,6) | no | `0` | |
| `stamp_duty` | Decimal(19,6) | no | `0` | |
| `withholding_amount` | Decimal(19,6) | no | `0` | |
| `social_security_amount` | Decimal(19,6) | no | `0` | |
| `net_amount` | Decimal(19,6) | no | `0` | |
| `prices_include_tax` | Bool | no | `false` | |
| `footer_discount_amount` | Decimal(19,6) | no | `0` | |
| `exigibility` | String(40) | sì | | |
| `split_payment` | Bool | no | `false` | |
| `stamp_duty_charged` | Bool | no | `false` | |
| `withholding_rate` | Decimal(19,6) | sì | | |
| `withholding_base_percent` | Decimal(19,6) | no | `100` | |
| `withholding_type` | String(4) | sì | | |
| `withholding_reason` | String(2) | sì | | |
| `social_security_fund` | String(4) | sì | | |
| `social_security_rate` | Decimal(19,6) | sì | | |
| `social_security_tax_code_id` | Int64 | sì | | -> `tax_codes` (Restrict) |
| `social_security_withheld` | Bool | no | `false` | |
| `enasarco_rate` | Decimal(19,6) | sì | | |
| `enasarco_amount` | Decimal(19,6) | no | `0` | |
| `cig` | String(15) | sì | | |
| `cup` | String(15) | sì | | |
| `transport_by` | String(40) | sì | | |
| `related_document_id` | Int64 | sì | | -> `purchase_orders` (Restrict) |
| `related_number` | String(30) | sì | | |
| `related_date` | Date | sì | | |
| `notes` | Text | sì | | |
| `gl_entry_id` | Int64 | sì | | |
| `vat_protocol` | Int64 | sì | | |
| `confirmed_at` | DateTimeUtc | sì | | |
| `confirmed_by` | String(100) | sì | | |
| `cancelled_at` | DateTimeUtc | sì | | |
| `cancel_reason` | String(200) | sì | | |
| `is_demo` | Bool | no | `false` | |
| `created_at` | DateTimeUtc | no | | |
| `created_by` | String(100) | sì | | |
| `updated_at` | DateTimeUtc | sì | | |
| `updated_by` | String(100) | sì | | |
| `row_version` | Int64 | no | `1` | |
- indice `ix_purchase_orders_date` su `document_date`
- indice `ix_purchase_orders_party` su `party_id`
- indice `ix_purchase_orders_status` su `status`
- indice unico `ux_purchase_orders_number` su `numerator_id`, `number`
#### `role_permissions`
| Colonna | Tipo | Null | Default | Note |
@@ -1743,6 +2208,399 @@ Migrazioni applicate in ordine:
- indice unico `ux_roles_code` su `code`
#### `sale_document_lines`
| Colonna | Tipo | Null | Default | Note |
|---|---|---|---|---|
| `id` | Int64 | no | | chiave primaria, identity |
| `document_id` | Int64 | no | | -> `sale_documents` (Cascade) |
| `line_number` | Int32 | no | | |
| `kind` | String(40) | no | | |
| `item_id` | Int64 | sì | | -> `items` (Restrict) |
| `description` | String(1000) | no | | |
| `unit_of_measure_id` | Int64 | sì | | -> `units_of_measure` (Restrict) |
| `quantity` | Decimal(19,6) | no | `0` | |
| `price` | Decimal(19,6) | no | `0` | |
| `price_source` | String(40) | no | | |
| `discount_formula` | String(30) | sì | | |
| `tax_code_id` | Int64 | sì | | -> `tax_codes` (Restrict) |
| `taxable_amount` | Decimal(19,6) | no | `0` | |
| `warehouse_id` | Int64 | sì | | -> `warehouses` (Restrict) |
| `delivery_date` | Date | sì | | |
| `fulfilled_quantity` | Decimal(19,6) | no | `0` | |
| `fulfillment_closed` | Bool | no | `false` | |
| `source_family` | String(40) | sì | | |
| `source_line_id` | Int64 | sì | | |
| `withholding_excluded` | Bool | no | `false` | |
| `account_code` | String(20) | sì | | |
| `cost_center_id` | Int64 | sì | | -> `cost_centers` (Restrict) |
| `job_id` | Int64 | sì | | -> `jobs` (Restrict) |
| `notes` | Text | sì | | |
| `sort_order` | Int32 | no | `0` | |
| `created_at` | DateTimeUtc | no | | |
| `created_by` | String(100) | sì | | |
| `updated_at` | DateTimeUtc | sì | | |
| `updated_by` | String(100) | sì | | |
| `row_version` | Int64 | no | `1` | |
- indice `ix_sale_document_lines_document` su `document_id`
- indice `ix_sale_document_lines_item` su `item_id`
- indice `ix_sale_document_lines_source` su `source_family`, `source_line_id`
#### `sale_documents`
| Colonna | Tipo | Null | Default | Note |
|---|---|---|---|---|
| `id` | Int64 | no | | chiave primaria, identity |
| `document_type_id` | Int64 | no | | -> `document_types` (Restrict) |
| `kind` | String(40) | no | | |
| `status` | String(40) | no | | |
| `numerator_id` | Int64 | sì | | -> `document_numerators` (Restrict) |
| `section` | String(10) | sì | | |
| `number` | Int64 | sì | | |
| `document_number` | String(30) | sì | | |
| `document_date` | Date | no | | |
| `year` | Int32 | no | | |
| `party_id` | Int64 | sì | | -> `parties` (Restrict) |
| `destination_id` | Int64 | sì | | -> `party_addresses` (Restrict) |
| `external_reference` | String(40) | sì | | |
| `external_date` | Date | sì | | |
| `currency_code` | String(3) | no | | |
| `exchange_rate` | Decimal(19,6) | no | `1` | |
| `price_list_id` | Int64 | sì | | -> `price_lists` (Restrict) |
| `payment_term_id` | Int64 | sì | | -> `payment_terms` (Restrict) |
| `payment_method_id` | Int64 | sì | | -> `payment_methods` (Restrict) |
| `bank_account_id` | Int64 | sì | | -> `bank_accounts` (Restrict) |
| `salesperson_id` | Int64 | sì | | -> `salespeople` (Restrict) |
| `warehouse_id` | Int64 | sì | | -> `warehouses` (Restrict) |
| `inventory_reason_id` | Int64 | sì | | -> `inventory_reasons` (Restrict) |
| `transport_reason_id` | Int64 | sì | | -> `transport_reasons` (Restrict) |
| `shipping_term_id` | Int64 | sì | | -> `shipping_terms` (Restrict) |
| `carrier_id` | Int64 | sì | | -> `carriers` (Restrict) |
| `goods_appearance_id` | Int64 | sì | | -> `goods_appearances` (Restrict) |
| `packages` | Int32 | sì | | |
| `gross_weight` | Decimal(19,6) | sì | | |
| `net_weight` | Decimal(19,6) | sì | | |
| `transport_start` | DateTimeUtc | sì | | |
| `valid_until` | Date | sì | | |
| `delivery_date` | Date | sì | | |
| `revision` | Int32 | no | `0` | |
| `printed` | Bool | no | `false` | |
| `sent` | Bool | no | `false` | |
| `posted` | Bool | no | `false` | |
| `installments_generated` | Bool | no | `false` | |
| `xml_generated` | Bool | no | `false` | |
| `taxable_amount` | Decimal(19,6) | no | `0` | |
| `tax_amount` | Decimal(19,6) | no | `0` | |
| `total_amount` | Decimal(19,6) | no | `0` | |
| `footer_discount` | String(30) | sì | | |
| `expenses_amount` | Decimal(19,6) | no | `0` | |
| `stamp_duty` | Decimal(19,6) | no | `0` | |
| `withholding_amount` | Decimal(19,6) | no | `0` | |
| `social_security_amount` | Decimal(19,6) | no | `0` | |
| `net_amount` | Decimal(19,6) | no | `0` | |
| `prices_include_tax` | Bool | no | `false` | |
| `footer_discount_amount` | Decimal(19,6) | no | `0` | |
| `exigibility` | String(40) | sì | | |
| `split_payment` | Bool | no | `false` | |
| `stamp_duty_charged` | Bool | no | `false` | |
| `withholding_rate` | Decimal(19,6) | sì | | |
| `withholding_base_percent` | Decimal(19,6) | no | `100` | |
| `withholding_type` | String(4) | sì | | |
| `withholding_reason` | String(2) | sì | | |
| `social_security_fund` | String(4) | sì | | |
| `social_security_rate` | Decimal(19,6) | sì | | |
| `social_security_tax_code_id` | Int64 | sì | | -> `tax_codes` (Restrict) |
| `social_security_withheld` | Bool | no | `false` | |
| `enasarco_rate` | Decimal(19,6) | sì | | |
| `enasarco_amount` | Decimal(19,6) | no | `0` | |
| `cig` | String(15) | sì | | |
| `cup` | String(15) | sì | | |
| `transport_by` | String(40) | sì | | |
| `related_document_id` | Int64 | sì | | -> `sale_documents` (Restrict) |
| `related_number` | String(30) | sì | | |
| `related_date` | Date | sì | | |
| `notes` | Text | sì | | |
| `gl_entry_id` | Int64 | sì | | |
| `vat_protocol` | Int64 | sì | | |
| `confirmed_at` | DateTimeUtc | sì | | |
| `confirmed_by` | String(100) | sì | | |
| `cancelled_at` | DateTimeUtc | sì | | |
| `cancel_reason` | String(200) | sì | | |
| `is_demo` | Bool | no | `false` | |
| `created_at` | DateTimeUtc | no | | |
| `created_by` | String(100) | sì | | |
| `updated_at` | DateTimeUtc | sì | | |
| `updated_by` | String(100) | sì | | |
| `row_version` | Int64 | no | `1` | |
- indice `ix_sale_documents_date` su `document_date`
- indice `ix_sale_documents_party` su `party_id`
- indice `ix_sale_documents_status` su `status`
- indice unico `ux_sale_documents_number` su `numerator_id`, `number`
#### `sale_order_lines`
| Colonna | Tipo | Null | Default | Note |
|---|---|---|---|---|
| `id` | Int64 | no | | chiave primaria, identity |
| `document_id` | Int64 | no | | -> `sale_orders` (Cascade) |
| `line_number` | Int32 | no | | |
| `kind` | String(40) | no | | |
| `item_id` | Int64 | sì | | -> `items` (Restrict) |
| `description` | String(1000) | no | | |
| `unit_of_measure_id` | Int64 | sì | | -> `units_of_measure` (Restrict) |
| `quantity` | Decimal(19,6) | no | `0` | |
| `price` | Decimal(19,6) | no | `0` | |
| `price_source` | String(40) | no | | |
| `discount_formula` | String(30) | sì | | |
| `tax_code_id` | Int64 | sì | | -> `tax_codes` (Restrict) |
| `taxable_amount` | Decimal(19,6) | no | `0` | |
| `warehouse_id` | Int64 | sì | | -> `warehouses` (Restrict) |
| `delivery_date` | Date | sì | | |
| `fulfilled_quantity` | Decimal(19,6) | no | `0` | |
| `fulfillment_closed` | Bool | no | `false` | |
| `source_family` | String(40) | sì | | |
| `source_line_id` | Int64 | sì | | |
| `withholding_excluded` | Bool | no | `false` | |
| `account_code` | String(20) | sì | | |
| `cost_center_id` | Int64 | sì | | -> `cost_centers` (Restrict) |
| `job_id` | Int64 | sì | | -> `jobs` (Restrict) |
| `notes` | Text | sì | | |
| `sort_order` | Int32 | no | `0` | |
| `created_at` | DateTimeUtc | no | | |
| `created_by` | String(100) | sì | | |
| `updated_at` | DateTimeUtc | sì | | |
| `updated_by` | String(100) | sì | | |
| `row_version` | Int64 | no | `1` | |
- indice `ix_sale_order_lines_document` su `document_id`
- indice `ix_sale_order_lines_item` su `item_id`
- indice `ix_sale_order_lines_source` su `source_family`, `source_line_id`
#### `sale_orders`
| Colonna | Tipo | Null | Default | Note |
|---|---|---|---|---|
| `id` | Int64 | no | | chiave primaria, identity |
| `document_type_id` | Int64 | no | | -> `document_types` (Restrict) |
| `kind` | String(40) | no | | |
| `status` | String(40) | no | | |
| `numerator_id` | Int64 | sì | | -> `document_numerators` (Restrict) |
| `section` | String(10) | sì | | |
| `number` | Int64 | sì | | |
| `document_number` | String(30) | sì | | |
| `document_date` | Date | no | | |
| `year` | Int32 | no | | |
| `party_id` | Int64 | sì | | -> `parties` (Restrict) |
| `destination_id` | Int64 | sì | | -> `party_addresses` (Restrict) |
| `external_reference` | String(40) | sì | | |
| `external_date` | Date | sì | | |
| `currency_code` | String(3) | no | | |
| `exchange_rate` | Decimal(19,6) | no | `1` | |
| `price_list_id` | Int64 | sì | | -> `price_lists` (Restrict) |
| `payment_term_id` | Int64 | sì | | -> `payment_terms` (Restrict) |
| `payment_method_id` | Int64 | sì | | -> `payment_methods` (Restrict) |
| `bank_account_id` | Int64 | sì | | -> `bank_accounts` (Restrict) |
| `salesperson_id` | Int64 | sì | | -> `salespeople` (Restrict) |
| `warehouse_id` | Int64 | sì | | -> `warehouses` (Restrict) |
| `inventory_reason_id` | Int64 | sì | | -> `inventory_reasons` (Restrict) |
| `transport_reason_id` | Int64 | sì | | -> `transport_reasons` (Restrict) |
| `shipping_term_id` | Int64 | sì | | -> `shipping_terms` (Restrict) |
| `carrier_id` | Int64 | sì | | -> `carriers` (Restrict) |
| `goods_appearance_id` | Int64 | sì | | -> `goods_appearances` (Restrict) |
| `packages` | Int32 | sì | | |
| `gross_weight` | Decimal(19,6) | sì | | |
| `net_weight` | Decimal(19,6) | sì | | |
| `transport_start` | DateTimeUtc | sì | | |
| `valid_until` | Date | sì | | |
| `delivery_date` | Date | sì | | |
| `revision` | Int32 | no | `0` | |
| `printed` | Bool | no | `false` | |
| `sent` | Bool | no | `false` | |
| `posted` | Bool | no | `false` | |
| `installments_generated` | Bool | no | `false` | |
| `xml_generated` | Bool | no | `false` | |
| `taxable_amount` | Decimal(19,6) | no | `0` | |
| `tax_amount` | Decimal(19,6) | no | `0` | |
| `total_amount` | Decimal(19,6) | no | `0` | |
| `footer_discount` | String(30) | sì | | |
| `expenses_amount` | Decimal(19,6) | no | `0` | |
| `stamp_duty` | Decimal(19,6) | no | `0` | |
| `withholding_amount` | Decimal(19,6) | no | `0` | |
| `social_security_amount` | Decimal(19,6) | no | `0` | |
| `net_amount` | Decimal(19,6) | no | `0` | |
| `prices_include_tax` | Bool | no | `false` | |
| `footer_discount_amount` | Decimal(19,6) | no | `0` | |
| `exigibility` | String(40) | sì | | |
| `split_payment` | Bool | no | `false` | |
| `stamp_duty_charged` | Bool | no | `false` | |
| `withholding_rate` | Decimal(19,6) | sì | | |
| `withholding_base_percent` | Decimal(19,6) | no | `100` | |
| `withholding_type` | String(4) | sì | | |
| `withholding_reason` | String(2) | sì | | |
| `social_security_fund` | String(4) | sì | | |
| `social_security_rate` | Decimal(19,6) | sì | | |
| `social_security_tax_code_id` | Int64 | sì | | -> `tax_codes` (Restrict) |
| `social_security_withheld` | Bool | no | `false` | |
| `enasarco_rate` | Decimal(19,6) | sì | | |
| `enasarco_amount` | Decimal(19,6) | no | `0` | |
| `cig` | String(15) | sì | | |
| `cup` | String(15) | sì | | |
| `transport_by` | String(40) | sì | | |
| `related_document_id` | Int64 | sì | | -> `sale_orders` (Restrict) |
| `related_number` | String(30) | sì | | |
| `related_date` | Date | sì | | |
| `notes` | Text | sì | | |
| `gl_entry_id` | Int64 | sì | | |
| `vat_protocol` | Int64 | sì | | |
| `confirmed_at` | DateTimeUtc | sì | | |
| `confirmed_by` | String(100) | sì | | |
| `cancelled_at` | DateTimeUtc | sì | | |
| `cancel_reason` | String(200) | sì | | |
| `is_demo` | Bool | no | `false` | |
| `created_at` | DateTimeUtc | no | | |
| `created_by` | String(100) | sì | | |
| `updated_at` | DateTimeUtc | sì | | |
| `updated_by` | String(100) | sì | | |
| `row_version` | Int64 | no | `1` | |
- indice `ix_sale_orders_date` su `document_date`
- indice `ix_sale_orders_party` su `party_id`
- indice `ix_sale_orders_status` su `status`
- indice unico `ux_sale_orders_number` su `numerator_id`, `number`
#### `sale_quotation_lines`
| Colonna | Tipo | Null | Default | Note |
|---|---|---|---|---|
| `id` | Int64 | no | | chiave primaria, identity |
| `document_id` | Int64 | no | | -> `sale_quotations` (Cascade) |
| `line_number` | Int32 | no | | |
| `kind` | String(40) | no | | |
| `item_id` | Int64 | sì | | -> `items` (Restrict) |
| `description` | String(1000) | no | | |
| `unit_of_measure_id` | Int64 | sì | | -> `units_of_measure` (Restrict) |
| `quantity` | Decimal(19,6) | no | `0` | |
| `price` | Decimal(19,6) | no | `0` | |
| `price_source` | String(40) | no | | |
| `discount_formula` | String(30) | sì | | |
| `tax_code_id` | Int64 | sì | | -> `tax_codes` (Restrict) |
| `taxable_amount` | Decimal(19,6) | no | `0` | |
| `warehouse_id` | Int64 | sì | | -> `warehouses` (Restrict) |
| `delivery_date` | Date | sì | | |
| `fulfilled_quantity` | Decimal(19,6) | no | `0` | |
| `fulfillment_closed` | Bool | no | `false` | |
| `source_family` | String(40) | sì | | |
| `source_line_id` | Int64 | sì | | |
| `withholding_excluded` | Bool | no | `false` | |
| `account_code` | String(20) | sì | | |
| `cost_center_id` | Int64 | sì | | -> `cost_centers` (Restrict) |
| `job_id` | Int64 | sì | | -> `jobs` (Restrict) |
| `notes` | Text | sì | | |
| `sort_order` | Int32 | no | `0` | |
| `created_at` | DateTimeUtc | no | | |
| `created_by` | String(100) | sì | | |
| `updated_at` | DateTimeUtc | sì | | |
| `updated_by` | String(100) | sì | | |
| `row_version` | Int64 | no | `1` | |
- indice `ix_sale_quotation_lines_document` su `document_id`
- indice `ix_sale_quotation_lines_item` su `item_id`
- indice `ix_sale_quotation_lines_source` su `source_family`, `source_line_id`
#### `sale_quotations`
| Colonna | Tipo | Null | Default | Note |
|---|---|---|---|---|
| `id` | Int64 | no | | chiave primaria, identity |
| `document_type_id` | Int64 | no | | -> `document_types` (Restrict) |
| `kind` | String(40) | no | | |
| `status` | String(40) | no | | |
| `numerator_id` | Int64 | sì | | -> `document_numerators` (Restrict) |
| `section` | String(10) | sì | | |
| `number` | Int64 | sì | | |
| `document_number` | String(30) | sì | | |
| `document_date` | Date | no | | |
| `year` | Int32 | no | | |
| `party_id` | Int64 | sì | | -> `parties` (Restrict) |
| `destination_id` | Int64 | sì | | -> `party_addresses` (Restrict) |
| `external_reference` | String(40) | sì | | |
| `external_date` | Date | sì | | |
| `currency_code` | String(3) | no | | |
| `exchange_rate` | Decimal(19,6) | no | `1` | |
| `price_list_id` | Int64 | sì | | -> `price_lists` (Restrict) |
| `payment_term_id` | Int64 | sì | | -> `payment_terms` (Restrict) |
| `payment_method_id` | Int64 | sì | | -> `payment_methods` (Restrict) |
| `bank_account_id` | Int64 | sì | | -> `bank_accounts` (Restrict) |
| `salesperson_id` | Int64 | sì | | -> `salespeople` (Restrict) |
| `warehouse_id` | Int64 | sì | | -> `warehouses` (Restrict) |
| `inventory_reason_id` | Int64 | sì | | -> `inventory_reasons` (Restrict) |
| `transport_reason_id` | Int64 | sì | | -> `transport_reasons` (Restrict) |
| `shipping_term_id` | Int64 | sì | | -> `shipping_terms` (Restrict) |
| `carrier_id` | Int64 | sì | | -> `carriers` (Restrict) |
| `goods_appearance_id` | Int64 | sì | | -> `goods_appearances` (Restrict) |
| `packages` | Int32 | sì | | |
| `gross_weight` | Decimal(19,6) | sì | | |
| `net_weight` | Decimal(19,6) | sì | | |
| `transport_start` | DateTimeUtc | sì | | |
| `valid_until` | Date | sì | | |
| `delivery_date` | Date | sì | | |
| `revision` | Int32 | no | `0` | |
| `printed` | Bool | no | `false` | |
| `sent` | Bool | no | `false` | |
| `posted` | Bool | no | `false` | |
| `installments_generated` | Bool | no | `false` | |
| `xml_generated` | Bool | no | `false` | |
| `taxable_amount` | Decimal(19,6) | no | `0` | |
| `tax_amount` | Decimal(19,6) | no | `0` | |
| `total_amount` | Decimal(19,6) | no | `0` | |
| `footer_discount` | String(30) | sì | | |
| `expenses_amount` | Decimal(19,6) | no | `0` | |
| `stamp_duty` | Decimal(19,6) | no | `0` | |
| `withholding_amount` | Decimal(19,6) | no | `0` | |
| `social_security_amount` | Decimal(19,6) | no | `0` | |
| `net_amount` | Decimal(19,6) | no | `0` | |
| `prices_include_tax` | Bool | no | `false` | |
| `footer_discount_amount` | Decimal(19,6) | no | `0` | |
| `exigibility` | String(40) | sì | | |
| `split_payment` | Bool | no | `false` | |
| `stamp_duty_charged` | Bool | no | `false` | |
| `withholding_rate` | Decimal(19,6) | sì | | |
| `withholding_base_percent` | Decimal(19,6) | no | `100` | |
| `withholding_type` | String(4) | sì | | |
| `withholding_reason` | String(2) | sì | | |
| `social_security_fund` | String(4) | sì | | |
| `social_security_rate` | Decimal(19,6) | sì | | |
| `social_security_tax_code_id` | Int64 | sì | | -> `tax_codes` (Restrict) |
| `social_security_withheld` | Bool | no | `false` | |
| `enasarco_rate` | Decimal(19,6) | sì | | |
| `enasarco_amount` | Decimal(19,6) | no | `0` | |
| `cig` | String(15) | sì | | |
| `cup` | String(15) | sì | | |
| `transport_by` | String(40) | sì | | |
| `related_document_id` | Int64 | sì | | -> `sale_quotations` (Restrict) |
| `related_number` | String(30) | sì | | |
| `related_date` | Date | sì | | |
| `notes` | Text | sì | | |
| `gl_entry_id` | Int64 | sì | | |
| `vat_protocol` | Int64 | sì | | |
| `confirmed_at` | DateTimeUtc | sì | | |
| `confirmed_by` | String(100) | sì | | |
| `cancelled_at` | DateTimeUtc | sì | | |
| `cancel_reason` | String(200) | sì | | |
| `is_demo` | Bool | no | `false` | |
| `created_at` | DateTimeUtc | no | | |
| `created_by` | String(100) | sì | | |
| `updated_at` | DateTimeUtc | sì | | |
| `updated_by` | String(100) | sì | | |
| `row_version` | Int64 | no | `1` | |
- indice `ix_sale_quotations_date` su `document_date`
- indice `ix_sale_quotations_party` su `party_id`
- indice `ix_sale_quotations_status` su `status`
- indice unico `ux_sale_quotations_number` su `numerator_id`, `number`
#### `salespeople`
| Colonna | Tipo | Null | Default | Note |
+16 -9
View File
@@ -3,19 +3,18 @@
> Punto di ripresa per ogni sessione. Aggiornare a fine sessione.
**Ultimo aggiornamento:** 2026-11-12
**Milestone corrente:** M5 — Motore documenti e Vendite (issue #47-#54, nel progetto in *Da fare*). M4 chiusa:
PR #121 in `main`, tag `v0.4.0`, immagine e release.
**Prossimo passo:** M5, a partire dal motore documenti (#47) e dal calcolo dei totali (#48). #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:** M6 — Acquisti e Magazzino (issue #55-#61), **non ancora iniziata**: si parte quando il
titolare lo dice. M5 chiusa: PR #124 in `main`, tag `v0.5.0`, immagine e release.
**Prossimo passo:** M6 dall'issue #55. #35 (PNG ad alta risoluzione) resta aperta e non blocca; #45 resta aperta solo
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).
## Fatto
- Specifica normativa in `docs/SPEC.md`; `CLAUDE.md` con emendamenti E1-E7.
- ADR 0001-0031.
- ADR 0001-0034.
- 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`,
@@ -59,6 +58,14 @@ 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).
- 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).
+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.
+2 -1
View File
@@ -1,6 +1,6 @@
# Changelog
> **Stato:** completa per 0.4.0 · **Ultima revisione:** 2026-11-12
> **Stato:** completa per 0.5.0 · **Ultima revisione:** 2026-11-12
Le novità di ogni versione sono nel file
[`CHANGELOG.md`](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/src/branch/main/CHANGELOG.md) del repository
@@ -11,6 +11,7 @@ Le novità di ogni versione sono nel file
| Versione | Data | Contenuto |
|---|---|---|
| 0.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. |
+17 -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.5.0 (dati di esempio di acquisti, magazzino e contabilità con i moduli, 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,22 @@ 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. 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.
+160
View File
@@ -0,0 +1,160 @@
# Guida all'uso
> **Stato:** completa per la versione 0.5 · **Ultima revisione:** 2026-11-12 · **Versione software:** 0.5.0 (M5)
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.5.0 | Arriva con |
|---|---|---|
| Accesso e sicurezza | password, verifica in due passaggi, codici di recupero, blocco dopo i tentativi sbagliati | — |
| Interfaccia | menu, schede, ricerca globale, notifiche, aiuto F1, dashboard a widget, temi e colori | — |
| Tabelle azienda | profilo azienda, esercizi, cambi, codici IVA, pagamenti, banche, depositi, tipi documento, numeratori e le altre tabelle di base | — |
| Anagrafiche | clienti, fornitori, contatti, controlli di partita IVA e codice fiscale, VIES | CRM (lead, opportunità): M11 |
| Articoli | articoli, categorie, listini con prezzi a validità, prezzi netti per cliente | giacenze: M6 |
| Vendite | preventivi, ordini, DDT, fatture, note, pro forma, fatturazione differita, stampa PDF, invio per e-mail | magazzino M6, contabilità M7, partite M8, XML SDI M9 |
| Acquisti e magazzino | — | M6 |
| Contabilità, IVA, scadenzario | — | M7, M8 |
| Fatturazione elettronica | — | M9 |
| Import ed export | clienti, fornitori, articoli e prezzi da CSV, Excel e JSON; esportazione dai radar | giacenze iniziali M6, piano dei conti M7 |
| 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. Allegati
![Pannello allegati](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/allegati-pannello.png)
Ogni anagrafica e ogni documento ha la scheda **Allegati**: carichi file dal computer, li vedi in anteprima, scarichi tutto in un archivio ZIP. I PDF che Khaemhat genera sono **versionati**: ogni stampa salvata o
e-mail inviata aggiunge una versione e le precedenti restano. Vedi [Allegati e file](Allegati-e-file).
## 9. Importare ed esportare
![Mappatura delle colonne](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/import-export-mappatura.png)
**Amministrazione → Import/Export** porta in Khaemhat clienti, fornitori, articoli e prezzi di listino da un file
CSV, Excel o JSON: scegli il file, abbini le colonne, guarda l'anteprima con gli errori riga per riga e conferma. Ogni radar
esporta le righe visibili. Vedi [Import/Export](Import-Export).
## 10. Personalizzare
![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) ·
[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.5.0 · **Ultima revisione:** 2026-11-12 · **Versione software:** 0.5.0 (M5; 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) |
+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 |
+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). **Prossima:** M6.
| # | 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
+274 -212
View File
@@ -1,288 +1,350 @@
# 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. Arrivano più avanti: lo **scarico di magazzino** e l'impegno (M6, con il
> magazzino), la **registrazione contabile** (M7), le **partite** e il controllo del fido (M8), il **file XML** per lo
> 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. Lo scarico del
magazzino arriva con M6.
## 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: 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}"
@@ -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,859 @@
using Khaemhat.Application.Audit;
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>
/// 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);
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 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);
}
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;
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 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);
}
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;
}
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,280 @@
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 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<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)));
}
@@ -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,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; }
}
+458
View File
@@ -0,0 +1,458 @@
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 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.</summary>
public long? VatProtocol { 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;
}
}
+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,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);
});
}
}
@@ -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;
}
+3 -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
+21 -20
View File
@@ -1,3 +1,4 @@
using Khaemhat.Core.Documents;
using Khaemhat.Core.Tables;
using Khaemhat.Fiscal.Abstractions;
@@ -46,25 +47,25 @@ public sealed class ItalianBaseTables : IBaseTablesTemplate
/// <inheritdoc />
public IReadOnlyList<DocumentTypeTemplate> DocumentTypes { get; } =
[
new("PRE", "Preventivo", NumeratorKind.Quotation, "PRE", null, null),
new("OC", "Ordine cliente", NumeratorKind.SalesOrder, "ORD", null, null),
new("DDT", "Documento di trasporto", NumeratorKind.DeliveryNote, "DDT", "SCA", null),
new("FI", "Fattura immediata", NumeratorKind.SalesInvoice, "FAT", null, "TD01"),
new("FA", "Fattura accompagnatoria", NumeratorKind.SalesInvoice, "FAT", "SCA", "TD01"),
new("FD", "Fattura differita", NumeratorKind.SalesInvoice, "FAT", null, "TD24"),
new("FACC", "Fattura di acconto", NumeratorKind.SalesInvoice, "FAT", null, "TD02"),
new("NC", "Nota di credito", NumeratorKind.SalesInvoice, "FAT", null, "TD04"),
new("ND", "Nota di debito", NumeratorKind.SalesInvoice, "FAT", null, "TD05"),
new("PAR", "Parcella", NumeratorKind.SalesInvoice, "FAT", null, "TD06"),
new("PF", "Fattura pro forma", NumeratorKind.Other, "PRF", null, null),
new("AF16", "Integrazione reverse charge interno", NumeratorKind.SalesInvoice, "AUT", null, "TD16"),
new("AF17", "Integrazione acquisto servizi dall'estero", NumeratorKind.SalesInvoice, "AUT", null, "TD17"),
new("AF18", "Integrazione acquisto beni intracomunitari", NumeratorKind.SalesInvoice, "AUT", null, "TD18"),
new("AF19", "Integrazione acquisto beni art. 17 c.2", NumeratorKind.SalesInvoice, "AUT", null, "TD19"),
new("OF", "Ordine fornitore", NumeratorKind.PurchaseOrder, "ORF", null, null),
new("DDTF", "DDT fornitore (carico)", NumeratorKind.Inventory, null, "CAR", null),
new("FF", "Fattura fornitore", NumeratorKind.PurchaseInvoice, "PRA", null, null),
new("NCF", "Nota di credito fornitore", NumeratorKind.PurchaseInvoice, "PRA", null, null),
new("MM", "Movimento di magazzino", NumeratorKind.Inventory, "MAG", null, null),
new("PRE", "Preventivo", NumeratorKind.Quotation, "PRE", null, null, DocumentKind.Quotation),
new("OC", "Ordine cliente", NumeratorKind.SalesOrder, "ORD", null, null, DocumentKind.SalesOrder),
new("DDT", "Documento di trasporto", NumeratorKind.DeliveryNote, "DDT", "SCA", null, DocumentKind.DeliveryNote),
new("FI", "Fattura immediata", NumeratorKind.SalesInvoice, "FAT", null, "TD01", DocumentKind.ImmediateInvoice),
new("FA", "Fattura accompagnatoria", NumeratorKind.SalesInvoice, "FAT", "SCA", "TD01", DocumentKind.AccompanyingInvoice),
new("FD", "Fattura differita", NumeratorKind.SalesInvoice, "FAT", null, "TD24", DocumentKind.DeferredInvoice),
new("FACC", "Fattura di acconto", NumeratorKind.SalesInvoice, "FAT", null, "TD02", DocumentKind.DownPaymentInvoice),
new("NC", "Nota di credito", NumeratorKind.SalesInvoice, "FAT", null, "TD04", DocumentKind.CreditNote),
new("ND", "Nota di debito", NumeratorKind.SalesInvoice, "FAT", null, "TD05", DocumentKind.DebitNote),
new("PAR", "Parcella", NumeratorKind.SalesInvoice, "FAT", null, "TD06", DocumentKind.Fee),
new("PF", "Fattura pro forma", NumeratorKind.Other, "PRF", null, null, DocumentKind.ProForma),
new("AF16", "Integrazione reverse charge interno", NumeratorKind.SalesInvoice, "AUT", null, "TD16", DocumentKind.SelfInvoice),
new("AF17", "Integrazione acquisto servizi dall'estero", NumeratorKind.SalesInvoice, "AUT", null, "TD17", DocumentKind.SelfInvoice),
new("AF18", "Integrazione acquisto beni intracomunitari", NumeratorKind.SalesInvoice, "AUT", null, "TD18", DocumentKind.SelfInvoice),
new("AF19", "Integrazione acquisto beni art. 17 c.2", NumeratorKind.SalesInvoice, "AUT", null, "TD19", DocumentKind.SelfInvoice),
new("OF", "Ordine fornitore", NumeratorKind.PurchaseOrder, "ORF", null, null, DocumentKind.PurchaseOrder),
new("DDTF", "DDT fornitore (carico)", NumeratorKind.Inventory, null, "CAR", null, DocumentKind.PurchaseDeliveryNote),
new("FF", "Fattura fornitore", NumeratorKind.PurchaseInvoice, "PRA", null, null, DocumentKind.PurchaseInvoice),
new("NCF", "Nota di credito fornitore", NumeratorKind.PurchaseInvoice, "PRA", null, null, DocumentKind.PurchaseCreditNote),
new("MM", "Movimento di magazzino", NumeratorKind.Inventory, "MAG", null, null, DocumentKind.InventoryEntry),
];
}
+445
View File
@@ -0,0 +1,445 @@
using System.Globalization;
using System.Net.Security;
using System.Net.Sockets;
using System.Text;
using System.Threading.Channels;
using Khaemhat.Core.Logging;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
namespace Khaemhat.Infrastructure.Mail;
/// <summary>A file attached to a message.</summary>
/// <param name="FileName">The file name.</param>
/// <param name="MediaType">The media type.</param>
/// <param name="Content">The bytes.</param>
public sealed record MailAttachment(string FileName, string MediaType, byte[] Content);
/// <summary>A message to send.</summary>
/// <param name="To">The recipients.</param>
/// <param name="Subject">The subject.</param>
/// <param name="Body">The text of the message.</param>
public sealed record OutgoingMail(IReadOnlyList<string> To, string Subject, string Body)
{
/// <summary>The recipients in copy.</summary>
public IReadOnlyList<string> Cc { get; init; } = [];
/// <summary>The address replies go to, when not the sender.</summary>
public string? ReplyTo { get; init; }
/// <summary>The attachments.</summary>
public IReadOnlyList<MailAttachment> Attachments { get; init; } = [];
/// <summary>What the message is about, for the log, such as <c>Fattura immediata 6/2026</c>.</summary>
public string? Reference { get; init; }
}
/// <summary>How the connection to the SMTP server is protected (<c>KHAEMHAT_SMTP_SECURITY</c>).</summary>
public enum SmtpTransportSecurity
{
/// <summary>Plain connection upgraded with STARTTLS (port 587).</summary>
StartTls = 0,
/// <summary>TLS from the first byte (port 465).</summary>
Ssl = 1,
/// <summary>No encryption: only for a relay on the local network.</summary>
None = 2,
}
/// <summary>The SMTP server (SPEC §6: <c>KHAEMHAT_SMTP_*</c>).</summary>
/// <param name="Host">The host; none when mail is not configured.</param>
/// <param name="Port">The port.</param>
/// <param name="User">The user, when the server wants authentication.</param>
/// <param name="Password">The password.</param>
/// <param name="From">The sender address.</param>
/// <param name="Security">The protection of the connection.</param>
public sealed record SmtpSettings(string? Host, int Port, string? User, string? Password, string? From, SmtpTransportSecurity Security)
{
/// <summary>Whether messages can be sent.</summary>
public bool IsConfigured => !string.IsNullOrWhiteSpace(Host) && !string.IsNullOrWhiteSpace(From);
/// <inheritdoc />
public override string ToString() => $"{Host}:{Port} ({Security})";
}
/// <summary>Sends a message now.</summary>
public interface IMailSender
{
/// <summary>Whether a server is configured.</summary>
bool IsConfigured { get; }
/// <summary>Sends a message.</summary>
/// <param name="mail">The message.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
/// <exception cref="MailException">The server refused the message or could not be reached.</exception>
Task SendAsync(OutgoingMail mail, CancellationToken cancellationToken = default);
}
/// <summary>A message the SMTP server refused, or a server that could not be reached.</summary>
public sealed class MailException : Exception
{
/// <summary>Creates the exception.</summary>
public MailException()
{
}
/// <summary>Creates the exception.</summary>
/// <param name="message">What went wrong.</param>
public MailException(string message)
: base(message)
{
}
/// <summary>Creates the exception.</summary>
/// <param name="message">What went wrong.</param>
/// <param name="innerException">The cause.</param>
public MailException(string message, Exception innerException)
: base(message, innerException)
{
}
}
/// <summary>
/// Writes a message as MIME (RFC 5322, 2045-2047): UTF-8 text in base64, attachments in base64 at 76 columns, headers
/// with non-ASCII text as encoded words.
/// </summary>
public static class MimeMessageWriter
{
/// <summary>Writes the message.</summary>
/// <param name="mail">The message.</param>
/// <param name="from">The sender.</param>
/// <param name="date">The date of the message.</param>
/// <param name="boundary">The MIME boundary; a new one when empty.</param>
/// <returns>The message, lines ended by CRLF.</returns>
public static string Write(OutgoingMail mail, string from, DateTimeOffset date, string? boundary = null)
{
ArgumentNullException.ThrowIfNull(mail);
ArgumentNullException.ThrowIfNull(from);
boundary ??= "=_kh_" + Guid.NewGuid().ToString("N");
var domain = from.Contains('@', StringComparison.Ordinal) ? from[(from.IndexOf('@', StringComparison.Ordinal) + 1)..] : "localhost";
var text = new StringBuilder();
void Line(string value) => text.Append(value).Append("\r\n");
Line("From: " + from);
Line("To: " + string.Join(", ", mail.To));
if (mail.Cc.Count > 0)
{
Line("Cc: " + string.Join(", ", mail.Cc));
}
if (mail.ReplyTo is { Length: > 0 } replyTo)
{
Line("Reply-To: " + replyTo);
}
Line("Subject: " + EncodeHeader(mail.Subject));
Line("Date: " + date.ToString("ddd, dd MMM yyyy HH:mm:ss ", CultureInfo.InvariantCulture) + date.ToString("zzz", CultureInfo.InvariantCulture).Replace(":", string.Empty, StringComparison.Ordinal));
Line("Message-ID: <" + Guid.NewGuid().ToString("N") + "@" + domain + ">");
Line("MIME-Version: 1.0");
Line("Content-Type: multipart/mixed; boundary=\"" + boundary + "\"");
Line(string.Empty);
Line("--" + boundary);
Line("Content-Type: text/plain; charset=utf-8");
Line("Content-Transfer-Encoding: base64");
Line(string.Empty);
Base64(text, Encoding.UTF8.GetBytes(mail.Body.Replace("\r\n", "\n", StringComparison.Ordinal).Replace("\n", "\r\n", StringComparison.Ordinal)));
foreach (var attachment in mail.Attachments)
{
Line("--" + boundary);
var name = EncodeHeader(attachment.FileName);
Line("Content-Type: " + attachment.MediaType + "; name=\"" + name + "\"");
Line("Content-Transfer-Encoding: base64");
Line("Content-Disposition: attachment; filename=\"" + name + "\"");
Line(string.Empty);
Base64(text, attachment.Content);
}
Line("--" + boundary + "--");
return text.ToString();
}
/// <summary>A header value, as an encoded word when it is not plain ASCII.</summary>
/// <param name="value">The value.</param>
/// <returns>The header text.</returns>
public static string EncodeHeader(string value)
{
ArgumentNullException.ThrowIfNull(value);
return value.All(c => c is >= ' ' and <= '~' && c != '"')
? value
: "=?utf-8?B?" + Convert.ToBase64String(Encoding.UTF8.GetBytes(value)) + "?=";
}
private static void Base64(StringBuilder text, byte[] bytes)
{
var encoded = Convert.ToBase64String(bytes);
for (var i = 0; i < encoded.Length; i += 76)
{
text.Append(encoded, i, Math.Min(76, encoded.Length - i)).Append("\r\n");
}
}
}
/// <summary>
/// An SMTP client written in house (SPEC §1.4, §6): STARTTLS or TLS from the start, AUTH PLAIN or LOGIN, one message
/// per connection. Enough for a business sending its documents; no pipelining, no DSN.
/// </summary>
/// <param name="settings">The server.</param>
/// <param name="clock">The clock (date of the messages).</param>
public sealed class SmtpMailSender(SmtpSettings settings, TimeProvider clock) : IMailSender
{
private static readonly TimeSpan Timeout = TimeSpan.FromSeconds(60);
/// <inheritdoc />
public bool IsConfigured => settings.IsConfigured;
/// <inheritdoc />
public async Task SendAsync(OutgoingMail mail, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(mail);
if (!settings.IsConfigured)
{
throw new MailException("No SMTP server is configured (KHAEMHAT_SMTP_HOST, KHAEMHAT_SMTP_FROM).");
}
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
timeout.CancelAfter(Timeout);
var token = timeout.Token;
try
{
using var client = new TcpClient();
await client.ConnectAsync(settings.Host!, settings.Port, token).ConfigureAwait(false);
Stream stream = client.GetStream();
if (settings.Security == SmtpTransportSecurity.Ssl)
{
stream = await TlsAsync(stream, token).ConfigureAwait(false);
}
var session = new Session(stream);
await session.ExpectAsync(220, token).ConfigureAwait(false);
var features = await session.CommandAsync("EHLO " + Environment.MachineName.ToLowerInvariant(), 250, token).ConfigureAwait(false);
if (settings.Security == SmtpTransportSecurity.StartTls)
{
await session.CommandAsync("STARTTLS", 220, token).ConfigureAwait(false);
session = new Session(await TlsAsync(stream, token).ConfigureAwait(false));
features = await session.CommandAsync("EHLO " + Environment.MachineName.ToLowerInvariant(), 250, token).ConfigureAwait(false);
}
if (!string.IsNullOrEmpty(settings.User))
{
if (features.Contains("PLAIN", StringComparison.OrdinalIgnoreCase) || !features.Contains("LOGIN", StringComparison.OrdinalIgnoreCase))
{
var plain = Convert.ToBase64String(Encoding.UTF8.GetBytes("\0" + settings.User + "\0" + settings.Password));
await session.CommandAsync("AUTH PLAIN " + plain, 235, token, secret: true).ConfigureAwait(false);
}
else
{
await session.CommandAsync("AUTH LOGIN", 334, token).ConfigureAwait(false);
await session.CommandAsync(Convert.ToBase64String(Encoding.UTF8.GetBytes(settings.User)), 334, token, secret: true).ConfigureAwait(false);
await session.CommandAsync(Convert.ToBase64String(Encoding.UTF8.GetBytes(settings.Password ?? string.Empty)), 235, token, secret: true).ConfigureAwait(false);
}
}
await session.CommandAsync("MAIL FROM:<" + Address(settings.From!) + ">", 250, token).ConfigureAwait(false);
foreach (var recipient in mail.To.Concat(mail.Cc))
{
await session.CommandAsync("RCPT TO:<" + Address(recipient) + ">", 250, token, alsoAccepted: 251).ConfigureAwait(false);
}
await session.CommandAsync("DATA", 354, token).ConfigureAwait(false);
var message = MimeMessageWriter.Write(mail, settings.From!, clock.GetLocalNow());
var stuffed = string.Join("\r\n", message.Split("\r\n").Select(l => l.StartsWith('.') ? "." + l : l));
await session.CommandAsync(stuffed.TrimEnd('\r', '\n') + "\r\n.", 250, token).ConfigureAwait(false);
await session.CommandAsync("QUIT", 221, token).ConfigureAwait(false);
}
catch (Exception ex) when (ex is SocketException or IOException or System.Security.Authentication.AuthenticationException
|| (ex is OperationCanceledException && !cancellationToken.IsCancellationRequested))
{
throw new MailException("The SMTP server " + settings + " could not be reached: " + ex.Message, ex);
}
}
// The address inside angle brackets: "Name <a@b>" gives a@b.
private static string Address(string text)
{
var start = text.IndexOf('<', StringComparison.Ordinal);
var end = text.IndexOf('>', StringComparison.Ordinal);
return start >= 0 && end > start ? text[(start + 1)..end].Trim() : text.Trim();
}
private async Task<Stream> TlsAsync(Stream inner, CancellationToken cancellationToken)
{
var tls = new SslStream(inner, leaveInnerStreamOpen: false);
await tls.AuthenticateAsClientAsync(new SslClientAuthenticationOptions { TargetHost = settings.Host }, cancellationToken).ConfigureAwait(false);
return tls;
}
// The dialogue on one stream: commands out, replies (possibly on several lines) in.
private sealed class Session(Stream stream)
{
private readonly byte[] _buffer = new byte[4096];
private readonly StringBuilder _pending = new();
public async Task<string> CommandAsync(string command, int expected, CancellationToken cancellationToken, bool secret = false, int? alsoAccepted = null)
{
await stream.WriteAsync(Encoding.UTF8.GetBytes(command + "\r\n"), cancellationToken).ConfigureAwait(false);
await stream.FlushAsync(cancellationToken).ConfigureAwait(false);
var (code, text) = await ReplyAsync(cancellationToken).ConfigureAwait(false);
if (code != expected && code != alsoAccepted)
{
var shown = secret ? command.Split(' ')[0] + " ***" : command.Length > 60 ? command[..60] + "…" : command;
throw new MailException($"The SMTP server answered {code} {text.Trim()} to {shown}.");
}
return text;
}
public async Task ExpectAsync(int expected, CancellationToken cancellationToken)
{
var (code, text) = await ReplyAsync(cancellationToken).ConfigureAwait(false);
if (code != expected)
{
throw new MailException($"The SMTP server greeted with {code} {text.Trim()}.");
}
}
private async Task<(int Code, string Text)> ReplyAsync(CancellationToken cancellationToken)
{
var text = new StringBuilder();
while (true)
{
var line = await LineAsync(cancellationToken).ConfigureAwait(false);
text.Append(line.Length > 4 ? line[4..] : string.Empty).Append('\n');
if (line.Length < 3 || !int.TryParse(line.AsSpan(0, 3), NumberStyles.None, CultureInfo.InvariantCulture, out var code))
{
throw new MailException("The SMTP server sent a reply that is not SMTP: " + line);
}
if (line.Length == 3 || line[3] != '-')
{
return (code, text.ToString());
}
}
}
private async Task<string> LineAsync(CancellationToken cancellationToken)
{
while (true)
{
var text = _pending.ToString();
var end = text.IndexOf("\r\n", StringComparison.Ordinal);
if (end >= 0)
{
_pending.Remove(0, end + 2);
return text[..end];
}
var read = await stream.ReadAsync(_buffer, cancellationToken).ConfigureAwait(false);
if (read == 0)
{
throw new MailException("The SMTP server closed the connection.");
}
_pending.Append(Encoding.UTF8.GetString(_buffer, 0, read));
}
}
}
}
/// <summary>Messages waiting to be sent.</summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Naming", "CA1711:Identifiers should not have incorrect suffix", Justification = "The name of SPEC §21: a queue of messages.")]
public interface IMailQueue
{
/// <summary>Whether a server is configured.</summary>
bool IsConfigured { get; }
/// <summary>Puts a message in the queue; it leaves in the background, the outcome goes to the log (section E-mail/PEC).</summary>
/// <param name="mail">The message.</param>
/// <returns>Whether the message was accepted.</returns>
bool Enqueue(OutgoingMail mail);
}
/// <summary>
/// The queue of outgoing mail (SPEC §12.6): a background service sends one message at a time, tries three times with
/// growing pauses, and writes each outcome in the log, section E-mail/PEC. The queue lives in memory: a message waiting
/// when the service stops is lost and its log says so.
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="logger">The log.</param>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Naming", "CA1711:Identifiers should not have incorrect suffix", Justification = "The name of SPEC §21: a queue of messages.")]
public sealed partial class MailQueue(IMailSender sender, ILogger<MailQueue> logger) : BackgroundService, IMailQueue
{
private const int Attempts = 3;
private readonly Channel<OutgoingMail> _channel = Channel.CreateBounded<OutgoingMail>(new BoundedChannelOptions(500) { SingleReader = true });
/// <inheritdoc />
public bool IsConfigured => sender.IsConfigured;
/// <summary>The pause between two attempts, shorter in tests.</summary>
public TimeSpan RetryDelay { get; init; } = TimeSpan.FromSeconds(30);
/// <inheritdoc />
public bool Enqueue(OutgoingMail mail)
{
ArgumentNullException.ThrowIfNull(mail);
var accepted = _channel.Writer.TryWrite(mail);
using (logger.BeginScope(LogSections.Scope(LogSection.Email)))
{
if (accepted)
{
LogQueued(logger, mail.Reference ?? mail.Subject, string.Join(", ", mail.To));
}
else
{
LogFull(logger, mail.Reference ?? mail.Subject);
}
}
return accepted;
}
/// <inheritdoc />
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
await foreach (var mail in _channel.Reader.ReadAllAsync(stoppingToken).ConfigureAwait(false))
{
using var scope = logger.BeginScope(LogSections.Scope(LogSection.Email));
var reference = mail.Reference ?? mail.Subject;
var to = string.Join(", ", mail.To);
for (var attempt = 1; attempt <= Attempts; attempt++)
{
try
{
await sender.SendAsync(mail, stoppingToken).ConfigureAwait(false);
LogSent(logger, reference, to, attempt);
break;
}
catch (MailException ex) when (attempt < Attempts)
{
LogRetry(logger, reference, to, attempt, ex.Message);
await Task.Delay(RetryDelay * attempt, stoppingToken).ConfigureAwait(false);
}
catch (MailException ex)
{
LogFailed(logger, ex, reference, to, attempt);
}
}
}
}
[LoggerMessage(EventId = 1301, Level = LogLevel.Information, Message = "Mail {Reference} queued for {To}.")]
private static partial void LogQueued(ILogger logger, string reference, string to);
[LoggerMessage(EventId = 1302, Level = LogLevel.Warning, Message = "Mail {Reference} refused: the queue is full.")]
private static partial void LogFull(ILogger logger, string reference);
[LoggerMessage(EventId = 1303, Level = LogLevel.Information, Message = "Mail {Reference} sent to {To} (attempt {Attempt}).")]
private static partial void LogSent(ILogger logger, string reference, string to, int attempt);
[LoggerMessage(EventId = 1304, Level = LogLevel.Warning, Message = "Mail {Reference} to {To} not sent at attempt {Attempt}: {Reason}. It will be tried again.")]
private static partial void LogRetry(ILogger logger, string reference, string to, int attempt, string reason);
[LoggerMessage(EventId = 1305, Level = LogLevel.Error, Message = "Mail {Reference} to {To} not sent after {Attempt} attempts.")]
private static partial void LogFailed(ILogger logger, Exception exception, string reference, string to, int attempt);
}
@@ -273,6 +273,12 @@ else
Value="@PartyScreens.Text(s.CompanyBankAccountId)" ValueChanged="v => Change(() => s.CompanyBankAccountId = PartyScreens.Id(v))" />
<KhNumberBox Label="@T["Parties.Fields.CreditLimit"]" Name="Sales.CreditLimit" Value="s.CreditLimit" ValueChanged="v => Change(() => s.CreditLimit = v)" Min="0" Span="3" />
<KhCheck Label="@T["Parties.Fields.Blocked"]" Name="Sales.Blocked" Value="s.Blocked" ValueChanged="v => Change(() => s.Blocked = v)" Span="3" />
<KhSelect TValue="string" Label="@T["Parties.Fields.ExcludedMonth1"]" Name="Sales.ExcludedMonth1" Options="MonthChoices" Empty="" Span="4"
Value="@s.ExcludedMonth1?.ToString(System.Globalization.CultureInfo.InvariantCulture)" ValueChanged="v => Change(() => s.ExcludedMonth1 = Month(v))" />
<KhSelect TValue="string" Label="@T["Parties.Fields.ExcludedMonth2"]" Name="Sales.ExcludedMonth2" Options="MonthChoices" Empty="" Span="4"
Value="@s.ExcludedMonth2?.ToString(System.Globalization.CultureInfo.InvariantCulture)" ValueChanged="v => Change(() => s.ExcludedMonth2 = Month(v))" />
<KhNumberBox Label="@T["Parties.Fields.ExcludedMonthsDay"]" Name="Sales.ExcludedMonthsDay" Value="s.ExcludedMonthsDay" ValueChanged="v => Change(() => s.ExcludedMonthsDay = (int?)v)"
Min="1" Max="31" Decimals="0" Span="4" Hint="@T["Parties.Hints.ExcludedMonths"]" />
</KhFieldGroup>
<KhFieldGroup Title="@T["Parties.Groups.Delivery"]" Icon="truck">
<KhSelect TValue="string" Label="@T["Parties.Fields.CarrierId"]" Name="Sales.CarrierId" Options="_lookups.Carriers" Empty=""
@@ -874,6 +880,13 @@ else
private void SetAddressKind(PartyAddress address, string? value) => Change(() => address.Kind = Enum.Parse<PartyAddressKind>(value!));
// The months a customer excludes from the due dates (August, December...), named in the language of the screen.
private IReadOnlyList<KhOption<string>> MonthChoices =>
[.. Enumerable.Range(1, 12).Select(m => new KhOption<string>(m.ToString(System.Globalization.CultureInfo.InvariantCulture),
T.Culture.TextInfo.ToTitleCase(T.Culture.DateTimeFormat.GetMonthName(m))))];
private static int? Month(string? value) => int.TryParse(value, System.Globalization.NumberStyles.None, System.Globalization.CultureInfo.InvariantCulture, out var m) ? m : null;
private void SetDelivery(PartySalesTerms terms, string? value) => Change(() => terms.SendDocuments = Enum.Parse<DocumentDelivery>(value!));
private Task SetSubjectAsync(string? value)
@@ -0,0 +1,334 @@
@page "/vendite/fatturazione-differita"
@attribute [Authorize]
@using Khaemhat.Application.Documents
@using Khaemhat.Application.Parties
@using Khaemhat.Application.Security
@using Khaemhat.Core.Documents
@using Khaemhat.Core.Parties
@using Khaemhat.Web.Documents
@using Khaemhat.Web.Tables
@inject ShellSession Session
@inject DocumentEditor Editor
@inject DocumentEngine Engine
@inject DocumentCopyService Copies
@inject PartyService Parties
@inject ToastService Toasts
@inject TimeProvider Clock
@* The deferred invoicing (SPEC §11.3, mockup 030): the confirmed delivery notes not yet invoiced in a period, for one
customer or all; one deferred invoice (TD24) per customer, or per delivery note, with a reference line for each
delivery note; the invoices can be issued at once. *@
<KhPageTitle Text="@T["Sales.Deferred.Title"]" Icon="layers" />
@if (!_loaded)
{
<p class="muted kh-pad">@T["Common.Loading"]</p>
}
else if (Session.Company is null)
{
<div class="kh-message"><KhIcon Name="building" Class="lg" /><h1>@T["Sales.NoCompany"]</h1></div>
}
else if (!Session.Permissions.Allows("sales.invoice.write") || !Session.Permissions.Allows("sales.delivery.read"))
{
<div class="kh-message">
<KhIcon Name="lock" Class="lg" />
<h1>@T["Pages.AccessDenied.Title"]</h1>
<p class="lead">@T["Pages.AccessDenied.Lead"]</p>
</div>
}
else
{
<div class="kh-import">
<div class="kh-import-side">
<KhPanel Title="@T["Sales.Deferred.Procedure"]" Icon="layers">
<KhVSteps Items="Steps" Current="_step" Label="@T["Sales.Deferred.Procedure"]" />
<div class="kh-import-options">
<KhDateBox Label="@T["Sales.Deferred.From"]" Name="From" Value="_from" ValueChanged="v => Reset(() => _from = v)" Span="6" Disabled="_busy" />
<KhDateBox Label="@T["Sales.Deferred.To"]" Name="To" Value="_to" ValueChanged="v => Reset(() => _to = v)" Span="6" Required="true" Disabled="_busy" />
<KhHotlink TItem="PartyRow" Label="@T["Sales.Deferred.Customer"]" Name="PartyId" Value="_party" ValueChanged="v => Reset(() => _party = v)" Span="12"
Search="SearchAsync" CodeOf="r => r.Code" DescriptionOf="r => r.Name" Hint="@T["Sales.Deferred.AllCustomers"]" Disabled="_busy" />
<KhDateBox Label="@T["Sales.Deferred.InvoiceDate"]" Name="InvoiceDate" Value="_invoiceDate" ValueChanged="v => _invoiceDate = v" Span="12" Required="true" Disabled="_busy" />
<KhSelect TValue="string" Label="@T["Sales.Deferred.Grouping"]" Name="Grouping" Options="GroupingChoices" Value="@(_perNote ? "note" : "party")"
ValueChanged="SetGrouping" Span="12" Disabled="_busy" />
<KhCheck Label="@T["Sales.Deferred.Issue"]" Name="Issue" Value="_issue" ValueChanged="v => _issue = v" Span="12" Disabled="_busy" />
<div class="c12 kh-endrow">
<button type="button" class="btn" disabled="@_busy" @onclick="SearchNotesAsync"><KhIcon Name="search" /> @T["Sales.Deferred.Search"]</button>
</div>
</div>
</KhPanel>
</div>
<div class="kh-import-main">
@if (_results.Count > 0)
{
<KhPanel Title="@T["Sales.Deferred.Results"]" Icon="check-circle">
<div class="gridwrap">
<table class="grid" aria-label="@T["Sales.Deferred.Results"]">
<thead>
<tr>
<th scope="col">@T["Sales.Fields.PartyId"]</th>
<th scope="col">@T["Sales.Deferred.Invoice"]</th>
<th scope="col">@T["Sales.Radar.State"]</th>
<th scope="col" class="num">@T["Sales.Totals.Total"]</th>
</tr>
</thead>
<tbody>
@foreach (var result in _results)
{
<tr>
<td>@result.PartyName</td>
@if (result.Record is { } record)
{
var state = SalesScreens.State(T, record.Header.Kind, record.Header.Status, null, Today);
<td class="code"><a href="@SalesScreens.RecordUrl(record.Header.Kind, record.Header.Id)">@(record.Header.DocumentNumber ?? T["Sales.DraftNumber"])</a></td>
<td><KhBadge Tone="state.Tone">@state.Text</KhBadge></td>
<td class="num">@T.Money(record.Header.TotalAmount)</td>
}
else
{
<td colspan="3" class="err"><KhIcon Name="alert-circle" /> @result.Error</td>
}
</tr>
}
</tbody>
</table>
</div>
<div class="kh-endrow kh-pad">
<a class="btn" href="vendite/fatture"><KhIcon Name="euro" /> @T["Sales.Sections.Invoices.Title"]</a>
<button type="button" class="btn" @onclick="Restart"><KhIcon Name="refresh" /> @T["Sales.Deferred.Again"]</button>
</div>
</KhPanel>
}
else
{
<KhPanel Title="@T["Sales.Deferred.Notes"]" Icon="truck">
<Actions>
<span class="muted sm">@T.Format("Sales.Deferred.Selected", _selected.Count, T.Money(SelectedTotal))</span>
<button type="button" class="btn primary" disabled="@(_selected.Count == 0 || _busy || _invoiceDate is null)" @onclick="GenerateAsync">
<KhIcon Name="send" /> @T["Sales.Deferred.Generate"]
</button>
</Actions>
<ChildContent>
@if (_notes is null)
{
<p class="muted kh-pad">@T["Sales.Deferred.Start"]</p>
}
else if (_notes.Count == 0)
{
<p class="muted kh-pad">@T["Sales.Deferred.None"]</p>
}
else
{
<div class="gridwrap">
<table class="grid" aria-label="@T["Sales.Deferred.Notes"]">
<thead>
<tr>
<th scope="col" class="kh-check"><input type="checkbox" checked="@(_selected.Count == _notes.Count)" aria-label="@T["Sales.Transform.All"]" @onchange="ToggleAll" /></th>
<th scope="col">@T["Sales.Kinds.DeliveryNote"]</th>
<th scope="col">@T["Sales.Fields.DocumentDate"]</th>
<th scope="col">@T["Sales.Fields.PartyId"]</th>
<th scope="col" class="num">@T["Sales.Deferred.Lines"]</th>
<th scope="col" class="num">@T["Sales.Totals.Taxable"]</th>
<th scope="col">@T["Sales.Deferred.Invoice"]</th>
</tr>
</thead>
<tbody>
@foreach (var note in _notes)
{
var id = note.Row.Id;
<tr>
<td class="kh-check"><input type="checkbox" checked="@_selected.Contains(id)" aria-label="@note.Row.DocumentNumber" @onchange="e => Toggle(id, e.Value is true)" /></td>
<td class="code"><a href="@SalesScreens.RecordUrl(note.Row.Kind, id)">@note.Row.DocumentNumber</a></td>
<td>@T.Date(note.Row.Date)</td>
<td>@note.Row.PartyName</td>
<td class="num">@note.Lines.Count</td>
<td class="num">@T.Money(note.Row.Taxable)</td>
<td class="muted">@InvoiceLabel(note)</td>
</tr>
}
</tbody>
</table>
</div>
}
</ChildContent>
</KhPanel>
}
</div>
</div>
}
@code {
private readonly HashSet<long> _selected = [];
private readonly List<DeferredResult> _results = [];
private IReadOnlyList<OpenDocument>? _notes;
private PartyRow? _party;
private DateOnly? _from;
private DateOnly? _to;
private DateOnly? _invoiceDate;
private bool _perNote;
private bool _issue;
private bool _busy;
private bool _loaded;
private int _step;
private DateOnly Today => DateOnly.FromDateTime(TimeZoneInfo.ConvertTime(Clock.GetUtcNow(), TimeZoneInfo.Local).DateTime);
private IReadOnlyList<KhStep> Steps =>
[
new(T["Sales.Deferred.Steps.Period"], T["Sales.Deferred.Steps.PeriodDetail"]),
new(T["Sales.Deferred.Steps.Choose"], T["Sales.Deferred.Steps.ChooseDetail"]),
new(T["Sales.Deferred.Steps.Generate"], T["Sales.Deferred.Steps.GenerateDetail"]),
];
private IReadOnlyList<KhOption<string>> GroupingChoices =>
[new("party", T["Sales.Deferred.PerParty"]), new("note", T["Sales.Deferred.PerNote"])];
private decimal SelectedTotal => _notes?.Where(n => _selected.Contains(n.Row.Id)).Sum(n => n.Row.Taxable) ?? 0m;
/// <inheritdoc />
protected override async Task OnInitializedAsync()
{
await Session.EnsureLoadedAsync();
// The usual run: the delivery notes of last month, invoiced on its last day.
var firstOfMonth = new DateOnly(Today.Year, Today.Month, 1);
_from = firstOfMonth.AddMonths(-1);
_to = firstOfMonth.AddDays(-1);
_invoiceDate = _to;
_loaded = true;
}
private void Reset(Action change)
{
change();
_notes = null;
_selected.Clear();
_step = 0;
}
private async Task<IReadOnlyList<PartyRow>> SearchAsync(string text, CancellationToken cancellationToken) =>
Session.Actor is { } actor && Session.Company?.Code is { } company && Session.Permissions.Allows(PartyService.ReadPermission)
? await Parties.SearchAsync(actor, company, PartyArchive.Customers, text, cancellationToken)
: [];
private async Task SearchNotesAsync()
{
if (Session.Actor is not { } actor || Session.Company?.Code is not { } company)
{
return;
}
if (_to is null)
{
Toasts.Show(ToastKind.Error, T["Sales.Deferred.ToRequired"]);
return;
}
_busy = true;
try
{
_notes = await Editor.OpenAsync(actor, company, DocumentFamily.SaleDocument, [DocumentKind.DeliveryNote], _party?.Id, _from, _to);
_selected.Clear();
_selected.UnionWith(_notes.Select(n => n.Row.Id));
_step = 1;
}
catch (AccessDeniedException)
{
Toasts.Show(ToastKind.Error, T["Pages.AccessDenied.Title"]);
}
finally
{
_busy = false;
}
}
private void Toggle(long id, bool on)
{
if (on)
{
_selected.Add(id);
}
else
{
_selected.Remove(id);
}
}
private void ToggleAll(ChangeEventArgs e)
{
_selected.Clear();
if (e.Value is true && _notes is not null)
{
_selected.UnionWith(_notes.Select(n => n.Row.Id));
}
}
// The invoices the run will make: one per customer (or per delivery note), in the order of the list.
private List<List<OpenDocument>> Groups() => _notes is null ? [] : _perNote
? [.. _notes.Where(n => _selected.Contains(n.Row.Id)).Select(n => new List<OpenDocument> { n })]
: [.. _notes.Where(n => _selected.Contains(n.Row.Id)).GroupBy(n => n.Row.PartyId).Select(g => g.ToList())];
private string? InvoiceLabel(OpenDocument note)
{
if (!_selected.Contains(note.Row.Id))
{
return null;
}
var groups = Groups();
var index = groups.FindIndex(g => g.Any(n => n.Row.Id == note.Row.Id));
return index < 0 ? null : T.Format("Sales.Deferred.InvoiceNumber", index + 1, groups[index].Count);
}
private async Task GenerateAsync()
{
if (Session.Actor is not { } actor || Session.Company?.Code is not { } company || _invoiceDate is not { } date)
{
return;
}
_busy = true;
_results.Clear();
try
{
foreach (var group in Groups())
{
var name = group[0].Row.PartyName ?? string.Empty;
try
{
var invoice = await Copies.MergeAsync(actor, company, DocumentFamily.SaleDocument, [.. group.Select(n => n.Row.Id)], "FD", date);
if (_issue)
{
invoice = await Engine.ConfirmAsync(actor, company, invoice.Family, invoice.Header.Id);
}
_results.Add(new(name, invoice, null));
}
catch (ValidationFailedException ex)
{
_results.Add(new(name, null, string.Join(" ", ex.Errors.Select(e => TableValues.SplitError(e).Code).Select(c => T.Contains(c) ? T[c] : c))));
}
catch (InvalidDocumentActionException)
{
_results.Add(new(name, null, T[InvalidDocumentActionException.Code]));
}
}
_step = 2;
var made = _results.Count(r => r.Record is not null);
Toasts.Show(made == _results.Count ? ToastKind.Success : ToastKind.Warning, T.Format("Sales.Deferred.Done", made, _results.Count));
}
finally
{
_busy = false;
}
}
private void SetGrouping(string? value) => _perNote = value == "note";
private void Restart()
{
_results.Clear();
Reset(() => { });
}
private sealed record DeferredResult(string PartyName, DocumentRecord? Record, string? Error);
}
@@ -0,0 +1,409 @@
@page "/vendite/{Segment}/nuovo"
@page "/vendite/{Segment}/{Id:long}"
@attribute [Authorize]
@inherits DocumentPage<DocumentRecord, DocumentLine>
@using Khaemhat.Application.Audit
@using Khaemhat.Application.Documents
@using Khaemhat.Application.Items
@using Khaemhat.Application.Parties
@using Khaemhat.Core.Documents
@using Khaemhat.Core.Tax
@using Khaemhat.Web.Documents
@using Khaemhat.Web.Parties
@* The record of a sales document (SPEC §11.3, mockups 020-022 and 026-029): quotation, order, delivery note, invoice of
every kind, pro forma, credit and debit note. Righe first with the VAT summary, due dates and totals underneath, then
Testata, Trasporto for the documents that move goods, Totali, Scadenze, Note, Allegati, Collegamenti, Storico. The
totals are computed while typing with the code of the save; the actions follow the state machine of the engine. *@
<KhPageTitle Text="@PageTitle" Icon="@(_section?.Icon ?? "file")" />
@if (!_loaded)
{
<p class="muted kh-pad">@T["Common.Loading"]</p>
}
else if (Session.Company is null)
{
<div class="kh-message"><KhIcon Name="building" Class="lg" /><h1>@T["Sales.NoCompany"]</h1></div>
}
else if (_denied)
{
<div class="kh-message">
<KhIcon Name="lock" Class="lg" />
<h1>@T["Pages.AccessDenied.Title"]</h1>
<p class="lead">@T["Pages.AccessDenied.Lead"]</p>
</div>
}
else if (Record is null || _section is null || _definition is null)
{
<div class="kh-message">
<KhIcon Name="alert" Class="lg" />
<h1>@T["Sales.NotFound"]</h1>
<a class="btn" href="@(_section is null ? SalesScreens.BasePath : SalesScreens.RadarUrl(_section))">@T["Sales.BackToList"]</a>
</div>
}
else
{
var h = Record.Header;
<KhRecordLayout Page="this">
<Heading>
<KhDocHead KindIcon="@_section.Icon" KindLabel="@_definition.Type.Description" Number="@(h.DocumentNumber ?? T["Sales.DraftNumber"])"
PartyName="@(_party?.Name ?? T["Sales.NoParty"])" PartyCode="@_party?.Code" PartyLines="PartyLines"
TotalLabel="@T[ShowsNet ? "Sales.Totals.Net" : "Sales.Totals.Total"]" TotalValue="@T.Money(ShowsNet ? h.NetAmount : h.TotalAmount)" SubValues="HeadStats">
<Facts>
<span>@T["Sales.Fields.DocumentDate"] <b>@T.Date(h.DocumentDate)</b></span>
@if (h.Kind == DocumentKind.Quotation && h.ValidUntil is { } until)
{
<span>@T["Sales.Fields.ValidUntil"] <b>@T.Date(until)</b></span>
}
@if (h.DeliveryDate is { } delivery)
{
<span>@T["Sales.Fields.DeliveryDate"] <b>@T.Date(delivery)</b></span>
}
@if (h.Revision > 0)
{
<span>@T["Sales.Fields.Revision"] <b>@h.Revision</b></span>
}
@if (h.RelatedNumber is { } related)
{
<span>@T["Sales.Fields.Related"] <b>@related</b>@(h.RelatedDate is { } rd ? " · " + T.Date(rd) : null)</span>
}
</Facts>
<State>
@{ var state = SalesScreens.State(T, h.Kind, h.Status, h.ValidUntil, Today); }
<KhBadge Tone="state.Tone">@state.Text</KhBadge>
@if (h.IsDemo)
{
<KhBadge Tone="KhTone.Info">@T["Sales.Demo"]</KhBadge>
}
@if (IsModified)
{
<KhBadge Tone="KhTone.Warning">@T["CompanyTables.Modified"]</KhBadge>
}
</State>
<Chips>
@if (PartyScreens.Describe(_lookups.PaymentTerms, h.PaymentTermId) is { } payment)
{
<KhChip Icon="coins" Text="@T["Sales.Fields.PaymentTermId"]" Value="@payment" />
}
@if (PartyScreens.Describe(_lookups.PriceLists, h.PriceListId) is { } list)
{
<KhChip Icon="tag" Text="@T["Sales.Fields.PriceListId"]" Value="@list" />
}
@if (PartyScreens.Describe(_lookups.Salespeople, h.SalespersonId) is { } agent)
{
<KhChip Icon="user" Text="@T["Sales.Fields.SalespersonId"]" Value="@agent" />
}
@if (h.SplitPayment)
{
<KhChip Icon="shield" Text="@T["Sales.Fields.SplitPayment"]" Value="@T["Common.Yes"]" />
}
</Chips>
</KhDocHead>
</Heading>
<ChildContent>
@switch (ActiveTab)
{
case TabIds.Lines:
@if (h.PartyId is null && !IsReadOnly)
{
<div class="callout info kh-doc-callout"><KhIcon Name="info" /> <span>@T["Sales.Hints.PartyFirst"]</span>
<button type="button" class="btn" @onclick="() => ShowTabAsync(TabIds.Header)">@T["Sales.Actions.ChooseParty"]</button></div>
}
<KhLinesGrid TLine="DocumentLine" @ref="_grid" Lines="Record.Lines" Columns="LineColumns" NewLine="NewLine" IsEmpty="IsEmptyLine"
IsDescriptive="l => l.Kind == DocumentLineKind.Description" NewDescriptive="NewDescriptionLine" DescriptionColumn="LineColumns[1]"
ReadOnly="IsReadOnly" OnChanged="LinesChangedAsync" Label="@T["Sales.Lines.Title"]" />
@if (Validation.Messages.Any(m => m.Field?.StartsWith("Lines.", StringComparison.Ordinal) == true))
{
<ul class="kh-doc-errors">
@foreach (var message in Validation.Messages.Where(m => m.Field?.StartsWith("Lines.", StringComparison.Ordinal) == true))
{
<li><KhIcon Name="alert-circle" /> @LineErrorText(message.Field!, message.Message)</li>
}
</ul>
}
<div class="kh-doc-panels">
<KhPanel Title="@T["Sales.Totals.Summary"]" Icon="euro" Tight="true">@TaxSummary</KhPanel>
<KhPanel Title="@T["Sales.Totals.Installments"]" Icon="calendar" Tight="true">@Installments</KhPanel>
<KhPanel Title="@T["Sales.Totals.Title"]" Icon="coins" Tight="true">@Totals</KhPanel>
</div>
break;
case TabIds.Header:
<KhForm Validation="Validation" ReadOnly="IsReadOnly" Layout="KhFormLayout.Groups" @ref="Form">
<KhFieldGroup Title="@T["Sales.Groups.Document"]" Icon="file">
<KhTextBox Label="@T["Sales.Fields.DocumentTypeId"]" Name="DocumentTypeId" Value="@(_definition.Code + " · " + _definition.Type.Description)" ReadOnly="true" Span="6" />
<KhTextBox Label="@T["Sales.Fields.DocumentNumber"]" Name="DocumentNumber" Value="@(h.DocumentNumber ?? T["Sales.NumberOnConfirm"])" ReadOnly="true" Mono="true" Span="6" />
<KhDateBox Label="@T["Sales.Fields.DocumentDate"]" Name="DocumentDate" Value="h.DocumentDate" Required="true" Span="4" ReadOnly="@(h.Number is not null)"
ValueChanged="v => ChangeAsync(() => { if (v is { } d) { h.DocumentDate = d; h.Year = d.Year; } })" />
@if (h.Kind == DocumentKind.Quotation)
{
<KhDateBox Label="@T["Sales.Fields.ValidUntil"]" Name="ValidUntil" Value="h.ValidUntil" ValueChanged="v => Change(() => h.ValidUntil = v)" Span="4" />
}
@if (h.Kind is DocumentKind.Quotation or DocumentKind.SalesOrder or DocumentKind.DeliveryNote or DocumentKind.ProForma)
{
<KhDateBox Label="@T["Sales.Fields.DeliveryDate"]" Name="DeliveryDate" Value="h.DeliveryDate" ValueChanged="v => Change(() => h.DeliveryDate = v)" Span="4" />
}
<KhTextBox Label="@T["Sales.Fields.ExternalReference"]" Name="ExternalReference" Value="@h.ExternalReference" ValueChanged="v => Change(() => h.ExternalReference = v)"
Span="8" MaxLength="60" Hint="@T["Sales.Hints.ExternalReference"]" />
<KhDateBox Label="@T["Sales.Fields.ExternalDate"]" Name="ExternalDate" Value="h.ExternalDate" ValueChanged="v => Change(() => h.ExternalDate = v)" Span="4" />
@if (IsNote)
{
<KhTextBox Label="@T["Sales.Fields.RelatedNumber"]" Name="RelatedNumber" Value="@h.RelatedNumber" ValueChanged="v => Change(() => h.RelatedNumber = v)"
Span="8" MaxLength="30" Mono="true" Hint="@T["Sales.Hints.Related"]" />
<KhDateBox Label="@T["Sales.Fields.RelatedDate"]" Name="RelatedDate" Value="h.RelatedDate" ValueChanged="v => Change(() => h.RelatedDate = v)" Span="4" />
}
</KhFieldGroup>
<KhFieldGroup Title="@T["Sales.Groups.Party"]" Icon="users">
<KhHotlink TItem="PartyRow" Label="@T["Sales.Fields.PartyId"]" Name="PartyId" Span="12" Required="true" Value="_party" ValueChanged="SetPartyAsync"
Search="SearchPartiesAsync" CodeOf="r => r.Code" DescriptionOf="r => r.Name" OnOpen="OpenParty" ReadOnly="@(Record.Lines.Any(l => l.SourceLineId is not null))" />
<KhSelect TValue="string" Label="@T["Sales.Fields.SalespersonId"]" Name="SalespersonId" Options="_lookups.Salespeople" Empty="" Span="6"
Value="@PartyScreens.Text(h.SalespersonId)" ValueChanged="v => Change(() => h.SalespersonId = PartyScreens.Id(v))" />
<KhSelect TValue="string" Label="@T["Sales.Fields.CurrencyCode"]" Name="CurrencyCode" Options="_lookups.Currencies" Span="6"
Value="@h.CurrencyCode" ValueChanged="SetCurrency" />
@if (h.PartyId is not null)
{
<p class="muted sm c12"><KhIcon Name="info" /> @T["Sales.Hints.PartyDefaults"]</p>
}
</KhFieldGroup>
<KhFieldGroup Title="@T["Sales.Groups.Conditions"]" Icon="coins">
<KhSelect TValue="string" Label="@T["Sales.Fields.PriceListId"]" Name="PriceListId" Options="_lookups.PriceLists" Empty="" Span="6"
Value="@PartyScreens.Text(h.PriceListId)" ValueChanged="v => Change(() => h.PriceListId = PartyScreens.Id(v))" />
<KhTextBox Label="@T["Sales.Fields.FooterDiscount"]" Name="FooterDiscount" Value="@h.FooterDiscount" ValueChanged="v => ChangeAsync(() => h.FooterDiscount = v)"
Span="3" Mono="true" MaxLength="30" Placeholder="10+5" />
<KhCheck Label="@T["Sales.Fields.PricesIncludeTax"]" Name="PricesIncludeTax" Value="h.PricesIncludeTax" ValueChanged="v => ChangeAsync(() => h.PricesIncludeTax = v)" Span="3" />
<KhSelect TValue="string" Label="@T["Sales.Fields.PaymentTermId"]" Name="PaymentTermId" Options="_lookups.PaymentTerms" Empty="" Span="6"
Value="@PartyScreens.Text(h.PaymentTermId)" ValueChanged="v => ChangeAsync(() => h.PaymentTermId = PartyScreens.Id(v))" />
<KhSelect TValue="string" Label="@T["Sales.Fields.PaymentMethodId"]" Name="PaymentMethodId" Options="_lookups.PaymentMethods" Empty="" Span="6"
Value="@PartyScreens.Text(h.PaymentMethodId)" ValueChanged="v => Change(() => h.PaymentMethodId = PartyScreens.Id(v))" />
<KhSelect TValue="string" Label="@T["Sales.Fields.BankAccountId"]" Name="BankAccountId" Options="_lookups.BankAccounts" Empty="" Span="12"
Value="@PartyScreens.Text(h.BankAccountId)" ValueChanged="v => Change(() => h.BankAccountId = PartyScreens.Id(v))" />
</KhFieldGroup>
@if (IsInvoice)
{
<KhFieldGroup Title="@T["Sales.Groups.Tax"]" Icon="shield">
<KhSelect TValue="string" Label="@T["Sales.Fields.Exigibility"]" Name="Exigibility" Options="ExigibilityChoices" Empty="" Span="6"
Value="@h.Exigibility?.ToString()" ValueChanged="SetExigibilityAsync" />
<KhCheck Label="@T["Sales.Fields.SplitPayment"]" Name="SplitPayment" Value="h.SplitPayment" ValueChanged="v => ChangeAsync(() => h.SplitPayment = v)" Span="3" />
<KhCheck Label="@T["Sales.Fields.StampDutyCharged"]" Name="StampDutyCharged" Value="h.StampDutyCharged" ValueChanged="v => ChangeAsync(() => h.StampDutyCharged = v)" Span="3" />
<KhTextBox Label="@T["Sales.Fields.Cig"]" Name="Cig" Value="@h.Cig" ValueChanged="v => Change(() => h.Cig = v)" Span="6" Mono="true" MaxLength="15" />
<KhTextBox Label="@T["Sales.Fields.Cup"]" Name="Cup" Value="@h.Cup" ValueChanged="v => Change(() => h.Cup = v)" Span="6" Mono="true" MaxLength="15" />
</KhFieldGroup>
<KhFieldGroup Title="@T["Sales.Groups.Withholding"]" Icon="coins">
<KhNumberBox Label="@T["Sales.Fields.WithholdingRate"]" Name="WithholdingRate" Value="h.WithholdingRate" ValueChanged="v => ChangeAsync(() => h.WithholdingRate = v)" Min="0" Max="100" Span="3" />
<KhNumberBox Label="@T["Sales.Fields.WithholdingBasePercent"]" Name="WithholdingBasePercent" Value="h.WithholdingBasePercent"
ValueChanged="v => ChangeAsync(() => h.WithholdingBasePercent = v ?? 100m)" Min="0" Max="100" Span="3" />
<KhTextBox Label="@T["Sales.Fields.WithholdingType"]" Name="WithholdingType" Value="@h.WithholdingType" ValueChanged="v => Change(() => h.WithholdingType = v)" Span="3" Mono="true" MaxLength="4" Placeholder="RT01" />
<KhTextBox Label="@T["Sales.Fields.WithholdingReason"]" Name="WithholdingReason" Value="@h.WithholdingReason" ValueChanged="v => Change(() => h.WithholdingReason = v)" Span="3" Mono="true" MaxLength="2" Placeholder="A" />
<KhTextBox Label="@T["Sales.Fields.SocialSecurityFund"]" Name="SocialSecurityFund" Value="@h.SocialSecurityFund" ValueChanged="v => Change(() => h.SocialSecurityFund = v)" Span="3" Mono="true" MaxLength="4" Placeholder="TC22" />
<KhNumberBox Label="@T["Sales.Fields.SocialSecurityRate"]" Name="SocialSecurityRate" Value="h.SocialSecurityRate" ValueChanged="v => ChangeAsync(() => h.SocialSecurityRate = v)" Min="0" Max="100" Span="3" />
<KhSelect TValue="string" Label="@T["Sales.Fields.SocialSecurityTaxCodeId"]" Name="SocialSecurityTaxCodeId" Options="_lookups.TaxCodes" Empty="" Span="3"
Value="@PartyScreens.Text(h.SocialSecurityTaxCodeId)" ValueChanged="v => ChangeAsync(() => h.SocialSecurityTaxCodeId = PartyScreens.Id(v))" />
<KhCheck Label="@T["Sales.Fields.SocialSecurityWithheld"]" Name="SocialSecurityWithheld" Value="h.SocialSecurityWithheld" ValueChanged="v => ChangeAsync(() => h.SocialSecurityWithheld = v)" Span="3" />
<KhNumberBox Label="@T["Sales.Fields.EnasarcoRate"]" Name="EnasarcoRate" Value="h.EnasarcoRate" ValueChanged="v => ChangeAsync(() => h.EnasarcoRate = v)" Min="0" Max="100" Span="3" />
<p class="muted sm c9">@T["Sales.Hints.Withholding"]</p>
</KhFieldGroup>
}
</KhForm>
break;
case SalesScreens.TransportTab:
<KhForm Validation="Validation" ReadOnly="IsReadOnly" Layout="KhFormLayout.Groups" @ref="Form">
<KhFieldGroup Title="@T["Sales.Groups.Transport"]" Icon="truck">
<KhSelect TValue="string" Label="@T["Sales.Fields.TransportReasonId"]" Name="TransportReasonId" Options="_lookups.TransportReasons" Empty="" Span="6"
Value="@PartyScreens.Text(h.TransportReasonId)" ValueChanged="v => Change(() => h.TransportReasonId = PartyScreens.Id(v))" />
<KhSelect TValue="string" Label="@T["Sales.Fields.TransportBy"]" Name="TransportBy" Options="TransportChoices" Empty="" Span="6"
Value="@h.TransportBy?.ToString()" ValueChanged="SetTransportBy" />
<KhSelect TValue="string" Label="@T["Sales.Fields.CarrierId"]" Name="CarrierId" Options="_lookups.Carriers" Empty="" Span="6"
Value="@PartyScreens.Text(h.CarrierId)" ValueChanged="v => Change(() => h.CarrierId = PartyScreens.Id(v))" />
<KhSelect TValue="string" Label="@T["Sales.Fields.ShippingTermId"]" Name="ShippingTermId" Options="_lookups.ShippingTerms" Empty="" Span="6"
Value="@PartyScreens.Text(h.ShippingTermId)" ValueChanged="v => Change(() => h.ShippingTermId = PartyScreens.Id(v))" />
<KhDateBox Label="@T["Sales.Fields.TransportStartDate"]" Name="TransportStart" Value="TransportDate" ValueChanged="SetTransportDate" Span="4" />
<KhTextBox Label="@T["Sales.Fields.TransportStartTime"]" Name="TransportStartTime" Type="time" Value="@TransportTime" ValueChanged="SetTransportTime" Span="2" />
<KhSelect TValue="string" Label="@T["Sales.Fields.WarehouseId"]" Name="WarehouseId" Options="_lookups.Warehouses" Empty="" Span="6"
Value="@PartyScreens.Text(h.WarehouseId)" ValueChanged="v => Change(() => h.WarehouseId = PartyScreens.Id(v))" />
</KhFieldGroup>
<KhFieldGroup Title="@T["Sales.Groups.Goods"]" Icon="box">
<KhSelect TValue="string" Label="@T["Sales.Fields.GoodsAppearanceId"]" Name="GoodsAppearanceId" Options="_lookups.GoodsAppearances" Empty="" Span="12"
Value="@PartyScreens.Text(h.GoodsAppearanceId)" ValueChanged="v => Change(() => h.GoodsAppearanceId = PartyScreens.Id(v))" />
<KhNumberBox Label="@T["Sales.Fields.Packages"]" Name="Packages" Value="h.Packages" ValueChanged="v => Change(() => h.Packages = (int?)v)" Min="0" Decimals="0" Span="4" />
<KhNumberBox Label="@T["Sales.Fields.GrossWeight"]" Name="GrossWeight" Value="h.GrossWeight" ValueChanged="v => Change(() => h.GrossWeight = v)" Min="0" Decimals="3" Span="4" />
<KhNumberBox Label="@T["Sales.Fields.NetWeight"]" Name="NetWeight" Value="h.NetWeight" ValueChanged="v => Change(() => h.NetWeight = v)" Min="0" Decimals="3" Span="4" />
<p class="muted sm c12">@T["Sales.Hints.Transport"]</p>
</KhFieldGroup>
</KhForm>
break;
case TabIds.Totals:
<div class="kh-doc-panels wide">
<KhPanel Title="@T["Sales.Totals.Summary"]" Icon="euro" Tight="true">@TaxSummary</KhPanel>
<KhPanel Title="@T["Sales.Totals.Title"]" Icon="coins" Tight="true">@Totals</KhPanel>
</div>
break;
case TabIds.DueDates:
<div class="kh-doc-panels single">
<KhPanel Title="@T["Sales.Totals.Installments"]" Icon="calendar" Tight="true">@Installments</KhPanel>
</div>
<p class="muted sm kh-pad"><KhIcon Name="info" /> @T[Behavior.Has(DocumentEffects.Installments) ? "Sales.Hints.Installments" : "Sales.Hints.InstallmentsForecast"]</p>
break;
case TabIds.Notes:
<KhForm Validation="Validation" ReadOnly="IsReadOnly" Layout="KhFormLayout.Groups" @ref="Form">
<KhFieldGroup Title="@T["Sales.Groups.Notes"]" Icon="edit" Wide="true">
<KhTextArea Label="@T["Sales.Fields.Notes"]" Name="Notes" Value="@h.Notes" ValueChanged="v => Change(() => h.Notes = v)" Span="12" Rows="6"
Hint="@T["Sales.Hints.Notes"]" />
</KhFieldGroup>
@if (h.CancelReason is { } reason)
{
<KhFieldGroup Title="@T["Sales.Groups.Cancelled"]" Icon="x-circle" Wide="true">
<KhTextArea Label="@T["Sales.Fields.CancelReason"]" Name="CancelReason" Value="@reason" ReadOnly="true" Span="12" Rows="2" />
</KhFieldGroup>
}
</KhForm>
break;
case TabIds.Attachments:
<div class="kh-tab-body"><KhAttachmentList Entity="@AttachmentEntity" EntityId="h.Id" OnCountChanged="SetAttachments" /></div>
break;
case TabIds.Links:
<div class="kh-tab-body">
@if (_links.Count == 0)
{
<p class="muted">@T["Sales.Links.Empty"]</p>
}
else
{
<div class="gridwrap">
<table class="grid" aria-label="@T["Ui.Record.Tabs.Links"]">
<thead>
<tr>
<th scope="col">@T["Sales.Links.Relation"]</th>
<th scope="col">@T["Sales.Radar.Kind"]</th>
<th scope="col">@T["Sales.Fields.DocumentNumber"]</th>
<th scope="col">@T["Sales.Fields.DocumentDate"]</th>
<th scope="col">@T["Sales.Radar.State"]</th>
<th scope="col" class="num">@T["Sales.Links.Quantity"]</th>
<th scope="col" class="num">@T["Sales.Totals.Total"]</th>
</tr>
</thead>
<tbody>
@foreach (var link in _links)
{
var linkState = SalesScreens.State(T, link.Kind, link.Status, null, Today);
<tr>
<td>@T["Sales.Links." + link.Direction]</td>
<td>@SalesScreens.KindName(T, link.Kind)</td>
<td class="code">
@if (SalesScreens.RecordUrl(link.Kind, link.Id) is { } url)
{
<a href="@url">@(link.DocumentNumber ?? T["Sales.DraftNumber"])</a>
}
else
{
@(link.DocumentNumber ?? T["Sales.DraftNumber"])
}
</td>
<td>@T.Date(link.Date)</td>
<td><KhBadge Tone="linkState.Tone">@linkState.Text</KhBadge></td>
<td class="num">@(link.Quantity > 0 ? T.Number(link.Quantity, 2) : null)</td>
<td class="num">@T.Money(link.Total)</td>
</tr>
}
</tbody>
</table>
</div>
}
</div>
break;
case TabIds.History:
<div class="kh-tab-body"><KhAuditList Items="_history" FieldName="FieldLabel" /></div>
break;
}
</ChildContent>
</KhRecordLayout>
<KhRadarDialog TItem="ItemRow" Id="sales.items" Open="_lookupLine is not null" Title="@T["Sales.Lines.ItemRadar"]" Columns="ItemColumns" Source="ListItemsAsync"
KeyOf="i => i.Id" InitialSearch="@_lookupText" OnPick="PickItemAsync" OnClose="CloseLookup" />
<KhDialog Open="_transform is not null" Title="@_transform?.Title" Icon="copy" Size="lg" OnClose="() => _transform = null">
<ChildContent>
@if (_transform is { } t)
{
<p class="muted">@t.Lead</p>
<div class="gridwrap">
<table class="grid" aria-label="@T["Sales.Lines.Title"]">
<thead>
<tr>
<th scope="col" class="kh-check"><input type="checkbox" checked="@(t.Selected.Count == t.Lines.Count)" aria-label="@T["Sales.Transform.All"]" @onchange="ToggleAllLines" /></th>
<th scope="col">@T["Sales.Lines.Description"]</th>
<th scope="col" class="num">@T["Sales.Lines.Quantity"]</th>
@if (t.Fulfils)
{
<th scope="col" class="num">@T["Sales.Lines.Residual"]</th>
}
<th scope="col" class="num">@T["Sales.Lines.Amount"]</th>
</tr>
</thead>
<tbody>
@foreach (var line in t.Lines)
{
var id = line.Id;
<tr class="@(line.Kind == DocumentLineKind.Description ? "kh-desc" : null)">
<td class="kh-check"><input type="checkbox" checked="@t.Selected.Contains(id)" aria-label="@line.Description" @onchange="e => ToggleLine(id, e.Value is true)" /></td>
<td>@line.Description</td>
<td class="num">@(DocumentLine.CarriesQuantity(line.Kind) ? T.Number(line.Quantity, 2) : null)</td>
@if (t.Fulfils)
{
<td class="num">@(DocumentLine.CarriesQuantity(line.Kind) ? T.Number(line.Residual, 2) : null)</td>
}
<td class="num">@(line.Kind == DocumentLineKind.Description ? null : T.Money(line.TaxableAmount))</td>
</tr>
}
</tbody>
</table>
</div>
}
</ChildContent>
<Footer>
<button type="button" class="btn" @onclick="() => _transform = null">@T["Common.Cancel"]</button>
<button type="button" class="btn primary" disabled="@(_transform?.Selected.Count == 0 || _busy)" @onclick="TransformAsync"><KhIcon Name="copy" /> @T["Sales.Transform.Create"]</button>
</Footer>
</KhDialog>
<KhDialog Open="_cancelling" Title="@T["Sales.Actions.Cancel"]" Icon="x-circle" OnClose="() => _cancelling = false">
<ChildContent>
<p>@T[Behavior.Lifecycle == DocumentLifecycle.Invoice ? "Sales.Cancel.LeadInvoice" : "Sales.Cancel.Lead"]</p>
<KhForm Validation="_cancelValidation" Layout="KhFormLayout.Groups">
<KhTextArea Label="@T["Sales.Fields.CancelReason"]" Name="CancelReason" Value="@_cancelReason" ValueChanged="v => _cancelReason = v" Span="12" Rows="3"
Required="@(Behavior.Lifecycle == DocumentLifecycle.Invoice)" />
</KhForm>
</ChildContent>
<Footer>
<button type="button" class="btn" @onclick="() => _cancelling = false">@T["Common.Cancel"]</button>
<button type="button" class="btn danger" disabled="@_busy" @onclick="CancelDocumentAsync"><KhIcon Name="x-circle" /> @T["Sales.Actions.Cancel"]</button>
</Footer>
</KhDialog>
<KhDialog Open="_mailing" Title="@T["Sales.Mail.Title"]" Icon="mail" Size="lg" OnClose="() => _mailing = false">
<ChildContent>
@if (!Mails.IsConfigured)
{
<div class="callout warn kh-doc-callout"><KhIcon Name="alert" /> <span>@T[DocumentMailErrors.NotConfigured]</span></div>
}
<p class="muted">@T["Sales.Mail.Lead"]</p>
<div class="kh-mail-form">
<KhForm Validation="_mailValidation" Layout="KhFormLayout.Groups">
<KhTextBox Label="@T["Sales.Mail.To"]" Name="To" Value="@_mailTo" ValueChanged="v => _mailTo = v" Span="12" Required="true" Hint="@T["Sales.Mail.ToHint"]" />
<KhTextBox Label="@T["Sales.Mail.Subject"]" Name="Subject" Value="@_mailSubject" ValueChanged="v => _mailSubject = v" Span="12" Required="true" />
<KhTextArea Label="@T["Sales.Mail.Body"]" Name="Body" Value="@_mailBody" ValueChanged="v => _mailBody = v" Span="12" Rows="9" />
</KhForm>
</div>
</ChildContent>
<Footer>
<button type="button" class="btn" @onclick="() => _mailing = false">@T["Common.Cancel"]</button>
<button type="button" class="btn primary" disabled="@(_busy || !Mails.IsConfigured)" @onclick="SendMailAsync"><KhIcon Name="send" /> @T["Sales.Mail.Send"]</button>
</Footer>
</KhDialog>
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,185 @@
@page "/vendite/{Segment}"
@attribute [Authorize]
@using Khaemhat.Application.Documents
@using Khaemhat.Core.Documents
@using Khaemhat.Web.Documents
@inject ShellSession Session
@inject DocumentEngine Engine
@inject DocumentEditor Editor
@inject NavigationManager Navigation
@inject TimeProvider Clock
@* The radar of a kind of sales documents (SPEC §11.3): quotations, orders, delivery notes, invoices (with pro forma
and fees), credit and debit notes. Search on number, reference and customer; filters for state, type and year;
totals of the page. Enter or double click opens the document. *@
<KhPageTitle Text="@Title" Icon="@(_section?.Icon ?? "cart")" />
@if (!_loaded)
{
<p class="muted kh-pad">@T["Common.Loading"]</p>
}
else if (Session.Company is null)
{
<div class="kh-message"><KhIcon Name="building" Class="lg" /><h1>@T["Sales.NoCompany"]</h1></div>
}
else if (_section is null)
{
<div class="kh-message"><KhIcon Name="alert" Class="lg" /><h1>@T["Pages.NotFound.Title"]</h1></div>
}
else if (!CanRead)
{
<div class="kh-message">
<KhIcon Name="lock" Class="lg" />
<h1>@T["Pages.AccessDenied.Title"]</h1>
<p class="lead">@T["Pages.AccessDenied.Lead"]</p>
</div>
}
else
{
<KhRadar TItem="DocumentRow" @key="_section.Segment" Id="@("sales." + _section.Segment)" Columns="Columns" Source="ListAsync" KeyOf="r => r.Id" Selectable="false"
OnOpen="Open" QuickFilters="QuickFilters" RowClass="RowClassOf" SearchPlaceholder="@T["Sales.Radar.Search"]" ExportName="@_section.Segment"
Label="@Title">
<Toolbar>
@if (NewTypes.Count > 0)
{
<button type="button" class="btn primary" @onclick="New"><KhIcon Name="plus" /> @T["Sales.Sections." + _section.Key + ".New"]</button>
}
@if (_section.Segment == "fatture" && Session.Permissions.Allows("sales.invoice.write"))
{
<a class="btn" href="@SalesScreens.DeferredInvoicingUrl"><KhIcon Name="layers" /> @T["Sales.Deferred.Title"]</a>
}
</Toolbar>
</KhRadar>
<KhDialog Open="_choosing" Title="@T["Sales.NewDocument"]" Icon="plus" OnClose="() => _choosing = false">
<ChildContent>
<div class="kh-choice-list">
@foreach (var type in NewTypes)
{
<button type="button" class="btn kh-choice" @onclick="() => Create(type.Code)">
<span class="code">@type.Code</span>
<b>@type.Type.Description</b>
<span class="muted sm">@T["Sales.Hints.Kinds." + type.Kind]</span>
</button>
}
</div>
</ChildContent>
</KhDialog>
}
@code {
private SalesSection? _section;
private IReadOnlyList<DocumentDefinition> _definitions = [];
private bool _loaded;
private bool _choosing;
/// <summary>The radar segment, such as <c>fatture</c>.</summary>
[Parameter]
public string? Segment { get; set; }
private string Title => _section is null ? T["Shell.Menu.Sales"] : T["Sales.Sections." + _section.Key + ".Title"];
private bool CanRead => _section is not null && Session.Permissions.Allows(DocumentBehaviors.Of(_section.Kinds[0]).ReadPermission);
private DateOnly Today => DateOnly.FromDateTime(TimeZoneInfo.ConvertTime(Clock.GetUtcNow(), TimeZoneInfo.Local).DateTime);
// The types of the radar the user may create, in the order of the section.
private List<DocumentDefinition> NewTypes => _section is null ? [] :
[.. _section.NewTypes.Select(code => _definitions.FirstOrDefault(d => d.Code == code)).OfType<DocumentDefinition>()
.Where(d => Session.Permissions.Allows(d.Behavior.WritePermission))];
private IReadOnlyList<KhColumn<DocumentRow>> Columns =>
[
new("number", T["Sales.Fields.DocumentNumber"], r => r.DocumentNumber ?? T["Sales.DraftNumber"]) { Kind = KhColumnKind.Code, Width = "130px" },
new("date", T["Sales.Fields.DocumentDate"], r => r.Date) { Kind = KhColumnKind.Date, Width = "100px" },
new("type", T["Sales.Radar.Kind"], r => SalesScreens.KindName(T, r.Kind)) { Width = "150px", Sortable = false, Visible = _section?.Kinds.Count > 1 },
new("party", T["Sales.Fields.PartyId"], r => r.PartyName) { Sortable = false },
new("reference", T["Sales.Fields.ExternalReference"], r => r.Reference) { Width = "140px" },
new("validUntil", T["Sales.Fields.ValidUntil"], r => r.ValidUntil) { Kind = KhColumnKind.Date, Width = "100px", Visible = _section?.Segment == "preventivi" },
new("delivery", T["Sales.Fields.DeliveryDate"], r => r.DeliveryDate) { Kind = KhColumnKind.Date, Width = "100px", Visible = _section?.Segment is "ordini" or "ddt" },
new("taxable", T["Sales.Totals.Taxable"], r => r.Taxable) { Kind = KhColumnKind.Money, Width = "120px" },
new("total", T["Sales.Totals.Total"], r => r.Total) { Kind = KhColumnKind.Money, Width = "120px" },
new("status", T["Sales.Radar.State"], r => StateOf(r).Text)
{
Width = "130px",
Template = r => @<KhBadge Tone="StateOf(r).Tone">@StateOf(r).Text</KhBadge>,
},
];
private IReadOnlyList<KhQuickFilter> QuickFilters
{
get
{
var filters = new List<KhQuickFilter>
{
new("status", T["Sales.Radar.State"], [new(string.Empty, T["Sales.Radar.All"]), .. States.Select(s => new KhOption<string>(s.ToString(), T["Sales.States." + s]))]),
};
if (_section is { Kinds.Count: > 1 })
{
filters.Add(new("kind", T["Sales.Radar.Kind"], [new(string.Empty, T["Sales.Radar.All"]), .. _section.Kinds.Select(k => new KhOption<string>(k.ToString(), SalesScreens.KindName(T, k)))]));
}
var year = Today.Year;
filters.Add(new("year", T["Sales.Radar.Year"],
[new(string.Empty, T["Sales.Radar.All"]), .. Enumerable.Range(0, 3).Select(i => new KhOption<string>((year - i).ToString(T.Culture), (year - i).ToString(T.Culture)))]));
return filters;
}
}
// The states that make sense for the life cycle of the radar.
private IEnumerable<DocumentStatus> States => _section is null ? [] :
DocumentBehaviors.Of(_section.Kinds[0]).Lifecycle == DocumentLifecycle.Invoice && _section.Kinds.All(k => DocumentBehaviors.Of(k).Lifecycle == DocumentLifecycle.Invoice)
? [DocumentStatus.Draft, DocumentStatus.Issued, DocumentStatus.Cancelled]
: [DocumentStatus.Draft, DocumentStatus.Confirmed, DocumentStatus.PartiallyFulfilled, DocumentStatus.Fulfilled, DocumentStatus.Closed, DocumentStatus.Cancelled, DocumentStatus.Issued];
/// <inheritdoc />
protected override async Task OnParametersSetAsync()
{
await Session.EnsureLoadedAsync();
_section = SalesScreens.Find(Segment);
if (!_loaded && Session.Actor is { } actor && Session.Company?.Code is { } company)
{
_definitions = await Engine.DefinitionsAsync(actor, company);
}
_loaded = true;
}
private (string Text, KhTone Tone) StateOf(DocumentRow row) => SalesScreens.State(T, row.Kind, row.Status, row.ValidUntil, Today);
private static string? RowClassOf(DocumentRow row) => row.Status == DocumentStatus.Cancelled ? "muted" : null;
private Task<ListPage<DocumentRow>> ListAsync(ListQuery query, CancellationToken cancellationToken) =>
Session.Actor is { } actor && Session.Company?.Code is { } company && _section is not null
? Editor.ListAsync(actor, company, _section.Family, _section.Kinds, query, cancellationToken)
: Task.FromResult(new ListPage<DocumentRow>([], 0, new Dictionary<string, decimal>()));
private void Open(DocumentRow row)
{
if (SalesScreens.RecordUrl(row.Kind, row.Id) is { } url)
{
Navigation.NavigateTo(url);
}
}
private void New()
{
if (NewTypes.Count == 1)
{
Create(NewTypes[0].Code);
}
else
{
_choosing = true;
}
}
private void Create(string code)
{
_choosing = false;
if (_section is not null)
{
Navigation.NavigateTo(SalesScreens.NewUrl(_section, code));
}
}
}
@@ -0,0 +1,252 @@
@page "/vendite/{Segment}/{Id:long}/stampa"
@attribute [Authorize]
@using Khaemhat.Application.Documents
@using Khaemhat.Application.Security
@using Khaemhat.Web.Documents
@using Khaemhat.Web.Hosting
@inject ShellSession Session
@inject DocumentPrintService Prints
@inject DocumentEngine Engine
@inject FileGenerationService Generation
@inject ToastService Toasts
@* The print preview of a sales document (SPEC §9.4, issue #52, mockup 025): the A4 sheet in HTML from the same model
as the PDF, with Stampa (the print of the browser), the PDF made by Khaemhat and "Salva come allegato", which keeps
the PDF among the attachments of the document as a new version. *@
<KhPageTitle Text="@Heading" Icon="printer" />
@if (_model is null)
{
<div class="kh-message">
<KhIcon Name="@(_missing ? "alert" : "printer")" Class="lg" />
<h1>@(_missing ? T["Sales.NotFound"] : T["Common.Loading"])</h1>
</div>
}
else
{
<div class="phead">
<div>
<div class="crumbs"><a href="@BackUrl">@_model.Title @_model.Number</a> › <b>@T["Sales.Print.Title"]</b></div>
<h1>@Heading</h1>
</div>
</div>
<KhPrintPreview PdfUrl="@PdfUrl(false)" PdfDownloadUrl="@PdfUrl(true)" OnSaveAttachment="SaveAsync" Saving="_saving">
<div class="kh-sheet-head">
<div class="kh-print-company">
@if (_model.LogoAttachmentId is { } logo)
{
<img class="kh-print-logo" src="@FileEndpoints.View(logo)" alt="" />
}
<div>
<div class="kh-sheet-company">@_model.Company.Name</div>
@foreach (var line in _model.Company.Lines)
{
<div class="kh-sheet-muted">@line</div>
}
</div>
</div>
<div class="kh-sheet-title">
<div class="k">@_model.Title</div>
<div class="kh-print-number">@_model.Number</div>
<div class="n">@_model.Date</div>
@if (_model.Watermark is { } mark)
{
<div class="kh-print-mark">@mark</div>
}
</div>
</div>
<div class="kh-print-top">
<dl class="kh-print-fields">
@foreach (var field in _model.Fields)
{
<dt>@field.Label</dt>
<dd>@field.Value</dd>
}
</dl>
<div class="kh-print-party">
<div class="kh-sheet-muted">@_model.PartyLabel <span class="mono">@_model.Party.Code</span></div>
<b>@_model.Party.Name</b>
@foreach (var line in _model.Party.Lines)
{
<div>@line</div>
}
</div>
</div>
<table class="kh-sheet-table">
<thead>
<tr>
@for (var i = 0; i < _model.LineHeaders.Count; i++)
{
<th class="@(i >= 3 ? "num" : null)">@_model.LineHeaders[i]</th>
}
</tr>
</thead>
<tbody>
@foreach (var line in _model.Lines)
{
if (line.IsDescription)
{
<tr class="kh-print-text"><td></td><td colspan="7">@line.Description</td></tr>
}
else
{
<tr>
<td class="mono">@line.Code</td>
<td>@line.Description</td>
<td>@line.Unit</td>
<td class="num">@line.Quantity</td>
<td class="num">@line.Price</td>
<td class="num">@line.Discount</td>
<td class="num">@line.Tax</td>
<td class="num">@line.Amount</td>
</tr>
}
}
</tbody>
</table>
@foreach (var note in _model.Notes)
{
<p class="kh-print-note">@note</p>
}
<div class="kh-print-sums">
<div>
@if (_model.Summary is { } summary)
{
@Table(summary)
}
@if (_model.Installments is { } installments)
{
@Table(installments)
}
</div>
<div class="kh-print-totals">
@foreach (var row in _model.Totals)
{
<span class="@(row.Strong ? "big" : null)">@row.Label</span>
<span class="@(row.Strong ? "big num" : "num")">@row.Value</span>
}
</div>
</div>
@if (_model.Transport.Count > 0)
{
<dl class="kh-print-transport">
@foreach (var field in _model.Transport)
{
<div><dt>@field.Label</dt><dd>@field.Value</dd></div>
}
</dl>
<div class="kh-print-signatures">
@foreach (var signature in _model.Signatures)
{
<div>@signature</div>
}
</div>
}
@if (_model.Footer is { } footer)
{
<p class="kh-sheet-foot">@footer</p>
}
</KhPrintPreview>
}
@code {
private SalesSection? _section;
private DocumentPrintModel? _model;
private bool _missing;
private bool _saving;
/// <summary>The radar segment, such as <c>fatture</c>.</summary>
[Parameter]
public string? Segment { get; set; }
/// <summary>The document.</summary>
[Parameter]
public long Id { get; set; }
private string Heading => _model is null ? T["Sales.Print.Title"] : T.Format("Sales.Print.Heading", _model.Title, _model.Number);
private string BackUrl => _section is null ? SalesScreens.BasePath : SalesScreens.BasePath + "/" + _section.Segment + "/" + Id.ToString(T.Culture);
/// <inheritdoc />
protected override async Task OnParametersSetAsync()
{
await Session.EnsureLoadedAsync();
_section = SalesScreens.Find(Segment);
if (_section is null || Session.Actor is not { } actor || Session.Company?.Code is not { } company)
{
_missing = true;
return;
}
try
{
_model = await Prints.BuildAsync(actor, company, _section.Family, Id);
}
catch (Exception ex) when (ex is KeyNotFoundException or AccessDeniedException)
{
_missing = true;
}
}
private string? PdfUrl(bool download) =>
_section is null ? null : FileEndpoints.Generated(DocumentPrintService.EntityOf(_section.Family), Id, DocumentPdfGenerator.GeneratorCode, download);
private async Task SaveAsync()
{
if (_section is null || Session.Actor is not { } actor || Session.Company?.Code is not { } company)
{
return;
}
_saving = true;
try
{
var saved = await Generation.GenerateAsync(actor, company, DocumentPrintService.EntityOf(_section.Family), Id, DocumentPdfGenerator.GeneratorCode);
await Engine.MarkPrintedAsync(actor, company, _section.Family, Id);
Toasts.Show(ToastKind.Success, T["Ui.Attachments.GeneratedToast"], saved.FileName);
}
catch (Exception ex) when (ex is AccessDeniedException or ValidationFailedException or KeyNotFoundException)
{
Toasts.Show(ToastKind.Error, T["Ui.Print.SaveAttachment"], T["Ui.Attachments.Denied"]);
}
finally
{
_saving = false;
}
}
private static RenderFragment Table(PrintTable table) => __builder =>
{
<div class="kh-print-block">
<div class="kh-print-block-title">@table.Title</div>
<table class="kh-sheet-table">
<thead>
<tr>
@for (var i = 0; i < table.Headers.Count; i++)
{
<th class="@(table.Numeric[i] ? "num" : null)">@table.Headers[i]</th>
}
</tr>
</thead>
<tbody>
@foreach (var row in table.Rows)
{
<tr>
@for (var i = 0; i < row.Count; i++)
{
<td class="@(table.Numeric[i] ? "num" : null)">@row[i]</td>
}
</tr>
}
</tbody>
</table>
</div>
};
}
@@ -0,0 +1,120 @@
using Khaemhat.Application.Security;
using Khaemhat.Application.Tables;
using Khaemhat.Core.Tables;
using Khaemhat.Web.Tables;
using Khaemhat.Web.Ui;
namespace Khaemhat.Web.Documents;
/// <summary>
/// The choices of the document screens, read once per page from the company tables: conditions, transport, the VAT
/// codes and units of the lines. Values are ids, except the currencies (by code); texts are <c>code · description</c>.
/// </summary>
public sealed class DocumentLookups
{
/// <summary>No choices, before loading.</summary>
public static DocumentLookups Empty { get; } = new();
/// <summary>Payment terms.</summary>
public IReadOnlyList<KhOption<string>> PaymentTerms { get; private init; } = [];
/// <summary>Payment methods.</summary>
public IReadOnlyList<KhOption<string>> PaymentMethods { get; private init; } = [];
/// <summary>Price lists.</summary>
public IReadOnlyList<KhOption<string>> PriceLists { get; private init; } = [];
/// <summary>Salespeople.</summary>
public IReadOnlyList<KhOption<string>> Salespeople { get; private init; } = [];
/// <summary>The company bank accounts.</summary>
public IReadOnlyList<KhOption<string>> BankAccounts { get; private init; } = [];
/// <summary>Warehouses.</summary>
public IReadOnlyList<KhOption<string>> Warehouses { get; private init; } = [];
/// <summary>Carriers.</summary>
public IReadOnlyList<KhOption<string>> Carriers { get; private init; } = [];
/// <summary>Shipping terms (porto).</summary>
public IReadOnlyList<KhOption<string>> ShippingTerms { get; private init; } = [];
/// <summary>Reasons of transport.</summary>
public IReadOnlyList<KhOption<string>> TransportReasons { get; private init; } = [];
/// <summary>Appearances of the goods.</summary>
public IReadOnlyList<KhOption<string>> GoodsAppearances { get; private init; } = [];
/// <summary>VAT codes.</summary>
public IReadOnlyList<KhOption<string>> TaxCodes { get; private init; } = [];
/// <summary>Units of measure.</summary>
public IReadOnlyList<KhOption<string>> Units { get; private init; } = [];
/// <summary>Currencies, by code.</summary>
public IReadOnlyList<KhOption<string>> Currencies { get; private init; } = [];
/// <summary>Reads the choices.</summary>
/// <param name="tables">The tables.</param>
/// <param name="actor">Who reads.</param>
/// <param name="company">The company.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The choices.</returns>
public static async Task<DocumentLookups> ReadAsync(TableService tables, Actor actor, string company, CancellationToken cancellationToken = default) => new()
{
PaymentTerms = await ReadAsync<PaymentTerm>(tables, actor, company, false, cancellationToken).ConfigureAwait(false),
PaymentMethods = await ReadAsync<PaymentMethod>(tables, actor, company, false, cancellationToken).ConfigureAwait(false),
PriceLists = await ReadAsync<PriceList>(tables, actor, company, false, cancellationToken).ConfigureAwait(false),
Salespeople = await ReadAsync<Salesperson>(tables, actor, company, false, cancellationToken).ConfigureAwait(false),
BankAccounts = await ReadAsync<BankAccount>(tables, actor, company, false, cancellationToken).ConfigureAwait(false),
Warehouses = await ReadAsync<Warehouse>(tables, actor, company, false, cancellationToken).ConfigureAwait(false),
Carriers = await ReadAsync<Carrier>(tables, actor, company, false, cancellationToken).ConfigureAwait(false),
ShippingTerms = await ReadAsync<ShippingTerm>(tables, actor, company, false, cancellationToken).ConfigureAwait(false),
TransportReasons = await ReadAsync<TransportReason>(tables, actor, company, false, cancellationToken).ConfigureAwait(false),
GoodsAppearances = await ReadAsync<GoodsAppearance>(tables, actor, company, false, cancellationToken).ConfigureAwait(false),
TaxCodes = await ReadAsync<TaxCode>(tables, actor, company, false, cancellationToken).ConfigureAwait(false),
Units = await ReadAsync<UnitOfMeasure>(tables, actor, company, false, cancellationToken).ConfigureAwait(false),
Currencies = await ReadAsync<Currency>(tables, actor, company, true, cancellationToken).ConfigureAwait(false),
};
/// <summary>The code of a choice (the part before <c> · </c>).</summary>
/// <param name="options">The choices.</param>
/// <param name="id">The id.</param>
/// <returns>The code, or <see langword="null"/>.</returns>
public static string? CodeOf(IReadOnlyList<KhOption<string>> options, long? id)
{
ArgumentNullException.ThrowIfNull(options);
if (id is null)
{
return null;
}
var value = id.Value.ToString(System.Globalization.CultureInfo.InvariantCulture);
var text = options.FirstOrDefault(o => o.Value == value)?.Text;
return text is null ? null : text.Split(" · ", 2)[0];
}
/// <summary>The id of the choice with a code, ignoring case.</summary>
/// <param name="options">The choices.</param>
/// <param name="code">The code typed.</param>
/// <returns>The id, or <see langword="null"/>.</returns>
public static long? IdOf(IReadOnlyList<KhOption<string>> options, string? code)
{
ArgumentNullException.ThrowIfNull(options);
if (string.IsNullOrWhiteSpace(code))
{
return null;
}
var wanted = code.Trim();
var match = options.FirstOrDefault(o => string.Equals(o.Text.Split(" · ", 2)[0], wanted, StringComparison.OrdinalIgnoreCase));
return match is null ? null : long.Parse(match.Value, System.Globalization.CultureInfo.InvariantCulture);
}
private static async Task<IReadOnlyList<KhOption<string>>> ReadAsync<T>(TableService tables, Actor actor, string company, bool byCode,
CancellationToken cancellationToken)
{
var choices = await TableValues.LookupAsync(tables, typeof(T), byCode, actor, company, cancellationToken).ConfigureAwait(false);
return [.. choices.Select(c => new KhOption<string>(c.Value, c.Text))];
}
}
+144
View File
@@ -0,0 +1,144 @@
using System.Globalization;
using Khaemhat.Application.Localization;
using Khaemhat.Core.Documents;
using Khaemhat.Web.Ui;
namespace Khaemhat.Web.Documents;
/// <summary>A radar of the sales menu and the document types it holds.</summary>
/// <param name="Segment">The path segment, such as <c>fatture</c>.</param>
/// <param name="Family">The family of the documents.</param>
/// <param name="Kinds">The kinds shown.</param>
/// <param name="NewTypes">The document types a user can create from the radar, the first being the usual one.</param>
/// <param name="Icon">The icon.</param>
/// <param name="Key">The key of the texts under <c>Sales.Sections</c>.</param>
public sealed record SalesSection(string Segment, DocumentFamily Family, IReadOnlyList<DocumentKind> Kinds, IReadOnlyList<string> NewTypes, string Icon, string Key);
/// <summary>
/// Addresses and labels of the sales screens (SPEC §11.3, mockups 020-030): one radar per menu entry under
/// <c>/vendite</c>, the record of a document under it, and the deferred invoicing.
/// </summary>
public static class SalesScreens
{
/// <summary>The menu area.</summary>
public const string BasePath = "vendite";
/// <summary>The deferred invoicing of the delivery notes.</summary>
public const string DeferredInvoicingUrl = BasePath + "/fatturazione-differita";
/// <summary>The tab of the transport data, after Testata, for delivery notes and accompanying invoices.</summary>
public const string TransportTab = "trasporto";
/// <summary>The radars, in the order of the menu.</summary>
public static IReadOnlyList<SalesSection> Sections { get; } =
[
new("preventivi", DocumentFamily.SaleQuotation, [DocumentKind.Quotation], ["PRE"], "file", "Quotes"),
new("ordini", DocumentFamily.SaleOrder, [DocumentKind.SalesOrder], ["OC"], "file-check", "Orders"),
new("ddt", DocumentFamily.SaleDocument, [DocumentKind.DeliveryNote], ["DDT"], "truck", "DeliveryNotes"),
new("fatture", DocumentFamily.SaleDocument,
[DocumentKind.ImmediateInvoice, DocumentKind.AccompanyingInvoice, DocumentKind.DeferredInvoice, DocumentKind.DownPaymentInvoice, DocumentKind.Fee, DocumentKind.ProForma],
["FI", "FA", "FD", "FACC", "PAR", "PF"], "euro", "Invoices"),
new("note-credito", DocumentFamily.SaleDocument, [DocumentKind.CreditNote, DocumentKind.DebitNote], ["NC", "ND"], "undo", "CreditNotes"),
];
/// <summary>The radar of a path segment.</summary>
/// <param name="segment">The segment.</param>
/// <returns>The radar, or <see langword="null"/>.</returns>
public static SalesSection? Find(string? segment) => Sections.FirstOrDefault(s => string.Equals(s.Segment, segment, StringComparison.OrdinalIgnoreCase));
/// <summary>The radar that holds a kind of document.</summary>
/// <param name="kind">The kind.</param>
/// <returns>The radar, or <see langword="null"/> for a kind outside sales.</returns>
public static SalesSection? Of(DocumentKind kind) => Sections.FirstOrDefault(s => s.Kinds.Contains(kind));
/// <summary>The address of a radar.</summary>
/// <param name="section">The radar.</param>
/// <returns>The address.</returns>
public static string RadarUrl(SalesSection section)
{
ArgumentNullException.ThrowIfNull(section);
return BasePath + "/" + section.Segment;
}
/// <summary>The address of a document.</summary>
/// <param name="kind">The kind.</param>
/// <param name="id">The document.</param>
/// <returns>The address, or <see langword="null"/> for a kind outside sales.</returns>
public static string? RecordUrl(DocumentKind kind, long id) =>
Of(kind) is { } section ? RadarUrl(section) + "/" + id.ToString(CultureInfo.InvariantCulture) : null;
/// <summary>The address of a new document of a type.</summary>
/// <param name="section">The radar.</param>
/// <param name="typeCode">The document type.</param>
/// <returns>The address.</returns>
public static string NewUrl(SalesSection section, string typeCode) => RadarUrl(section) + "/nuovo?tipo=" + Uri.EscapeDataString(typeCode);
/// <summary>The print preview of a document.</summary>
/// <param name="section">The radar.</param>
/// <param name="id">The document.</param>
/// <returns>The relative URL.</returns>
public static string PrintUrl(SalesSection section, long id)
{
ArgumentNullException.ThrowIfNull(section);
return RadarUrl(section) + "/" + id.ToString(System.Globalization.CultureInfo.InvariantCulture) + "/stampa";
}
/// <summary>The name of a kind, such as <c>Fattura immediata</c>.</summary>
/// <param name="texts">The texts.</param>
/// <param name="kind">The kind.</param>
/// <returns>The name.</returns>
public static string KindName(ITexts texts, DocumentKind kind)
{
ArgumentNullException.ThrowIfNull(texts);
return texts["Sales.Kinds." + kind];
}
/// <summary>The label and tone of a state; a quotation shows its outcome (accepted, refused, expired).</summary>
/// <param name="texts">The texts.</param>
/// <param name="kind">The kind.</param>
/// <param name="status">The state.</param>
/// <param name="validUntil">Until when a quotation is valid.</param>
/// <param name="today">Today.</param>
/// <returns>The label and the tone.</returns>
public static (string Text, KhTone Tone) State(ITexts texts, DocumentKind kind, DocumentStatus status, DateOnly? validUntil, DateOnly today)
{
ArgumentNullException.ThrowIfNull(texts);
if (kind == DocumentKind.Quotation)
{
switch (status)
{
case DocumentStatus.Fulfilled or DocumentStatus.PartiallyFulfilled:
return (texts["Sales.Outcomes.Accepted"], KhTone.Ok);
case DocumentStatus.Closed:
return (texts["Sales.Outcomes.Refused"], KhTone.Error);
case DocumentStatus.Confirmed when validUntil is { } until && until < today:
return (texts["Sales.Outcomes.Expired"], KhTone.Warning);
case DocumentStatus.Confirmed:
return (texts["Sales.Outcomes.Sent"], KhTone.Info);
}
}
var tone = status switch
{
DocumentStatus.Draft => KhTone.Neutral,
DocumentStatus.Confirmed or DocumentStatus.Issued => KhTone.Info,
DocumentStatus.PartiallyFulfilled => KhTone.Warning,
DocumentStatus.Fulfilled or DocumentStatus.SdiDelivered => KhTone.Ok,
DocumentStatus.Cancelled or DocumentStatus.SdiRejected or DocumentStatus.SdiNotDelivered => KhTone.Error,
_ => KhTone.Accent,
};
return (texts["Sales.States." + status], tone);
}
/// <summary>The choices of an enumeration, labelled from <c>Sales.{group}.{value}</c>.</summary>
/// <typeparam name="TEnum">The enumeration.</typeparam>
/// <param name="texts">The texts.</param>
/// <param name="group">The group of texts.</param>
/// <returns>The choices.</returns>
public static IReadOnlyList<KhOption<string>> Choices<TEnum>(ITexts texts, string group)
where TEnum : struct, Enum
{
ArgumentNullException.ThrowIfNull(texts);
return [.. Enum.GetValues<TEnum>().Select(v => new KhOption<string>(v.ToString(), texts["Sales." + group + "." + v]))];
}
}
@@ -148,6 +148,12 @@ internal static class KhaemhatServices
services.AddSingleton<Khaemhat.Application.Items.ItemService>();
services.AddSingleton<Khaemhat.Application.Items.PriceListService>();
// The document engine (ADR 0032): one engine, the copies, a typed service per family.
services.AddSingleton<Khaemhat.Application.Documents.DocumentEngine>();
services.AddSingleton<Khaemhat.Application.Documents.DocumentCopyService>();
services.AddSingleton<Khaemhat.Application.Documents.DocumentEditor>();
services.AddSingleton(typeof(Khaemhat.Application.Documents.DocumentService<,>));
// Guided import and export (ADR 0031): the entities in the order of the screen.
services.AddSingleton<Khaemhat.Application.ImportExport.IImportTarget>(sp => ActivatorUtilities.CreateInstance<Khaemhat.Application.ImportExport.PartiesImportTarget>(
sp, Khaemhat.Core.Parties.PartyKind.Customer));
@@ -170,6 +176,8 @@ internal static class KhaemhatServices
// Companies and start.
services.AddSingleton<ICompanySeeder, PredefinedRolesSeeder>();
services.AddSingleton<ICompanySeeder>(sp => sp.GetRequiredService<SeedRunner>());
services.AddSingleton<DemoSalesSeeder>();
services.AddSingleton<ICompanySeeder>(sp => sp.GetRequiredService<DemoSalesSeeder>());
services.AddSingleton<CompanyService>();
services.AddSingleton<CompanyContextResolver>();
services.AddScoped<ICompanyContext, WebCompanyContext>();
@@ -220,6 +228,23 @@ internal static class KhaemhatServices
services.AddSingleton<IFileScanner, NoOpFileScanner>();
services.AddSingleton<IFileStore, VolumeFileStore>();
services.AddSingleton<AttachmentService>();
services.AddSingleton<Khaemhat.Application.Documents.DocumentPrintService>();
services.AddSingleton<IFileGenerator, Khaemhat.Application.Documents.DocumentPdfGenerator>();
// Mail (#52): the SMTP client written in house, the queue that sends in the background, documents by e-mail.
services.AddSingleton(new Khaemhat.Infrastructure.Mail.SmtpSettings(
options.SmtpHost, options.SmtpPortNumber, options.SmtpUser, options.SmtpPassword, options.SmtpFrom,
options.SmtpSecurityMode switch
{
SmtpSecurity.Ssl => Khaemhat.Infrastructure.Mail.SmtpTransportSecurity.Ssl,
SmtpSecurity.None => Khaemhat.Infrastructure.Mail.SmtpTransportSecurity.None,
_ => Khaemhat.Infrastructure.Mail.SmtpTransportSecurity.StartTls,
}));
services.AddSingleton<Khaemhat.Infrastructure.Mail.IMailSender, Khaemhat.Infrastructure.Mail.SmtpMailSender>();
services.AddSingleton<Khaemhat.Infrastructure.Mail.MailQueue>();
services.AddSingleton<Khaemhat.Infrastructure.Mail.IMailQueue>(sp => sp.GetRequiredService<Khaemhat.Infrastructure.Mail.MailQueue>());
services.AddHostedService(sp => sp.GetRequiredService<Khaemhat.Infrastructure.Mail.MailQueue>());
services.AddSingleton<Khaemhat.Application.Documents.DocumentMailService>();
services.AddSingleton<IFileGenerator, DemoPdfGenerator>();
services.AddSingleton<IFileGenerator, DemoCsvGenerator>();
services.AddSingleton<IFileGenerator, DemoXlsxGenerator>();
+3
View File
@@ -129,6 +129,9 @@ public static class SeedCommand
{
Print(code, "dati dimostrativi, scala " + options.Scale.ToString(CultureInfo.InvariantCulture),
await runner.RunAsync(code, SeedKind.Demo, options.Scale).ConfigureAwait(false));
// The demo documents go through the document engine, after the masters they use.
await services.GetRequiredService<DemoSalesSeeder>().SeedAsync(code, new CompanySeedContext(IsNew: false, Base: false, Demo: true)).ConfigureAwait(false);
}
}
@@ -0,0 +1,57 @@
{
"document": {
"not-found": "Il documento non esiste più.",
"action": {
"not-allowed": "Nello stato attuale del documento questa operazione non è ammessa."
},
"type": {
"missing": "Il tipo documento non esiste.",
"no-kind": "Il tipo documento non ha un genere: sceglilo in Tabelle azienda, Tipi documento.",
"disabled": "Il tipo documento è disattivato.",
"family": "Questo tipo documento appartiene a un'altra famiglia di documenti.",
"locked": "Il tipo di un documento già salvato non si può cambiare."
},
"party": {
"required": "Indica il cliente o il fornitore."
},
"mail": {
"not-configured": "L'invio delle e-mail non è configurato: chiedi all'amministratore di impostare il server SMTP (KHAEMHAT_SMTP_HOST e KHAEMHAT_SMTP_FROM).",
"recipient-invalid": "Indica uno o più indirizzi e-mail validi, separati da virgola.",
"subject-required": "Scrivi l'oggetto del messaggio.",
"queue-full": "Troppi messaggi in attesa di invio: riprova tra qualche minuto."
},
"date": {
"required": "Indica la data del documento.",
"numbered": "La data di un documento numerato non si può cambiare."
},
"lines": {
"required": "Il documento non ha righe."
},
"line": {
"kind-not-allowed": "Questo tipo di riga non è ammesso in questo documento.",
"description-required": "Ogni riga ha bisogno di una descrizione.",
"item-required": "Una riga articolo ha bisogno dell'articolo.",
"below-fulfilled": "La quantità non può scendere sotto quella già evasa.",
"fulfilled-removed": "Una riga già evasa da altri documenti non si può togliere.",
"source-invalid": "La riga d'origine non esiste o non può essere evasa da questo documento.",
"discount-invalid": "Lo sconto si scrive come percentuali separate da +, ad esempio 10+5.",
"tax-required": "Indica il codice IVA della riga: serve per i registri IVA e la fattura elettronica."
},
"cancel": {
"reason-required": "Per annullare una fattura indica il motivo.",
"has-followers": "Altri documenti evadono questo: annulla prima quelli."
},
"copy": {
"direction": "Si trasforma solo in un documento della stessa direzione (vendita o acquisto).",
"nothing-left": "Non c'è più nulla da evadere.",
"source-not-open": "Il documento non è confermato o è chiuso o annullato: non si può evadere.",
"parties": "I documenti scelti sono di clienti o fornitori diversi: si uniscono solo documenti della stessa controparte."
},
"number": {
"date-before-last": "La data è anteriore a quella dell'ultimo documento numerato: con questo numeratore non sono ammessi documenti fuori sequenza.",
"numerator-missing": "Il numeratore del tipo documento non esiste.",
"numerator-disabled": "Il numeratore del tipo documento è disattivato.",
"too-long": "Il numero formattato supera i 30 caratteri: accorcia il formato del numeratore."
}
}
}
@@ -11,6 +11,7 @@
},
"files": {
"generators": {
"document_pdf": "Stampa del documento in PDF",
"demo_pdf": "Documento di prova in PDF",
"demo_csv": "Righe in CSV (per Excel)",
"demo_xlsx": "Righe in Excel (XLSX)"
@@ -101,6 +101,9 @@
"Attachments": "Allegati",
"Birth": "Dati di nascita"
},
"Hints": {
"ExcludedMonths": "Le scadenze che cadono in un mese escluso passano a questo giorno del mese successivo (10 se vuoto)."
},
"Fields": {
"Code": "Codice",
"PreviousCode": "Codice precedente",
@@ -148,6 +151,9 @@
"WarehouseId": "Deposito",
"CreditLimit": "Fido",
"Blocked": "Ordini bloccati",
"ExcludedMonth1": "Primo mese escluso",
"ExcludedMonth2": "Secondo mese escluso",
"ExcludedMonthsDay": "Scadenza spostata al giorno",
"GroupDeliveryNotes": "Raggruppa i DDT in fattura",
"InvoiceDay": "Giorno di fatturazione",
"SendDocuments": "Invio dei documenti",
@@ -0,0 +1,93 @@
{
"Print": {
"Draft": "Bozza",
"Of": "del {0}",
"Customer": "Spett.le",
"Supplier": "Fornitore",
"NoParty": "Intestatario da indicare",
"VatNumber": "P. IVA {0}",
"TaxCode": "C.F. {0}",
"Rea": "REA {0} {1}",
"ShareCapital": "Cap. soc. {0} i.v.",
"Phone": "Tel. {0}",
"Pec": "PEC {0}",
"Watermarks": {
"Draft": "Bozza, non valida",
"Cancelled": "Annullato",
"Demo": "Dato dimostrativo"
},
"Fields": {
"Payment": "Pagamento",
"Bank": "Banca d'appoggio",
"Reference": "Vs. riferimento",
"ValidUntil": "Valido fino al",
"Delivery": "Consegna prevista",
"Salesperson": "Agente",
"Revision": "Revisione",
"Cig": "CIG",
"Cup": "CUP",
"Related": "Documento collegato"
},
"Lines": {
"Code": "Codice",
"Description": "Descrizione",
"Unit": "UM",
"Quantity": "Quantità",
"Price": "Prezzo",
"Discount": "Sconti",
"Tax": "IVA",
"Amount": "Importo"
},
"Summary": {
"Title": "Riepilogo IVA",
"Code": "Codice IVA",
"Rate": "Aliquota",
"Taxable": "Imponibile",
"Tax": "Imposta"
},
"Installments": {
"Title": "Scadenze",
"Number": "N.",
"Due": "Scadenza",
"Method": "Modalità",
"Amount": "Importo"
},
"Totals": {
"Goods": "Totale merce",
"FooterDiscount": "Sconto di piede",
"Expenses": "Spese",
"SocialSecurity": "Cassa previdenza",
"Taxable": "Imponibile",
"Tax": "IVA",
"StampDuty": "Bollo",
"Total": "Totale documento",
"Withholding": "Ritenuta d'acconto",
"Enasarco": "Enasarco",
"SplitPayment": "IVA in scissione dei pagamenti",
"Net": "Netto a pagare"
},
"Transport": {
"Reason": "Causale del trasporto",
"By": "Trasporto a cura del",
"Carrier": "Vettore",
"Port": "Porto",
"Appearance": "Aspetto dei beni",
"Packages": "Colli",
"GrossWeight": "Peso lordo (kg)",
"NetWeight": "Peso netto (kg)",
"Start": "Inizio trasporto",
"SignatureDriver": "Firma del conducente",
"SignatureCarrier": "Firma del vettore",
"SignatureRecipient": "Firma del destinatario"
},
"Mail": {
"Subject": "{{Documento}} n. {{Numero}} del {{Data}} · {{Azienda}}",
"Body": "Gentile {{Cliente}},\n\nin allegato trovate il documento {{Documento}} n. {{Numero}} del {{Data}}, per un totale di {{Totale}}.\n\nRestiamo a disposizione per qualsiasi chiarimento.\n\nCordiali saluti,\n{{Azienda}}"
},
"Notes": {
"SplitPayment": "Operazione con scissione dei pagamenti (art. 17-ter del DPR 633/1972): l'IVA è versata dal cliente all'Erario.",
"ProForma": "Documento pro forma, privo di valore fiscale: la fattura sarà emessa al pagamento.",
"Deferred": "Fattura differita (art. 21, comma 4, del DPR 633/1972) relativa ai documenti di trasporto indicati."
}
}
}
+309
View File
@@ -0,0 +1,309 @@
{
"Sales": {
"NoCompany": "Scegli un'azienda per vedere i documenti di vendita.",
"NotFound": "Documento non trovato",
"BackToList": "Torna all'elenco",
"DraftNumber": "Bozza",
"NumberOnConfirm": "Assegnato alla conferma",
"NoParty": "Cliente da scegliere",
"Demo": "Dato dimostrativo",
"NewDocument": "Nuovo documento",
"Sections": {
"Quotes": { "Title": "Preventivi", "New": "Nuovo preventivo" },
"Orders": { "Title": "Ordini clienti", "New": "Nuovo ordine" },
"DeliveryNotes": { "Title": "Documenti di trasporto", "New": "Nuovo DDT" },
"Invoices": { "Title": "Fatture di vendita", "New": "Nuova fattura" },
"CreditNotes": { "Title": "Note di credito e di debito", "New": "Nuova nota" }
},
"Kinds": {
"Quotation": "Preventivo",
"SalesOrder": "Ordine cliente",
"DeliveryNote": "DDT",
"ImmediateInvoice": "Fattura immediata",
"AccompanyingInvoice": "Fattura accompagnatoria",
"DeferredInvoice": "Fattura differita",
"DownPaymentInvoice": "Fattura di acconto",
"CreditNote": "Nota di credito",
"DebitNote": "Nota di debito",
"Fee": "Parcella",
"ProForma": "Pro forma",
"SelfInvoice": "Autofattura",
"PurchaseOrder": "Ordine fornitore",
"PurchaseDeliveryNote": "DDT fornitore",
"PurchaseInvoice": "Fattura fornitore",
"PurchaseCreditNote": "Nota di credito fornitore",
"InventoryEntry": "Movimento di magazzino"
},
"States": {
"Draft": "Bozza",
"Confirmed": "Confermato",
"PartiallyFulfilled": "Evaso in parte",
"Fulfilled": "Evaso",
"Closed": "Chiuso",
"Cancelled": "Annullato",
"Issued": "Emessa",
"SdiGenerated": "XML generato",
"SdiSent": "Inviata allo SdI",
"SdiDelivered": "Consegnata",
"SdiRejected": "Scartata",
"SdiNotDelivered": "Non consegnata"
},
"Outcomes": {
"Sent": "In attesa di risposta",
"Accepted": "Accettato",
"Refused": "Rifiutato",
"Expired": "Scaduto"
},
"LineKinds": {
"Item": "Articolo",
"Free": "Riga libera",
"Description": "Descrizione",
"Expense": "Spese",
"Discount": "Sconto"
},
"Exigibilities": {
"Immediate": "Immediata (I)",
"Deferred": "Differita, IVA per cassa (D)",
"SplitPayment": "Scissione dei pagamenti (S)"
},
"TransportBy": {
"Sender": "Mittente",
"Recipient": "Destinatario",
"Carrier": "Vettore"
},
"Tabs": {
"Transport": "Trasporto"
},
"Head": {
"Vat": "P. IVA",
"TaxCode": "C.F."
},
"Radar": {
"Search": "Cerca per numero, riferimento o cliente",
"All": "Tutti",
"Kind": "Tipo",
"State": "Stato",
"Year": "Anno"
},
"Groups": {
"Document": "Documento",
"Party": "Cliente",
"Conditions": "Condizioni",
"Tax": "Dati fiscali",
"Withholding": "Ritenuta, cassa previdenza, ENASARCO",
"Transport": "Trasporto",
"Goods": "Merce",
"Notes": "Note",
"Cancelled": "Annullamento"
},
"Fields": {
"DocumentTypeId": "Tipo documento",
"DocumentNumber": "Numero",
"DocumentDate": "Data",
"ValidUntil": "Valido fino al",
"DeliveryDate": "Consegna",
"Revision": "Revisione",
"Related": "Rettifica",
"ExternalReference": "Riferimento cliente",
"ExternalDate": "Data riferimento",
"RelatedNumber": "Fattura rettificata",
"RelatedDate": "Data fattura rettificata",
"PartyId": "Cliente",
"SalespersonId": "Agente",
"CurrencyCode": "Valuta",
"PriceListId": "Listino",
"FooterDiscount": "Sconto di piede",
"PricesIncludeTax": "Prezzi IVA compresa",
"PaymentTermId": "Pagamento",
"PaymentMethodId": "Modalità di pagamento",
"BankAccountId": "Banca d'appoggio",
"Exigibility": "Esigibilità IVA",
"SplitPayment": "Split payment",
"StampDutyCharged": "Bollo addebitato al cliente",
"Cig": "CIG",
"Cup": "CUP",
"WithholdingRate": "Ritenuta %",
"WithholdingBasePercent": "Base ritenuta %",
"WithholdingType": "Tipo ritenuta",
"WithholdingReason": "Causale pagamento",
"SocialSecurityFund": "Cassa previdenza",
"SocialSecurityRate": "Cassa %",
"SocialSecurityTaxCodeId": "IVA sulla cassa",
"SocialSecurityWithheld": "Cassa soggetta a ritenuta",
"EnasarcoRate": "ENASARCO %",
"TransportReasonId": "Causale del trasporto",
"TransportBy": "Trasporto a cura del",
"CarrierId": "Vettore",
"ShippingTermId": "Porto",
"TransportStartDate": "Inizio trasporto",
"TransportStartTime": "Ora",
"WarehouseId": "Magazzino",
"GoodsAppearanceId": "Aspetto dei beni",
"Packages": "Colli",
"GrossWeight": "Peso lordo (kg)",
"NetWeight": "Peso netto (kg)",
"Notes": "Note",
"CancelReason": "Motivo dell'annullamento",
"TaxableAmount": "Imponibile",
"TaxAmount": "IVA",
"TotalAmount": "Totale",
"Status": "Stato",
"Number": "Progressivo",
"Printed": "Stampato",
"Sent": "Inviato"
},
"Hints": {
"PartyFirst": "Scegli prima il cliente: il documento ne riprende listino, pagamento, agente, banca e dati fiscali.",
"PartyDefaults": "Cambiando cliente il documento riprende le sue condizioni; puoi poi modificarle qui.",
"ExternalReference": "Ad esempio il numero d'ordine del cliente.",
"Related": "La fattura che questa nota corregge, riportata nel file per lo SdI.",
"Withholding": "Ritenuta, cassa ed ENASARCO si calcolano sulle righe non escluse; si tolgono dal netto a pagare, non dal totale.",
"Transport": "Colli e pesi vanno nella stampa del DDT; il magazzino si muove con la conferma (M6).",
"Installments": "Le scadenze nascono dalla condizione di pagamento, sul netto a pagare. Lo scadenzario arriva con M8.",
"InstallmentsForecast": "Per preventivi, ordini e pro forma le scadenze sono una previsione: quelle vere nascono con la fattura.",
"Notes": "Le note compaiono nella stampa, sotto le righe.",
"Kinds": {
"Quotation": "Offerta al cliente, con validità e revisioni.",
"SalesOrder": "Impegno del cliente, evaso da DDT e fatture.",
"DeliveryNote": "Accompagna la merce; si fattura con la differita.",
"ImmediateInvoice": "TD01, emessa insieme alla cessione o prestazione.",
"AccompanyingInvoice": "TD01 che accompagna anche la merce, con i dati del trasporto.",
"DeferredInvoice": "TD24, raccoglie i DDT del mese.",
"DownPaymentInvoice": "TD02, per un acconto su un ordine.",
"CreditNote": "TD04, storna in tutto o in parte una fattura.",
"DebitNote": "TD05, aggiunge importi a una fattura.",
"Fee": "TD06, per i professionisti, con ritenuta e cassa.",
"ProForma": "Non fiscale: anticipa la fattura al cliente."
}
},
"Lines": {
"Title": "Righe documento",
"Item": "Articolo",
"Description": "Descrizione",
"Unit": "UM",
"Quantity": "Quantità",
"Price": "Prezzo",
"Discount": "Sconti",
"Tax": "IVA",
"Delivery": "Consegna",
"Fulfilled": "Evasa",
"Residual": "Da evadere",
"Amount": "Importo",
"ItemRadar": "Cerca articolo",
"ItemMissing": "L'articolo non esiste più.",
"ErrorAt": "Riga {0}: {1}"
},
"Totals": {
"Title": "Totali",
"Summary": "Castelletto IVA",
"SummaryEmpty": "Il castelletto si compone mentre scrivi le righe.",
"Installments": "Scadenze",
"InstallmentsEmpty": "Nessuna scadenza: il documento non ha importo da pagare.",
"InstallmentsNoTerm": "Scegli la condizione di pagamento per vedere le scadenze.",
"TaxCode": "Codice IVA",
"Rate": "Aliquota",
"Taxable": "Imponibile",
"Tax": "IVA",
"Total": "Totale documento",
"Net": "Netto a pagare",
"Goods": "Totale merce",
"FooterDiscount": "Sconto di piede",
"Expenses": "Spese",
"SocialSecurity": "Cassa previdenza",
"StampDuty": "Bollo (a carico dell'azienda)",
"StampDutyCharged": "Bollo",
"Withholding": "Ritenuta d'acconto",
"Enasarco": "ENASARCO",
"SplitPayment": "IVA in split payment",
"DueDate": "Scadenza",
"Method": "Modalità",
"Amount": "Importo"
},
"Links": {
"Empty": "Nessun documento collegato.",
"Relation": "Relazione",
"Quantity": "Quantità evasa",
"Source": "Origine",
"Target": "Evaso da",
"Related": "Rettifica"
},
"Actions": {
"Confirm": "Conferma",
"Issue": "Emetti",
"Create": "Crea {0}",
"Duplicate": "Duplica",
"Close": "Chiudi",
"Refuse": "Segna come rifiutato",
"Reopen": "Riapri",
"Cancel": "Annulla documento",
"ChooseParty": "Scegli il cliente",
"AddExpense": "Aggiungi riga spese",
"AddDiscount": "Aggiungi riga sconto"
},
"Confirm": {
"IssueText": "La fattura riceve il numero definitivo e non si potrà più modificare: per correggerla servirà una nota di credito. Procedere?",
"Issued": "Fattura {0} emessa.",
"Confirmed": "Documento {0} confermato."
},
"Cancel": {
"Lead": "Il documento resta in archivio come annullato e non conta più nelle evasioni.",
"LeadInvoice": "Annullare una fattura emessa è un'eccezione (ad esempio mai inviata allo SdI): indica il motivo, che resta nello storico."
},
"Transform": {
"LeadFulfil": "Scegli le righe da evadere: il nuovo documento riprende la quantità ancora da evadere, che puoi ridurre prima di confermarlo.",
"LeadCopy": "Scegli le righe da copiare nel nuovo documento.",
"All": "Tutte le righe",
"Create": "Crea il documento",
"Created": "{0} creato in bozza."
},
"Mail": {
"Title": "Invia per e-mail",
"Lead": "Il PDF del documento viene salvato tra gli allegati come nuova versione e parte in allegato al messaggio.",
"To": "Destinatari",
"ToHint": "Più indirizzi separati da virgola.",
"Subject": "Oggetto",
"Body": "Messaggio",
"Send": "Invia",
"Queued": "Messaggio in coda di invio",
"QueuedDetail": "A {0}: l'esito è nel log, sezione E-mail/PEC."
},
"Print": {
"Title": "Anteprima di stampa",
"Heading": "Anteprima di stampa · {0} {1}"
},
"Deferred": {
"Title": "Fatturazione differita",
"Procedure": "Procedura",
"Steps": {
"Period": "Periodo e cliente",
"PeriodDetail": "I DDT confermati e non ancora fatturati.",
"Choose": "Scelta dei DDT",
"ChooseDetail": "Togli quelli da fatturare più avanti.",
"Generate": "Fatture",
"GenerateDetail": "Una fattura differita (TD24) per cliente o per DDT."
},
"From": "DDT dal",
"To": "DDT al",
"ToRequired": "Indica fino a quale data cercare i DDT.",
"Customer": "Cliente",
"AllCustomers": "Vuoto per i DDT di tutti i clienti.",
"InvoiceDate": "Data delle fatture",
"Grouping": "Raggruppamento",
"PerParty": "Una fattura per cliente",
"PerNote": "Una fattura per DDT",
"Issue": "Emetti subito le fatture (altrimenti restano in bozza)",
"Search": "Cerca i DDT",
"Notes": "DDT da fatturare nel periodo",
"Start": "Indica il periodo e premi Cerca i DDT.",
"None": "Nessun DDT da fatturare nel periodo.",
"Lines": "Righe",
"Invoice": "Fattura",
"InvoiceNumber": "Fattura {0} ({1} DDT)",
"Selected": "{0} DDT · {1}",
"Generate": "Genera fatture",
"Results": "Fatture generate",
"Done": "{0} fatture generate su {1}.",
"Again": "Nuova fatturazione"
}
}
}
+2 -1
View File
@@ -67,7 +67,8 @@
"Orders": "Ordini clienti",
"DeliveryNotes": "DDT",
"Invoices": "Fatture",
"CreditNotes": "Note di credito"
"CreditNotes": "Note di credito",
"DeferredInvoicing": "Fatturazione differita"
},
"Purchases": {
"_": "Acquisti",
@@ -255,6 +255,7 @@
"IsDefault": "Predefinito",
"Symbol": "Simbolo",
"Decimals": "Decimali",
"DocumentKind": "Genere",
"NumeratorId": "Numeratore",
"InventoryReasonId": "Causale di magazzino",
"EInvoiceType": "Tipo TD",
@@ -266,6 +267,7 @@
"Prefix": "Prefisso",
"Format": "Formato",
"LastNumber": "Ultimo numero",
"LastDate": "Data dell'ultimo numero",
"GapsAllowed": "Ammessi buchi di numerazione",
"CurrencyCode": "Valuta",
"VatIncluded": "IVA inclusa",
@@ -353,6 +355,25 @@
"Journal": "Prima nota",
"Other": "Altro"
},
"DocumentKind": {
"Quotation": "Preventivo",
"SalesOrder": "Ordine cliente",
"DeliveryNote": "DDT di vendita",
"ImmediateInvoice": "Fattura immediata",
"AccompanyingInvoice": "Fattura accompagnatoria",
"DeferredInvoice": "Fattura differita",
"DownPaymentInvoice": "Fattura di acconto",
"CreditNote": "Nota di credito",
"DebitNote": "Nota di debito",
"Fee": "Parcella",
"ProForma": "Pro forma",
"SelfInvoice": "Autofattura o integrazione",
"PurchaseOrder": "Ordine fornitore",
"PurchaseDeliveryNote": "DDT fornitore",
"PurchaseInvoice": "Fattura fornitore",
"PurchaseCreditNote": "Nota di credito fornitore",
"InventoryEntry": "Movimento di magazzino"
},
"StockEffect": {
"None": "Nessuno",
"Load": "Carico",
@@ -446,6 +467,9 @@
"numerator": {
"format": "Il formato deve contenere il segnaposto del numero e solo segnaposto noti (anno, prefisso, sezionale)."
},
"document-type": {
"kind-required": "Scegli il genere: dice come si comportano i documenti di questo tipo."
},
"year": {
"range": "Anno fuori intervallo."
},
+3 -3
View File
@@ -54,15 +54,15 @@ public static class MenuCatalog
]),
new("Shell.Menu.Section.Operations",
[
Area("Shell.Menu.Parties", "users", "/anagrafiche", ModuleCodes.Core, "parties.party.read", "M4",
Area("Shell.Menu.Parties", "users", "/anagrafiche", ModuleCodes.Core, "parties.party.read", null,
("Shell.Menu.Parties.Customers", "clienti"), ("Shell.Menu.Parties.Suppliers", "fornitori"), ("Shell.Menu.Parties.Contacts", "contatti"),
("Shell.Menu.Parties.Items", "articoli"), ("Shell.Menu.Parties.PriceLists", "listini"), ("Shell.Menu.Parties.Categories", "categorie")),
Area("Shell.Menu.Crm", "target", "/crm", ModuleCodes.Crm, "crm.lead.read", "M11",
("Shell.Menu.Crm.Dashboard", "cruscotto"), ("Shell.Menu.Crm.Leads", "lead"), ("Shell.Menu.Crm.Pipeline", "pipeline"),
("Shell.Menu.Crm.Agenda", "agenda"), ("Shell.Menu.Crm.Tickets", "ticket"), ("Shell.Menu.Crm.Campaigns", "campagne")),
Area("Shell.Menu.Sales", "cart", "/vendite", ModuleCodes.Core, "sales.invoice.read", "M5",
Area("Shell.Menu.Sales", "cart", "/vendite", ModuleCodes.Core, "sales.invoice.read", null,
("Shell.Menu.Sales.Quotes", "preventivi"), ("Shell.Menu.Sales.Orders", "ordini"), ("Shell.Menu.Sales.DeliveryNotes", "ddt"),
("Shell.Menu.Sales.Invoices", "fatture"), ("Shell.Menu.Sales.CreditNotes", "note-credito")),
("Shell.Menu.Sales.Invoices", "fatture"), ("Shell.Menu.Sales.CreditNotes", "note-credito"), ("Shell.Menu.Sales.DeferredInvoicing", "fatturazione-differita")),
Area("Shell.Menu.Purchases", "truck", "/acquisti", ModuleCodes.Core, "purchases.order.read", "M6",
("Shell.Menu.Purchases.Orders", "ordini"), ("Shell.Menu.Purchases.Receipts", "ricevimenti"), ("Shell.Menu.Purchases.Invoices", "fatture")),
Area("Shell.Menu.Inventory", "box", "/magazzino", ModuleCodes.Core, "inventory.stock.read", "M6",
+3 -1
View File
@@ -194,6 +194,7 @@ public static class TableScreens
Fields =
[
new(nameof(DocumentType.Kind), TableFieldKind.Choice) { Required = true, InGrid = true, Width = "170px" },
new(nameof(DocumentType.DocumentKind), TableFieldKind.Choice) { Required = true, InGrid = true, Width = "190px" },
new(nameof(DocumentType.NumeratorId), TableFieldKind.Lookup) { Lookup = typeof(DocumentNumerator), InGrid = true, Width = "120px" },
new(nameof(DocumentType.InventoryReasonId), TableFieldKind.Lookup) { Lookup = typeof(InventoryReason) },
new(nameof(DocumentType.EInvoiceType), TableFieldKind.CodeList) { CodeList = EInvoice(f => f.DocumentTypes), InGrid = true, Width = "90px" },
@@ -212,7 +213,8 @@ public static class TableScreens
new(nameof(DocumentNumerator.Prefix), TableFieldKind.Code) { MaxLength = 10, Span = 4 },
new(nameof(DocumentNumerator.Format)) { Required = true, Span = 8, InGrid = true, Width = "180px" },
new(nameof(DocumentNumerator.LastNumber), TableFieldKind.Number) { Min = 0, InGrid = true, Width = "100px", Span = 4 },
new(nameof(DocumentNumerator.GapsAllowed), TableFieldKind.Bool) { Span = 8 },
new(nameof(DocumentNumerator.LastDate), TableFieldKind.Date) { Span = 4 },
new(nameof(DocumentNumerator.GapsAllowed), TableFieldKind.Bool) { Span = 4 },
],
},
new("listini", "price-lists", typeof(PriceList), "tag", TableGroup.Sales)
+47
View File
@@ -356,3 +356,50 @@ h1[tabindex="-1"]:focus { outline: none; box-shadow: none; }
.grid tbody tr td.kh-import-cell-err { background: var(--kh-err-soft); }
.grid tbody tr td.kh-import-cell-warn { background: var(--kh-warn-soft); }
@media (max-width: 1100px) { .kh-import { grid-template-columns: 1fr; } }
/* Sales documents (SPEC §11.3, mockups 020-030): the panels under the lines, errors of the lines, the choice of a type. */
.kh-doc-panels { display: grid; grid-template-columns: minmax(0, 1.8fr) minmax(0, 1.2fr) minmax(270px, 1fr); gap: var(--kh-gap); padding: 14px 16px; align-items: start; }
.kh-doc-panels.wide { grid-template-columns: minmax(0, 2fr) minmax(0, 1fr); }
.kh-doc-panels.single { grid-template-columns: minmax(0, 720px); }
.kh-doc-panels .grid.compact td, .kh-doc-panels .grid.compact th { padding: 5px 10px; }
.kh-doc-panels .totals span { white-space: nowrap; }
.kh-doc-panels .totals { gap: 4px 12px; }
.kh-doc-panels .totals span:nth-child(even) { min-width: 0; }
.kh-doc-panels .totals .big, .kh-doc-panels .totals .big + span { font-size: 15.5px; }
.kh-doc-panels .kh-total-row td { font-weight: 600; border-top: 1px solid var(--kh-border); }
.kh-doc-callout { margin: 12px 16px 0; align-items: center; }
.kh-doc-callout span { flex: 1; }
.kh-doc-errors { list-style: none; margin: 8px 16px 0; padding: 8px 12px; border-radius: var(--kh-radius-lg); background: var(--kh-err-soft); font-size: 12.5px; display: grid; gap: 4px; }
.kh-choice-list { display: grid; gap: 8px; }
.kh-choice { display: grid; grid-template-columns: 56px minmax(0, 1fr); grid-template-rows: auto auto; gap: 2px 10px; height: auto; padding: 10px 12px; text-align: left; justify-content: stretch; }
.kh-choice .code { grid-row: span 2; align-self: center; font: 600 12px var(--kh-mono); color: var(--kh-accent); }
.kh-choice .muted { font-weight: 400; }
@media (max-width: 1099px) { .kh-doc-panels, .kh-doc-panels.wide { grid-template-columns: 1fr; } }
/* Print preview of a document (issue #52, mockup 025): the same model as the PDF. */
.kh-print-company { display: flex; gap: 12px; align-items: flex-start; }
.kh-print-logo { max-height: 15mm; max-width: 45mm; object-fit: contain; }
.kh-print-number { font-size: 18pt; font-weight: 700; }
.kh-print-mark { margin-top: 4px; color: #b54708; font-weight: 700; text-transform: uppercase; font-size: 9pt; }
.kh-print-top { display: grid; grid-template-columns: 1fr 1fr; gap: 16px; margin-bottom: 14px; font-size: 9.5pt; }
.kh-print-fields { display: grid; grid-template-columns: auto 1fr; gap: 3px 12px; margin: 0; align-content: start; }
.kh-print-fields dt { color: #6b7280; }
.kh-print-fields dd { margin: 0; }
.kh-print-party { border: 1px solid #d9dde3; border-radius: 4px; padding: 8px 10px; display: grid; gap: 2px; }
.kh-print-party b { font-size: 11pt; }
.kh-print-text td { color: #6b7280; font-style: italic; }
.kh-print-note { font-size: 9pt; margin: 10px 0 0; }
.kh-print-sums { display: grid; grid-template-columns: minmax(0, 1.4fr) minmax(0, 1fr); gap: 16px; margin-top: 14px; align-items: start; }
.kh-print-block + .kh-print-block { margin-top: 12px; }
.kh-print-block-title { font-weight: 700; color: #1F5F8B; font-size: 9.5pt; margin-bottom: 4px; }
.kh-print-totals { display: grid; grid-template-columns: 1fr auto; gap: 4px 12px; background: #eceff3; padding: 10px 12px; border-radius: 4px; font-size: 9.5pt; }
.kh-print-totals .num { text-align: right; white-space: nowrap; }
.kh-print-totals .big { font-size: 12pt; font-weight: 700; color: #1F5F8B; padding-top: 4px; }
.kh-print-transport { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 8px 12px; margin: 16px 0 0; font-size: 9pt; }
.kh-print-transport dt { color: #6b7280; font-size: 8pt; }
.kh-print-transport dd { margin: 0; }
.kh-print-signatures { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 12px; margin-top: 16px; font-size: 8pt; color: #6b7280; }
.kh-print-signatures div { border-bottom: 1px solid #9aa1ab; padding-bottom: 28px; }
/* The message of "Invia per e-mail" (issue #52): room for the whole text proposed by the template. */
.kh-mail-form textarea.in { min-height: 190px; }
@@ -0,0 +1,169 @@
using Khaemhat.Application.Documents;
using Khaemhat.Core.Documents;
using Khaemhat.Core.Tax;
using Khaemhat.Fiscal.Italy;
namespace Khaemhat.Application.Tests;
/// <summary>
/// Reference cases of the totals (SPEC §11.3, issue #48): cascaded discounts, footer discount, expenses, tax summary,
/// stamp duty, social security and withholding, split payment, prices with VAT, rounding to the cent, installments.
/// </summary>
[TestClass]
public sealed class DocumentTotalsTests
{
private static readonly ItalianTaxEngine Engine = new();
private static readonly TotalsTax Vat22 = new(1, 22m);
private static readonly TotalsTax Exempt = new(2, 0m, "N4", LegalReference: "Esente art. 10 DPR 633/72");
private static readonly TotalsTax Excluded = new(3, 0m, "N1", LegalReference: "Escluso art. 15 DPR 633/72");
private static TotalsLine Item(decimal quantity, decimal price, TotalsTax tax, string? discount = null) =>
new(DocumentLineKind.Item, quantity, price, discount, tax);
[TestMethod]
public void Invoice_with_discounts_expenses_and_exempt_lines_carries_the_stamp_duty()
{
var totals = DocumentTotalsCalculator.Compute(
[
Item(3m, 12.35m, Vat22, "10+5"),
Item(1m, 100m, Vat22),
new(DocumentLineKind.Description, 0m, 0m, null, null),
new(DocumentLineKind.Expense, 0m, 10m, null, Vat22),
Item(2m, 50m, Exempt),
],
new TotalsOptions { StampDutyApplies = true, StampDutyCharged = true },
Engine);
CollectionAssert.AreEqual(new[] { 31.68m, 100m, 0m, 10m, 100m }, totals.LineAmounts.ToArray());
Assert.HasCount(2, totals.Summary);
Assert.AreEqual(141.68m, totals.Summary[0].Taxable);
Assert.AreEqual(31.17m, totals.Summary[0].TaxAmount);
Assert.AreEqual("N4", totals.Summary[1].Tax.Nature);
Assert.AreEqual(100m, totals.Summary[1].Taxable);
Assert.AreEqual(241.68m, totals.Taxable);
Assert.AreEqual(31.17m, totals.Tax);
Assert.AreEqual(10m, totals.Expenses);
Assert.AreEqual(2m, totals.StampDuty);
Assert.AreEqual(274.85m, totals.Total);
Assert.AreEqual(274.85m, totals.Net);
}
[TestMethod]
public void Stamp_duty_not_charged_stays_out_of_the_total_and_below_the_threshold_is_not_due()
{
var notCharged = DocumentTotalsCalculator.Compute([Item(1m, 100m, Exempt)], new TotalsOptions { StampDutyApplies = true }, Engine);
Assert.AreEqual(2m, notCharged.StampDuty);
Assert.AreEqual(100m, notCharged.Total);
var below = DocumentTotalsCalculator.Compute([Item(1m, 77.47m, Exempt)], new TotalsOptions { StampDutyApplies = true, StampDutyCharged = true }, Engine);
Assert.AreEqual(0m, below.StampDuty);
Assert.AreEqual(77.47m, below.Total);
}
[TestMethod]
public void Footer_discount_applies_to_goods_and_not_to_expenses()
{
var totals = DocumentTotalsCalculator.Compute(
[Item(3m, 12.35m, Vat22, "10+5"), Item(1m, 100m, Vat22), new(DocumentLineKind.Expense, 1m, 10m, null, Vat22)],
new TotalsOptions { FooterDiscount = "5" },
Engine);
Assert.AreEqual(31.68m, totals.LineAmounts[0], "the line keeps its own amount");
Assert.AreEqual(6.59m, totals.FooterDiscountAmount);
Assert.AreEqual(135.09m, totals.Taxable);
Assert.AreEqual(29.72m, totals.Tax);
}
[TestMethod]
public void Fee_with_social_security_withheld_and_withholding_tax()
{
var totals = DocumentTotalsCalculator.Compute(
[new(DocumentLineKind.Free, 1m, 1000m, null, Vat22), new(DocumentLineKind.Expense, 1m, 50m, null, Excluded, WithholdingExcluded: true)],
new TotalsOptions { SocialSecurityRate = 4m, SocialSecurityWithheld = true, WithholdingRate = 20m },
Engine);
Assert.AreEqual(40m, totals.SocialSecurity);
Assert.AreEqual(1040m, totals.Summary[0].Taxable);
Assert.AreEqual(228.80m, totals.Tax);
Assert.AreEqual(1090m, totals.Taxable);
Assert.AreEqual(1318.80m, totals.Total);
Assert.AreEqual(208m, totals.Withholding);
Assert.AreEqual(1110.80m, totals.Net);
}
[TestMethod]
public void Agent_commissions_withhold_on_half_and_enasarco()
{
var totals = DocumentTotalsCalculator.Compute(
[new(DocumentLineKind.Free, 1m, 2000m, null, Vat22)],
new TotalsOptions { WithholdingRate = 23m, WithholdingBasePercent = 50m, EnasarcoRate = 8.5m },
Engine);
Assert.AreEqual(230m, totals.Withholding);
Assert.AreEqual(170m, totals.Enasarco);
Assert.AreEqual(2440m - 230m - 170m, totals.Net);
}
[TestMethod]
public void Split_payment_leaves_the_vat_out_of_the_amount_to_pay()
{
var totals = DocumentTotalsCalculator.Compute([Item(1m, 1000m, Vat22)], new TotalsOptions { SplitPayment = true }, Engine);
Assert.AreEqual(TaxExigibility.SplitPayment, totals.Summary[0].Tax.Exigibility);
Assert.AreEqual(1220m, totals.Total);
Assert.AreEqual(220m, totals.SplitPaymentTax);
Assert.AreEqual(1000m, totals.Net);
}
[TestMethod]
public void Prices_with_vat_are_split_back_per_group_and_discount_lines_subtract()
{
var gross = DocumentTotalsCalculator.Compute([Item(1m, 122m, Vat22), Item(2m, 10.99m, Vat22)], new TotalsOptions { PricesIncludeTax = true }, Engine);
Assert.AreEqual(118.02m, gross.Taxable);
Assert.AreEqual(25.96m, gross.Tax);
Assert.AreEqual(143.98m, gross.Total);
var discounted = DocumentTotalsCalculator.Compute([Item(1m, 100m, Vat22), new(DocumentLineKind.Discount, 0m, 10m, null, Vat22)], new TotalsOptions(), Engine);
Assert.AreEqual(-10m, discounted.LineAmounts[1]);
Assert.AreEqual(90m, discounted.Taxable);
Assert.AreEqual(19.80m, discounted.Tax);
}
[TestMethod]
public void Halves_round_away_from_zero_on_lines_and_on_the_tax_of_the_group()
{
var totals = DocumentTotalsCalculator.Compute([Item(1m, 0.125m, Vat22), Item(1m, 2.125m, Vat22)], new TotalsOptions(), Engine);
CollectionAssert.AreEqual(new[] { 0.13m, 2.13m }, totals.LineAmounts.ToArray());
Assert.AreEqual(2.26m, totals.Taxable);
Assert.AreEqual(0.50m, totals.Tax, "22% of 2.26 is 0.4972, rounded once on the group");
}
[TestMethod]
public void Installments_move_to_end_of_month_and_carry_the_vat_on_the_first()
{
var dues = InstallmentGenerator.Generate(new DateOnly(2026, 1, 15), 1220m, 220m,
[new(30, true, null, 50m), new(60, true, null, 50m)], vatOnFirst: true, null, Engine.Round);
Assert.HasCount(2, dues);
Assert.AreEqual(new DateOnly(2026, 2, 28), dues[0].DueDate);
Assert.AreEqual(720m, dues[0].Amount);
Assert.AreEqual(new DateOnly(2026, 3, 31), dues[1].DueDate);
Assert.AreEqual(500m, dues[1].Amount);
}
[TestMethod]
public void Installments_with_fixed_day_excluded_months_and_rounding_on_the_last()
{
Assert.AreEqual(new DateOnly(2026, 4, 10), InstallmentGenerator.DueDate(new DateOnly(2026, 1, 15), new(60, true, 10, 100m), null));
Assert.AreEqual(new DateOnly(2026, 2, 5), InstallmentGenerator.DueDate(new DateOnly(2026, 1, 20), new(0, false, 5, 100m), null));
Assert.AreEqual(new DateOnly(2026, 9, 10), InstallmentGenerator.DueDate(new DateOnly(2026, 7, 1), new(60, true, null, 100m), new ExcludedMonths(8, 12)));
var thirds = InstallmentGenerator.Generate(new DateOnly(2026, 1, 1), 100m, 0m,
[new(30, false, null, 33.33m), new(60, false, null, 33.33m), new(90, false, null, 33.34m)], false, null, Engine.Round);
CollectionAssert.AreEqual(new[] { 33.33m, 33.33m, 33.34m }, thirds.Select(d => d.Amount).ToArray());
var single = InstallmentGenerator.Generate(new DateOnly(2026, 8, 3), 50m, 0m, [], false, new ExcludedMonths(8, null, 15), Engine.Round);
Assert.AreEqual(new DateOnly(2026, 9, 15), single[0].DueDate);
Assert.IsEmpty(InstallmentGenerator.Generate(new DateOnly(2026, 1, 1), 0m, 0m, [], false, null, Engine.Round));
}
}
@@ -7,6 +7,7 @@
<ItemGroup>
<ProjectReference Include="../../src/Khaemhat.Application/Khaemhat.Application.csproj" />
<ProjectReference Include="../../src/Khaemhat.Data.Sqlite/Khaemhat.Data.Sqlite.csproj" />
<ProjectReference Include="../../src/Khaemhat.Fiscal.Italy/Khaemhat.Fiscal.Italy.csproj" />
</ItemGroup>
</Project>
@@ -72,6 +72,8 @@ public sealed class CronExpressionTests
Assert.AreEqual("Sistema", LogSections.Label(LogSection.System));
Assert.AreEqual(LogSection.Authentication, LogSections.FromCategory("Khaemhat.Application.Security.SignInService"));
Assert.AreEqual(LogSection.ScheduledJobs, LogSections.FromCategory("Khaemhat.Application.Jobs.JobScheduler"));
Assert.AreEqual(LogSection.Documents, LogSections.FromCategory("Khaemhat.Application.Documents.DocumentEngine"));
Assert.AreEqual(LogSection.Email, LogSections.FromCategory("Khaemhat.Infrastructure.Mail.MailQueue"));
Assert.AreEqual("Performance", LogSections.Scope(LogSection.Performance).Single().Value);
}
}
@@ -0,0 +1,121 @@
using Khaemhat.Core.Documents;
namespace Khaemhat.Core.Tests.Documents;
/// <summary>The declarative rules of the document engine (issue #47): behaviours, states, fulfilment.</summary>
[TestClass]
public sealed class DocumentRulesTests
{
[TestMethod]
public void EveryKind_HasABehaviour_AndFulfilsOnlyKindsOfTheSameDirection()
{
Assert.HasCount(Enum.GetValues<DocumentKind>().Length, DocumentBehaviors.All);
foreach (var behavior in DocumentBehaviors.All)
{
Assert.IsNotEmpty(behavior.Lines, behavior.Kind.ToString());
foreach (var source in behavior.Sources)
{
Assert.AreEqual(behavior.Direction, DocumentBehaviors.Of(source).Direction, $"{behavior.Kind} fulfils {source}");
}
// Invoices are the only documents that reach the exchange system.
Assert.AreEqual(behavior.Lifecycle == DocumentLifecycle.Invoice, behavior.Has(DocumentEffects.EInvoice), behavior.Kind.ToString());
}
Assert.AreEqual(DocumentFamily.SaleDocument, DocumentBehaviors.Of(DocumentKind.DeliveryNote).Family);
Assert.IsTrue(DocumentBehaviors.Of(DocumentKind.DeferredInvoice).Fulfils(DocumentKind.DeliveryNote));
Assert.IsFalse(DocumentBehaviors.Of(DocumentKind.DeferredInvoice).Fulfils(DocumentKind.SalesOrder));
Assert.IsTrue(DocumentBehaviors.Of(DocumentKind.Quotation).NeedsParty);
Assert.IsFalse(DocumentBehaviors.Of(DocumentKind.InventoryEntry).NeedsParty);
CollectionAssert.AreEquivalent(
new[] { DocumentKind.DeliveryNote, DocumentKind.ImmediateInvoice, DocumentKind.AccompanyingInvoice, DocumentKind.DeferredInvoice, DocumentKind.DownPaymentInvoice,
DocumentKind.CreditNote, DocumentKind.DebitNote, DocumentKind.Fee, DocumentKind.ProForma, DocumentKind.SelfInvoice },
DocumentBehaviors.KindsOf(DocumentFamily.SaleDocument).ToArray());
}
[TestMethod]
public void OrderLifecycle_MovesThroughItsStates_AndRefusesTheRest()
{
const DocumentLifecycle Order = DocumentLifecycle.Order;
Assert.AreEqual(DocumentStatus.Confirmed, DocumentStateMachine.Apply(Order, DocumentStatus.Draft, DocumentAction.Confirm));
Assert.AreEqual(DocumentStatus.Closed, DocumentStateMachine.Apply(Order, DocumentStatus.PartiallyFulfilled, DocumentAction.Close));
Assert.AreEqual(DocumentStatus.Confirmed, DocumentStateMachine.Apply(Order, DocumentStatus.Closed, DocumentAction.Reopen));
Assert.AreEqual(DocumentStatus.Cancelled, DocumentStateMachine.Apply(Order, DocumentStatus.Confirmed, DocumentAction.Cancel));
Assert.IsTrue(DocumentStateMachine.IsEditable(Order, DocumentStatus.PartiallyFulfilled));
Assert.IsFalse(DocumentStateMachine.IsEditable(Order, DocumentStatus.Fulfilled));
var refused = Assert.ThrowsExactly<InvalidDocumentActionException>(() => DocumentStateMachine.Apply(Order, DocumentStatus.PartiallyFulfilled, DocumentAction.Cancel));
Assert.AreEqual(DocumentAction.Cancel, refused.Action);
Assert.ThrowsExactly<InvalidDocumentActionException>(() => DocumentStateMachine.Apply(Order, DocumentStatus.Confirmed, DocumentAction.Delete));
Assert.ThrowsExactly<InvalidDocumentActionException>(() => DocumentStateMachine.Apply(Order, DocumentStatus.Draft, DocumentAction.Issue));
Assert.ThrowsExactly<InvalidDocumentActionException>(() => DocumentStateMachine.Apply(Order, DocumentStatus.Cancelled, DocumentAction.Reopen));
Assert.ThrowsExactly<InvalidDocumentActionException>(() => DocumentStateMachine.Apply(Order, DocumentStatus.Issued, DocumentAction.Copy), "Not a state of the cycle.");
}
[TestMethod]
public void InvoiceLifecycle_IsUnchangeableOnceIssued_AndCancelledOnlyBeforeTheExchangeSystemHasIt()
{
const DocumentLifecycle Invoice = DocumentLifecycle.Invoice;
var status = DocumentStatus.Draft;
foreach (var action in new[] { DocumentAction.Issue, DocumentAction.GenerateXml, DocumentAction.Send, DocumentAction.MarkDelivered })
{
status = DocumentStateMachine.Apply(Invoice, status, action);
}
Assert.AreEqual(DocumentStatus.SdiDelivered, status);
CollectionAssert.AreEqual(new[] { DocumentAction.Copy }, DocumentStateMachine.Actions(Invoice, DocumentStatus.SdiDelivered).ToArray());
foreach (var issued in DocumentStateMachine.States(Invoice).Where(s => s != DocumentStatus.Draft))
{
Assert.IsFalse(DocumentStateMachine.IsEditable(Invoice, issued), issued.ToString());
Assert.IsFalse(DocumentStateMachine.Allows(Invoice, issued, DocumentAction.Delete), issued.ToString());
}
Assert.IsTrue(DocumentStateMachine.Allows(Invoice, DocumentStatus.SdiGenerated, DocumentAction.Cancel));
Assert.IsTrue(DocumentStateMachine.Allows(Invoice, DocumentStatus.SdiRejected, DocumentAction.Cancel));
Assert.IsFalse(DocumentStateMachine.Allows(Invoice, DocumentStatus.SdiSent, DocumentAction.Cancel));
Assert.IsFalse(DocumentStateMachine.Allows(Invoice, DocumentStatus.Draft, DocumentAction.Confirm), "Invoices are issued, not confirmed.");
Assert.AreEqual(DocumentStatus.SdiGenerated, DocumentStateMachine.Apply(Invoice, DocumentStatus.SdiRejected, DocumentAction.GenerateXml));
}
[TestMethod]
public void SimpleLifecycle_HasDraftConfirmedCancelled()
{
CollectionAssert.AreEqual(
new[] { DocumentStatus.Draft, DocumentStatus.Confirmed, DocumentStatus.Cancelled }, DocumentStateMachine.States(DocumentLifecycle.Simple).ToArray());
Assert.ThrowsExactly<InvalidDocumentActionException>(() => DocumentStateMachine.Apply(DocumentLifecycle.Simple, DocumentStatus.Confirmed, DocumentAction.Close));
}
[TestMethod]
public void Fulfilment_SumsTheLinks_AndClosedLinesCountAsFulfilled()
{
var lines = new List<DocumentLine>
{
new SaleOrderLine { Id = 1, Kind = DocumentLineKind.Item, Quantity = 10m },
new SaleOrderLine { Id = 2, Kind = DocumentLineKind.Free, Quantity = 4m },
new SaleOrderLine { Id = 3, Kind = DocumentLineKind.Description },
new SaleOrderLine { Id = 4, Kind = DocumentLineKind.Expense, Quantity = 1m },
};
Assert.AreEqual(FulfillmentState.None, FulfillmentCalculator.StateOf(lines));
var changed = FulfillmentCalculator.Apply(lines, [Link(1, 6m), Link(1, 1m)]);
Assert.HasCount(1, changed);
Assert.AreEqual(7m, lines[0].FulfilledQuantity);
Assert.AreEqual(3m, lines[0].Residual);
Assert.AreEqual(0m, lines[3].Residual, "Expenses are not fulfilled.");
Assert.AreEqual(FulfillmentState.Partial, FulfillmentCalculator.StateOf(lines));
FulfillmentCalculator.Apply(lines, [Link(1, 12m), Link(2, 1m)]);
Assert.AreEqual(0m, lines[0].Residual, "More than ordered leaves nothing to fulfil.");
Assert.AreEqual(FulfillmentState.Partial, FulfillmentCalculator.StateOf(lines));
lines[1].FulfillmentClosed = true;
Assert.AreEqual(FulfillmentState.Fulfilled, FulfillmentCalculator.StateOf(lines));
Assert.AreEqual(DocumentStatus.Fulfilled, DocumentStateMachine.AfterFulfillment(DocumentLifecycle.Order, DocumentStatus.Confirmed, FulfillmentState.Fulfilled));
Assert.AreEqual(DocumentStatus.Confirmed, DocumentStateMachine.AfterFulfillment(DocumentLifecycle.Order, DocumentStatus.PartiallyFulfilled, FulfillmentState.None));
Assert.AreEqual(DocumentStatus.Closed, DocumentStateMachine.AfterFulfillment(DocumentLifecycle.Order, DocumentStatus.Closed, FulfillmentState.Fulfilled));
Assert.AreEqual(DocumentStatus.Issued, DocumentStateMachine.AfterFulfillment(DocumentLifecycle.Invoice, DocumentStatus.Issued, FulfillmentState.Fulfilled));
}
private static DocumentLink Link(long sourceLine, decimal quantity) =>
new() { SourceFamily = DocumentFamily.SaleOrder, SourceLineId = sourceLine, Quantity = quantity };
}
@@ -0,0 +1,92 @@
using Khaemhat.Application.Documents;
using Khaemhat.Application.Security;
using Khaemhat.Core.Tables;
using Khaemhat.Data.Migrations;
using Khaemhat.Data.Querying;
using Khaemhat.Data.Tests.Support;
namespace Khaemhat.Data.Tests;
/// <summary>Document numbering on both engines (issue #47): concurrent confirmations never share a number.</summary>
[TestClass]
public sealed class DocumentNumberingTests
{
private static readonly DateOnly Day = new(2026, 11, 12);
[TestMethod]
[DataRow(TestDatabase.Sqlite)]
[DataRow(TestDatabase.Postgres)]
public async Task ConcurrentConfirmations_GetEveryNumberOnce_AndRollbacksGiveTheNumberBack(string engine)
{
await using var db = await TestDatabase.CreateAsync(engine);
var id = await NumeratorAsync(db);
const int Workers = 24;
var results = await Task.WhenAll(Enumerable.Range(0, Workers).Select(i => Task.Run(async () =>
{
await using var uow = await db.OpenAsync();
await uow.BeginAsync();
var number = await DocumentNumberingService.NextAsync(uow, id, Day);
await Task.Yield();
if (i % 4 == 0)
{
await uow.RollbackAsync();
return (long?)null;
}
await uow.CommitAsync();
return number.Number;
})));
var given = results.OfType<long>().Order().ToArray();
CollectionAssert.AreEqual(Enumerable.Range(1, given.Length).Select(n => (long)n).ToArray(), given, "Each number once, none skipped.");
await using var check = await db.OpenAsync();
var numerator = await check.Repository<DocumentNumerator, long>().GetAsync(id);
Assert.AreEqual((long)given.Length, numerator!.LastNumber);
Assert.AreEqual(Day, numerator.LastDate);
}
[TestMethod]
[DataRow(TestDatabase.Sqlite)]
[DataRow(TestDatabase.Postgres)]
public async Task Numbering_RefusesDatesBeforeTheLast_AndStartsANewYearFromOne(string engine)
{
await using var db = await TestDatabase.CreateAsync(engine);
var id = await NumeratorAsync(db);
await using var uow = await db.OpenAsync();
await uow.BeginAsync();
var first = await DocumentNumberingService.NextAsync(uow, id, Day);
Assert.AreEqual("FV-2026/0001", first.Text);
var refused = await Assert.ThrowsExactlyAsync<ValidationFailedException>(() => DocumentNumberingService.NextAsync(uow, id, Day.AddDays(-1)));
Assert.AreEqual(DocumentNumberingService.DateBeforeLast, refused.Errors.Single());
Assert.AreEqual("FV-2027/0001", await DocumentNumberingService.PreviewAsync(uow, id, new DateOnly(2027, 1, 2)));
// The first document of a new year creates the numerator of that year with the same rules.
var next = await DocumentNumberingService.NextAsync(uow, id, new DateOnly(2027, 1, 2));
Assert.AreEqual(1L, next.Number);
Assert.AreEqual("FV-2027/0001", next.Text);
Assert.AreNotEqual(id, next.Numerator.Id);
Assert.AreEqual(2, (await uow.Repository<DocumentNumerator, long>().ListAsync(Query.For<DocumentNumerator>().Where(n => n.Code == "FAT"))).Items.Count);
Assert.AreEqual(2L, (await DocumentNumberingService.NextAsync(uow, id, Day.AddDays(1))).Number, "2026 goes on by itself.");
await uow.CommitAsync();
// No document carries the number given in 2027: the check lists it as missing.
CollectionAssert.AreEqual(new long[] { 1 }, (await DocumentNumberingService.FindGapsAsync(uow, next.Numerator.Id)).ToArray());
}
private static async Task<long> NumeratorAsync(TestDatabase db)
{
await new MigrationRunner(db.Context).RunAsync(db.Target, MigrationCatalog.ForCompany());
await using var setup = await db.OpenAsync();
return await setup.Repository<DocumentNumerator, long>().InsertAsync(new DocumentNumerator
{
Code = "FAT",
Description = "Fatture",
Kind = NumeratorKind.SalesInvoice,
Year = 2026,
Prefix = "FV",
Format = "{prefix}-{year}/{number:D4}",
});
}
}
@@ -9,6 +9,8 @@
<ProjectReference Include="../../src/Khaemhat.Data.Sqlite/Khaemhat.Data.Sqlite.csproj" />
<ProjectReference Include="../../src/Khaemhat.Data.PostgreSql/Khaemhat.Data.PostgreSql.csproj" />
<ProjectReference Include="../../src/Khaemhat.Infrastructure/Khaemhat.Infrastructure.csproj" />
<!-- The document numbering (issue #47) runs against both engines here, the only tests the tag CI runs on PostgreSQL. -->
<ProjectReference Include="../../src/Khaemhat.Application/Khaemhat.Application.csproj" />
</ItemGroup>
</Project>
@@ -78,6 +78,9 @@ public sealed class MappingTests
"discount_policies", "document_numerators", "document_types", "cost_centers", "jobs", "code_sequences",
"parties", "party_addresses", "party_contacts", "party_bank_accounts", "party_sales_terms", "party_purchase_terms", "party_fiscal",
"items", "item_uoms", "item_barcodes", "item_prices", "item_suppliers", "item_substitutes", "party_item_codes",
"sale_quotations", "sale_quotation_lines", "sale_orders", "sale_order_lines", "sale_documents", "sale_document_lines",
"purchase_orders", "purchase_order_lines", "purchase_documents", "purchase_document_lines", "inventory_documents", "inventory_document_lines",
"document_links", "document_tax_summaries", "document_installments",
];
CollectionAssert.AreEquivalent(expected, registry.Maps.Select(m => m.Table).ToArray());
}
@@ -0,0 +1,76 @@
using Khaemhat.Application.Documents;
using Khaemhat.Application.Instance;
using Khaemhat.Application.Querying;
using Khaemhat.Application.Security;
using Khaemhat.Application.Seeding;
using Khaemhat.Application.Tables;
using Khaemhat.Core.Documents;
using Khaemhat.Core.Security;
using Khaemhat.Web.Tests.Hosting;
using Microsoft.Extensions.DependencyInjection;
namespace Khaemhat.Web.Tests.Documents;
/// <summary>The demo sales (SPEC §14, issue #53): every kind of sales document, in every state, made through the engine.</summary>
[TestClass]
public sealed class DemoSalesTests
{
private static readonly Actor Root = new(TestInstance.SuperUser, UserLevel.SuperUser, 1, null, null);
[TestMethod]
public async Task DemoSeed_MakesTheSalesOfTheYear_Once()
{
var (app, _, company) = await TestInstance.StartAsync(CancellationToken.None);
await using (app)
{
await app.Services.GetRequiredService<SeedRunner>().RunAsync(company, SeedKind.Demo);
var seeder = app.Services.GetRequiredService<DemoSalesSeeder>();
var context = new CompanySeedContext(IsNew: false, Base: false, Demo: true);
await seeder.SeedAsync(company, context);
var editor = app.Services.GetRequiredService<DocumentEditor>();
var all = await AllAsync(editor, company);
Assert.IsTrue(all.All(r => r.Date.Year == DateTime.Now.Year && r.Date <= DateOnly.FromDateTime(DateTime.Now)), "Dates of this year, never in the future.");
int Count(DocumentKind kind, DocumentStatus status) => all.Count(r => r.Kind == kind && r.Status == status);
Assert.AreEqual(2, Count(DocumentKind.Quotation, DocumentStatus.Fulfilled), "Two quotations became orders.");
Assert.AreEqual(1, Count(DocumentKind.Quotation, DocumentStatus.Closed), "One was refused.");
Assert.AreEqual(1, Count(DocumentKind.Quotation, DocumentStatus.Draft));
Assert.AreEqual(1, Count(DocumentKind.SalesOrder, DocumentStatus.Confirmed), "An order still to deliver.");
Assert.AreEqual(3, Count(DocumentKind.SalesOrder, DocumentStatus.Fulfilled));
Assert.AreEqual(2, Count(DocumentKind.DeliveryNote, DocumentStatus.Fulfilled), "Two delivery notes already invoiced.");
Assert.AreEqual(3, Count(DocumentKind.DeliveryNote, DocumentStatus.Confirmed), "Three for the deferred invoicing.");
Assert.AreEqual(4, Count(DocumentKind.ImmediateInvoice, DocumentStatus.Issued));
Assert.AreEqual(1, Count(DocumentKind.ImmediateInvoice, DocumentStatus.Draft));
Assert.AreEqual(2, Count(DocumentKind.DeferredInvoice, DocumentStatus.Issued));
Assert.AreEqual(1, Count(DocumentKind.CreditNote, DocumentStatus.Issued));
Assert.AreEqual(1, all.Count(r => r.Kind == DocumentKind.ProForma));
Assert.IsTrue(all.Where(r => r.Status != DocumentStatus.Draft).All(r => r.DocumentNumber is not null && r.Total > 0m));
// The issued invoices and the note share one numerator, numbered in date order.
var numbered = all.Where(r => r.Kind is DocumentKind.ImmediateInvoice or DocumentKind.DeferredInvoice or DocumentKind.CreditNote && r.Status == DocumentStatus.Issued)
.OrderBy(r => r.Date).ThenBy(r => r.Id).Select(r => r.DocumentNumber).ToList();
Assert.HasCount(7, numbered);
CollectionAssert.AllItemsAreUnique(numbered);
var profile = await app.Services.GetRequiredService<CompanyProfileService>().GetAsync(Root, company);
Assert.AreEqual(DemoSalesSeeder.CompanyVatNumber, profile.VatNumber);
// Run again, nothing changes.
await seeder.SeedAsync(company, context);
Assert.HasCount(all.Count, await AllAsync(editor, company));
await app.StopAsync();
}
}
private static async Task<List<DocumentRow>> AllAsync(DocumentEditor editor, string company)
{
var all = new List<DocumentRow>();
foreach (var family in new[] { DocumentFamily.SaleQuotation, DocumentFamily.SaleOrder, DocumentFamily.SaleDocument })
{
all.AddRange((await editor.ListAsync(Root, company, family, [.. Enum.GetValues<DocumentKind>()], new ListQuery { Limit = 200 })).Items);
}
return all;
}
}
@@ -0,0 +1,231 @@
using Khaemhat.Application.Documents;
using Khaemhat.Application.Parties;
using Khaemhat.Application.Security;
using Khaemhat.Application.Tables;
using Khaemhat.Core.Documents;
using Khaemhat.Core.Parties;
using Khaemhat.Core.Security;
using Khaemhat.Core.Tables;
using Khaemhat.Data;
using Khaemhat.Web.Tests.Hosting;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
namespace Khaemhat.Web.Tests.Documents;
/// <summary>The document engine on a real instance (issue #47): definitions, numbering, states, copies and fulfilment.</summary>
[TestClass]
public sealed class DocumentEngineTests
{
private static readonly Actor Root = new(TestInstance.SuperUser, UserLevel.SuperUser, 1, null, null);
[TestMethod]
public async Task OrderToDeliveryNotesToDeferredInvoice_FollowsTheFulfilmentLineByLine()
{
var (app, _, company) = await TestInstance.StartAsync(CancellationToken.None);
await using (app)
{
var orders = app.Services.GetRequiredService<DocumentService<SaleOrder, SaleOrderLine>>();
var sales = app.Services.GetRequiredService<DocumentService<SaleDocument, SaleDocumentLine>>();
var copies = app.Services.GetRequiredService<DocumentCopyService>();
var customer = await CustomerAsync(app, company);
var vat = await VatAsync(app, company);
var year = DateTime.Now.Year;
var order = await orders.NewAsync(Root, company, "OC");
Assert.AreEqual(DocumentKind.SalesOrder, order.Header.Kind);
order.Header.PartyId = customer;
order.Lines.Add(new SaleOrderLine { Kind = DocumentLineKind.Free, Description = "Valvola a sfera 1/2\"", Quantity = 10m, Price = 5m, TaxCodeId = vat });
order.Lines.Add(new SaleOrderLine { Kind = DocumentLineKind.Free, Description = "Raccordo a T", Quantity = 4m, Price = 2m, TaxCodeId = vat });
order.Lines.Add(new SaleOrderLine { Kind = DocumentLineKind.Description, Description = "Consegna in cantiere" });
order = await orders.SaveAsync(Root, company, order);
Assert.AreEqual(DocumentStatus.Draft, order.Header.Status);
Assert.IsNull(order.Header.Number, "Numbered at confirmation.");
CollectionAssert.AreEqual(new[] { 1, 2, 3 }, order.Lines.Select(l => l.LineNumber).ToArray());
order = await orders.ConfirmAsync(Root, company, order.Header.Id);
Assert.AreEqual(DocumentStatus.Confirmed, order.Header.Status);
Assert.AreEqual($"OC-{year}-0001", order.Header.DocumentNumber);
Assert.AreEqual(Root.UserName, order.Header.ConfirmedBy);
// First delivery: part of the first line only.
var first = Typed(await copies.CopyAsync(Root, company, DocumentFamily.SaleOrder, order.Header.Id, "DDT"));
Assert.AreEqual(DocumentKind.DeliveryNote, first.Header.Kind);
Assert.HasCount(3, first.Lines);
Assert.AreEqual(order.Lines[0].Id, first.Lines[0].SourceLineId);
Assert.IsNull(first.Lines[2].SourceLineId, "Descriptions are copied without a link.");
first.Lines[0].Quantity = 6m;
first.Lines.RemoveAt(1);
first = await sales.SaveAsync(Root, company, first);
Assert.AreEqual(DocumentStatus.Confirmed, (await orders.GetAsync(Root, company, order.Header.Id))!.Header.Status, "A draft fulfils nothing.");
first = await sales.ConfirmAsync(Root, company, first.Header.Id);
Assert.AreEqual($"1/{year}", first.Header.DocumentNumber);
order = (await orders.GetAsync(Root, company, order.Header.Id))!;
Assert.AreEqual(DocumentStatus.PartiallyFulfilled, order.Header.Status);
Assert.AreEqual(6m, order.Lines[0].FulfilledQuantity);
Assert.AreEqual(4m, order.Lines[0].Residual);
// The order can still change, but not below what was delivered.
order.Lines[0].Quantity = 5m;
var below = await Assert.ThrowsExactlyAsync<ValidationFailedException>(() => orders.SaveAsync(Root, company, order));
Assert.AreEqual("Lines.0.Quantity:" + DocumentErrors.LineBelowFulfilled, below.Errors.Single());
await Assert.ThrowsExactlyAsync<InvalidDocumentActionException>(() => orders.CancelAsync(Root, company, order.Header.Id, null));
// Second delivery: the rest.
var second = await copies.CopyAsync(Root, company, DocumentFamily.SaleOrder, order.Header.Id, "DDT");
CollectionAssert.AreEqual(new[] { 4m, 4m, 0m }, second.Lines.Select(l => l.Quantity).ToArray());
await sales.ConfirmAsync(Root, company, second.Header.Id);
Assert.AreEqual(DocumentStatus.Fulfilled, (await orders.GetAsync(Root, company, order.Header.Id))!.Header.Status);
await Assert.ThrowsExactlyAsync<ValidationFailedException>(() => copies.CopyAsync(Root, company, DocumentFamily.SaleOrder, order.Header.Id, "DDT"));
// Cancelling a delivery gives its quantities back.
var cancelled = await sales.CancelAsync(Root, company, second.Header.Id, null);
Assert.AreEqual(DocumentStatus.Cancelled, cancelled.Header.Status);
Assert.AreEqual($"2/{year}", cancelled.Header.DocumentNumber, "The number stays.");
order = (await orders.GetAsync(Root, company, order.Header.Id))!;
Assert.AreEqual(DocumentStatus.PartiallyFulfilled, order.Header.Status);
Assert.AreEqual(0m, order.Lines[1].FulfilledQuantity);
// Closing the rest, then reopening, comes back to what the lines say.
Assert.AreEqual(DocumentStatus.Closed, (await orders.CloseAsync(Root, company, order.Header.Id)).Header.Status);
await Assert.ThrowsExactlyAsync<ValidationFailedException>(() => copies.CopyAsync(Root, company, DocumentFamily.SaleOrder, order.Header.Id, "DDT"));
Assert.AreEqual(DocumentStatus.PartiallyFulfilled, (await orders.ReopenAsync(Root, company, order.Header.Id)).Header.Status);
// The deferred invoice fulfils the delivery note; once issued it is unchangeable.
var invoice = Typed(await copies.CopyAsync(Root, company, DocumentFamily.SaleDocument, first.Header.Id, "FD"));
invoice = await sales.ConfirmAsync(Root, company, invoice.Header.Id);
Assert.AreEqual(DocumentStatus.Issued, invoice.Header.Status);
Assert.AreEqual($"1/{year}", invoice.Header.DocumentNumber, "Invoices have their own numerator.");
Assert.AreEqual(DocumentStatus.Fulfilled, (await sales.GetAsync(Root, company, first.Header.Id))!.Header.Status);
invoice.Header.Notes = "Changed";
await Assert.ThrowsExactlyAsync<InvalidDocumentActionException>(() => sales.SaveAsync(Root, company, invoice));
await Assert.ThrowsExactlyAsync<InvalidDocumentActionException>(() => sales.DeleteAsync(Root, company, invoice.Header.Id));
await Assert.ThrowsExactlyAsync<InvalidDocumentActionException>(() => sales.CancelAsync(Root, company, first.Header.Id, null), "Fulfilled by the invoice.");
var reason = await Assert.ThrowsExactlyAsync<ValidationFailedException>(() => sales.CancelAsync(Root, company, invoice.Header.Id, " "));
Assert.AreEqual("CancelReason:" + DocumentErrors.CancelReasonRequired, reason.Errors.Single());
invoice = await sales.CancelAsync(Root, company, invoice.Header.Id, "Emessa per errore");
Assert.AreEqual("Emessa per errore", invoice.Header.CancelReason);
Assert.AreEqual(DocumentStatus.Confirmed, (await sales.GetAsync(Root, company, first.Header.Id))!.Header.Status);
await app.StopAsync();
}
}
[TestMethod]
public async Task Invoices_AreCheckedAndNumberedWithoutGapsInDateOrder_AndDraftsAreDeleted()
{
var (app, _, company) = await TestInstance.StartAsync(CancellationToken.None);
await using (app)
{
var engine = app.Services.GetRequiredService<DocumentEngine>();
var sales = app.Services.GetRequiredService<DocumentService<SaleDocument, SaleDocumentLine>>();
var customer = await CustomerAsync(app, company);
var vat = await VatAsync(app, company);
var year = DateTime.Now.Year;
var definitions = await engine.DefinitionsAsync(Root, company);
Assert.HasCount(20, definitions, "Every seeded type has its kind.");
Assert.AreEqual(DocumentKind.DeferredInvoice, definitions.Single(d => d.Code == "FD").Kind);
Assert.AreEqual(DocumentAction.Issue, definitions.Single(d => d.Code == "FI").ConfirmAction);
await Assert.ThrowsExactlyAsync<ValidationFailedException>(() => sales.NewAsync(Root, company, "OC"), "An order is not a sale document.");
var draft = await sales.NewAsync(Root, company, "FI");
draft.Lines.Add(new SaleDocumentLine { Kind = DocumentLineKind.Item, Description = "Senza articolo", Quantity = 1m });
draft.Lines.Add(new SaleDocumentLine { Kind = DocumentLineKind.Free, Description = " ", Quantity = 1m });
var refused = await Assert.ThrowsExactlyAsync<ValidationFailedException>(() => sales.SaveAsync(Root, company, draft));
CollectionAssert.AreEquivalent(
new[] { "PartyId:" + DocumentErrors.PartyRequired, "Lines.0.ItemId:" + DocumentErrors.LineItemRequired, "Lines.1.Description:" + DocumentErrors.LineDescriptionRequired },
refused.Errors.ToArray());
var delivery = await sales.NewAsync(Root, company, "DDT");
delivery.Header.PartyId = customer;
delivery.Lines.Add(new SaleDocumentLine { Kind = DocumentLineKind.Expense, Description = "Trasporto", Quantity = 1m });
var expense = await Assert.ThrowsExactlyAsync<ValidationFailedException>(() => sales.SaveAsync(Root, company, delivery));
Assert.AreEqual("Lines.0.Kind:" + DocumentErrors.LineKindNotAllowed, expense.Errors.Single());
var later = await InvoiceAsync(sales, company, customer, vat, new DateOnly(year, 3, 10));
var earlier = await InvoiceAsync(sales, company, customer, vat, new DateOnly(year, 3, 9));
var empty = await sales.SaveAsync(Root, company, await NewInvoiceAsync(sales, company, customer, vat, new DateOnly(year, 3, 11), lines: false));
var noLines = await Assert.ThrowsExactlyAsync<ValidationFailedException>(() => sales.ConfirmAsync(Root, company, empty.Header.Id));
Assert.AreEqual("Lines:" + DocumentErrors.LinesRequired, noLines.Errors.Single());
Assert.AreEqual($"1/{year}", (await sales.ConfirmAsync(Root, company, later.Header.Id)).Header.DocumentNumber);
var outOfOrder = await Assert.ThrowsExactlyAsync<ValidationFailedException>(() => sales.ConfirmAsync(Root, company, earlier.Header.Id));
Assert.AreEqual(DocumentNumberingService.DateBeforeLast, outOfOrder.Errors.Single());
Assert.AreEqual(DocumentStatus.Draft, (await sales.GetAsync(Root, company, earlier.Header.Id))!.Header.Status, "Nothing changed.");
earlier.Header.DocumentDate = new DateOnly(year, 3, 12);
earlier = await sales.SaveAsync(Root, company, earlier);
var issued = await sales.ConfirmAsync(Root, company, earlier.Header.Id);
Assert.AreEqual(2L, issued.Header.Number);
var factory = app.Services.GetRequiredService<IUnitOfWorkFactory>();
await using (var uow = await factory.CreateAsync(DatabaseScope.Company(company)))
{
Assert.IsEmpty(await DocumentNumberingService.FindGapsAsync(uow, issued.Header.NumeratorId!.Value));
}
var actions = await engine.ActionsAsync(Root, new DocumentRecord { Family = DocumentFamily.SaleDocument, Header = issued.Header });
CollectionAssert.AreEquivalent(new[] { DocumentAction.Copy, DocumentAction.GenerateXml, DocumentAction.Cancel }, actions.ToArray());
await sales.DeleteAsync(Root, company, empty.Header.Id);
Assert.IsNull(await sales.GetAsync(Root, company, empty.Header.Id));
// A type of the company needs a kind to be used.
var tables = app.Services.GetRequiredService<TableService>();
var noKind = await Assert.ThrowsExactlyAsync<ValidationFailedException>(() =>
tables.SaveAsync(Root, company, new DocumentType { Code = "FX", Description = "Fattura speciale", Kind = NumeratorKind.SalesInvoice }));
Assert.IsTrue(noKind.Errors.Any(e => e.EndsWith(TableCatalog.DocumentKindRequired, StringComparison.Ordinal)), string.Join(", ", noKind.Errors));
await app.StopAsync();
}
}
[TestMethod]
public void EveryErrorCodeAndKind_HasAnItalianText()
{
var keys = new[] { typeof(DocumentErrors), typeof(DocumentNumberingService), typeof(DocumentDefinitionService) }
.SelectMany(t => t.GetFields())
.Where(f => f.IsLiteral && f.FieldType == typeof(string))
.Select(f => (string)f.GetRawConstantValue()!)
.Append(InvalidDocumentActionException.Code)
.Append(TableCatalog.DocumentKindRequired)
.Concat(Enum.GetValues<DocumentKind>().Select(k => Khaemhat.Web.Tables.TableScreens.EnumKey(k)))
.ToList();
var missing = keys.Where(k => !Shell.ShellTests.Texts.Contains(k)).ToList();
Assert.IsEmpty(missing, string.Join(", ", missing));
}
private static async Task<DocumentRecord<SaleDocument, SaleDocumentLine>> NewInvoiceAsync(
DocumentService<SaleDocument, SaleDocumentLine> sales, string company, long customer, long vat, DateOnly date, bool lines = true)
{
var invoice = await sales.NewAsync(Root, company, "FI");
invoice.Header.PartyId = customer;
invoice.Header.DocumentDate = date;
if (lines)
{
invoice.Lines.Add(new SaleDocumentLine { Kind = DocumentLineKind.Free, Description = "Assistenza tecnica", Quantity = 2m, Price = 40m, TaxCodeId = vat });
}
return invoice;
}
private static async Task<DocumentRecord<SaleDocument, SaleDocumentLine>> InvoiceAsync(
DocumentService<SaleDocument, SaleDocumentLine> sales, string company, long customer, long vat, DateOnly date) =>
await sales.SaveAsync(Root, company, await NewInvoiceAsync(sales, company, customer, vat, date));
private static DocumentRecord<SaleDocument, SaleDocumentLine> Typed(DocumentRecord record) =>
new() { Header = (SaleDocument)record.Header, Lines = [.. record.Lines.Cast<SaleDocumentLine>()] };
private static async Task<long> VatAsync(WebApplication app, string company) =>
(await app.Services.GetRequiredService<TableService>().ActiveAsync<TaxCode>(Root, company)).Single(t => t.Code == "22").Id;
private static async Task<long> CustomerAsync(WebApplication app, string company)
{
var parties = app.Services.GetRequiredService<PartyService>();
var record = await parties.NewAsync(Root, company, PartyKind.Customer);
record.Party.Name = "Rossi Impianti S.r.l.";
record.Party.VatNumber = "01234567897";
return (await parties.SaveAsync(Root, company, record)).Party.Id;
}
}
@@ -0,0 +1,223 @@
using System.Net;
using System.Net.Sockets;
using System.Text;
using Khaemhat.Application.Documents;
using Khaemhat.Application.Files;
using Khaemhat.Application.Querying;
using Khaemhat.Application.Security;
using Khaemhat.Application.Seeding;
using Khaemhat.Application.Instance;
using Khaemhat.Core.Documents;
using Khaemhat.Core.Security;
using Khaemhat.Infrastructure.Mail;
using Khaemhat.Web.Tests.Hosting;
using Microsoft.Extensions.DependencyInjection;
namespace Khaemhat.Web.Tests.Documents;
/// <summary>Printing and sending documents (SPEC §9.4, §12.6, issue #52): the print model, the PDF, MIME, SMTP and the queue.</summary>
[TestClass]
public sealed class DocumentPrintMailTests
{
private static readonly Actor Root = new(TestInstance.SuperUser, UserLevel.SuperUser, 1, null, null);
[TestMethod]
public void Template_FillsKnownFields_AndKeepsUnknownOnes()
{
var text = MailTemplateRenderer.Render("{{Documento}} n. {{ numero }} per {{Cliente}} {{Sconosciuto}}", new Dictionary<string, string?>
{
["Documento"] = "Fattura",
["Numero"] = "7/2026",
["Cliente"] = null,
});
Assert.AreEqual("Fattura n. 7/2026 per {{Sconosciuto}}", text);
}
[TestMethod]
public void Mime_WritesTextAndAttachmentInBase64()
{
var mail = new OutgoingMail(["a@example.com", "b@example.com"], "Fattura n. 7 · Granai", "Buongiorno,\nin allegato.")
{
Attachments = [new MailAttachment("fattura-7.pdf", "application/pdf", Encoding.ASCII.GetBytes("%PDF-1.7 test"))],
};
var text = MimeMessageWriter.Write(mail, "Granai <ufficio@example.com>", new DateTimeOffset(2026, 3, 2, 9, 30, 0, TimeSpan.FromHours(1)), "BOUNDARY");
StringAssert.Contains(text, "To: a@example.com, b@example.com\r\n");
StringAssert.Contains(text, "Subject: =?utf-8?B?" + Convert.ToBase64String(Encoding.UTF8.GetBytes("Fattura n. 7 · Granai")) + "?=\r\n");
StringAssert.Contains(text, "Date: Mon, 02 Mar 2026 09:30:00 +0100\r\n");
StringAssert.Contains(text, "Content-Type: multipart/mixed; boundary=\"BOUNDARY\"");
StringAssert.Contains(text, Convert.ToBase64String(Encoding.UTF8.GetBytes("Buongiorno,\r\nin allegato.")));
StringAssert.Contains(text, "Content-Disposition: attachment; filename=\"fattura-7.pdf\"");
StringAssert.Contains(text, Convert.ToBase64String(Encoding.ASCII.GetBytes("%PDF-1.7 test")));
Assert.IsTrue(text.EndsWith("--BOUNDARY--\r\n", StringComparison.Ordinal));
Assert.AreEqual("plain", MimeMessageWriter.EncodeHeader("plain"));
}
[TestMethod]
public async Task Smtp_SendsTheMessage_ThroughTheDialogue()
{
using var listener = new TcpListener(IPAddress.Loopback, 0);
listener.Start();
var port = ((IPEndPoint)listener.LocalEndpoint).Port;
var server = Task.Run(() => FakeServerAsync(listener));
var settings = new SmtpSettings("127.0.0.1", port, "demo", "test-only", "Granai <ufficio@example.com>", SmtpTransportSecurity.None);
var sender = new SmtpMailSender(settings, TimeProvider.System);
await sender.SendAsync(new OutgoingMail(["cliente@example.com"], "Prova", "Testo") { Cc = ["copia@example.com"] });
var (commands, data) = await server;
Assert.IsTrue(commands[0].StartsWith("EHLO ", StringComparison.Ordinal));
Assert.AreEqual("AUTH PLAIN " + Convert.ToBase64String(Encoding.UTF8.GetBytes("\0demo\0test-only")), commands[1]);
CollectionAssert.Contains(commands, "MAIL FROM:<ufficio@example.com>");
CollectionAssert.Contains(commands, "RCPT TO:<cliente@example.com>");
CollectionAssert.Contains(commands, "RCPT TO:<copia@example.com>");
Assert.AreEqual("QUIT", commands[^1]);
StringAssert.Contains(data, "Subject: Prova");
StringAssert.Contains(data, "Cc: copia@example.com");
}
[TestMethod]
public async Task Smtp_UnreachableServer_IsAMailException()
{
using var listener = new TcpListener(IPAddress.Loopback, 0);
listener.Start();
var port = ((IPEndPoint)listener.LocalEndpoint).Port;
listener.Stop();
var sender = new SmtpMailSender(new SmtpSettings("127.0.0.1", port, null, null, "ufficio@example.com", SmtpTransportSecurity.None), TimeProvider.System);
await Assert.ThrowsExactlyAsync<MailException>(() => sender.SendAsync(new OutgoingMail(["a@example.com"], "Prova", "Testo")));
await Assert.ThrowsExactlyAsync<MailException>(() => new SmtpMailSender(new SmtpSettings(null, 25, null, null, null, SmtpTransportSecurity.None), TimeProvider.System)
.SendAsync(new OutgoingMail(["a@example.com"], "Prova", "Testo")));
}
[TestMethod]
public async Task Invoice_PrintsToPdf_AndLeavesByMail()
{
var queue = new FakeQueue();
var (app, _, company) = await TestInstance.StartAsync(services => services.AddSingleton<IMailQueue>(queue), CancellationToken.None);
await using (app)
{
await app.Services.GetRequiredService<SeedRunner>().RunAsync(company, SeedKind.Demo);
await app.Services.GetRequiredService<DemoSalesSeeder>().SeedAsync(company, new CompanySeedContext(IsNew: false, Base: false, Demo: true));
var editor = app.Services.GetRequiredService<DocumentEditor>();
var engine = app.Services.GetRequiredService<DocumentEngine>();
var invoices = await editor.ListAsync(Root, company, DocumentFamily.SaleDocument, [DocumentKind.ImmediateInvoice], new ListQuery { Limit = 50 });
var invoice = invoices.Items.First(r => r.Status == DocumentStatus.Issued);
var family = DocumentFamily.SaleDocument;
// The model: every label comes from the resources, the lines and the totals are there.
var model = await app.Services.GetRequiredService<DocumentPrintService>().BuildAsync(Root, company, family, invoice.Id);
Assert.AreEqual(invoice.DocumentNumber, model.Number);
Assert.IsNotNull(model.Watermark, "A document of the demo says so on the sheet.");
Assert.IsNotEmpty(model.Lines);
Assert.IsNotNull(model.Summary, "The VAT summary.");
var texts = new[] { model.Title, model.PartyLabel }.Concat(model.LineHeaders).Concat(model.Fields.Select(f => f.Label)).Concat(model.Totals.Select(t => t.Label));
Assert.IsFalse(texts.Any(t => t.StartsWith('[')), "Missing keys: " + string.Join(", ", texts.Where(t => t.StartsWith('['))));
Assert.AreEqual("sales.saledocument", DocumentPrintService.EntityOf(family));
Assert.AreEqual(family, DocumentPrintService.FamilyOf("sales.saledocument"));
// The PDF, kept among the attachments.
var generated = await app.Services.GetRequiredService<FileGenerationService>()
.GenerateAsync(Root, company, DocumentPrintService.EntityOf(family), invoice.Id, DocumentPdfGenerator.GeneratorCode);
Assert.AreEqual("application/pdf", generated.Mime);
Assert.IsTrue(generated.FileName.EndsWith(".pdf", StringComparison.Ordinal));
var pdf = await ReadAsync(app.Services.GetRequiredService<AttachmentService>(), company, generated.Id);
Assert.AreEqual("%PDF", Encoding.ASCII.GetString(pdf, 0, 4));
await engine.MarkPrintedAsync(Root, company, family, invoice.Id);
Assert.IsTrue((await engine.GetAsync(Root, company, family, invoice.Id))!.Header.Printed);
// The mail: proposed from the template, refused when incomplete, queued with the PDF when complete.
var mails = app.Services.GetRequiredService<DocumentMailService>();
var draft = await mails.DraftAsync(Root, company, family, invoice.Id);
StringAssert.Contains(draft.Subject, invoice.DocumentNumber!);
Assert.IsFalse(draft.Body.Contains("{{", StringComparison.Ordinal), draft.Body);
var refused = await Assert.ThrowsExactlyAsync<ValidationFailedException>(() => mails.SendAsync(Root, company, family, invoice.Id, draft with { To = "non-un-indirizzo", Subject = " " }));
CollectionAssert.AreEquivalent(new[] { "To:" + DocumentMailErrors.RecipientInvalid, "Subject:" + DocumentMailErrors.SubjectRequired }, refused.Errors.ToList());
Assert.IsEmpty(queue.Mails);
await mails.SendAsync(Root, company, family, invoice.Id, draft with { To = "amministrazione@example.com; copia@example.com" });
var mail = queue.Mails.Single();
CollectionAssert.AreEqual(new[] { "amministrazione@example.com", "copia@example.com" }, mail.To.ToList());
Assert.AreEqual("%PDF", Encoding.ASCII.GetString(mail.Attachments.Single().Content, 0, 4));
Assert.IsTrue((await engine.GetAsync(Root, company, family, invoice.Id))!.Header.Sent);
queue.Configured = false;
var off = await Assert.ThrowsExactlyAsync<ValidationFailedException>(() => mails.SendAsync(Root, company, family, invoice.Id, draft with { To = "a@example.com" }));
CollectionAssert.Contains(off.Errors.ToList(), ":" + DocumentMailErrors.NotConfigured);
await app.StopAsync();
}
}
private static async Task<byte[]> ReadAsync(AttachmentService attachments, string company, long id)
{
await using var content = await attachments.OpenAsync(Root, company, id);
using var buffer = new MemoryStream();
await content.Content.CopyToAsync(buffer);
return buffer.ToArray();
}
// A server that says yes to everything and keeps what it receives.
private static async Task<(List<string> Commands, string Data)> FakeServerAsync(TcpListener listener)
{
using var client = await listener.AcceptTcpClientAsync();
var stream = client.GetStream();
using var reader = new StreamReader(stream, Encoding.UTF8);
using var writer = new StreamWriter(stream, new UTF8Encoding(false)) { NewLine = "\r\n", AutoFlush = true };
var commands = new List<string>();
var data = new StringBuilder();
await writer.WriteLineAsync("220 fake ESMTP");
while (await reader.ReadLineAsync() is { } line)
{
commands.Add(line);
if (line.StartsWith("EHLO", StringComparison.Ordinal))
{
await writer.WriteLineAsync("250-fake");
await writer.WriteLineAsync("250 AUTH PLAIN");
}
else if (line.StartsWith("AUTH", StringComparison.Ordinal))
{
await writer.WriteLineAsync("235 ok");
}
else if (line == "DATA")
{
await writer.WriteLineAsync("354 go on");
while (await reader.ReadLineAsync() is { } body && body != ".")
{
data.Append(body).Append('\n');
}
await writer.WriteLineAsync("250 queued");
}
else if (line == "QUIT")
{
await writer.WriteLineAsync("221 bye");
break;
}
else
{
await writer.WriteLineAsync("250 ok");
}
}
return (commands, data.ToString());
}
private sealed class FakeQueue : IMailQueue
{
public List<OutgoingMail> Mails { get; } = [];
public bool Configured { get; set; } = true;
public bool IsConfigured => Configured;
public bool Enqueue(OutgoingMail mail)
{
Mails.Add(mail);
return true;
}
}
}
@@ -0,0 +1,196 @@
using Khaemhat.Application.Documents;
using Khaemhat.Application.Parties;
using Khaemhat.Application.Querying;
using Khaemhat.Application.Security;
using Khaemhat.Application.Tables;
using Khaemhat.Core.Documents;
using Khaemhat.Core.Parties;
using Khaemhat.Core.Security;
using Khaemhat.Core.Tables;
using Khaemhat.Web.Documents;
using Khaemhat.Web.Tests.Hosting;
using Khaemhat.Web.Ui;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
namespace Khaemhat.Web.Tests.Documents;
/// <summary>
/// The sales screens on a real instance (issues #48-#51): what the editor proposes, the totals saved with the document,
/// the radar, the deferred invoicing of several delivery notes and customers.
/// </summary>
[TestClass]
public sealed class SalesFlowTests
{
private static readonly Actor Root = new(TestInstance.SuperUser, UserLevel.SuperUser, 1, null, null);
[TestMethod]
public async Task Save_WritesTheVatSummaryAndTheInstallments_FromTheTermsOfTheCustomer()
{
var (app, _, company) = await TestInstance.StartAsync(CancellationToken.None);
await using (app)
{
var engine = app.Services.GetRequiredService<DocumentEngine>();
var editor = app.Services.GetRequiredService<DocumentEditor>();
var tables = app.Services.GetRequiredService<TableService>();
var taxes = await tables.ActiveAsync<TaxCode>(Root, company);
var terms = await tables.ActiveAsync<PaymentTerm>(Root, company);
var vat22 = taxes.Single(t => t.Code == "22").Id;
var vat10 = taxes.Single(t => t.Code == "10").Id;
var endOfMonth = terms.Single(t => t.Code == "BB30FM").Id;
var customer = await CustomerAsync(app, company, "Bianchi Forniture S.p.A.", "07654321012", endOfMonth);
var invoice = await engine.NewAsync(Root, company, "FI");
invoice.Header.DocumentDate = new DateOnly(DateTime.Now.Year, 3, 10);
await editor.ApplyPartyAsync(Root, company, invoice, customer);
Assert.AreEqual(customer, invoice.Header.PartyId);
Assert.AreEqual(endOfMonth, invoice.Header.PaymentTermId, "The terms of the customer are proposed.");
invoice.Lines.Add(new SaleDocumentLine { Kind = DocumentLineKind.Free, Description = "Quadro elettrico", Quantity = 2m, Price = 150m, DiscountFormula = "10", TaxCodeId = vat22 });
invoice.Lines.Add(new SaleDocumentLine { Kind = DocumentLineKind.Free, Description = "Manuale d'uso", Quantity = 1m, Price = 20m, TaxCodeId = vat10 });
invoice.Lines.Add(new SaleDocumentLine { Kind = DocumentLineKind.Description, Description = "Consegna al magazzino centrale" });
// The preview computes what the save will write, without writing.
var preview = await editor.PreviewAsync(Root, company, invoice);
Assert.AreEqual(290m, invoice.Header.TaxableAmount);
Assert.HasCount(2, preview.Summary);
var saved = await engine.SaveAsync(Root, company, invoice);
Assert.AreEqual(270m, saved.Lines[0].TaxableAmount, "2 x 150 less 10%.");
Assert.AreEqual(290m, saved.Header.TaxableAmount);
Assert.AreEqual(59.40m + 2m, saved.Header.TaxAmount);
Assert.AreEqual(351.40m, saved.Header.TotalAmount);
CollectionAssert.AreEquivalent(new[] { 22m, 10m }, saved.Figures.Summary.Select(s => s.Rate).ToArray());
var due = saved.Figures.Installments.Single();
Assert.AreEqual(351.40m, due.Amount);
Assert.AreEqual(new DateOnly(DateTime.Now.Year, 4, 30), due.DueDate, "30 days, end of month.");
// Read back, the figures are those written.
var read = await engine.GetAsync(Root, company, DocumentFamily.SaleDocument, saved.Header.Id);
Assert.HasCount(2, read!.Figures.Summary);
Assert.HasCount(1, read.Figures.Installments);
// The radar finds the draft by the name of the customer.
var page = await editor.ListAsync(Root, company, DocumentFamily.SaleDocument, [DocumentKind.ImmediateInvoice], new ListQuery { Search = "bianchi" });
Assert.AreEqual(saved.Header.Id, page.Items.Single().Id);
Assert.AreEqual("Bianchi Forniture S.p.A.", page.Items[0].PartyName);
Assert.AreEqual(351.40m, page.Items[0].Total);
await app.StopAsync();
}
}
[TestMethod]
public async Task DeferredInvoicing_MergesTheDeliveryNotesOfOneCustomer_AndLeavesTheOthersOpen()
{
var (app, _, company) = await TestInstance.StartAsync(CancellationToken.None);
await using (app)
{
var engine = app.Services.GetRequiredService<DocumentEngine>();
var editor = app.Services.GetRequiredService<DocumentEditor>();
var copies = app.Services.GetRequiredService<DocumentCopyService>();
var first = await CustomerAsync(app, company, "Rossi Impianti S.r.l.", "02987654304", null);
var second = await CustomerAsync(app, company, "Verdi Costruzioni S.n.c.", "03111222331", null);
var month = new DateOnly(DateTime.Now.Year, 2, 1);
var notes = new List<DocumentRecord>
{
await DeliveryNoteAsync(engine, company, first, month.AddDays(2), "Tubo multistrato 16 mm", 50m),
await DeliveryNoteAsync(engine, company, second, month.AddDays(5), "Collettore 4 vie", 2m),
await DeliveryNoteAsync(engine, company, first, month.AddDays(9), "Raccordo a pressare", 30m),
};
var open = await editor.OpenAsync(Root, company, DocumentFamily.SaleDocument, [DocumentKind.DeliveryNote], null, month, month.AddMonths(1).AddDays(-1));
Assert.HasCount(3, open);
CollectionAssert.AreEqual(new[] { "Rossi Impianti S.r.l.", "Rossi Impianti S.r.l.", "Verdi Costruzioni S.n.c." }, open.Select(o => o.Row.PartyName).ToArray());
var mixed = await Assert.ThrowsExactlyAsync<ValidationFailedException>(() =>
copies.MergeAsync(Root, company, DocumentFamily.SaleDocument, [notes[0].Header.Id, notes[1].Header.Id], "FD"));
Assert.AreEqual(":" + DocumentErrors.CopyParties, mixed.Errors.Single());
var invoiceDate = month.AddMonths(1).AddDays(-1);
var invoice = await copies.MergeAsync(Root, company, DocumentFamily.SaleDocument, [notes[0].Header.Id, notes[2].Header.Id], "FD", invoiceDate);
Assert.AreEqual(DocumentKind.DeferredInvoice, invoice.Header.Kind);
Assert.AreEqual(invoiceDate, invoice.Header.DocumentDate);
Assert.HasCount(4, invoice.Lines, "A reference line before the lines of each delivery note.");
StringAssert.StartsWith(invoice.Lines[0].Description, "Rif. DDT n. " + notes[0].Header.DocumentNumber);
Assert.AreEqual(DocumentLineKind.Description, invoice.Lines[2].Kind);
Assert.AreEqual(0m, invoice.Header.TaxableAmount, "Without VAT codes nothing is taxable yet.");
// An invoice needs the VAT of every line before it is issued.
var untaxed = await Assert.ThrowsExactlyAsync<ValidationFailedException>(() => engine.ConfirmAsync(Root, company, DocumentFamily.SaleDocument, invoice.Header.Id));
CollectionAssert.AreEquivalent(
new[] { "Lines.1.TaxCodeId:" + DocumentErrors.LineTaxRequired, "Lines.3.TaxCodeId:" + DocumentErrors.LineTaxRequired }, untaxed.Errors.ToArray());
var vat22 = (await app.Services.GetRequiredService<TableService>().ActiveAsync<TaxCode>(Root, company)).Single(t => t.Code == "22").Id;
foreach (var line in invoice.Lines.Where(l => l.Kind != DocumentLineKind.Description))
{
line.TaxCodeId = vat22;
}
invoice = await engine.SaveAsync(Root, company, invoice);
Assert.AreEqual(80m * 3m, invoice.Header.TaxableAmount, "50 + 30 pieces at 3 euro.");
Assert.AreEqual(52.80m, invoice.Header.TaxAmount);
await engine.ConfirmAsync(Root, company, DocumentFamily.SaleDocument, invoice.Header.Id);
Assert.AreEqual(DocumentStatus.Fulfilled, (await engine.GetAsync(Root, company, DocumentFamily.SaleDocument, notes[0].Header.Id))!.Header.Status);
Assert.AreEqual(DocumentStatus.Fulfilled, (await engine.GetAsync(Root, company, DocumentFamily.SaleDocument, notes[2].Header.Id))!.Header.Status);
var left = await editor.OpenAsync(Root, company, DocumentFamily.SaleDocument, [DocumentKind.DeliveryNote], null, month, invoiceDate);
Assert.AreEqual(notes[1].Header.Id, left.Single().Row.Id);
// The invoice knows where its lines come from.
var links = await editor.LinksAsync(Root, company, (await engine.GetAsync(Root, company, DocumentFamily.SaleDocument, invoice.Header.Id))!);
CollectionAssert.AreEquivalent(new[] { notes[0].Header.Id, notes[2].Header.Id }, links.Select(l => l.Id).ToArray());
Assert.IsTrue(links.All(l => l.Direction == LinkDirection.Source));
await app.StopAsync();
}
}
[TestMethod]
public void Screens_MapEveryKindToItsRadar_AndHaveTheirTexts()
{
var invoices = SalesScreens.Find("FATTURE")!;
Assert.AreEqual(DocumentFamily.SaleDocument, invoices.Family);
Assert.AreEqual("vendite/fatture/12", SalesScreens.RecordUrl(DocumentKind.Fee, 12));
Assert.AreEqual("vendite/note-credito/3", SalesScreens.RecordUrl(DocumentKind.DebitNote, 3));
Assert.AreEqual("vendite/ddt/nuovo?tipo=DDT", SalesScreens.NewUrl(SalesScreens.Find("ddt")!, "DDT"));
Assert.IsNull(SalesScreens.RecordUrl(DocumentKind.PurchaseInvoice, 1));
// Each sales kind belongs to one radar only.
var kinds = SalesScreens.Sections.SelectMany(s => s.Kinds).ToList();
Assert.HasCount(kinds.Distinct().Count(), kinds);
var texts = Shell.ShellTests.Texts;
var today = new DateOnly(2026, 5, 10);
Assert.AreEqual((texts["Sales.Outcomes.Expired"], KhTone.Warning), SalesScreens.State(texts, DocumentKind.Quotation, DocumentStatus.Confirmed, today.AddDays(-1), today));
Assert.AreEqual((texts["Sales.Outcomes.Accepted"], KhTone.Ok), SalesScreens.State(texts, DocumentKind.Quotation, DocumentStatus.Fulfilled, null, today));
Assert.AreEqual((texts["Sales.Outcomes.Refused"], KhTone.Error), SalesScreens.State(texts, DocumentKind.Quotation, DocumentStatus.Closed, null, today));
var keys = Enum.GetValues<DocumentKind>().Select(k => "Sales.Kinds." + k)
.Concat(Enum.GetValues<DocumentStatus>().Select(s => "Sales.States." + s))
.Concat(kinds.Select(k => "Sales.Hints.Kinds." + k))
.Concat(SalesScreens.Sections.SelectMany(s => new[] { "Sales.Sections." + s.Key + ".Title", "Sales.Sections." + s.Key + ".New" }))
.Concat(Enum.GetValues<LinkDirection>().Select(d => "Sales.Links." + d))
.Concat(Enum.GetValues<DocumentLineKind>().Select(k => "Sales.LineKinds." + k));
var missing = keys.Where(k => !texts.Contains(k)).ToList();
Assert.IsEmpty(missing, string.Join(", ", missing));
}
private static async Task<DocumentRecord> DeliveryNoteAsync(DocumentEngine engine, string company, long customer, DateOnly date, string what, decimal quantity)
{
var note = await engine.NewAsync(Root, company, "DDT");
note.Header.PartyId = customer;
note.Header.DocumentDate = date;
note.Lines.Add(new SaleDocumentLine { Kind = DocumentLineKind.Free, Description = what, Quantity = quantity, Price = 3m });
note = await engine.SaveAsync(Root, company, note);
return await engine.ConfirmAsync(Root, company, DocumentFamily.SaleDocument, note.Header.Id);
}
private static async Task<long> CustomerAsync(WebApplication app, string company, string name, string vatNumber, long? paymentTermId)
{
var parties = app.Services.GetRequiredService<PartyService>();
var record = await parties.NewAsync(Root, company, PartyKind.Customer);
record.Party.Name = name;
record.Party.VatNumber = vatNumber;
record.Sales.PaymentTermId = paymentTermId;
return (await parties.SaveAsync(Root, company, record)).Party.Id;
}
}