diff --git a/CHANGELOG.md b/CHANGELOG.md index d2df3f8..75133c9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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` 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 diff --git a/README.md b/README.md index fd439e3..f055dbf 100644 --- a/README.md +++ b/README.md @@ -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: +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/-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 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**: 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:` (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) | (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 | | -## 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). diff --git a/docs/DATA-MODEL.md b/docs/DATA-MODEL.md index 471e9b0..d60d59f 100644 --- a/docs/DATA-MODEL.md +++ b/docs/DATA-MODEL.md @@ -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 | diff --git a/docs/STATUS.md b/docs/STATUS.md index 63edb64..ab96acd 100644 --- a/docs/STATUS.md +++ b/docs/STATUS.md @@ -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, diff --git a/docs/adr/0032-motore-documenti.md b/docs/adr/0032-motore-documenti.md new file mode 100644 index 0000000..bb3dc82 --- /dev/null +++ b/docs/adr/0032-motore-documenti.md @@ -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::` (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` (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). diff --git a/docs/adr/0033-totali-e-scadenze-dei-documenti.md b/docs/adr/0033-totali-e-scadenze-dei-documenti.md new file mode 100644 index 0000000..6eb78f4 --- /dev/null +++ b/docs/adr/0033-totali-e-scadenze-dei-documenti.md @@ -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). diff --git a/docs/adr/0034-stampa-e-invio-dei-documenti.md b/docs/adr/0034-stampa-e-invio-dei-documenti.md new file mode 100644 index 0000000..09e6c59 --- /dev/null +++ b/docs/adr/0034-stampa-e-invio-dei-documenti.md @@ -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). diff --git a/docs/wiki/Allegati-e-file.md b/docs/wiki/Allegati-e-file.md index 664b007..d99b9af 100644 --- a/docs/wiki/Allegati-e-file.md +++ b/docs/wiki/Allegati-e-file.md @@ -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. diff --git a/docs/wiki/Changelog.md b/docs/wiki/Changelog.md index 25d6fbc..7fa9a19 100644 --- a/docs/wiki/Changelog.md +++ b/docs/wiki/Changelog.md @@ -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. | diff --git a/docs/wiki/Dati-di-base-e-esempio.md b/docs/wiki/Dati-di-base-e-esempio.md index fef72f5..85b07bf 100644 --- a/docs/wiki/Dati-di-base-e-esempio.md +++ b/docs/wiki/Dati-di-base-e-esempio.md @@ -1,6 +1,6 @@ # Dati di base e di esempio -> **Stato:** completa per 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. diff --git a/docs/wiki/Guida-utente.md b/docs/wiki/Guida-utente.md new file mode 100644 index 0000000..979fd8c --- /dev/null +++ b/docs/wiki/Guida-utente.md @@ -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) diff --git a/docs/wiki/Home.md b/docs/wiki/Home.md index 9970cb0..5ad5149 100644 --- a/docs/wiki/Home.md +++ b/docs/wiki/Home.md @@ -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) | diff --git a/docs/wiki/Impostazioni.md b/docs/wiki/Impostazioni.md index 65ebcbc..9d81430 100644 --- a/docs/wiki/Impostazioni.md +++ b/docs/wiki/Impostazioni.md @@ -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*. diff --git a/docs/wiki/Log.md b/docs/wiki/Log.md index fb105ff..b0e9d7c 100644 --- a/docs/wiki/Log.md +++ b/docs/wiki/Log.md @@ -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 | diff --git a/docs/wiki/Primi-passi.md b/docs/wiki/Primi-passi.md index 4b8bb9c..79d3883 100644 --- a/docs/wiki/Primi-passi.md +++ b/docs/wiki/Primi-passi.md @@ -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 diff --git a/docs/wiki/Roadmap.md b/docs/wiki/Roadmap.md index dc05874..dc2906b 100644 --- a/docs/wiki/Roadmap.md +++ b/docs/wiki/Roadmap.md @@ -13,7 +13,7 @@ Il lavoro di dettaglio è nelle issue di Gitea, raggruppate per Finché il prodotto è in sviluppo le versioni restano **0.x**, anche dopo M13: la **1.0.0** sarà pubblicata solo quando verrà deciso esplicitamente. -**Completate:** M0 (0.0.1), M1 (0.1.0), M2 (0.2.0), M3 (0.3.0), M4 (0.4.0). **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 | |---|---|---|---| diff --git a/docs/wiki/Tabelle-azienda.md b/docs/wiki/Tabelle-azienda.md index 92d7be3..da6f66c 100644 --- a/docs/wiki/Tabelle-azienda.md +++ b/docs/wiki/Tabelle-azienda.md @@ -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 diff --git a/docs/wiki/Vendite.md b/docs/wiki/Vendite.md index 8d6cd6c..2c65130 100644 --- a/docs/wiki/Vendite.md +++ b/docs/wiki/Vendite.md @@ -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) diff --git a/docs/wiki/_Sidebar.md b/docs/wiki/_Sidebar.md index 0a39344..acf2037 100644 --- a/docs/wiki/_Sidebar.md +++ b/docs/wiki/_Sidebar.md @@ -1,5 +1,8 @@ **[Khaemhat](Home)** +**Guida** +- [Guida all'uso](Guida-utente) + **Installazione** - [Primi passi](Primi-passi) - [Unraid](Installazione-Unraid) diff --git a/docs/wiki/img/accesso-login.png b/docs/wiki/img/accesso-login.png new file mode 100644 index 0000000..b79dc14 Binary files /dev/null and b/docs/wiki/img/accesso-login.png differ diff --git a/docs/wiki/img/accesso-verifica.png b/docs/wiki/img/accesso-verifica.png new file mode 100644 index 0000000..d05798c Binary files /dev/null and b/docs/wiki/img/accesso-verifica.png differ diff --git a/docs/wiki/img/vendite-collegamenti.png b/docs/wiki/img/vendite-collegamenti.png new file mode 100644 index 0000000..67b8c10 Binary files /dev/null and b/docs/wiki/img/vendite-collegamenti.png differ diff --git a/docs/wiki/img/vendite-ddt-trasporto.png b/docs/wiki/img/vendite-ddt-trasporto.png new file mode 100644 index 0000000..af3b367 Binary files /dev/null and b/docs/wiki/img/vendite-ddt-trasporto.png differ diff --git a/docs/wiki/img/vendite-documento-testata.png b/docs/wiki/img/vendite-documento-testata.png new file mode 100644 index 0000000..def5807 Binary files /dev/null and b/docs/wiki/img/vendite-documento-testata.png differ diff --git a/docs/wiki/img/vendite-documento.png b/docs/wiki/img/vendite-documento.png new file mode 100644 index 0000000..47864cd Binary files /dev/null and b/docs/wiki/img/vendite-documento.png differ diff --git a/docs/wiki/img/vendite-email.png b/docs/wiki/img/vendite-email.png new file mode 100644 index 0000000..f2dfc1b Binary files /dev/null and b/docs/wiki/img/vendite-email.png differ diff --git a/docs/wiki/img/vendite-fatturazione-differita.png b/docs/wiki/img/vendite-fatturazione-differita.png new file mode 100644 index 0000000..2dc7f57 Binary files /dev/null and b/docs/wiki/img/vendite-fatturazione-differita.png differ diff --git a/docs/wiki/img/vendite-fatture-radar.png b/docs/wiki/img/vendite-fatture-radar.png new file mode 100644 index 0000000..2ec9f72 Binary files /dev/null and b/docs/wiki/img/vendite-fatture-radar.png differ diff --git a/docs/wiki/img/vendite-nota-credito.png b/docs/wiki/img/vendite-nota-credito.png new file mode 100644 index 0000000..b7e35b2 Binary files /dev/null and b/docs/wiki/img/vendite-nota-credito.png differ diff --git a/docs/wiki/img/vendite-nuovo-tipo.png b/docs/wiki/img/vendite-nuovo-tipo.png new file mode 100644 index 0000000..586cbed Binary files /dev/null and b/docs/wiki/img/vendite-nuovo-tipo.png differ diff --git a/docs/wiki/img/vendite-preventivi-radar.png b/docs/wiki/img/vendite-preventivi-radar.png new file mode 100644 index 0000000..ae3c7d8 Binary files /dev/null and b/docs/wiki/img/vendite-preventivi-radar.png differ diff --git a/docs/wiki/img/vendite-stampa-ddt.png b/docs/wiki/img/vendite-stampa-ddt.png new file mode 100644 index 0000000..2ecaf15 Binary files /dev/null and b/docs/wiki/img/vendite-stampa-ddt.png differ diff --git a/docs/wiki/img/vendite-stampa.png b/docs/wiki/img/vendite-stampa.png new file mode 100644 index 0000000..bb6516e Binary files /dev/null and b/docs/wiki/img/vendite-stampa.png differ diff --git a/docs/wiki/img/vendite-trasforma.png b/docs/wiki/img/vendite-trasforma.png new file mode 100644 index 0000000..778b071 Binary files /dev/null and b/docs/wiki/img/vendite-trasforma.png differ diff --git a/scripts/run-dev.sh b/scripts/run-dev.sh index b714a75..ad55cf2 100755 --- a/scripts/run-dev.sh +++ b/scripts/run-dev.sh @@ -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}" diff --git a/src/Khaemhat.Application/Documents/DocumentCalculation.cs b/src/Khaemhat.Application/Documents/DocumentCalculation.cs new file mode 100644 index 0000000..3f301ab --- /dev/null +++ b/src/Khaemhat.Application/Documents/DocumentCalculation.cs @@ -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; + +/// The totals of a stored document: its tax summary and installments, as written by the last save. +/// The tax summary. +/// The installments. +public sealed record DocumentFigures(IReadOnlyList Summary, IReadOnlyList Installments) +{ + /// No figures. + public static DocumentFigures Empty { get; } = new([], []); +} + +/// +/// Applies and to a document being saved: +/// writes the line amounts and header totals, then replaces its tax summary and installments (issue #48). +/// +internal static class DocumentCalculation +{ + /// Computes the totals of a document in place. + /// The unit of work. + /// The country's tax engine. + /// The behaviour of the document. + /// The document. + /// Cancellation. + /// The tax summary and installments to write once the document has its id. + public static async Task 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(); + 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); + } + + /// Replaces the tax summary and installments of a document. + /// The unit of work. + /// The family. + /// The document. + /// The new rows. + /// Cancellation. + /// A task. + public static async Task WriteAsync(IUnitOfWork uow, DocumentFamily family, long documentId, DocumentFigures figures, CancellationToken cancellationToken) + { + var summaries = uow.Repository(); + var installments = uow.Repository(); + var where = SqlFragment.Of($"family = {family.ToString()} AND document_id = {documentId}"); + foreach (var old in (await summaries.ListAsync(Query.For().Where(where), cancellationToken).ConfigureAwait(false)).Items) + { + await summaries.DeleteAsync(old.Id, cancellationToken).ConfigureAwait(false); + } + + foreach (var old in (await installments.ListAsync(Query.For().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); + } + } + + /// Reads the tax summary and installments of a document. + /// The unit of work. + /// The family. + /// The document. + /// Cancellation. + /// The rows. + public static async Task 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() + .ListAsync(Query.For().Where(where).OrderByDescending(s => s.Rate), cancellationToken).ConfigureAwait(false); + var installments = await uow.Repository() + .ListAsync(Query.For().Where(where).OrderBy(s => s.Number), cancellationToken).ConfigureAwait(false); + return new DocumentFigures(summary.Items, installments.Items); + } + + private static async Task> 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().ListAsync(Query.For().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> InstallmentsAsync( + IUnitOfWork uow, ITaxEngine engine, DocumentBehavior behavior, DocumentRecord record, DocumentTotals totals, CancellationToken cancellationToken) + { + var header = record.Header; + PaymentTerm? term = null; + IReadOnlyList termLines = []; + if (header.PaymentTermId is { } termId) + { + term = await uow.Repository().GetAsync(termId, cancellationToken).ConfigureAwait(false); + termLines = (await uow.Repository() + .ListAsync(Query.For().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() + .FindAsync(Query.For().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 })]; + } +} diff --git a/src/Khaemhat.Application/Documents/DocumentCopyService.cs b/src/Khaemhat.Application/Documents/DocumentCopyService.cs new file mode 100644 index 0000000..00163f7 --- /dev/null +++ b/src/Khaemhat.Application/Documents/DocumentCopyService.cs @@ -0,0 +1,257 @@ +using System.Globalization; +using Khaemhat.Application.Security; +using Khaemhat.Core.Documents; +using Khaemhat.Data; + +namespace Khaemhat.Application.Documents; + +/// +/// 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. +/// +public sealed class DocumentCopyService +{ + private readonly DocumentEngine _engine; + private readonly PermissionService _permissions; + private readonly TimeProvider _clock; + + /// Creates the service. + /// The engine. + /// The permissions. + /// The clock. + public DocumentCopyService(DocumentEngine engine, PermissionService permissions, TimeProvider clock) + { + ArgumentNullException.ThrowIfNull(engine); + ArgumentNullException.ThrowIfNull(permissions); + ArgumentNullException.ThrowIfNull(clock); + _engine = engine; + _permissions = permissions; + _clock = clock; + } + + /// Copies a document into a new draft and saves it. + /// Who copies. + /// The company. + /// The family of the source. + /// The source. + /// The type of the new document, such as DDT. + /// The lines to copy; all when empty. + /// Cancellation. + /// The new draft. + /// The copy is not possible. + public Task CopyAsync( + Actor actor, string companyCode, DocumentFamily family, long id, string targetTypeCode, IReadOnlyCollection? lineIds = null, + CancellationToken cancellationToken = default) => + MergeAsync(actor, companyCode, family, [id], targetTypeCode, null, lineIds, cancellationToken); + + /// + /// 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. + /// + /// Who copies. + /// The company. + /// The family of the sources. + /// The sources, in order. + /// The type of the new document. + /// The date of the new document; today when empty. + /// The lines to copy; all when empty. + /// Cancellation. + /// The new draft. + /// The copy is not possible. + public async Task MergeAsync( + Actor actor, string companyCode, DocumentFamily family, IReadOnlyList ids, string targetTypeCode, DateOnly? date = null, + IReadOnlyCollection? lineIds = null, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(actor); + ArgumentNullException.ThrowIfNull(ids); + if (ids.Count == 0) + { + throw new ValidationFailedException([":" + DocumentErrors.CopyNothingLeft]); + } + + var sources = new List(); + 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(); + 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; + } +} diff --git a/src/Khaemhat.Application/Documents/DocumentDefinition.cs b/src/Khaemhat.Application/Documents/DocumentDefinition.cs new file mode 100644 index 0000000..6f9cc87 --- /dev/null +++ b/src/Khaemhat.Application/Documents/DocumentDefinition.cs @@ -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; + +/// +/// 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. +/// +/// The row of document_types. +/// The behaviour of its kind. +public sealed record DocumentDefinition(DocumentType Type, DocumentBehavior Behavior) +{ + /// The code of the type. + public string Code => Type.Code; + + /// The kind. + public DocumentKind Kind => Behavior.Kind; + + /// The family (tables). + public DocumentFamily Family => Behavior.Family; + + /// The life cycle. + public DocumentLifecycle Lifecycle => Behavior.Lifecycle; + + /// The action that confirms the documents: issue for invoices, confirm for the others. + public DocumentAction ConfirmAction => Lifecycle == DocumentLifecycle.Invoice ? DocumentAction.Issue : DocumentAction.Confirm; +} + +/// Reads the definitions of the company's document types. +public static class DocumentDefinitionService +{ + /// Error: the document type does not exist. + public const string TypeMissing = "document.type.missing"; + + /// Error: the document type has no kind. + public const string TypeWithoutKind = "document.type.no-kind"; + + /// Error: the document type is disabled. + public const string TypeDisabled = "document.type.disabled"; + + /// The definition of a document type. + /// A company unit of work. + /// The type. + /// Cancellation. + /// The definition. + /// The type is missing or has no kind. + public static async Task GetAsync(IUnitOfWork uow, long typeId, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(uow); + var type = await uow.Repository().GetAsync(typeId, cancellationToken).ConfigureAwait(false) + ?? throw new ValidationFailedException([nameof(DocumentHeader.DocumentTypeId) + ":" + TypeMissing]); + return Of(type); + } + + /// The definition of a document type by code. + /// A company unit of work. + /// The code, such as FI. + /// Cancellation. + /// The definition. + /// The type is missing or has no kind. + public static async Task GetAsync(IUnitOfWork uow, string code, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(uow); + var normalized = (code ?? string.Empty).Trim().ToUpperInvariant(); + var type = await uow.Repository().FindAsync(Query.For().Where(t => t.Code == normalized), cancellationToken).ConfigureAwait(false) + ?? throw new ValidationFailedException([nameof(DocumentHeader.DocumentTypeId) + ":" + TypeMissing]); + return Of(type); + } + + /// The definitions of every usable type (enabled, with a kind), by code. + /// A company unit of work. + /// Cancellation. + /// The definitions. + public static async Task> ListAsync(IUnitOfWork uow, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(uow); + var types = await uow.Repository().ListAsync(Query.For().OrderBy(t => t.Code), cancellationToken).ConfigureAwait(false); + return [.. types.Items.Where(t => !t.Disabled && t.DocumentKind is not null).Select(Of)]; + } + + /// The definition of a type row. + /// The row. + /// The definition. + /// The type has no kind. + 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]); + } +} diff --git a/src/Khaemhat.Application/Documents/DocumentEditor.cs b/src/Khaemhat.Application/Documents/DocumentEditor.cs new file mode 100644 index 0000000..d011826 --- /dev/null +++ b/src/Khaemhat.Application/Documents/DocumentEditor.cs @@ -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; + +/// A document in a radar. +/// The document. +/// The family. +/// The kind. +/// The code of the document type. +/// The number as printed; empty for drafts. +/// The date. +/// The party. +/// The code of the party. +/// The name of the party. +/// The state. +/// The taxable amount. +/// The total. +/// The amount to pay. +/// The reference of the other side. +/// The delivery date. +/// Until when a quotation is valid. +/// The revision of a quotation. +/// Demo data. +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); + +/// A document linked to another one. +/// The family. +/// The document. +/// The kind. +/// The number. +/// The date. +/// The state. +/// The total. +/// Where it stands: before (source), after (fulfils it) or corrected (note). +/// The quantity fulfilled between the two. +public sealed record LinkedDocument( + DocumentFamily Family, long Id, DocumentKind Kind, string? DocumentNumber, DateOnly Date, DocumentStatus Status, decimal Total, + LinkDirection Direction, decimal Quantity); + +/// How a linked document relates to the one shown. +public enum LinkDirection +{ + /// The document shown fulfils it (an order of a delivery note). + Source = 0, + + /// It fulfils the document shown (a delivery note of an order). + Target = 1, + + /// The invoice a note corrects, or a note that corrects the invoice shown. + Related = 2, +} + +/// An open document with something left to fulfil, for the guided fulfilment and the deferred invoicing. +/// The document. +/// The lines with a residual. +public sealed record OpenDocument(DocumentRow Row, IReadOnlyList Lines); + +/// +/// 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. +/// +public sealed class DocumentEditor +{ + private readonly IUnitOfWorkFactory _factory; + private readonly PermissionService _permissions; + private readonly CompanyFiscalContext _packs; + + /// Creates the service. + /// The units of work. + /// The permissions. + /// The fiscal packs. + public DocumentEditor(IUnitOfWorkFactory factory, PermissionService permissions, CompanyFiscalContext packs) + { + ArgumentNullException.ThrowIfNull(factory); + ArgumentNullException.ThrowIfNull(permissions); + ArgumentNullException.ThrowIfNull(packs); + _factory = factory; + _permissions = permissions; + _packs = packs; + } + + /// A page of documents of some kinds of a family. + /// Who reads. + /// The company. + /// The family. + /// The kinds; all of the family when empty. + /// The request; the search also looks at the code and name of the party. + /// Cancellation. + /// The page. + public async Task> ListAsync( + Actor actor, string companyCode, DocumentFamily family, IReadOnlyCollection 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.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().ListAsync( + Query.For().Where(SqlFragment.Of($"(LOWER(name) LIKE {pattern} OR LOWER(code) LIKE {pattern})")).Take(500), cancellationToken).ConfigureAwait(false); + var any = new List + { + 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(await RowsAsync(uow, family, page.Items, cancellationToken).ConfigureAwait(false), page.Total, page.Totals); + } + + /// + /// 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). + /// + /// Who edits. + /// The company. + /// The document, changed in place. + /// The party; none clears it. + /// Cancellation. + /// A task. + 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().GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException("party.not-found"); + var fiscal = await uow.Repository().FindAsync(Query.For().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().FindAsync(Query.For().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() + .ListAsync(Query.For().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().FindAsync(Query.For(), cancellationToken).ConfigureAwait(false); + header.BankAccountId = profile?.DefaultBankAccountId; + } + } + else + { + var terms = await uow.Repository().FindAsync(Query.For().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().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; + } + } + } + + /// + /// 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. + /// + /// Who edits. + /// The company. + /// The document. + /// The line, changed in place. + /// The item. + /// Cancellation. + /// A task. + 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().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().FindAsync(Query.For().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().FindAsync(Query.For().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().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); + } + } + + /// + /// Computes the totals of a document being edited, without saving: line amounts and header totals change in place. + /// + /// Who edits. + /// The company. + /// The document. + /// Cancellation. + /// The tax summary and installments the save would write. + public async Task 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); + } + + /// The documents linked to one: the ones it fulfils, the ones that fulfil it, the invoice a note corrects. + /// Who reads. + /// The company. + /// The document. + /// Cancellation. + /// The linked documents. + public async Task> 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().ListAsync( + Query.For().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(); + 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)]; + } + + /// + /// 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. + /// + /// Who reads. + /// The company. + /// The family of the sources. + /// The kinds of the sources. + /// The party; all when empty. + /// The first date; none when empty. + /// The last date; none when empty. + /// Cancellation. + /// The documents, by party and date. + public async Task> OpenAsync( + Actor actor, string companyCode, DocumentFamily family, IReadOnlyCollection 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.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(); + 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> RowsAsync(IUnitOfWork uow, DocumentFamily family, IReadOnlyList 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() + : (await uow.Repository().ListAsync(Query.For().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() + : (await uow.Repository().ListAsync(Query.For().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); + }), + ]; + } +} diff --git a/src/Khaemhat.Application/Documents/DocumentEngine.cs b/src/Khaemhat.Application/Documents/DocumentEngine.cs new file mode 100644 index 0000000..a13a8c6 --- /dev/null +++ b/src/Khaemhat.Application/Documents/DocumentEngine.cs @@ -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; + +/// A document with its lines, whatever the family. +public sealed class DocumentRecord +{ + /// The family. + public DocumentFamily Family { get; init; } + + /// The header. + public required DocumentHeader Header { get; init; } + + /// The lines, in order. + public List Lines { get; init; } = []; + + /// The tax summary and installments written by the last save. + public DocumentFigures Figures { get; init; } = DocumentFigures.Empty; +} + +/// The error codes of the document engine; the interface translates them (Documents.json). +public static class DocumentErrors +{ + /// The document does not exist. + public const string NotFound = "document.not-found"; + + /// A customer or supplier is needed. + public const string PartyRequired = "document.party.required"; + + /// The date is missing. + public const string DateRequired = "document.date.required"; + + /// The date of a numbered document cannot change. + public const string DateNumbered = "document.date.numbered"; + + /// The type belongs to another family of documents. + public const string TypeFamily = "document.type.family"; + + /// The type of a confirmed document cannot change. + public const string TypeLocked = "document.type.locked"; + + /// The document has no lines. + public const string LinesRequired = "document.lines.required"; + + /// The kind of line is not accepted by the document. + public const string LineKindNotAllowed = "document.line.kind-not-allowed"; + + /// A line without description. + public const string LineDescriptionRequired = "document.line.description-required"; + + /// An item line without item. + public const string LineItemRequired = "document.line.item-required"; + + /// A quantity below what later documents already fulfilled. + public const string LineBelowFulfilled = "document.line.below-fulfilled"; + + /// A line fulfilled by later documents cannot be removed. + public const string LineFulfilledRemoved = "document.line.fulfilled-removed"; + + /// The line to fulfil does not exist or belongs to a kind the document does not fulfil. + public const string LineSourceInvalid = "document.line.source-invalid"; + + /// A cancelled invoice needs a reason. + public const string CancelReasonRequired = "document.cancel.reason-required"; + + /// Later documents fulfil this one: cancel them first. + public const string CancelHasFollowers = "document.cancel.has-followers"; + + /// A copy changes direction (sale to purchase). + public const string CopyDirection = "document.copy.direction"; + + /// Nothing is left to fulfil. + public const string CopyNothingLeft = "document.copy.nothing-left"; + + /// A closed or cancelled document cannot be fulfilled. + public const string CopySourceNotOpen = "document.copy.source-not-open"; + + /// Error: documents of different parties cannot go into one document. + public const string CopyParties = "document.copy.parties"; + + /// Error: a discount formula that cannot be read. + public const string LineDiscountInvalid = "document.line.discount-invalid"; + + /// Error: a line of an invoice without its VAT code. + public const string LineTaxRequired = "document.line.tax-required"; +} + +/// +/// 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 +/// and . +/// +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 _logger; + + /// Creates the engine. + /// The units of work. + /// The permissions. + /// The history. + /// The fiscal calendar (open periods). + /// The fiscal pack of each company (tax rounding, stamp duty). + /// The clock. + /// The log (section Documenti): confirmations, changes of state, deletions. + public DocumentEngine( + IUnitOfWorkFactory factory, PermissionService permissions, AuditTrail audit, FiscalYearService fiscal, CompanyFiscalContext packs, TimeProvider clock, + ILogger 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; + + /// The definitions of the usable document types. + /// Who asks. + /// The company. + /// Cancellation. + /// The definitions the actor can see. + public async Task> 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(); + 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; + } + + /// A new draft of a type, not saved: today's date and the defaults of the type. + /// Who creates. + /// The company. + /// The document type, such as FI. + /// Cancellation. + /// The draft. + public async Task 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 }; + } + + /// Reads a document. + /// Who reads. + /// The company. + /// The family. + /// The document. + /// Cancellation. + /// The document, if any. + public async Task 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; + } + + /// + /// 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. + /// + /// Who saves. + /// The company. + /// The document. + /// Cancellation. + /// The document as saved. + /// The document breaks a rule. + /// The state does not admit changes. + public async Task 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); + } + + /// + /// Confirms a document, or issues an invoice: checks it, numbers it, records the fulfilment of the documents its + /// lines come from. + /// + /// Who confirms. + /// The company. + /// The family. + /// The document. + /// Cancellation. + /// The document as confirmed. + public async Task 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); + } + + /// + /// 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). + /// + /// Who cancels. + /// The company. + /// The family. + /// The document. + /// Why. + /// Cancellation. + /// The document as cancelled. + public Task 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); + + /// Closes what is left to fulfil of an order, quotation, delivery note or pro forma. + /// Who closes. + /// The company. + /// The family. + /// The document. + /// Cancellation. + /// The document as closed. + public Task CloseAsync(Actor actor, string companyCode, DocumentFamily family, long id, CancellationToken cancellationToken = default) => + ChangeStateAsync(actor, companyCode, family, id, DocumentAction.Close, null, null, cancellationToken); + + /// Reopens a closed document: its state comes back from the fulfilment of its lines. + /// Who reopens. + /// The company. + /// The family. + /// The document. + /// Cancellation. + /// The document as reopened. + public Task 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); + + /// + /// Records a step of the electronic invoice (file generated, sent, delivered, rejected, not delivered); the module + /// of the electronic invoice (M8) calls it. + /// + /// Who records it. + /// The company. + /// The family. + /// The document. + /// The step. + /// Cancellation. + /// The document. + public Task 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); + } + + /// Records that the document was printed (its PDF kept among the attachments); the state does not change. + /// Who prints: needs to read the document. + /// The company. + /// The family. + /// The document. + /// Cancellation. + /// A task. + public Task MarkPrintedAsync(Actor actor, string companyCode, DocumentFamily family, long id, CancellationToken cancellationToken = default) => + MarkAsync(actor, companyCode, family, id, h => h.Printed = true, cancellationToken); + + /// Records that the document was sent by e-mail; the state does not change. + /// Who sends: needs to read the document. + /// The company. + /// The family. + /// The document. + /// Cancellation. + /// A task. + public Task MarkSentAsync(Actor actor, string companyCode, DocumentFamily family, long id, CancellationToken cancellationToken = default) => + MarkAsync(actor, companyCode, family, id, h => h.Sent = true, cancellationToken); + + /// Deletes a draft. + /// Who deletes. + /// The company. + /// The family. + /// The document. + /// Cancellation. + /// A task. + 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); + } + + /// The actions the state of a document admits for an actor. + /// Who asks. + /// The document. + /// Cancellation. + /// The actions. + public async Task> ActionsAsync(Actor actor, DocumentRecord record, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(record); + var behavior = DocumentBehaviors.Of(record.Header.Kind); + var result = new List(); + 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 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), + }; + } + + /// Checks a document against its definition; is the stored one. + internal static List Check(DocumentDefinition definition, DocumentRecord record, DocumentRecord? before) + { + var errors = new List(); + 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; + } + + /// Writes the header and replaces the lines of a draft or open document. + internal async Task 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 ChangeStateAsync( + Actor actor, + string companyCode, + DocumentFamily family, + long id, + DocumentAction action, + Func? before, + Func? 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 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(); + 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(); + var mine = (await links.ListAsync(Query.For().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> LinksFromAsync(IUnitOfWork uow, DocumentFamily family, long id, CancellationToken cancellationToken) => + (await uow.Repository().ListAsync(Query.For().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); +} diff --git a/src/Khaemhat.Application/Documents/DocumentMail.cs b/src/Khaemhat.Application/Documents/DocumentMail.cs new file mode 100644 index 0000000..19f04f7 --- /dev/null +++ b/src/Khaemhat.Application/Documents/DocumentMail.cs @@ -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; + +/// +/// Fills a mail template (SPEC §12.6): {{Name}} becomes the value of the field, unknown fields stay as they are +/// so that a typing error shows in the message instead of disappearing. +/// +public static partial class MailTemplateRenderer +{ + /// Fills a template. + /// The template. + /// The values by name (case does not matter). + /// The text. + public static string Render(string template, IReadOnlyDictionary fields) + { + ArgumentNullException.ThrowIfNull(template); + ArgumentNullException.ThrowIfNull(fields); + var lookup = new Dictionary(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(); +} + +/// A message about a document, as the user is about to send it. +/// The recipients, separated by commas or semicolons. +/// The subject. +/// The text. +public sealed record DocumentMailDraft(string To, string Subject, string Body); + +/// The errors of (text keys). +public static class DocumentMailErrors +{ + /// No SMTP server is configured. + public const string NotConfigured = "document.mail.not-configured"; + + /// No recipient, or one that is not an e-mail address. + public const string RecipientInvalid = "document.mail.recipient-invalid"; + + /// The subject is empty. + public const string SubjectRequired = "document.mail.subject-required"; + + /// The queue is full. + public const string QueueFull = "document.mail.queue-full"; +} + +/// +/// Sends a document by e-mail (SPEC §9.4, §12.6, issue #52): proposes recipient, subject and text from the templates +/// (Print.Mail.*) 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. +/// +/// The printed form of documents. +/// The document engine. +/// The generated files (the PDF). +/// The attachments. +/// The mail queue. +/// The units of work. +/// The texts. +public sealed partial class DocumentMailService( + DocumentPrintService prints, DocumentEngine engine, FileGenerationService generation, AttachmentService attachments, IMailQueue queue, IUnitOfWorkFactory factory, + ITexts texts) +{ + /// Whether mail can be sent from this instance. + public bool IsConfigured => queue.IsConfigured; + + /// The message proposed for a document. + /// Who sends. + /// The company. + /// The family. + /// The document. + /// Cancellation. + /// The draft. + public async Task 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().GetAsync(partyId, cancellationToken).ConfigureAwait(false))?.Email; + } + + var fields = new Dictionary + { + ["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)); + } + + /// Sends a document: the PDF becomes a new attachment version and leaves with the message. + /// Who sends. + /// The company. + /// The family. + /// The document. + /// The message. + /// Cancellation. + /// The PDF attached. + /// The message is not complete, or mail is not configured. + public async Task 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(); + 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; + } + + /// The addresses of a recipient field (commas, semicolons or spaces between them). + /// The field. + /// The addresses. + public static IReadOnlyList 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(); +} diff --git a/src/Khaemhat.Application/Documents/DocumentNumberingService.cs b/src/Khaemhat.Application/Documents/DocumentNumberingService.cs new file mode 100644 index 0000000..97759e5 --- /dev/null +++ b/src/Khaemhat.Application/Documents/DocumentNumberingService.cs @@ -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; + +/// A number given to a document. +/// The numerator row (code and year) that gave it, already updated. +/// The progressive number. +/// The number as printed. +public sealed record AssignedNumber(DocumentNumerator Numerator, long Number, string Text); + +/// +/// 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. +/// +public static class DocumentNumberingService +{ + /// Error: on a numerator without gaps the date precedes the last document numbered. + public const string DateBeforeLast = "document.number.date-before-last"; + + /// Error: the numerator of the document type does not exist. + public const string NumeratorMissing = "document.number.numerator-missing"; + + /// Error: the numerator is disabled. + public const string NumeratorDisabled = "document.number.numerator-disabled"; + + /// Error: the formatted number is longer than the column. + public const string NumberTooLong = "document.number.too-long"; + + /// The longest number as printed. + public const int MaxLength = 30; + + /// The lock that serializes the numbering of a numerator in a year. + /// The numerator code. + /// The year. + /// The lock key. + public static string LockKey(string code, int year) => "numerator:" + code + ":" + year.ToString(CultureInfo.InvariantCulture); + + /// + /// 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. + /// + /// A company unit of work inside a transaction. + /// The numerator of the document type. + /// The date of the document. + /// Cancellation. + /// The number. + /// The numerator is missing or disabled, or the date is out of sequence. + public static async Task NextAsync(IUnitOfWork uow, long numeratorId, DateOnly date, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(uow); + var numerators = uow.Repository(); + 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); + } + + /// What the next number would be, without giving it (the preview of a draft). + /// A company unit of work. + /// The numerator of the document type. + /// The date. + /// Cancellation. + /// The number as printed, or when the numerator is missing. + public static async Task PreviewAsync(IUnitOfWork uow, long numeratorId, DateOnly date, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(uow); + var numerators = uow.Repository(); + 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().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); + } + + /// + /// 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. + /// + /// A company unit of work. + /// The numerator row (code and year). + /// Cancellation. + /// The missing numbers, in order. + public static async Task> FindGapsAsync(IUnitOfWork uow, long numeratorId, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(uow); + var numerator = await uow.Repository().GetAsync(numeratorId, cancellationToken).ConfigureAwait(false) + ?? throw new ValidationFailedException([NumeratorMissing]); + var used = new HashSet(); + 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(sql, cancellationToken).ConfigureAwait(false)); + } + + var missing = new List(); + for (var n = 1L; n <= numerator.LastNumber; n++) + { + if (!used.Contains(n)) + { + missing.Add(n); + } + } + + return missing; + } + + private static async Task ForYearAsync(IUnitOfWork uow, DocumentNumerator template, int year, CancellationToken cancellationToken) + { + var numerators = uow.Repository(); + var code = template.Code; + if (await numerators.FindAsync(Query.For().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().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; + } +} diff --git a/src/Khaemhat.Application/Documents/DocumentPdfGenerator.cs b/src/Khaemhat.Application/Documents/DocumentPdfGenerator.cs new file mode 100644 index 0000000..b9bf3b8 --- /dev/null +++ b/src/Khaemhat.Application/Documents/DocumentPdfGenerator.cs @@ -0,0 +1,440 @@ +using Khaemhat.Application.Files; +using Khaemhat.Application.Security; +using Khaemhat.Infrastructure.Files; + +namespace Khaemhat.Application.Documents; + +/// +/// 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 +/// Rigenera writes the current state after a change. +/// +/// The printed form of documents. +/// The attachments (the logo of the company). +public sealed class DocumentPdfGenerator(DocumentPrintService prints, AttachmentService attachments) : IFileGenerator +{ + /// The code of the generator. + 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"); + + /// + public string Code => GeneratorCode; + + /// + public string TitleKey => "files.generators.document_pdf"; + + /// + public string MediaType => PdfWriter.MediaType; + + /// + public string Extension => ".pdf"; + + /// + public bool Supports(string entity) => DocumentPrintService.FamilyOf(entity) is not null; + + /// + public string FileName(FileGenerationContext context) + { + ArgumentNullException.ThrowIfNull(context); + return Stem(context) + Extension; + } + + /// + 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 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 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 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); + } + } +} diff --git a/src/Khaemhat.Application/Documents/DocumentPrint.cs b/src/Khaemhat.Application/Documents/DocumentPrint.cs new file mode 100644 index 0000000..e33deb4 --- /dev/null +++ b/src/Khaemhat.Application/Documents/DocumentPrint.cs @@ -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; + +/// A block of name and lines: the company in the letterhead, the party in the address box. +/// The name. +/// The code of the party, when there is one. +/// Address, tax numbers, contacts. +public sealed record PrintParty(string Name, string? Code, IReadOnlyList Lines); + +/// A label and its value. +/// The label. +/// The value, formatted. +public sealed record PrintField(string Label, string Value); + +/// A row of the totals. +/// The label. +/// The amount, formatted. +/// Whether it is the amount to pay. +public sealed record PrintRow(string Label, string Value, bool Strong); + +/// A line of the document as printed; every value formatted, empty for a descriptive line. +/// The item code. +/// The description. +/// The unit of measure. +/// The quantity. +/// The unit price. +/// The discounts, such as 10+5. +/// The VAT code. +/// The amount. +/// Whether the line is only text. +public sealed record PrintLine( + string? Code, string Description, string? Unit, string? Quantity, string? Price, string? Discount, string? Tax, string? Amount, bool IsDescription); + +/// A small table (VAT summary, installments) with its headings and rows. +/// The title. +/// The headings. +/// Which columns hold numbers (aligned right). +/// The rows, formatted. +public sealed record PrintTable(string Title, IReadOnlyList Headers, IReadOnlyList Numeric, IReadOnlyList> Rows); + +/// +/// 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. +/// +public sealed record DocumentPrintModel +{ + /// The kind, such as Fattura immediata. + public required string Title { get; init; } + + /// The number, or the draft label. + public required string Number { get; init; } + + /// The date. + public required string Date { get; init; } + + /// A mark across the sheet: draft, cancelled, demo; none for a valid document. + public string? Watermark { get; init; } + + /// The company in the letterhead. + public required PrintParty Company { get; init; } + + /// The logo of the company, a JPEG, when it has one. + public byte[]? Logo { get; init; } + + /// The attachment of the logo, for the HTML preview. + public long? LogoAttachmentId { get; init; } + + /// The heading of the address box (Spett.le, Fornitore). + public required string PartyLabel { get; init; } + + /// The customer or supplier. + public required PrintParty Party { get; init; } + + /// Payment, reference, validity, delivery, agent, CIG and CUP. + public required IReadOnlyList Fields { get; init; } + + /// The headings of the lines. + public required IReadOnlyList LineHeaders { get; init; } + + /// The lines. + public required IReadOnlyList Lines { get; init; } + + /// The VAT summary; empty for documents without VAT. + public PrintTable? Summary { get; init; } + + /// The installments; empty when the document has none. + public PrintTable? Installments { get; init; } + + /// The totals, the amount to pay last. + public required IReadOnlyList Totals { get; init; } + + /// The transport data of a delivery note or accompanying invoice; empty otherwise. + public required IReadOnlyList Transport { get; init; } + + /// The signature boxes of a delivery note. + public required IReadOnlyList Signatures { get; init; } + + /// Notes printed under the lines (document notes, legal notes such as split payment). + public required IReadOnlyList Notes { get; init; } + + /// The footer of the company. + public string? Footer { get; init; } + + /// The name of the file without extension, such as fattura-immediata-6-2026. + public required string FileStem { get; init; } +} + +/// +/// 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 (Print.*); the same model feeds the HTML preview and the PDF generator. +/// +/// The document engine (reads the document with its permission). +/// The units of work. +/// The company registry (name of a company without profile). +/// The texts. +public sealed class DocumentPrintService(DocumentEngine engine, IUnitOfWorkFactory factory, ICompanyRegistry companies, ITexts texts) +{ + private static readonly Dictionary Entities = new Dictionary + { + [DocumentFamily.SaleQuotation] = "sales.salequotation", + [DocumentFamily.SaleOrder] = "sales.saleorder", + [DocumentFamily.SaleDocument] = "sales.saledocument", + [DocumentFamily.PurchaseOrder] = "purchases.purchaseorder", + [DocumentFamily.PurchaseDocument] = "purchases.purchasedocument", + [DocumentFamily.InventoryDocument] = "inventory.inventorydocument", + }; + + /// The entity of the attachments of a family, such as sales.saledocument. + /// The family. + /// The entity. + public static string EntityOf(DocumentFamily family) => Entities[family]; + + /// The family of an attachment entity. + /// The entity. + /// The family, or none for another entity. + public static DocumentFamily? FamilyOf(string? entity) => + Entities.Where(e => string.Equals(e.Value, entity, StringComparison.Ordinal)).Select(e => (DocumentFamily?)e.Key).FirstOrDefault(); + + /// The printed form of a document. + /// Who prints: needs to read the document. + /// The company. + /// The family. + /// The document. + /// The logo, read by the caller with its own permission (a JPEG for the PDF). + /// Cancellation. + /// The model. + /// No such document. + public async Task BuildAsync( + Actor actor, string companyCode, DocumentFamily family, long id, Func>? 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().FindAsync(Query.For(), 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().GetAsync(partyId, cancellationToken).ConfigureAwait(false) : null; + + var lookups = new Lookups(uow, cancellationToken); + var behavior = definition.Behavior; + var lines = new List(); + 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(itemId).ConfigureAwait(false))?.Code : null; + lines.Add(new PrintLine( + code, + line.Description, + await lookups.CodeAsync(line.UnitOfMeasureId).ConfigureAwait(false), + texts.Number(line.Quantity, 2), + texts.Money(line.Price), + string.IsNullOrWhiteSpace(line.DiscountFormula) ? null : line.DiscountFormula, + await lookups.CodeAsync(line.TaxCodeId).ConfigureAwait(false), + texts.Money(line.TaxableAmount), + false)); + } + + var fields = new List(); + void Field(string key, string? value) + { + if (!string.IsNullOrWhiteSpace(value)) + { + fields.Add(new PrintField(texts["Print.Fields." + key], value)); + } + } + + Field("Payment", await lookups.DescriptionAsync(h.PaymentTermId).ConfigureAwait(false)); + if (h.BankAccountId is { } bankId && await lookups.GetAsync(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(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(); + var signatures = new List(); + 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(h.TransportReasonId).ConfigureAwait(false)); + Transport("By", h.TransportBy is { } by ? texts["Sales.TransportBy." + by] : null); + Transport("Carrier", await lookups.DescriptionAsync(h.CarrierId).ConfigureAwait(false)); + Transport("Port", await lookups.DescriptionAsync(h.ShippingTermId).ConfigureAwait(false)); + Transport("Appearance", await lookups.DescriptionAsync(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>(); + foreach (var row in record.Figures.Summary) + { + var tax = row.TaxCodeId is { } taxId ? await lookups.GetAsync(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>(); + foreach (var due in record.Figures.Installments) + { + rows.Add([ + due.Number.ToString(texts.Culture), + texts.Date(due.DueDate), + await lookups.DescriptionAsync(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(); + 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(); + 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(); + 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 TotalsOf(DocumentRecord record, DocumentDefinition definition) + { + var h = record.Header; + var rows = new List(); + 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 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 GetAsync(long id) + where T : Core.Entities.Entity, new() + { + if (!_cache.TryGetValue((typeof(T), id), out var found)) + { + found = await uow.Repository().GetAsync(id, cancellationToken).ConfigureAwait(false); + _cache[(typeof(T), id)] = found; + } + + return (T?)found; + } + + public async Task CodeAsync(long? id) + where T : CodedEntity, new() => + id is { } value ? (await GetAsync(value).ConfigureAwait(false))?.Code : null; + + public async Task DescriptionAsync(long? id) + where T : CodedEntity, new() => + id is { } value ? (await GetAsync(value).ConfigureAwait(false))?.Description : null; + } +} diff --git a/src/Khaemhat.Application/Documents/DocumentService.cs b/src/Khaemhat.Application/Documents/DocumentService.cs new file mode 100644 index 0000000..3937ed7 --- /dev/null +++ b/src/Khaemhat.Application/Documents/DocumentService.cs @@ -0,0 +1,149 @@ +using Khaemhat.Application.Security; +using Khaemhat.Core.Documents; + +namespace Khaemhat.Application.Documents; + +/// A document of one family, with its lines. +/// The header. +/// The line. +public sealed class DocumentRecord + where THeader : DocumentHeader, new() + where TLine : DocumentLine, new() +{ + /// The header. + public THeader Header { get; set; } = new(); + + /// The lines, in order. + public List Lines { get; set; } = []; +} + +/// +/// 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. +/// +/// The header. +/// The line. +public sealed class DocumentService + where THeader : DocumentHeader, new() + where TLine : DocumentLine, new() +{ + private readonly DocumentEngine _engine; + private readonly DocumentCopyService _copies; + + /// Creates the service. + /// The engine. + /// The copies. + public DocumentService(DocumentEngine engine, DocumentCopyService copies) + { + ArgumentNullException.ThrowIfNull(engine); + ArgumentNullException.ThrowIfNull(copies); + _engine = engine; + _copies = copies; + } + + /// The family. + public DocumentFamily Family => FamilyOfHeader; + + private static readonly DocumentFamily FamilyOfHeader = DocumentStores.FamilyOf(); + + /// A new draft of a type of this family, not saved. + /// Who creates. + /// The company. + /// The document type. + /// Cancellation. + /// The draft. + public async Task> 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); + } + + /// Reads a document. + /// Who reads. + /// The company. + /// The document. + /// Cancellation. + /// The document, if any. + public async Task?> 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; + + /// Saves a draft, or an order still open. + /// Who saves. + /// The company. + /// The document. + /// Cancellation. + /// The document as saved. + public async Task> SaveAsync(Actor actor, string companyCode, DocumentRecord 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); + } + + /// Confirms a document, or issues an invoice. + /// Who confirms. + /// The company. + /// The document. + /// Cancellation. + /// The document. + public async Task> ConfirmAsync(Actor actor, string companyCode, long id, CancellationToken cancellationToken = default) => + Typed(await _engine.ConfirmAsync(actor, companyCode, Family, id, cancellationToken).ConfigureAwait(false)); + + /// Cancels a document. + /// Who cancels. + /// The company. + /// The document. + /// Why (required for invoices). + /// Cancellation. + /// The document. + public async Task> CancelAsync(Actor actor, string companyCode, long id, string? reason, CancellationToken cancellationToken = default) => + Typed(await _engine.CancelAsync(actor, companyCode, Family, id, reason, cancellationToken).ConfigureAwait(false)); + + /// Closes what is left to fulfil. + /// Who closes. + /// The company. + /// The document. + /// Cancellation. + /// The document. + public async Task> CloseAsync(Actor actor, string companyCode, long id, CancellationToken cancellationToken = default) => + Typed(await _engine.CloseAsync(actor, companyCode, Family, id, cancellationToken).ConfigureAwait(false)); + + /// Reopens a closed document. + /// Who reopens. + /// The company. + /// The document. + /// Cancellation. + /// The document. + public async Task> ReopenAsync(Actor actor, string companyCode, long id, CancellationToken cancellationToken = default) => + Typed(await _engine.ReopenAsync(actor, companyCode, Family, id, cancellationToken).ConfigureAwait(false)); + + /// Deletes a draft. + /// Who deletes. + /// The company. + /// The document. + /// Cancellation. + /// A task. + public Task DeleteAsync(Actor actor, string companyCode, long id, CancellationToken cancellationToken = default) => + _engine.DeleteAsync(actor, companyCode, Family, id, cancellationToken); + + /// Copies a document of this family into a new draft of any type of the same direction. + /// Who copies. + /// The company. + /// The source. + /// The type of the new document. + /// The lines to copy; all when empty. + /// Cancellation. + /// The new draft, in its own family. + public Task CopyAsync( + Actor actor, string companyCode, long id, string targetTypeCode, IReadOnlyCollection? lineIds = null, CancellationToken cancellationToken = default) => + _copies.CopyAsync(actor, companyCode, Family, id, targetTypeCode, lineIds, cancellationToken); + + private static DocumentRecord Typed(DocumentRecord record) => + new() { Header = (THeader)record.Header, Lines = [.. record.Lines.Cast()] }; +} diff --git a/src/Khaemhat.Application/Documents/DocumentStores.cs b/src/Khaemhat.Application/Documents/DocumentStores.cs new file mode 100644 index 0000000..aa55ea5 --- /dev/null +++ b/src/Khaemhat.Application/Documents/DocumentStores.cs @@ -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; + +/// +/// 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). +/// +internal interface IDocumentStore +{ + /// The family. + DocumentFamily Family { get; } + + /// The header table. + string HeaderTable { get; } + + /// A new header of the family. + /// The header. + DocumentHeader NewHeader(); + + /// A new line of the family. + /// The line. + DocumentLine NewLine(); + + /// Reads a header. + /// The unit of work. + /// The document. + /// Cancellation. + /// The header, if any. + Task GetAsync(IUnitOfWork uow, long id, CancellationToken cancellationToken); + + /// Reads the lines of a document in their order. + /// The unit of work. + /// The document. + /// Cancellation. + /// The lines. + Task> LinesAsync(IUnitOfWork uow, long documentId, CancellationToken cancellationToken); + + /// Reads a line. + /// The unit of work. + /// The line. + /// Cancellation. + /// The line, if any. + Task GetLineAsync(IUnitOfWork uow, long id, CancellationToken cancellationToken); + + /// Inserts a header. + /// The unit of work. + /// The header. + /// Cancellation. + /// A task. + Task InsertAsync(IUnitOfWork uow, DocumentHeader header, CancellationToken cancellationToken); + + /// Updates a header. + /// The unit of work. + /// The header. + /// Cancellation. + /// A task. + Task UpdateAsync(IUnitOfWork uow, DocumentHeader header, CancellationToken cancellationToken); + + /// Deletes a header and, by cascade, its lines. + /// The unit of work. + /// The document. + /// Cancellation. + /// A task. + Task DeleteAsync(IUnitOfWork uow, long id, CancellationToken cancellationToken); + + /// Inserts a line. + /// The unit of work. + /// The line. + /// Cancellation. + /// A task. + Task InsertLineAsync(IUnitOfWork uow, DocumentLine line, CancellationToken cancellationToken); + + /// Updates a line. + /// The unit of work. + /// The line. + /// Cancellation. + /// A task. + Task UpdateLineAsync(IUnitOfWork uow, DocumentLine line, CancellationToken cancellationToken); + + /// Deletes a line. + /// The unit of work. + /// The line. + /// Cancellation. + /// A task. + Task DeleteLineAsync(IUnitOfWork uow, long id, CancellationToken cancellationToken); + + /// Writes a change of a header in the history, under the name of its class. + /// The history. + /// The unit of work. + /// What happened. + /// The document. + /// The header before. + /// The header after. + /// Who did it. + /// Cancellation. + /// A task. + Task RecordAsync( + AuditTrail audit, IUnitOfWork uow, AuditAction action, long id, DocumentHeader? before, DocumentHeader? after, string? userName, + CancellationToken cancellationToken); + + /// A page of headers: the list request, plus the conditions the caller adds (kinds, search on parties). + Task> ListAsync(IUnitOfWork uow, ListQuery list, IReadOnlyList conditions, CancellationToken cancellationToken); + + /// Headers by id. + Task> ManyAsync(IUnitOfWork uow, IReadOnlyCollection ids, CancellationToken cancellationToken); + + /// Lines by id. + Task> LinesByIdAsync(IUnitOfWork uow, IReadOnlyCollection ids, CancellationToken cancellationToken); +} + +/// The store of one family. +/// The header. +/// The line. +internal sealed class DocumentStore(DocumentFamily family, string headerTable) : IDocumentStore + where THeader : DocumentHeader, new() + where TLine : DocumentLine, new() +{ + /// + public DocumentFamily Family => family; + + /// + public string HeaderTable => headerTable; + + /// + public DocumentHeader NewHeader() => new THeader(); + + /// + public DocumentLine NewLine() => new TLine(); + + /// + public async Task GetAsync(IUnitOfWork uow, long id, CancellationToken cancellationToken) => + await uow.Repository().GetAsync(id, cancellationToken).ConfigureAwait(false); + + /// + public async Task> 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().ListAsync(Query.For().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()]; + } + + /// + public async Task GetLineAsync(IUnitOfWork uow, long id, CancellationToken cancellationToken) => + await uow.Repository().GetAsync(id, cancellationToken).ConfigureAwait(false); + + /// + public async Task InsertAsync(IUnitOfWork uow, DocumentHeader header, CancellationToken cancellationToken) => + header.Id = await uow.Repository().InsertAsync((THeader)header, cancellationToken).ConfigureAwait(false); + + /// + public Task UpdateAsync(IUnitOfWork uow, DocumentHeader header, CancellationToken cancellationToken) => + uow.Repository().UpdateAsync((THeader)header, cancellationToken); + + /// + public Task DeleteAsync(IUnitOfWork uow, long id, CancellationToken cancellationToken) => + uow.Repository().DeleteAsync(id, cancellationToken); + + /// + public async Task InsertLineAsync(IUnitOfWork uow, DocumentLine line, CancellationToken cancellationToken) => + line.Id = await uow.Repository().InsertAsync((TLine)line, cancellationToken).ConfigureAwait(false); + + /// + public Task UpdateLineAsync(IUnitOfWork uow, DocumentLine line, CancellationToken cancellationToken) => + uow.Repository().UpdateAsync((TLine)line, cancellationToken); + + /// + public Task DeleteLineAsync(IUnitOfWork uow, long id, CancellationToken cancellationToken) => + uow.Repository().DeleteAsync(id, cancellationToken); + + /// + 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); + + /// + public async Task> ListAsync(IUnitOfWork uow, ListQuery list, IReadOnlyList conditions, CancellationToken cancellationToken) + { + var query = Query.For(); + foreach (var condition in conditions) + { + query = query.Where(condition); + } + + var fields = DocumentListFields.Fields; + var page = await uow.Repository().ListAsync(fields.Apply(query, list), cancellationToken).ConfigureAwait(false); + return new ListPage([.. page.Items], page.TotalCount, new Dictionary()); + } + + /// + public async Task> ManyAsync(IUnitOfWork uow, IReadOnlyCollection ids, CancellationToken cancellationToken) + { + if (ids.Count == 0) + { + return []; + } + + var list = ids.ToList(); + var rows = await uow.Repository().ListAsync(Query.For().Where(h => list.Contains(h.Id)), cancellationToken).ConfigureAwait(false); + return [.. rows.Items]; + } + + /// + public async Task> LinesByIdAsync(IUnitOfWork uow, IReadOnlyCollection ids, CancellationToken cancellationToken) + { + if (ids.Count == 0) + { + return []; + } + + var list = ids.ToList(); + var rows = await uow.Repository().ListAsync(Query.For().Where(l => list.Contains(l.Id)), cancellationToken).ConfigureAwait(false); + return [.. rows.Items]; + } +} + +/// The fields of the document radars (ADR 0032): the same for every family. +/// The header. +internal static class DocumentListFields + where THeader : DocumentHeader +{ + /// The fields. + public static ListFields Fields { get; } = new ListFields() + .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)); +} + +/// The stores of the six families. +internal static class DocumentStores +{ + private static readonly Dictionary ByFamily = new IDocumentStore[] + { + new DocumentStore(DocumentFamily.SaleQuotation, "sale_quotations"), + new DocumentStore(DocumentFamily.SaleOrder, "sale_orders"), + new DocumentStore(DocumentFamily.SaleDocument, "sale_documents"), + new DocumentStore(DocumentFamily.PurchaseOrder, "purchase_orders"), + new DocumentStore(DocumentFamily.PurchaseDocument, "purchase_documents"), + new DocumentStore(DocumentFamily.InventoryDocument, "inventory_documents"), + }.ToDictionary(s => s.Family); + + /// Every store. + public static IEnumerable All => ByFamily.Values; + + /// The store of a family. + /// The family. + /// The store. + public static IDocumentStore Of(DocumentFamily family) => ByFamily[family]; + + /// The family of a header class. + /// The header. + /// The family. + public static DocumentFamily FamilyOf() + where THeader : DocumentHeader, new() + { + var type = typeof(THeader); + return All.Single(s => s.NewHeader().GetType() == type).Family; + } +} diff --git a/src/Khaemhat.Application/Documents/DocumentTotalsCalculator.cs b/src/Khaemhat.Application/Documents/DocumentTotalsCalculator.cs new file mode 100644 index 0000000..a6d82f1 --- /dev/null +++ b/src/Khaemhat.Application/Documents/DocumentTotalsCalculator.cs @@ -0,0 +1,257 @@ +using Khaemhat.Application.Tables; +using Khaemhat.Core.Documents; +using Khaemhat.Core.Tax; +using Khaemhat.Fiscal.Abstractions; + +namespace Khaemhat.Application.Documents; + +/// The VAT of a line, from its tax code. +/// The tax code. +/// The rate in percent. +/// The nature of operations without VAT. +/// When the VAT becomes due. +/// The non-deductible share (purchases). +/// The law printed for operations without VAT. +public sealed record TotalsTax( + long? TaxCodeId, + decimal Rate, + string? Nature = null, + TaxExigibility Exigibility = TaxExigibility.Immediate, + decimal NonDeductiblePercent = 0m, + string? LegalReference = null); + +/// A line as the calculator sees it. +/// The kind of line. +/// The quantity (expenses and discounts without quantity count as one). +/// The unit price, with VAT when the document's prices include it. +/// The discounts, such as 10+5. +/// The VAT; lines without it are left out of the summary. +/// The line is out of the withholding and of the social security contribution. +public sealed record TotalsLine( + DocumentLineKind Kind, + decimal Quantity, + decimal Price, + string? DiscountFormula, + TotalsTax? Tax, + bool WithholdingExcluded = false); + +/// The settings of the document that change its totals. +public sealed record TotalsOptions +{ + /// The prices include VAT: the taxable amount is computed back from each VAT group. + public bool PricesIncludeTax { get; init; } + + /// The discount on the goods (not on expenses), such as 5 or 10+5. + public string? FooterDiscount { get; init; } + + /// The exigibility of the whole document (cash basis, deferred), when not the one of the tax codes. + public TaxExigibility? Exigibility { get; init; } + + /// Split payment: the VAT is paid by the customer to the State. + public bool SplitPayment { get; init; } + + /// The document can carry the stamp duty (invoices and notes). + public bool StampDutyApplies { get; init; } + + /// The stamp duty is added to the total. + public bool StampDutyCharged { get; init; } + + /// The withholding rate, percent. + public decimal? WithholdingRate { get; init; } + + /// The share of the amount the withholding applies to, percent. + public decimal WithholdingBasePercent { get; init; } = 100m; + + /// The social security contribution rate, percent. + public decimal? SocialSecurityRate { get; init; } + + /// The VAT of the contribution; the one of the first taxed line when empty. + public TotalsTax? SocialSecurityTax { get; init; } + + /// The contribution is part of the withholding base. + public bool SocialSecurityWithheld { get; init; } + + /// The ENASARCO rate withheld, percent. + public decimal? EnasarcoRate { get; init; } +} + +/// A line of the computed tax summary. +/// The VAT of the group, with the exigibility of the document. +/// The taxable amount. +/// The VAT. +/// The non-deductible part of the VAT. +public sealed record TotalsSummaryLine(TotalsTax Tax, decimal Taxable, decimal TaxAmount, decimal NonDeductibleTax); + +/// The totals of a document. +/// The amount of each line (quantity × price less its discounts), in the order given. +/// The tax summary, by rate (highest first). +/// The total of the expense lines. +/// What the footer discount took off. +/// The social security contribution. +/// The taxable amount. +/// The VAT. +/// The stamp duty due (charged or not). +/// The total of the document. +/// The withholding tax. +/// The ENASARCO contribution withheld. +/// The VAT the customer pays to the State. +/// The amount to pay. +public sealed record DocumentTotals( + IReadOnlyList LineAmounts, + IReadOnlyList Summary, + decimal Expenses, + decimal FooterDiscountAmount, + decimal SocialSecurity, + decimal Taxable, + decimal Tax, + decimal StampDuty, + decimal Total, + decimal Withholding, + decimal Enasarco, + decimal SplitPaymentTax, + decimal Net); + +/// +/// 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 DatiRiepilogo); social security contribution with its own VAT; stamp duty; withholding, ENASARCO +/// and split payment taken off the amount to pay. +/// +public static class DocumentTotalsCalculator +{ + /// Computes the totals. + /// The lines. + /// The settings of the document. + /// The country's rounding and stamp duty rules. + /// The totals. + public static DocumentTotals Compute(IReadOnlyList 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(); + 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); + } + + /// The factor of a discount formula: 10+5 is 0.855; an empty or invalid formula is 1. + /// The formula. + /// The factor. + 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 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; } + } +} diff --git a/src/Khaemhat.Application/Documents/InstallmentGenerator.cs b/src/Khaemhat.Application/Documents/InstallmentGenerator.cs new file mode 100644 index 0000000..2789c77 --- /dev/null +++ b/src/Khaemhat.Application/Documents/InstallmentGenerator.cs @@ -0,0 +1,110 @@ +namespace Khaemhat.Application.Documents; + +/// An installment of payment terms. +/// Days from the document date. +/// Move to the end of that month. +/// A fixed day: of the next month after the end-of-month move, else the next such day. +/// The share of the amount, percent. +public sealed record InstallmentRule(int Days, bool EndOfMonth, int? FixedDay, decimal Percent); + +/// Months without due dates (mesi esclusi): a due date in them moves to a day of the next month. +/// The first month (1-12). +/// The second month. +/// The day of the next month. +public sealed record ExcludedMonths(int? First, int? Second, int Day = 10) +{ + /// Whether a month is excluded. + /// The month. + /// Whether it is. + public bool Contains(int month) => First == month || Second == month; +} + +/// A computed installment. +/// The order, from 1. +/// The due date. +/// The amount. +public sealed record InstallmentDue(int Number, DateOnly DueDate, decimal Amount); + +/// +/// 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. +/// +public static class InstallmentGenerator +{ + /// Computes the installments. + /// The document date. + /// The amount to pay. + /// The VAT included in (for ). + /// The installments of the terms; none means one installment on the document date. + /// All the VAT is paid with the first installment. + /// The months without due dates. + /// Rounding to the cent. + /// The installments, empty for a zero amount. + public static IReadOnlyList Generate( + DateOnly date, decimal amount, decimal tax, IReadOnlyList rules, bool vatOnFirst, ExcludedMonths? excluded, Func 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(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; + } + + /// The due date of an installment. + /// The document date. + /// The installment. + /// The months without due dates. + /// The due date. + 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))); +} diff --git a/src/Khaemhat.Application/Seeding/BaseTablesSeeder.cs b/src/Khaemhat.Application/Seeding/BaseTablesSeeder.cs index 4564270..a1636df 100644 --- a/src/Khaemhat.Application/Seeding/BaseTablesSeeder.cs +++ b/src/Khaemhat.Application/Seeding/BaseTablesSeeder.cs @@ -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, diff --git a/src/Khaemhat.Application/Seeding/DemoSalesSeeder.cs b/src/Khaemhat.Application/Seeding/DemoSalesSeeder.cs new file mode 100644 index 0000000..1fa80f7 --- /dev/null +++ b/src/Khaemhat.Application/Seeding/DemoSalesSeeder.cs @@ -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; + +/// +/// 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. +/// +/// The document engine. +/// The document editor (party terms, item prices). +/// The transformations between documents. +/// The company profiles. +/// The units of work. +/// The clock. +public sealed class DemoSalesSeeder( + DocumentEngine engine, DocumentEditor editor, DocumentCopyService copies, CompanyProfileService profiles, IUnitOfWorkFactory factory, TimeProvider clock) + : ICompanySeeder +{ + /// The fictitious VAT number of the demo company (valid check digit). + 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; + + /// + public int Order => 20; + + /// + 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 ReadAsync(string companyCode, CancellationToken cancellationToken) + { + await using var uow = await factory.CreateAsync(DatabaseScope.Company(companyCode), cancellationToken).ConfigureAwait(false); + if (await uow.Repository().CountAsync(Query.For(), cancellationToken).ConfigureAwait(false) > 0 + || await uow.Repository().CountAsync(Query.For(), cancellationToken).ConfigureAwait(false) > 0) + { + return null; + } + + var parties = (await uow.Repository().ListAsync(Query.For().Where(p => p.IsDemo), cancellationToken).ConfigureAwait(false)).Items + .GroupBy(p => p.Name, StringComparer.Ordinal).ToDictionary(g => g.Key, g => g.First().Id, StringComparer.Ordinal); + var items = (await uow.Repository().ListAsync(Query.For().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 Parties, IReadOnlyList Goods, IReadOnlyList 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 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 CopyAsync(DocumentRecord source, string type, DateOnly date, IReadOnlyCollection? lines = null) => + owner.Copies.MergeAsync(Seed, company, source.Family, [source.Header.Id], type, date, lines, cancellationToken); + + private Task ConfirmAsync(DocumentRecord record) => + owner.Engine.ConfirmAsync(Seed, company, record.Family, record.Header.Id, cancellationToken); + } +} diff --git a/src/Khaemhat.Application/Tables/TableCatalog.cs b/src/Khaemhat.Application/Tables/TableCatalog.cs index b50a8fe..50000ec 100644 --- a/src/Khaemhat.Application/Tables/TableCatalog.cs +++ b/src/Khaemhat.Application/Tables/TableCatalog.cs @@ -66,6 +66,9 @@ public sealed partial class TableCatalog /// Error: another price list is already the base one. public const string BaseDuplicate = "tables.price-list.base-duplicate"; + /// A document type without a kind. + public const string DocumentKindRequired = "tables.document-type.kind-required"; + /// The maximum depth of item categories. 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(); diff --git a/src/Khaemhat.Core/Documents/DocumentBehaviors.cs b/src/Khaemhat.Core/Documents/DocumentBehaviors.cs new file mode 100644 index 0000000..e9f4e47 --- /dev/null +++ b/src/Khaemhat.Core/Documents/DocumentBehaviors.cs @@ -0,0 +1,113 @@ +namespace Khaemhat.Core.Documents; + +/// How the documents of a kind behave (ADR 0032). +/// The kind. +/// The tables that hold them. +/// Customer, supplier or internal. +/// The states they go through. +/// What confirming them does. +/// The line kinds they accept. +/// The kinds whose lines they fulfil (order to delivery note, delivery note to invoice...). +/// The permission to see them. +/// The permission to create and change drafts. +/// The permission to confirm or issue, cancel, close and reopen. +/// The permission to delete drafts. +public sealed record DocumentBehavior( + DocumentKind Kind, + DocumentFamily Family, + DocumentDirection Direction, + DocumentLifecycle Lifecycle, + DocumentEffects Effects, + IReadOnlyList Lines, + IReadOnlyList Sources, + string ReadPermission, + string WritePermission, + string ConfirmPermission, + string DeletePermission) +{ + /// Whether the documents need a customer or supplier. + public bool NeedsParty => Direction != DocumentDirection.Internal; + + /// Whether the documents have the given effect. + /// The effect. + /// Whether they have it. + public bool Has(DocumentEffects effect) => (Effects & effect) == effect; + + /// Whether the documents fulfil the lines of documents of another kind. + /// The kind of the source. + /// Whether a copy from it creates fulfilment links. + public bool Fulfils(DocumentKind source) => Sources.Contains(source); +} + +/// The behaviour of every . +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 ByKind = Build().ToDictionary(b => b.Kind); + + /// Every behaviour, in the order of . + public static IReadOnlyList All { get; } = [.. ByKind.Values.OrderBy(b => b.Kind)]; + + /// The behaviour of a kind. + /// The kind. + /// The behaviour. + public static DocumentBehavior Of(DocumentKind kind) => + ByKind.TryGetValue(kind, out var behavior) ? behavior : throw new ArgumentOutOfRangeException(nameof(kind), kind, "Unknown document kind."); + + /// The kinds kept in a family. + /// The family. + /// The kinds. + public static IReadOnlyList KindsOf(DocumentFamily family) => [.. All.Where(b => b.Family == family).Select(b => b.Kind)]; + + private static IEnumerable 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); +} diff --git a/src/Khaemhat.Core/Documents/DocumentKinds.cs b/src/Khaemhat.Core/Documents/DocumentKinds.cs new file mode 100644 index 0000000..1ebff92 --- /dev/null +++ b/src/Khaemhat.Core/Documents/DocumentKinds.cs @@ -0,0 +1,248 @@ +namespace Khaemhat.Core.Documents; + +/// The family of a document: the pair of tables that holds it (SPEC §11.3). +public enum DocumentFamily +{ + /// Quotations (sale_quotations). + SaleQuotation = 0, + + /// Customer orders (sale_orders). + SaleOrder = 1, + + /// Delivery notes, invoices, credit and debit notes, pro forma, fees, self-invoices (sale_documents). + SaleDocument = 2, + + /// Supplier orders (purchase_orders). + PurchaseOrder = 3, + + /// Supplier delivery notes, invoices and credit notes (purchase_documents). + PurchaseDocument = 4, + + /// Warehouse entries (inventory_documents). + InventoryDocument = 5, +} + +/// Who the document is with. +public enum DocumentDirection +{ + /// A customer: the company sells. + Sale = 0, + + /// A supplier: the company buys. + Purchase = 1, + + /// Nobody: an internal document. + Internal = 2, +} + +/// +/// 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. +/// +public enum DocumentKind +{ + /// A quotation to a customer. + Quotation = 0, + + /// A customer order. + SalesOrder = 1, + + /// A delivery note (DDT) to a customer. + DeliveryNote = 2, + + /// An immediate invoice. + ImmediateInvoice = 3, + + /// An accompanying invoice: an invoice that is also the delivery note. + AccompanyingInvoice = 4, + + /// A deferred invoice of one or more delivery notes. + DeferredInvoice = 5, + + /// A down payment invoice. + DownPaymentInvoice = 6, + + /// A credit note to a customer. + CreditNote = 7, + + /// A debit note to a customer. + DebitNote = 8, + + /// A professional fee invoice (parcella). + Fee = 9, + + /// A pro forma invoice, without fiscal effects. + ProForma = 10, + + /// A self-invoice or integration of a purchase (reverse charge, purchases from abroad). + SelfInvoice = 11, + + /// An order to a supplier. + PurchaseOrder = 12, + + /// A delivery note of a supplier (goods received). + PurchaseDeliveryNote = 13, + + /// An invoice of a supplier. + PurchaseInvoice = 14, + + /// A credit note of a supplier. + PurchaseCreditNote = 15, + + /// A warehouse entry: loads, unloads, transfers. + InventoryEntry = 16, +} + +/// The life cycle a document follows (ADR 0032). +public enum DocumentLifecycle +{ + /// Draft, confirmed, partially fulfilled, fulfilled, closed, cancelled: quotations, orders, delivery notes, pro forma. + Order = 0, + + /// Draft, issued, then the states of the exchange system: sale invoices and self-invoices. + Invoice = 1, + + /// Draft, confirmed, cancelled: supplier invoices, warehouse entries. + Simple = 2, +} + +/// The state of a document (SPEC §11.3). +public enum DocumentStatus +{ + /// Being written: no number, no effects. + Draft = 0, + + /// Confirmed: numbered, effects applied. + Confirmed = 1, + + /// Some lines fulfilled by later documents. + PartiallyFulfilled = 2, + + /// Every line fulfilled. + Fulfilled = 3, + + /// Closed by hand: what is left will not be fulfilled. + Closed = 4, + + /// Cancelled: the number stays, the effects are removed. + Cancelled = 5, + + /// An invoice issued: numbered and no longer changeable. + Issued = 6, + + /// The electronic invoice file has been generated. + SdiGenerated = 7, + + /// The electronic invoice has been sent to the exchange system. + SdiSent = 8, + + /// The exchange system delivered the invoice. + SdiDelivered = 9, + + /// The exchange system rejected the invoice. + SdiRejected = 10, + + /// The exchange system could not deliver the invoice (made available to the customer). + SdiNotDelivered = 11, +} + +/// What a user or a procedure can do with a document; the state machine says when. +public enum DocumentAction +{ + /// Change the header or the lines. + Edit = 0, + + /// Delete a draft that was never numbered. + Delete = 1, + + /// Confirm: number and apply the effects (orders, delivery notes, simple documents). + Confirm = 2, + + /// Issue an invoice: number it and make it unchangeable. + Issue = 3, + + /// Cancel: keep the number, remove the effects. + Cancel = 4, + + /// Close what is left to fulfil. + Close = 5, + + /// Reopen a closed document. + Reopen = 6, + + /// Make a new draft from the document (duplicate or transform). + Copy = 7, + + /// Record that the electronic invoice file was generated. + GenerateXml = 8, + + /// Record that the electronic invoice was sent. + Send = 9, + + /// Record the delivery receipt. + MarkDelivered = 10, + + /// Record the rejection. + MarkRejected = 11, + + /// Record that the invoice could not be delivered. + MarkNotDelivered = 12, +} + +/// What confirming a document does to the rest of the company's data (applied by the modules: M6, M7, M8). +[Flags] +public enum DocumentEffects +{ + /// No effect. + None = 0, + + /// Moves stock (load or unload by the warehouse reason). + Inventory = 1, + + /// Commits stock to customers (orders). + Commitment = 2, + + /// Records quantities ordered from suppliers. + Ordered = 4, + + /// Posts to the general ledger and the VAT registers. + Ledger = 8, + + /// Generates the installments of the payment schedule. + Installments = 16, + + /// Produces an electronic invoice. + EInvoice = 32, +} + +/// The kind of a document line. +public enum DocumentLineKind +{ + /// An item of the catalogue, with quantity and price. + Item = 0, + + /// A line with quantity and price but no item. + Free = 1, + + /// Text only. + Description = 2, + + /// An ancillary expense (transport, collection). + Expense = 3, + + /// A discount, premium or allowance. + Discount = 4, +} + +/// Who carries the goods (delivery note: trasporto a cura del). +public enum TransportResponsibility +{ + /// The sender (mittente). + Sender = 0, + + /// The recipient (destinatario). + Recipient = 1, + + /// A carrier (vettore). + Carrier = 2, +} diff --git a/src/Khaemhat.Core/Documents/DocumentStateMachine.cs b/src/Khaemhat.Core/Documents/DocumentStateMachine.cs new file mode 100644 index 0000000..69b5b60 --- /dev/null +++ b/src/Khaemhat.Core/Documents/DocumentStateMachine.cs @@ -0,0 +1,157 @@ +namespace Khaemhat.Core.Documents; + +/// +/// 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: computes them. +/// +public static class DocumentStateMachine +{ + private static readonly Dictionary<(DocumentLifecycle, DocumentStatus), Dictionary> Rules = Build(); + + /// The states a life cycle uses, in order. + /// The life cycle. + /// The states. + public static IReadOnlyList States(DocumentLifecycle lifecycle) => + [.. Rules.Keys.Where(k => k.Item1 == lifecycle).Select(k => k.Item2).OrderBy(s => s)]; + + /// The actions a state admits. + /// The life cycle. + /// The state. + /// The actions, in the order of . + public static IReadOnlyList Actions(DocumentLifecycle lifecycle, DocumentStatus status) => + Rules.TryGetValue((lifecycle, status), out var actions) ? [.. actions.Keys.OrderBy(a => a)] : []; + + /// Whether a state admits an action. + /// The life cycle. + /// The state. + /// The action. + /// Whether it is admitted. + public static bool Allows(DocumentLifecycle lifecycle, DocumentStatus status, DocumentAction action) => + Rules.TryGetValue((lifecycle, status), out var actions) && actions.ContainsKey(action); + + /// The state after an action. + /// The life cycle. + /// The state. + /// The action. + /// The new state (the same one for actions that do not move it, such as edit and copy). + /// The state does not admit the action. + 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); + + /// Whether the header and lines can change in a state. + /// The life cycle. + /// The state. + /// Whether they can. + public static bool IsEditable(DocumentLifecycle lifecycle, DocumentStatus status) => Allows(lifecycle, status, DocumentAction.Edit); + + /// Whether a document in this state counts: confirmed or issued, and not cancelled. + /// The state. + /// Whether its effects and links are in force. + public static bool IsInForce(DocumentStatus status) => status is not (DocumentStatus.Draft or DocumentStatus.Cancelled); + + /// + /// 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. + /// + /// The life cycle. + /// The state. + /// What the lines say. + /// The new state. + 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> Build() + { + var rules = new Dictionary<(DocumentLifecycle, DocumentStatus), Dictionary>(); + + 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; + } +} + +/// An action the state of the document does not admit. +public sealed class InvalidDocumentActionException : InvalidOperationException +{ + /// The error code for the interface. + public const string Code = "document.action.not-allowed"; + + /// Creates the exception. + public InvalidDocumentActionException() + : base(Code) + { + } + + /// Creates the exception. + /// The message. + public InvalidDocumentActionException(string message) + : base(message) + { + } + + /// Creates the exception. + /// The message. + /// The cause. + public InvalidDocumentActionException(string message, Exception innerException) + : base(message, innerException) + { + } + + /// Creates the exception. + /// The life cycle. + /// The state. + /// The refused action. + 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; + } + + /// The life cycle. + public DocumentLifecycle Lifecycle { get; } + + /// The state. + public DocumentStatus Status { get; } + + /// The refused action. + public DocumentAction Action { get; } +} diff --git a/src/Khaemhat.Core/Documents/Documents.cs b/src/Khaemhat.Core/Documents/Documents.cs new file mode 100644 index 0000000..cf8cbc9 --- /dev/null +++ b/src/Khaemhat.Core/Documents/Documents.cs @@ -0,0 +1,458 @@ +using Khaemhat.Core.Entities; +using Khaemhat.Core.Items; +using Khaemhat.Core.Tax; + +namespace Khaemhat.Core.Documents; + +/// +/// 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. +/// +public abstract class DocumentHeader : Entity, IDemoMarkable +{ + /// The document type of the company. + public long DocumentTypeId { get; set; } + + /// The kind, copied from the type when the document is created. + public DocumentKind Kind { get; set; } + + /// The state. + public DocumentStatus Status { get; set; } + + /// The numerator row (code and year) that gave the number. + public long? NumeratorId { get; set; } + + /// The section (sezionale) of the numerator. + public string? Section { get; set; } + + /// The progressive number; empty until confirmation. + public long? Number { get; set; } + + /// The number as printed, such as 12/2026. + public string? DocumentNumber { get; set; } + + /// The date of the document. + public DateOnly DocumentDate { get; set; } + + /// The year of the numbering. + public int Year { get; set; } + + /// The customer or supplier. + public long? PartyId { get; set; } + + /// The destination (an address of the party). + public long? DestinationId { get; set; } + + /// The reference of the other side: customer order number, supplier invoice or delivery note number. + public string? ExternalReference { get; set; } + + /// The date of the reference. + public DateOnly? ExternalDate { get; set; } + + /// The currency. + public string CurrencyCode { get; set; } = "EUR"; + + /// The exchange rate to euro. + public decimal ExchangeRate { get; set; } = 1m; + + /// The price list. + public long? PriceListId { get; set; } + + /// The payment terms. + public long? PaymentTermId { get; set; } + + /// The payment method. + public long? PaymentMethodId { get; set; } + + /// The bank account of the company that collects or pays. + public long? BankAccountId { get; set; } + + /// The agent. + public long? SalespersonId { get; set; } + + /// The warehouse. + public long? WarehouseId { get; set; } + + /// The warehouse reason. + public long? InventoryReasonId { get; set; } + + /// The reason of the transport. + public long? TransportReasonId { get; set; } + + /// The shipping terms (porto). + public long? ShippingTermId { get; set; } + + /// The carrier. + public long? CarrierId { get; set; } + + /// The appearance of the goods. + public long? GoodsAppearanceId { get; set; } + + /// The number of packages. + public int? Packages { get; set; } + + /// The gross weight in kg. + public decimal? GrossWeight { get; set; } + + /// The net weight in kg. + public decimal? NetWeight { get; set; } + + /// When the transport starts. + public DateTime? TransportStart { get; set; } + + /// Until when a quotation is valid. + public DateOnly? ValidUntil { get; set; } + + /// The delivery date requested or promised. + public DateOnly? DeliveryDate { get; set; } + + /// The revision of a quotation. + public int Revision { get; set; } + + /// Printed at least once. + public bool Printed { get; set; } + + /// Sent by e-mail at least once. + public bool Sent { get; set; } + + /// Posted to the ledger. + public bool Posted { get; set; } + + /// Installments generated in the payment schedule. + public bool InstallmentsGenerated { get; set; } + + /// Electronic invoice file generated. + public bool XmlGenerated { get; set; } + + /// The taxable amount. + public decimal TaxableAmount { get; set; } + + /// The tax. + public decimal TaxAmount { get; set; } + + /// The total of the document. + public decimal TotalAmount { get; set; } + + /// The discount on the total (percent formula, such as 5 or 10+5). + public string? FooterDiscount { get; set; } + + /// The ancillary expenses. + public decimal ExpensesAmount { get; set; } + + /// The stamp duty. + public decimal StampDuty { get; set; } + + /// The withholding tax. + public decimal WithholdingAmount { get; set; } + + /// The social security contribution (cassa previdenza). + public decimal SocialSecurityAmount { get; set; } + + /// The amount to pay. + public decimal NetAmount { get; set; } + + /// The prices of the lines include VAT: the taxable amount is computed back from them. + public bool PricesIncludeTax { get; set; } + + /// The amount taken off the lines by . + public decimal FooterDiscountAmount { get; set; } + + /// When the VAT of the document becomes due, when not the one of its tax codes (split payment, cash basis). + public TaxExigibility? Exigibility { get; set; } + + /// Split payment: the public administration pays the VAT to the State, not to the company. + public bool SplitPayment { get; set; } + + /// The stamp duty is charged to the customer (added to the total). + public bool StampDutyCharged { get; set; } + + /// The withholding tax rate, percent; none when the document has no withholding. + public decimal? WithholdingRate { get; set; } + + /// The share of the amount the withholding is computed on, percent (100 for fees, 50 or 20 for agents). + public decimal WithholdingBasePercent { get; set; } = 100m; + + /// The withholding type of the e-invoice, such as RT01. + public string? WithholdingType { get; set; } + + /// The payment reason of the withholding (e-invoice), such as A. + public string? WithholdingReason { get; set; } + + /// The social security fund (cassa previdenza) of the e-invoice, such as TC22. + public string? SocialSecurityFund { get; set; } + + /// The contribution rate of the fund, percent. + public decimal? SocialSecurityRate { get; set; } + + /// The VAT code of the contribution; the one of the first line when empty. + public long? SocialSecurityTaxCodeId { get; set; } + + /// The contribution is subject to the withholding tax (INPS 4%). + public bool SocialSecurityWithheld { get; set; } + + /// The ENASARCO rate withheld from the commissions of an agent, percent. + public decimal? EnasarcoRate { get; set; } + + /// The ENASARCO contribution withheld. + public decimal EnasarcoAmount { get; set; } + + /// The tender code (CIG) of a public contract. + public string? Cig { get; set; } + + /// The project code (CUP) of a public contract. + public string? Cup { get; set; } + + /// Who carries the goods (delivery notes, accompanying invoices). + public TransportResponsibility? TransportBy { get; set; } + + /// The document a credit or debit note corrects, in the same family. + public long? RelatedDocumentId { get; set; } + + /// The number of the corrected document, also for documents outside Khaemhat. + public string? RelatedNumber { get; set; } + + /// The date of the corrected document. + public DateOnly? RelatedDate { get; set; } + + /// The notes printed on the document. + public string? Notes { get; set; } + + /// The ledger entry, once posted (M7). + public long? GlEntryId { get; set; } + + /// The VAT protocol of a supplier invoice. + public long? VatProtocol { get; set; } + + /// When the document was confirmed or issued. + public DateTime? ConfirmedAt { get; set; } + + /// Who confirmed or issued it. + public string? ConfirmedBy { get; set; } + + /// When it was cancelled. + public DateTime? CancelledAt { get; set; } + + /// Why it was cancelled. + public string? CancelReason { get; set; } + + /// + public bool IsDemo { get; set; } + + /// A shallow copy of the same class (the state before a change, for the history). + /// The copy. + public DocumentHeader Clone() => (DocumentHeader)MemberwiseClone(); +} + +/// A line of a document (SPEC §11.3). +public abstract class DocumentLine : Entity +{ + /// The document. + public long DocumentId { get; set; } + + /// The progressive number of the line (1, 2...), the one printed and sent. + public int LineNumber { get; set; } + + /// The kind of line. + public DocumentLineKind Kind { get; set; } + + /// The item. + public long? ItemId { get; set; } + + /// The description. + public string Description { get; set; } = string.Empty; + + /// The unit of measure. + public long? UnitOfMeasureId { get; set; } + + /// The quantity. + public decimal Quantity { get; set; } + + /// The unit price. + public decimal Price { get; set; } + + /// Where the price comes from. + public PriceSource PriceSource { get; set; } + + /// The discounts, such as 10+5. + public string? DiscountFormula { get; set; } + + /// The VAT code. + public long? TaxCodeId { get; set; } + + /// The taxable amount of the line. + public decimal TaxableAmount { get; set; } + + /// The warehouse of the line, when different from the header. + public long? WarehouseId { get; set; } + + /// The delivery date of the line. + public DateOnly? DeliveryDate { get; set; } + + /// How much later documents fulfilled. + public decimal FulfilledQuantity { get; set; } + + /// The rest will not be fulfilled (line closed by hand). + public bool FulfillmentClosed { get; set; } + + /// The family of the line this one was copied from to fulfil it. + public DocumentFamily? SourceFamily { get; set; } + + /// The line this one fulfils. + public long? SourceLineId { get; set; } + + /// The line is left out of the withholding tax and of the social security contribution (expenses paid on behalf). + public bool WithholdingExcluded { get; set; } + + /// The ledger account (M7). + public string? AccountCode { get; set; } + + /// The cost centre. + public long? CostCenterId { get; set; } + + /// The job (commessa). + public long? JobId { get; set; } + + /// Notes of the line. + public string? Notes { get; set; } + + /// The order on screen and in print. + public int SortOrder { get; set; } + + /// What is left to fulfil: zero for closed lines and lines without quantity. + public decimal Residual => FulfillmentClosed || !CarriesQuantity(Kind) ? 0m : Math.Max(0m, Quantity - FulfilledQuantity); + + /// A shallow copy of the same class. + /// The copy. + public DocumentLine Clone() => (DocumentLine)MemberwiseClone(); + + /// Whether lines of a kind carry a quantity that later documents can fulfil. + /// The kind. + /// Whether they do. + public static bool CarriesQuantity(DocumentLineKind kind) => kind is DocumentLineKind.Item or DocumentLineKind.Free; +} + +/// A quotation (sale_quotations). +public sealed class SaleQuotation : DocumentHeader; + +/// A line of a quotation. +public sealed class SaleQuotationLine : DocumentLine; + +/// A customer order (sale_orders). +public sealed class SaleOrder : DocumentHeader; + +/// A line of a customer order. +public sealed class SaleOrderLine : DocumentLine; + +/// A delivery note, invoice, credit or debit note, pro forma, fee or self-invoice (sale_documents). +public sealed class SaleDocument : DocumentHeader; + +/// A line of a sale document. +public sealed class SaleDocumentLine : DocumentLine; + +/// A supplier order (purchase_orders). +public sealed class PurchaseOrder : DocumentHeader; + +/// A line of a supplier order. +public sealed class PurchaseOrderLine : DocumentLine; + +/// A supplier delivery note, invoice or credit note (purchase_documents). +public sealed class PurchaseDocument : DocumentHeader; + +/// A line of a purchase document. +public sealed class PurchaseDocumentLine : DocumentLine; + +/// A warehouse entry (inventory_documents). +public sealed class InventoryDocument : DocumentHeader; + +/// A line of a warehouse entry. +public sealed class InventoryDocumentLine : DocumentLine; + +/// +/// A fulfilment link (document_links): 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). +/// +public sealed class DocumentLink : Entity +{ + /// The family of the fulfilling document. + public DocumentFamily TargetFamily { get; set; } + + /// The fulfilling document. + public long TargetDocumentId { get; set; } + + /// The fulfilling line. + public long TargetLineId { get; set; } + + /// The family of the fulfilled document. + public DocumentFamily SourceFamily { get; set; } + + /// The fulfilled document. + public long SourceDocumentId { get; set; } + + /// The fulfilled line. + public long SourceLineId { get; set; } + + /// The quantity fulfilled. + public decimal Quantity { get; set; } +} + +/// +/// A line of the tax summary of a document (castelletto IVA, document_tax_summaries): one per VAT code, +/// written by the totals calculator each time the document is saved. +/// +public sealed class DocumentTaxSummary : Entity +{ + /// The family of the document. + public DocumentFamily Family { get; set; } + + /// The document. + public long DocumentId { get; set; } + + /// The VAT code. + public long? TaxCodeId { get; set; } + + /// The rate in percent. + public decimal Rate { get; set; } + + /// The nature of operations without VAT. + public string? Nature { get; set; } + + /// When the VAT becomes due. + public TaxExigibility Exigibility { get; set; } + + /// The non-deductible share, percent. + public decimal NonDeductiblePercent { get; set; } + + /// The law printed for operations without VAT. + public string? LegalReference { get; set; } + + /// The taxable amount. + public decimal Taxable { get; set; } + + /// The VAT. + public decimal Tax { get; set; } + + /// The non-deductible part of the VAT. + public decimal NonDeductibleTax { get; set; } +} + +/// An installment of a document (document_installments), from its payment terms. +public sealed class DocumentInstallment : Entity +{ + /// The family of the document. + public DocumentFamily Family { get; set; } + + /// The document. + public long DocumentId { get; set; } + + /// The order, from 1. + public int Number { get; set; } + + /// The due date. + public DateOnly DueDate { get; set; } + + /// The amount. + public decimal Amount { get; set; } + + /// The payment method. + public long? PaymentMethodId { get; set; } +} diff --git a/src/Khaemhat.Core/Documents/FulfillmentCalculator.cs b/src/Khaemhat.Core/Documents/FulfillmentCalculator.cs new file mode 100644 index 0000000..53f878b --- /dev/null +++ b/src/Khaemhat.Core/Documents/FulfillmentCalculator.cs @@ -0,0 +1,61 @@ +namespace Khaemhat.Core.Documents; + +/// What the lines of a document say about its fulfilment. +public enum FulfillmentState +{ + /// Nothing fulfilled. + None = 0, + + /// Something fulfilled, something left. + Partial = 1, + + /// Every line fulfilled or closed. + Fulfilled = 2, +} + +/// Line-by-line fulfilment (SPEC §11.3, ADR 0032): quantities from the links, state of the document from the lines. +public static class FulfillmentCalculator +{ + /// Writes on each line the quantity fulfilled by the links that point to it. + /// The lines of the fulfilled document. + /// The links in force (of confirmed documents) towards those lines. + /// The lines whose quantity changed. + public static IReadOnlyList Apply(IEnumerable lines, IEnumerable 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(); + foreach (var line in lines) + { + var fulfilled = byLine.GetValueOrDefault(line.Id); + if (line.FulfilledQuantity != fulfilled) + { + line.FulfilledQuantity = fulfilled; + changed.Add(line); + } + } + + return changed; + } + + /// The fulfilment of a document from its lines; lines without quantity do not count. + /// The lines. + /// The state. + public static FulfillmentState StateOf(IEnumerable 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; + } +} diff --git a/src/Khaemhat.Core/Logging/LogSection.cs b/src/Khaemhat.Core/Logging/LogSection.cs index 106b465..b410bcf 100644 --- a/src/Khaemhat.Core/Logging/LogSection.cs +++ b/src/Khaemhat.Core/Logging/LogSection.cs @@ -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, diff --git a/src/Khaemhat.Core/Parties/Parties.cs b/src/Khaemhat.Core/Parties/Parties.cs index 63a7e82..6177c45 100644 --- a/src/Khaemhat.Core/Parties/Parties.cs +++ b/src/Khaemhat.Core/Parties/Parties.cs @@ -339,6 +339,15 @@ public sealed class PartySalesTerms : Entity /// The day of the month the deferred invoices are issued, if fixed. public int? InvoiceDay { get; set; } + /// A month without due dates (1-12), such as August: they move to the next month. + public int? ExcludedMonth1 { get; set; } + + /// A second month without due dates, such as December. + public int? ExcludedMonth2 { get; set; } + + /// The day of the next month a due date in an excluded month moves to (10 when empty). + public int? ExcludedMonthsDay { get; set; } + /// How the documents are sent. public DocumentDelivery SendDocuments { get; set; } diff --git a/src/Khaemhat.Core/Tables/BaseTables.cs b/src/Khaemhat.Core/Tables/BaseTables.cs index 77326c5..e5ca6fa 100644 --- a/src/Khaemhat.Core/Tables/BaseTables.cs +++ b/src/Khaemhat.Core/Tables/BaseTables.cs @@ -408,6 +408,9 @@ public sealed class DocumentNumerator : CodedEntity /// Whether gaps are allowed (never for invoices, credit notes and final entries). public bool GapsAllowed { get; set; } + + /// The date of the last document numbered: without gaps, no later document may have an earlier date. + public DateOnly? LastDate { get; set; } } /// A type of document: the links between a document and its numerator, warehouse reason and SDI type. @@ -416,6 +419,9 @@ public sealed class DocumentType : CodedEntity /// The family of document. public NumeratorKind Kind { get; set; } + /// What the documents of this type are, which decides how they behave (ADR 0032); empty for types not yet usable. + public Documents.DocumentKind? DocumentKind { get; set; } + /// The numerator. public long? NumeratorId { get; set; } diff --git a/src/Khaemhat.Data/CompanyDatabase/DocumentMaps.cs b/src/Khaemhat.Data/CompanyDatabase/DocumentMaps.cs new file mode 100644 index 0000000..29bf09b --- /dev/null +++ b/src/Khaemhat.Data/CompanyDatabase/DocumentMaps.cs @@ -0,0 +1,108 @@ +using Khaemhat.Core.Documents; +using Khaemhat.Data.Mapping; + +namespace Khaemhat.Data.CompanyDatabase; + +/// The columns shared by the six document headers (ADR 0032). +/// The header. +public abstract class DocumentHeaderMap : EntityMap + where T : DocumentHeader, new() +{ + /// Creates the map. + /// The table of the family. + 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); + } +} + +/// The columns shared by the six tables of lines. +/// The line. +public abstract class DocumentLineMap : EntityMap + where T : DocumentLine, new() +{ + /// Creates the map. + /// The table of the lines. + protected DocumentLineMap(string table) + { + ToTable(table); + Map(x => x.Description).MaxLength(1000); + Map(x => x.DiscountFormula).MaxLength(30); + Map(x => x.AccountCode).MaxLength(20); + } +} + +/// Map of to sale_quotations. +public sealed class SaleQuotationMap() : DocumentHeaderMap("sale_quotations"); + +/// Map of to sale_quotation_lines. +public sealed class SaleQuotationLineMap() : DocumentLineMap("sale_quotation_lines"); + +/// Map of to sale_orders. +public sealed class SaleOrderMap() : DocumentHeaderMap("sale_orders"); + +/// Map of to sale_order_lines. +public sealed class SaleOrderLineMap() : DocumentLineMap("sale_order_lines"); + +/// Map of to sale_documents. +public sealed class SaleDocumentMap() : DocumentHeaderMap("sale_documents"); + +/// Map of to sale_document_lines. +public sealed class SaleDocumentLineMap() : DocumentLineMap("sale_document_lines"); + +/// Map of to purchase_orders. +public sealed class PurchaseOrderMap() : DocumentHeaderMap("purchase_orders"); + +/// Map of to purchase_order_lines. +public sealed class PurchaseOrderLineMap() : DocumentLineMap("purchase_order_lines"); + +/// Map of to purchase_documents. +public sealed class PurchaseDocumentMap() : DocumentHeaderMap("purchase_documents"); + +/// Map of to purchase_document_lines. +public sealed class PurchaseDocumentLineMap() : DocumentLineMap("purchase_document_lines"); + +/// Map of to inventory_documents. +public sealed class InventoryDocumentMap() : DocumentHeaderMap("inventory_documents"); + +/// Map of to inventory_document_lines. +public sealed class InventoryDocumentLineMap() : DocumentLineMap("inventory_document_lines"); + +/// Map of to document_links. +public sealed class DocumentLinkMap : EntityMap +{ + /// Creates the map. + public DocumentLinkMap() => ToTable("document_links"); +} + +/// Map of to document_tax_summaries. +public sealed class DocumentTaxSummaryMap : EntityMap +{ + /// Creates the map. + public DocumentTaxSummaryMap() + { + ToTable("document_tax_summaries"); + Map(x => x.Nature).MaxLength(10); + Map(x => x.LegalReference).MaxLength(100); + } +} + +/// Map of to document_installments. +public sealed class DocumentInstallmentMap : EntityMap +{ + /// Creates the map. + public DocumentInstallmentMap() => ToTable("document_installments"); +} diff --git a/src/Khaemhat.Data/CompanyDatabase/Migrations/M20261112_003_CreateDocuments.cs b/src/Khaemhat.Data/CompanyDatabase/Migrations/M20261112_003_CreateDocuments.cs new file mode 100644 index 0000000..78da870 --- /dev/null +++ b/src/Khaemhat.Data/CompanyDatabase/Migrations/M20261112_003_CreateDocuments.cs @@ -0,0 +1,243 @@ +using Khaemhat.Data.Migrations; +using Khaemhat.Data.Schema; + +namespace Khaemhat.Data.CompanyDatabase.Migrations; + +/// +/// 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. +/// +[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"), + ]; + + /// + 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); + }); + } +} diff --git a/src/Khaemhat.Data/Querying/ExpressionTranslator.cs b/src/Khaemhat.Data/Querying/ExpressionTranslator.cs index 0f2368b..cb21d3c 100644 --- a/src/Khaemhat.Data/Querying/ExpressionTranslator.cs +++ b/src/Khaemhat.Data/Querying/ExpressionTranslator.cs @@ -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; } diff --git a/src/Khaemhat.Fiscal.Abstractions/Features.cs b/src/Khaemhat.Fiscal.Abstractions/Features.cs index 2f5cbc2..727d475 100644 --- a/src/Khaemhat.Fiscal.Abstractions/Features.cs +++ b/src/Khaemhat.Fiscal.Abstractions/Features.cs @@ -221,8 +221,10 @@ public sealed record PaymentTermTemplate(string Code, string Description, string /// The numerator of the base data (FAT, DDT...), if the document is numbered by the company. /// The warehouse reason of the base data (SCA, CAR...), if the document moves goods. /// The type of the e-invoice format, if the document is sent electronically. +/// What the documents are, which decides how they behave (ADR 0032). 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); /// /// The rows of the base tables that depend on the country's rules (SPEC §14): payment methods and terms with the codes diff --git a/src/Khaemhat.Fiscal.Italy/ItalianBaseTables.cs b/src/Khaemhat.Fiscal.Italy/ItalianBaseTables.cs index 1b7b629..e015538 100644 --- a/src/Khaemhat.Fiscal.Italy/ItalianBaseTables.cs +++ b/src/Khaemhat.Fiscal.Italy/ItalianBaseTables.cs @@ -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 /// public IReadOnlyList 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), ]; } diff --git a/src/Khaemhat.Infrastructure/Mail/Mail.cs b/src/Khaemhat.Infrastructure/Mail/Mail.cs new file mode 100644 index 0000000..8c706e8 --- /dev/null +++ b/src/Khaemhat.Infrastructure/Mail/Mail.cs @@ -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; + +/// A file attached to a message. +/// The file name. +/// The media type. +/// The bytes. +public sealed record MailAttachment(string FileName, string MediaType, byte[] Content); + +/// A message to send. +/// The recipients. +/// The subject. +/// The text of the message. +public sealed record OutgoingMail(IReadOnlyList To, string Subject, string Body) +{ + /// The recipients in copy. + public IReadOnlyList Cc { get; init; } = []; + + /// The address replies go to, when not the sender. + public string? ReplyTo { get; init; } + + /// The attachments. + public IReadOnlyList Attachments { get; init; } = []; + + /// What the message is about, for the log, such as Fattura immediata 6/2026. + public string? Reference { get; init; } +} + +/// How the connection to the SMTP server is protected (KHAEMHAT_SMTP_SECURITY). +public enum SmtpTransportSecurity +{ + /// Plain connection upgraded with STARTTLS (port 587). + StartTls = 0, + + /// TLS from the first byte (port 465). + Ssl = 1, + + /// No encryption: only for a relay on the local network. + None = 2, +} + +/// The SMTP server (SPEC §6: KHAEMHAT_SMTP_*). +/// The host; none when mail is not configured. +/// The port. +/// The user, when the server wants authentication. +/// The password. +/// The sender address. +/// The protection of the connection. +public sealed record SmtpSettings(string? Host, int Port, string? User, string? Password, string? From, SmtpTransportSecurity Security) +{ + /// Whether messages can be sent. + public bool IsConfigured => !string.IsNullOrWhiteSpace(Host) && !string.IsNullOrWhiteSpace(From); + + /// + public override string ToString() => $"{Host}:{Port} ({Security})"; +} + +/// Sends a message now. +public interface IMailSender +{ + /// Whether a server is configured. + bool IsConfigured { get; } + + /// Sends a message. + /// The message. + /// Cancellation. + /// A task. + /// The server refused the message or could not be reached. + Task SendAsync(OutgoingMail mail, CancellationToken cancellationToken = default); +} + +/// A message the SMTP server refused, or a server that could not be reached. +public sealed class MailException : Exception +{ + /// Creates the exception. + public MailException() + { + } + + /// Creates the exception. + /// What went wrong. + public MailException(string message) + : base(message) + { + } + + /// Creates the exception. + /// What went wrong. + /// The cause. + public MailException(string message, Exception innerException) + : base(message, innerException) + { + } +} + +/// +/// 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. +/// +public static class MimeMessageWriter +{ + /// Writes the message. + /// The message. + /// The sender. + /// The date of the message. + /// The MIME boundary; a new one when empty. + /// The message, lines ended by CRLF. + 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(); + } + + /// A header value, as an encoded word when it is not plain ASCII. + /// The value. + /// The header text. + 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"); + } + } +} + +/// +/// 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. +/// +/// The server. +/// The clock (date of the messages). +public sealed class SmtpMailSender(SmtpSettings settings, TimeProvider clock) : IMailSender +{ + private static readonly TimeSpan Timeout = TimeSpan.FromSeconds(60); + + /// + public bool IsConfigured => settings.IsConfigured; + + /// + 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 " 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 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 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 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)); + } + } + } +} + +/// Messages waiting to be sent. +[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 +{ + /// Whether a server is configured. + bool IsConfigured { get; } + + /// Puts a message in the queue; it leaves in the background, the outcome goes to the log (section E-mail/PEC). + /// The message. + /// Whether the message was accepted. + bool Enqueue(OutgoingMail mail); +} + +/// +/// 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. +/// +/// The sender. +/// The log. +[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 logger) : BackgroundService, IMailQueue +{ + private const int Attempts = 3; + private readonly Channel _channel = Channel.CreateBounded(new BoundedChannelOptions(500) { SingleReader = true }); + + /// + public bool IsConfigured => sender.IsConfigured; + + /// The pause between two attempts, shorter in tests. + public TimeSpan RetryDelay { get; init; } = TimeSpan.FromSeconds(30); + + /// + 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; + } + + /// + 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); +} diff --git a/src/Khaemhat.Web/Components/Pages/Parties/PartyPage.razor b/src/Khaemhat.Web/Components/Pages/Parties/PartyPage.razor index 96533f7..e032ea4 100644 --- a/src/Khaemhat.Web/Components/Pages/Parties/PartyPage.razor +++ b/src/Khaemhat.Web/Components/Pages/Parties/PartyPage.razor @@ -273,6 +273,12 @@ else Value="@PartyScreens.Text(s.CompanyBankAccountId)" ValueChanged="v => Change(() => s.CompanyBankAccountId = PartyScreens.Id(v))" /> + + + Change(() => address.Kind = Enum.Parse(value!)); + // The months a customer excludes from the due dates (August, December...), named in the language of the screen. + private IReadOnlyList> MonthChoices => + [.. Enumerable.Range(1, 12).Select(m => new KhOption(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(value!)); private Task SetSubjectAsync(string? value) diff --git a/src/Khaemhat.Web/Components/Pages/Sales/DeferredInvoicingPage.razor b/src/Khaemhat.Web/Components/Pages/Sales/DeferredInvoicingPage.razor new file mode 100644 index 0000000..755507d --- /dev/null +++ b/src/Khaemhat.Web/Components/Pages/Sales/DeferredInvoicingPage.razor @@ -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. *@ + + +@if (!_loaded) +{ +

@T["Common.Loading"]

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

@T["Sales.NoCompany"]

+} +else if (!Session.Permissions.Allows("sales.invoice.write") || !Session.Permissions.Allows("sales.delivery.read")) +{ +
+ +

@T["Pages.AccessDenied.Title"]

+

@T["Pages.AccessDenied.Lead"]

+
+} +else +{ +
+
+ + +
+ + + + + + +
+ +
+
+
+
+
+ @if (_results.Count > 0) + { + +
+ + + + + + + + + + + @foreach (var result in _results) + { + + + @if (result.Record is { } record) + { + var state = SalesScreens.State(T, record.Header.Kind, record.Header.Status, null, Today); + + + + } + else + { + + } + + } + +
@T["Sales.Fields.PartyId"]@T["Sales.Deferred.Invoice"]@T["Sales.Radar.State"]@T["Sales.Totals.Total"]
@result.PartyName@(record.Header.DocumentNumber ?? T["Sales.DraftNumber"])@state.Text@T.Money(record.Header.TotalAmount) @result.Error
+
+
+ @T["Sales.Sections.Invoices.Title"] + +
+
+ } + else + { + + + @T.Format("Sales.Deferred.Selected", _selected.Count, T.Money(SelectedTotal)) + + + + @if (_notes is null) + { +

@T["Sales.Deferred.Start"]

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

@T["Sales.Deferred.None"]

+ } + else + { +
+ + + + + + + + + + + + + + @foreach (var note in _notes) + { + var id = note.Row.Id; + + + + + + + + + + } + +
@T["Sales.Kinds.DeliveryNote"]@T["Sales.Fields.DocumentDate"]@T["Sales.Fields.PartyId"]@T["Sales.Deferred.Lines"]@T["Sales.Totals.Taxable"]@T["Sales.Deferred.Invoice"]
@note.Row.DocumentNumber@T.Date(note.Row.Date)@note.Row.PartyName@note.Lines.Count@T.Money(note.Row.Taxable)@InvoiceLabel(note)
+
+ } +
+
+ } +
+
+} + +@code { + private readonly HashSet _selected = []; + private readonly List _results = []; + private IReadOnlyList? _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 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> 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; + + /// + 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> 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> Groups() => _notes is null ? [] : _perNote + ? [.. _notes.Where(n => _selected.Contains(n.Row.Id)).Select(n => new List { 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); +} diff --git a/src/Khaemhat.Web/Components/Pages/Sales/SalesDocumentPage.razor b/src/Khaemhat.Web/Components/Pages/Sales/SalesDocumentPage.razor new file mode 100644 index 0000000..cf5330b --- /dev/null +++ b/src/Khaemhat.Web/Components/Pages/Sales/SalesDocumentPage.razor @@ -0,0 +1,409 @@ +@page "/vendite/{Segment}/nuovo" +@page "/vendite/{Segment}/{Id:long}" +@attribute [Authorize] +@inherits DocumentPage +@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. *@ + + +@if (!_loaded) +{ +

@T["Common.Loading"]

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

@T["Sales.NoCompany"]

+} +else if (_denied) +{ +
+ +

@T["Pages.AccessDenied.Title"]

+

@T["Pages.AccessDenied.Lead"]

+
+} +else if (Record is null || _section is null || _definition is null) +{ +
+ +

@T["Sales.NotFound"]

+ @T["Sales.BackToList"] +
+} +else +{ + var h = Record.Header; + + + + + @T["Sales.Fields.DocumentDate"] @T.Date(h.DocumentDate) + @if (h.Kind == DocumentKind.Quotation && h.ValidUntil is { } until) + { + @T["Sales.Fields.ValidUntil"] @T.Date(until) + } + @if (h.DeliveryDate is { } delivery) + { + @T["Sales.Fields.DeliveryDate"] @T.Date(delivery) + } + @if (h.Revision > 0) + { + @T["Sales.Fields.Revision"] @h.Revision + } + @if (h.RelatedNumber is { } related) + { + @T["Sales.Fields.Related"] @related@(h.RelatedDate is { } rd ? " · " + T.Date(rd) : null) + } + + + @{ var state = SalesScreens.State(T, h.Kind, h.Status, h.ValidUntil, Today); } + @state.Text + @if (h.IsDemo) + { + @T["Sales.Demo"] + } + @if (IsModified) + { + @T["CompanyTables.Modified"] + } + + + @if (PartyScreens.Describe(_lookups.PaymentTerms, h.PaymentTermId) is { } payment) + { + + } + @if (PartyScreens.Describe(_lookups.PriceLists, h.PriceListId) is { } list) + { + + } + @if (PartyScreens.Describe(_lookups.Salespeople, h.SalespersonId) is { } agent) + { + + } + @if (h.SplitPayment) + { + + } + + + + + @switch (ActiveTab) + { + case TabIds.Lines: + @if (h.PartyId is null && !IsReadOnly) + { +
@T["Sales.Hints.PartyFirst"] +
+ } + + @if (Validation.Messages.Any(m => m.Field?.StartsWith("Lines.", StringComparison.Ordinal) == true)) + { +
    + @foreach (var message in Validation.Messages.Where(m => m.Field?.StartsWith("Lines.", StringComparison.Ordinal) == true)) + { +
  • @LineErrorText(message.Field!, message.Message)
  • + } +
+ } +
+ @TaxSummary + @Installments + @Totals +
+ break; + + case TabIds.Header: + + + + + + @if (h.Kind == DocumentKind.Quotation) + { + + } + @if (h.Kind is DocumentKind.Quotation or DocumentKind.SalesOrder or DocumentKind.DeliveryNote or DocumentKind.ProForma) + { + + } + + + @if (IsNote) + { + + + } + + + + + + @if (h.PartyId is not null) + { +

@T["Sales.Hints.PartyDefaults"]

+ } +
+ + + + + + + + + @if (IsInvoice) + { + + + + + + + + + + + + + + + + + +

@T["Sales.Hints.Withholding"]

+
+ } +
+ break; + + case SalesScreens.TransportTab: + + + + + + + + + + + + + + + +

@T["Sales.Hints.Transport"]

+
+
+ break; + + case TabIds.Totals: +
+ @TaxSummary + @Totals +
+ break; + + case TabIds.DueDates: +
+ @Installments +
+

@T[Behavior.Has(DocumentEffects.Installments) ? "Sales.Hints.Installments" : "Sales.Hints.InstallmentsForecast"]

+ break; + + case TabIds.Notes: + + + + + @if (h.CancelReason is { } reason) + { + + + + } + + break; + + case TabIds.Attachments: +
+ break; + + case TabIds.Links: +
+ @if (_links.Count == 0) + { +

@T["Sales.Links.Empty"]

+ } + else + { +
+ + + + + + + + + + + + + + @foreach (var link in _links) + { + var linkState = SalesScreens.State(T, link.Kind, link.Status, null, Today); + + + + + + + + + + } + +
@T["Sales.Links.Relation"]@T["Sales.Radar.Kind"]@T["Sales.Fields.DocumentNumber"]@T["Sales.Fields.DocumentDate"]@T["Sales.Radar.State"]@T["Sales.Links.Quantity"]@T["Sales.Totals.Total"]
@T["Sales.Links." + link.Direction]@SalesScreens.KindName(T, link.Kind) + @if (SalesScreens.RecordUrl(link.Kind, link.Id) is { } url) + { + @(link.DocumentNumber ?? T["Sales.DraftNumber"]) + } + else + { + @(link.DocumentNumber ?? T["Sales.DraftNumber"]) + } + @T.Date(link.Date)@linkState.Text@(link.Quantity > 0 ? T.Number(link.Quantity, 2) : null)@T.Money(link.Total)
+
+ } +
+ break; + + case TabIds.History: +
+ break; + } +
+
+ + + + + + @if (_transform is { } t) + { +

@t.Lead

+
+ + + + + + + @if (t.Fulfils) + { + + } + + + + + @foreach (var line in t.Lines) + { + var id = line.Id; + + + + + @if (t.Fulfils) + { + + } + + + } + +
@T["Sales.Lines.Description"]@T["Sales.Lines.Quantity"]@T["Sales.Lines.Residual"]@T["Sales.Lines.Amount"]
@line.Description@(DocumentLine.CarriesQuantity(line.Kind) ? T.Number(line.Quantity, 2) : null)@(DocumentLine.CarriesQuantity(line.Kind) ? T.Number(line.Residual, 2) : null)@(line.Kind == DocumentLineKind.Description ? null : T.Money(line.TaxableAmount))
+
+ } +
+
+ + +
+
+ + + +

@T[Behavior.Lifecycle == DocumentLifecycle.Invoice ? "Sales.Cancel.LeadInvoice" : "Sales.Cancel.Lead"]

+ + + +
+
+ + +
+
+ + + + @if (!Mails.IsConfigured) + { +
@T[DocumentMailErrors.NotConfigured]
+ } +

@T["Sales.Mail.Lead"]

+
+ + + + + +
+
+
+ + +
+
+} diff --git a/src/Khaemhat.Web/Components/Pages/Sales/SalesDocumentPage.razor.cs b/src/Khaemhat.Web/Components/Pages/Sales/SalesDocumentPage.razor.cs new file mode 100644 index 0000000..e52d490 --- /dev/null +++ b/src/Khaemhat.Web/Components/Pages/Sales/SalesDocumentPage.razor.cs @@ -0,0 +1,1372 @@ +using System.Globalization; +using Khaemhat.Application.Audit; +using Khaemhat.Application.Documents; +using Khaemhat.Application.Files; +using Khaemhat.Application.Items; +using Khaemhat.Application.Localization; +using Khaemhat.Application.Parties; +using Khaemhat.Application.Querying; +using Khaemhat.Application.Security; +using Khaemhat.Application.Tables; +using Khaemhat.Core.Common; +using Khaemhat.Core.Documents; +using Khaemhat.Core.Tax; +using Khaemhat.Web.Components.Ui; +using Khaemhat.Web.Documents; +using Khaemhat.Web.Parties; +using Khaemhat.Web.Shell; +using Khaemhat.Web.Tables; +using Khaemhat.Web.Ui; +using Microsoft.AspNetCore.Components; + +namespace Khaemhat.Web.Components.Pages.Sales; + +/// The record of a sales document: loading, lines, live totals, state actions and transformations. +public sealed partial class SalesDocumentPage +{ + private readonly Dictionary _items = []; + private readonly Dictionary _typedCodes = new(ReferenceEqualityComparer.Instance); + private readonly KhValidation _cancelValidation = new(); + private SalesSection? _section; + private DocumentDefinition? _definition; + private IReadOnlyList _definitions = []; + private DocumentLookups _lookups = DocumentLookups.Empty; + private PartyRow? _party; + private IReadOnlyList _actions = []; + private IReadOnlyList _links = []; + private IReadOnlyList _history = []; + private int _attachments; + private bool _loaded; + private bool _denied; + private bool _busy; + private (string? Segment, long? Id, string? Type)? _shown; + private KhLinesGrid? _grid; + private DocumentLine? _lookupLine; + private string? _lookupText; + private TaskCompletionSource? _lookupDone; + private CancellationTokenSource? _preview; + private TransformRequest? _transform; + private bool _cancelling; + private string? _cancelReason; + private readonly KhValidation _mailValidation = new(); + private bool _mailing; + private string? _mailTo; + private string? _mailSubject; + private string? _mailBody; + private IReadOnlyList>? _lineColumns; + + /// The radar segment, such as fatture. + [Parameter] + public string? Segment { get; set; } + + /// The document; none for a new one. + [Parameter] + public long? Id { get; set; } + + /// The type of a new document, such as FI. + [SupplyParameterFromQuery(Name = "tipo")] + public string? TypeCode { get; set; } + + [Inject] + private ShellSession Session { get; set; } = default!; + + [Inject] + private DocumentEngine Engine { get; set; } = default!; + + [Inject] + private DocumentEditor Editor { get; set; } = default!; + + [Inject] + private DocumentCopyService Copies { get; set; } = default!; + + [Inject] + private PartyService Parties { get; set; } = default!; + + [Inject] + private ItemService Items { get; set; } = default!; + + [Inject] + private TableService Tables { get; set; } = default!; + + [Inject] + private AttachmentService Attachments { get; set; } = default!; + + [Inject] + private AuditTrailService Audit { get; set; } = default!; + + [Inject] + private DocumentMailService Mails { get; set; } = default!; + + [Inject] + private TimeProvider Clock { get; set; } = default!; + + private DocumentHeader H => Record!.Header; + + private DocumentBehavior Behavior => DocumentBehaviors.Of(Record!.Header.Kind); + + private DateOnly Today => DateOnly.FromDateTime(TimeZoneInfo.ConvertTime(Clock.GetUtcNow(), TimeZoneInfo.Local).DateTime); + + private string PageTitle => Record is null || _definition is null + ? T["Shell.Menu.Sales"] + : _definition.Type.Description + " " + (Record.Header.DocumentNumber ?? T["Sales.DraftNumber"]); + + private bool IsInvoice => Record is not null && (Behavior.Lifecycle == DocumentLifecycle.Invoice || H.Kind == DocumentKind.ProForma); + + private bool IsNote => Record is not null && H.Kind is DocumentKind.CreditNote or DocumentKind.DebitNote; + + private bool ShowsNet => Record is not null && H.NetAmount != H.TotalAmount && H.NetAmount != 0m; + + private bool CanWrite => Record is not null && Session.Permissions.Allows(Behavior.WritePermission); + + // The entity of the attachments, such as sales.saledocument. + private string AttachmentEntity => "sales." + Record!.Header.GetType().Name.ToLowerInvariant(); + + /// + public override bool IsReadOnly => Record is null || !CanWrite || !(IsNew || _actions.Contains(DocumentAction.Edit)); + + /// + protected override bool IsNew => Record is { Header.Id: 0 }; + + /// + protected override bool CanDelete => !IsNew && _actions.Contains(DocumentAction.Delete); + + /// + protected override IList Lines => Record?.Lines ?? []; + + /// + protected override string? NewUrl => _section is not null && _definition is not null && CanWrite ? SalesScreens.NewUrl(_section, _definition.Code) : null; + + /// + protected override int? AttachmentCount => IsNew || Record is null ? null : _attachments; + + /// + public override IReadOnlyList Tabs + { + get + { + if (Record is null) + { + return []; + } + + var tabs = new List + { + TabOf(TabIds.Lines, "list", "Ui.Record.Tabs.Lines", Record.Lines.Count), + TabOf(TabIds.Header, "file", "Ui.Record.Tabs.Header"), + }; + if (Behavior.Has(DocumentEffects.Inventory)) + { + tabs.Add(TabOf(SalesScreens.TransportTab, "truck", "Sales.Tabs.Transport")); + } + + tabs.Add(TabOf(TabIds.Totals, "euro", "Ui.Record.Tabs.Totals")); + tabs.Add(TabOf(TabIds.DueDates, "calendar", "Ui.Record.Tabs.DueDates", Record.Figures.Installments.Count)); + tabs.Add(TabOf(TabIds.Notes, "edit", "Ui.Record.Tabs.Notes")); + if (!IsNew) + { + tabs.Add(TabOf(TabIds.Attachments, "paperclip", "Ui.Record.Tabs.Attachments", _attachments)); + tabs.Add(TabOf(TabIds.Links, "link", "Ui.Record.Tabs.Links", _links.Count)); + tabs.Add(TabOf(TabIds.History, "history", "Ui.Record.Tabs.History")); + } + + return tabs; + } + } + + private KhTabItem TabOf(string id, string icon, string key, int? count = null) + { + // A tab with errors shows how many; otherwise how many details it holds. + var errors = Validation.Messages.Count(m => TabOfField(m.Field) == id); + return new(id, icon, T[key], errors > 0 ? errors : count is > 0 ? count : null); + } + + private static readonly HashSet TransportFields = + [ + nameof(DocumentHeader.TransportReasonId), nameof(DocumentHeader.TransportBy), nameof(DocumentHeader.CarrierId), nameof(DocumentHeader.ShippingTermId), + nameof(DocumentHeader.TransportStart), nameof(DocumentHeader.WarehouseId), nameof(DocumentHeader.GoodsAppearanceId), nameof(DocumentHeader.Packages), + nameof(DocumentHeader.GrossWeight), nameof(DocumentHeader.NetWeight), + ]; + + private static string TabOfField(string? field) => field switch + { + null or "" => TabIds.Lines, + _ when field.StartsWith("Lines", StringComparison.Ordinal) => TabIds.Lines, + nameof(DocumentHeader.Notes) => TabIds.Notes, + _ when TransportFields.Contains(field) => SalesScreens.TransportTab, + _ => TabIds.Header, + }; + + // ---- Loading ---------------------------------------------------------------------------------------------------- + + /// + protected override async Task OnParametersSetAsync() + { + await Session.EnsureLoadedAsync(); + if (Session.Actor is not { } actor || Session.Company?.Code is not { } company) + { + _loaded = true; + return; + } + + var wanted = (Segment, Id, TypeCode); + if (_shown == wanted && Record is not null) + { + return; + } + + _section = SalesScreens.Find(Segment); + if (!_loaded) + { + _lookups = await DocumentLookups.ReadAsync(Tables, actor, company); + _definitions = await Engine.DefinitionsAsync(actor, company); + } + + _shown = wanted; + await ReloadAsync(); + MarkSaved(); + if (IsNew && Record is not null) + { + // A new document starts from the customer. + await ShowTabAsync(TabIds.Header); + } + + _loaded = true; + } + + /// + protected override async Task ReloadAsync() + { + if (Session.Actor is not { } actor || Session.Company?.Code is not { } company || _section is null) + { + return; + } + + Validation.Clear(); + _typedCodes.Clear(); + _denied = false; + try + { + if (Id is { } id) + { + Record = await Engine.GetAsync(actor, company, _section.Family, id); + if (Record is not null && !_section.Kinds.Contains(Record.Header.Kind)) + { + // The address of another radar: show the document where it belongs. + if (SalesScreens.RecordUrl(Record.Header.Kind, id) is { } url) + { + Navigation.NavigateTo(url, new NavigationOptions { ReplaceHistoryEntry = true }); + } + + Record = null; + } + } + else + { + var type = _section.NewTypes.FirstOrDefault(t => string.Equals(t, TypeCode, StringComparison.OrdinalIgnoreCase)) ?? _section.NewTypes[0]; + Record = await Engine.NewAsync(actor, company, type); + await PreviewNowAsync(); + } + } + catch (AccessDeniedException) + { + _denied = true; + Record = null; + } + + _definition = Record is null ? null : _definitions.FirstOrDefault(d => d.Type.Id == Record.Header.DocumentTypeId); + await LoadSideAsync(actor, company); + } + + private async Task LoadSideAsync(Actor actor, string company) + { + if (Record is null) + { + return; + } + + _actions = await Engine.ActionsAsync(actor, Record); + _party = Record.Header.PartyId is { } partyId && Session.Permissions.Allows(PartyService.ReadPermission) + ? (await Parties.RowsAsync(actor, company, [partyId])) is [var partyRow, ..] ? partyRow : null + : null; + long[] items = [.. Record.Lines.Where(l => l.ItemId is not null).Select(l => l.ItemId!.Value).Distinct().Where(i => !_items.ContainsKey(i))]; + if (items.Length > 0) + { + foreach (var row in await Items.RowsAsync(actor, company, items)) + { + _items[row.Id] = row; + } + } + + if (IsNew) + { + _links = []; + _history = []; + _attachments = 0; + return; + } + + _links = await Editor.LinksAsync(actor, company, Record); + _history = await Audit.HistoryAsync(actor, company, Record.Header.GetType().Name, Record.Header.Id.ToString(CultureInfo.InvariantCulture), Behavior.ReadPermission); + _attachments = Session.Permissions.Allows(AttachmentService.ReadPermission) + ? await Attachments.CountAsync(actor, company, AttachmentEntity, Record.Header.Id) + : 0; + } + + // ---- Head ------------------------------------------------------------------------------------------------------- + + private IReadOnlyList PartyLines + { + get + { + if (_party is null) + { + return []; + } + + var lines = new List(); + if (_party.City is { } city) + { + lines.Add(_party.Province is { } province ? city + " (" + province + ")" : city); + } + + if (_party.VatNumber is { } vat) + { + lines.Add(T["Sales.Head.Vat"] + " " + vat); + } + else if (_party.TaxCode is { } taxCode) + { + lines.Add(T["Sales.Head.TaxCode"] + " " + taxCode); + } + + return lines; + } + } + + private IReadOnlyList HeadStats => + [ + new(T["Sales.Totals.Taxable"], T.Money(H.TaxableAmount)), + new(T["Sales.Totals.Tax"], T.Money(H.TaxAmount)), + .. ShowsNet ? [new KhStat(T["Sales.Totals.Total"], T.Money(H.TotalAmount))] : Array.Empty(), + ]; + + // ---- Lines ------------------------------------------------------------------------------------------------------ + + private IReadOnlyList> LineColumns => _lineColumns ??= BuildColumns(); + + private List> BuildColumns() + { + var columns = new List> + { + new("item", T["Sales.Lines.Item"], ItemCode) { Kind = KhColumnKind.Code, Width = "120px", SetText = SetItemCode, Lookup = LookupItemAsync }, + new("description", T["Sales.Lines.Description"], l => l.Description) { SetText = (l, v) => l.Description = v ?? string.Empty }, + new("unit", T["Sales.Lines.Unit"], l => DocumentLookups.CodeOf(_lookups.Units, l.UnitOfMeasureId)) + { + Width = "56px", SetText = (l, v) => l.UnitOfMeasureId = DocumentLookups.IdOf(_lookups.Units, v), + }, + new("quantity", T["Sales.Lines.Quantity"], l => DocumentLine.CarriesQuantity(l.Kind) ? l.Quantity : null) + { + Kind = KhColumnKind.Number, Width = "86px", SetNumber = (l, v) => l.Quantity = v ?? 0m, + }, + new("price", T["Sales.Lines.Price"], l => l.Kind == DocumentLineKind.Description ? null : l.Price) + { + Kind = KhColumnKind.Money, Width = "104px", SetNumber = SetPrice, + }, + new("discount", T["Sales.Lines.Discount"], l => l.DiscountFormula) { Width = "76px", SetText = (l, v) => l.DiscountFormula = v }, + new("tax", T["Sales.Lines.Tax"], l => DocumentLookups.CodeOf(_lookups.TaxCodes, l.TaxCodeId)) + { + Width = "64px", SetText = (l, v) => l.TaxCodeId = DocumentLookups.IdOf(_lookups.TaxCodes, v), + }, + }; + if (Record is not null && H.Kind is DocumentKind.SalesOrder or DocumentKind.Quotation) + { + columns.Add(new("delivery", T["Sales.Lines.Delivery"], l => l.DeliveryDate is { } d ? d.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture) : null) + { + Kind = KhColumnKind.Date, Width = "96px", SetText = (l, v) => l.DeliveryDate = ParseDate(v), + }); + } + + if (Record is not null && Behavior.Lifecycle == DocumentLifecycle.Order) + { + columns.Add(new("fulfilled", T["Sales.Lines.Fulfilled"], l => l.FulfilledQuantity > 0m ? l.FulfilledQuantity : null) { Kind = KhColumnKind.Number, Width = "76px" }); + } + + columns.Add(new("amount", T["Sales.Lines.Amount"], l => l.Kind == DocumentLineKind.Description ? null : l.TaxableAmount) { Kind = KhColumnKind.Money, Width = "112px" }); + return columns; + } + + private static DateOnly? ParseDate(string? text) => + DateOnly.TryParse(text, CultureInfo.GetCultureInfo("it-IT"), DateTimeStyles.None, out var date) ? date : null; + + private static void SetPrice(DocumentLine line, decimal? value) => line.Price = value ?? 0m; + + private string? ItemCode(DocumentLine line) => + _typedCodes.TryGetValue(line, out var typed) ? typed + : line.ItemId is { } id && _items.TryGetValue(id, out var row) ? row.Code + : line.Kind switch + { + DocumentLineKind.Expense => T["Sales.LineKinds.Expense"], + DocumentLineKind.Discount => T["Sales.LineKinds.Discount"], + _ => null, + }; + + private void SetItemCode(DocumentLine line, string? code) + { + if (string.IsNullOrWhiteSpace(code)) + { + _typedCodes.Remove(line); + if (line.Kind == DocumentLineKind.Item) + { + line.Kind = DocumentLineKind.Free; + line.ItemId = null; + } + + return; + } + + _typedCodes[line] = code.Trim().ToUpperInvariant(); + } + + private DocumentLine NewLine() + { + var line = CreateLine(Record!.Family); + line.Kind = DocumentLineKind.Free; + line.TaxCodeId = DefaultTaxCode(); + return line; + } + + private DocumentLine NewDescriptionLine() + { + var line = CreateLine(Record!.Family); + line.Kind = DocumentLineKind.Description; + return line; + } + + private DocumentLine NewKindLine(DocumentLineKind kind) + { + var line = NewLine(); + line.Kind = kind; + line.Description = T["Sales.LineKinds." + kind]; + line.Quantity = 0m; + line.WithholdingExcluded = kind == DocumentLineKind.Expense; + return line; + } + + private async Task AddKindLineAsync(DocumentLineKind kind) + { + Record!.Lines.Add(NewKindLine(kind)); + await ShowTabAsync(TabIds.Lines); + MarkModified(); + SchedulePreview(); + } + + // The VAT code a new line proposes: the one of the last line that has one. + private long? DefaultTaxCode() => Record?.Lines.LastOrDefault(l => l.TaxCodeId is not null)?.TaxCodeId; + + private static DocumentLine CreateLine(DocumentFamily family) => family switch + { + DocumentFamily.SaleQuotation => new SaleQuotationLine(), + DocumentFamily.SaleOrder => new SaleOrderLine(), + _ => new SaleDocumentLine(), + }; + + private bool IsEmptyLine(DocumentLine line) => + line.ItemId is null && line.Description.Length == 0 && line.Quantity == 0m && line.Price == 0m && !_typedCodes.ContainsKey(line); + + private async Task LinesChangedAsync() + { + MarkModified(); + foreach (var line in Record!.Lines) + { + // A line with a quantity but no kind of its own is a free line; a line with an item is an item line. + if (line.Kind == DocumentLineKind.Free && line.ItemId is not null) + { + line.Kind = DocumentLineKind.Item; + } + } + + if (_typedCodes.Count > 0) + { + await ResolveCodesAsync(); + } + + SchedulePreview(); + } + + // The codes typed in the item column: an exact code fills the line, otherwise the item radar opens on the text. + private async Task ResolveCodesAsync() + { + if (Session.Actor is not { } actor || Session.Company?.Code is not { } company) + { + return; + } + + foreach (var (line, code) in _typedCodes.ToList()) + { + if (!Record!.Lines.Contains(line)) + { + continue; + } + + var found = await Items.SearchAsync(actor, company, code, H.PartyId); + var match = found.FirstOrDefault(i => string.Equals(i.Code, code, StringComparison.OrdinalIgnoreCase)) + ?? (found.Count == 1 ? found[0] : null); + _typedCodes.Remove(line); + if (match is not null) + { + await FillAsync(line, match); + } + else + { + await LookupItemAsync(line, code); + } + } + } + + private async Task FillAsync(DocumentLine line, ItemRow item) + { + if (Session.Actor is not { } actor || Session.Company?.Code is not { } company) + { + return; + } + + _items[item.Id] = item; + try + { + await Editor.FillLineAsync(actor, company, Record!, line, item.Id); + } + catch (KeyNotFoundException) + { + Toasts.Show(ToastKind.Error, T["Sales.Lines.ItemMissing"]); + } + + MarkModified(); + } + + private Task LookupItemAsync(DocumentLine line) => LookupItemAsync(line, null); + + private Task LookupItemAsync(DocumentLine line, string? text) + { + _lookupLine = line; + _lookupText = text ?? ItemCode(line); + _lookupDone = new TaskCompletionSource(); + StateHasChanged(); + return _lookupDone.Task; + } + + private async Task PickItemAsync(ItemRow item) + { + if (_lookupLine is { } line) + { + if (!Record!.Lines.Contains(line)) + { + Record.Lines.Add(line); + } + + await FillAsync(line, item); + CloseLookup(); + SchedulePreview(); + await Task.Yield(); + if (_grid is not null) + { + await _grid.FocusCellAsync(line, "quantity"); + } + } + } + + private void CloseLookup() + { + _lookupLine = null; + _lookupText = null; + _lookupDone?.TrySetResult(); + } + + private IReadOnlyList> ItemColumns => + [ + new("code", T["Items.Fields.Code"], i => i.Code) { Kind = KhColumnKind.Code, Width = "130px" }, + new("description", T["Items.Fields.Description"], i => i.Description), + new("unit", T["Items.Radar.Unit"], i => PartyScreens.Describe(_lookups.Units, i.UnitOfMeasureId)) { Width = "60px", Sortable = false }, + new("brand", T["Items.Fields.Brand"], i => i.Brand) { Width = "120px" }, + new("basePrice", T["Items.Radar.BasePrice"], i => i.BasePrice) { Kind = KhColumnKind.Money, Width = "110px", Sortable = false }, + ]; + + private Task> ListItemsAsync(ListQuery query, CancellationToken cancellationToken) => + Session.Actor is { } actor && Session.Company?.Code is { } company + ? Items.ListAsync(actor, company, query with { Filters = [.. query.Filters, ListFilter.Of("disabled", ListFilterOperator.Equals, "false")] }, cancellationToken) + : Task.FromResult(new ListPage([], 0, new Dictionary())); + + private string LineErrorText(string field, string text) + { + var parts = field.Split('.'); + return parts.Length > 1 && int.TryParse(parts[1], NumberStyles.None, CultureInfo.InvariantCulture, out var index) + ? T.Format("Sales.Lines.ErrorAt", index + 1, text) + : text; + } + + // ---- Totals ----------------------------------------------------------------------------------------------------- + + private void SchedulePreview() + { + _preview?.Cancel(); + _preview?.Dispose(); + _preview = new CancellationTokenSource(); + var token = _preview.Token; + _ = InvokeAsync(async () => + { + try + { + await Task.Delay(250, token); + await PreviewNowAsync(token); + StateHasChanged(); + } + catch (OperationCanceledException) + { + // A newer change computes again. + } + }); + } + + private async Task PreviewNowAsync(CancellationToken cancellationToken = default) + { + if (Record is null || Session.Actor is not { } actor || Session.Company?.Code is not { } company) + { + return; + } + + try + { + var figures = await Editor.PreviewAsync(actor, company, Record, cancellationToken); + Record = new DocumentRecord { Family = Record.Family, Header = Record.Header, Lines = Record.Lines, Figures = figures }; + } + catch (Exception ex) when (ex is ValidationFailedException or KeyNotFoundException or FormatException or ArgumentException) + { + // Half-typed lines (a discount being written, a VAT code missing): the totals wait for the next change. + } + } + + private RenderFragment TaxSummary => __builder => + { + var summary = Record!.Figures.Summary; + if (summary.Count == 0) + { + __builder.OpenElement(0, "p"); + __builder.AddAttribute(1, "class", "muted sm kh-pad"); + __builder.AddContent(2, T["Sales.Totals.SummaryEmpty"]); + __builder.CloseElement(); + return; + } + + __builder.OpenElement(10, "table"); + __builder.AddAttribute(11, "class", "grid compact"); + __builder.AddAttribute(12, "aria-label", T["Sales.Totals.Summary"]); + __builder.OpenElement(13, "thead"); + __builder.OpenElement(14, "tr"); + foreach (var (title, numeric) in new[] { (T["Sales.Totals.TaxCode"], false), (T["Sales.Totals.Rate"], true), (T["Sales.Totals.Taxable"], true), (T["Sales.Totals.Tax"], true) }) + { + __builder.OpenElement(15, "th"); + __builder.AddAttribute(16, "scope", "col"); + __builder.AddAttribute(17, "class", numeric ? "num" : null); + __builder.AddContent(18, title); + __builder.CloseElement(); + } + + __builder.CloseElement(); + __builder.CloseElement(); + __builder.OpenElement(20, "tbody"); + foreach (var row in summary) + { + __builder.OpenElement(21, "tr"); + Cell(__builder, PartyScreens.Describe(_lookups.TaxCodes, row.TaxCodeId, full: true) ?? row.Nature ?? string.Empty, false); + Cell(__builder, T.Number(row.Rate, 2) + "%", true); + Cell(__builder, T.Money(row.Taxable), true); + Cell(__builder, T.Money(row.Tax), true); + __builder.CloseElement(); + } + + __builder.OpenElement(30, "tr"); + __builder.AddAttribute(31, "class", "kh-total-row"); + Cell(__builder, T["Sales.Totals.Total"], false); + Cell(__builder, string.Empty, true); + Cell(__builder, T.Money(summary.Sum(r => r.Taxable)), true); + Cell(__builder, T.Money(summary.Sum(r => r.Tax)), true); + __builder.CloseElement(); + __builder.CloseElement(); + __builder.CloseElement(); + }; + + private RenderFragment Installments => __builder => + { + var rows = Record!.Figures.Installments; + if (rows.Count == 0) + { + __builder.OpenElement(0, "p"); + __builder.AddAttribute(1, "class", "muted sm kh-pad"); + __builder.AddContent(2, T[H.PaymentTermId is null ? "Sales.Totals.InstallmentsNoTerm" : "Sales.Totals.InstallmentsEmpty"]); + __builder.CloseElement(); + return; + } + + __builder.OpenElement(10, "table"); + __builder.AddAttribute(11, "class", "grid compact"); + __builder.AddAttribute(12, "aria-label", T["Sales.Totals.Installments"]); + __builder.OpenElement(13, "thead"); + __builder.OpenElement(14, "tr"); + foreach (var (title, numeric) in new[] { ("#", false), (T["Sales.Totals.DueDate"], false), (T["Sales.Totals.Method"], false), (T["Sales.Totals.Amount"], true) }) + { + __builder.OpenElement(15, "th"); + __builder.AddAttribute(16, "scope", "col"); + __builder.AddAttribute(17, "class", numeric ? "num" : null); + __builder.AddContent(18, title); + __builder.CloseElement(); + } + + __builder.CloseElement(); + __builder.CloseElement(); + __builder.OpenElement(20, "tbody"); + foreach (var row in rows) + { + __builder.OpenElement(21, "tr"); + Cell(__builder, row.Number.ToString(T.Culture), false); + Cell(__builder, T.Date(row.DueDate), false); + Cell(__builder, PartyScreens.Describe(_lookups.PaymentMethods, row.PaymentMethodId) ?? string.Empty, false); + Cell(__builder, T.Money(row.Amount), true); + __builder.CloseElement(); + } + + __builder.CloseElement(); + __builder.CloseElement(); + }; + + private RenderFragment Totals => __builder => + { + var h = H; + var rows = new List<(string Label, decimal Value, bool Big)> + { + (T["Sales.Totals.Goods"], Record!.Lines.Where(l => l.Kind is DocumentLineKind.Item or DocumentLineKind.Free or DocumentLineKind.Discount).Sum(l => l.TaxableAmount), false), + }; + if (h.FooterDiscountAmount != 0m) + { + rows.Add((T["Sales.Totals.FooterDiscount"] + (h.FooterDiscount is { } f ? " " + f + "%" : null), -h.FooterDiscountAmount, false)); + } + + if (h.ExpensesAmount != 0m) + { + rows.Add((T["Sales.Totals.Expenses"], h.ExpensesAmount, false)); + } + + if (h.SocialSecurityAmount != 0m) + { + rows.Add((T["Sales.Totals.SocialSecurity"], h.SocialSecurityAmount, false)); + } + + rows.Add((T["Sales.Totals.Taxable"], h.TaxableAmount, false)); + rows.Add((T["Sales.Totals.Tax"], h.TaxAmount, false)); + if (h.StampDuty != 0m) + { + rows.Add((T[h.StampDutyCharged ? "Sales.Totals.StampDutyCharged" : "Sales.Totals.StampDuty"], h.StampDuty, false)); + } + + rows.Add((T["Sales.Totals.Total"], h.TotalAmount, !ShowsNet)); + if (h.WithholdingAmount != 0m) + { + rows.Add((T["Sales.Totals.Withholding"], -h.WithholdingAmount, false)); + } + + if (h.EnasarcoAmount != 0m) + { + rows.Add((T["Sales.Totals.Enasarco"], -h.EnasarcoAmount, false)); + } + + if (h.SplitPayment && h.TaxAmount != 0m) + { + rows.Add((T["Sales.Totals.SplitPayment"], -h.TaxAmount, false)); + } + + if (ShowsNet) + { + rows.Add((T["Sales.Totals.Net"], h.NetAmount, true)); + } + + __builder.OpenElement(0, "div"); + __builder.AddAttribute(1, "class", "totals kh-pad"); + foreach (var (label, value, big) in rows) + { + __builder.OpenElement(2, "span"); + __builder.AddAttribute(3, "class", big ? "big" : null); + __builder.AddContent(4, label); + __builder.CloseElement(); + __builder.OpenElement(5, "span"); + __builder.AddContent(6, T.Money(value)); + __builder.CloseElement(); + } + + __builder.CloseElement(); + }; + + private static void Cell(Microsoft.AspNetCore.Components.Rendering.RenderTreeBuilder builder, string text, bool numeric) + { + builder.OpenElement(40, "td"); + builder.AddAttribute(41, "class", numeric ? "num" : null); + builder.AddContent(42, text); + builder.CloseElement(); + } + + // ---- Header ----------------------------------------------------------------------------------------------------- + + private IReadOnlyList> ExigibilityChoices => SalesScreens.Choices(T, "Exigibilities"); + + private IReadOnlyList> TransportChoices => SalesScreens.Choices(T, "TransportBy"); + + private DateOnly? TransportDate => H.TransportStart is { } start ? DateOnly.FromDateTime(start) : null; + + private string? TransportTime => H.TransportStart?.ToString("HH:mm", CultureInfo.InvariantCulture); + + private void SetTransportDate(DateOnly? date) => Change(() => + H.TransportStart = date is { } d ? d.ToDateTime(H.TransportStart is { } s ? TimeOnly.FromDateTime(s) : new TimeOnly(8, 0)) : null); + + private void SetTransportTime(string? text) => Change(() => + { + if (TimeOnly.TryParse(text, CultureInfo.InvariantCulture, out var time)) + { + H.TransportStart = (TransportDate ?? Today).ToDateTime(time); + } + }); + + private async Task SetPartyAsync(PartyRow? row) + { + if (Record is null || Session.Actor is not { } actor || Session.Company?.Code is not { } company) + { + return; + } + + _party = row; + await Editor.ApplyPartyAsync(actor, company, Record, row?.Id); + MarkModified(); + await PreviewNowAsync(); + StateHasChanged(); + } + + private async Task> SearchPartiesAsync(string text, CancellationToken cancellationToken) => + Session.Actor is { } actor && Session.Company?.Code is { } company && Session.Permissions.Allows(PartyService.ReadPermission) + ? await Parties.SearchAsync(actor, company, PartyArchive.Customers, text, cancellationToken) + : []; + + private void OpenParty(PartyRow row) => Navigation.NavigateTo(PartyScreens.RecordUrl(PartyArchive.Customers, row.Id)); + + private void Change(Action change) + { + change(); + MarkModified(); + } + + private async Task ChangeAsync(Action change) + { + change(); + MarkModified(); + await PreviewNowAsync(); + } + + private Task SetExigibilityAsync(string? value) => + ChangeAsync(() => H.Exigibility = Enum.TryParse(value, out var exigibility) ? exigibility : null); + + private void SetTransportBy(string? value) => + Change(() => H.TransportBy = Enum.TryParse(value, out var by) ? by : null); + + private void SetCurrency(string? code) => Change(() => H.CurrencyCode = code ?? "EUR"); + + private void SetAttachments(int count) => _attachments = count; + + private string? FieldLabel(string field) + { + var key = "Sales.Fields." + field.Split('.')[^1]; + return T.Contains(key) ? T[key] : null; + } + + // ---- Save and delete -------------------------------------------------------------------------------------------- + + /// + protected override async Task SaveCoreAsync() + { + if (Record is null || Session.Actor is not { } actor || Session.Company?.Code is not { } company || _busy) + { + return false; + } + + _busy = true; + Validation.Clear(); + try + { + if (_typedCodes.Count > 0) + { + await ResolveCodesAsync(); + } + + var wasNew = IsNew; + Record = await Engine.SaveAsync(actor, company, Record); + await LoadSideAsync(actor, company); + if (wasNew && SalesScreens.RecordUrl(Record.Header.Kind, Record.Header.Id) is { } url) + { + MarkSaved(); + _shown = (Segment, Record.Header.Id, TypeCode); + Navigation.NavigateTo(url, new NavigationOptions { ReplaceHistoryEntry = true }); + } + + return true; + } + catch (ValidationFailedException ex) + { + Refuse(ex.Errors); + return false; + } + catch (InvalidDocumentActionException) + { + Toasts.Show(ToastKind.Error, T[InvalidDocumentActionException.Code]); + return false; + } + catch (ConcurrencyException) + { + Toasts.Show(ToastKind.Error, T["CompanyTables.NotSaved"], T["CompanyTables.Concurrency"]); + return false; + } + finally + { + _busy = false; + } + } + + private void Refuse(IEnumerable errors) + { + foreach (var (field, code) in errors.Select(TableValues.SplitError)) + { + Validation.Add(field, Message(code)); + } + + // Show the tab of the first error when the open one has none. + if (!Validation.Messages.Any(m => TabOfField(m.Field) == ActiveTab) && Validation.Messages is [var first, ..]) + { + _ = ShowTabAsync(TabOfField(first.Field)); + } + + // Errors without a field have nowhere to show: a message says them. + foreach (var message in Validation.Messages.Where(m => string.IsNullOrEmpty(m.Field))) + { + Toasts.Show(ToastKind.Error, message.Message); + } + } + + private string Message(string code) => T.Contains(code) ? T[code] : T["CompanyTables.UnknownError"]; + + /// + protected override async Task DeleteCoreAsync() + { + if (Record is not { Header.Id: > 0 } record || Session.Actor is not { } actor || Session.Company?.Code is not { } company || _section is null) + { + return; + } + + await RunAsync(async () => + { + await Engine.DeleteAsync(actor, company, record.Family, record.Header.Id); + Navigation.NavigateTo(SalesScreens.RadarUrl(_section)); + }); + } + + /// + protected override Task RadarAsync() + { + if (_section is not null) + { + Navigation.NavigateTo(SalesScreens.RadarUrl(_section)); + } + + return Task.CompletedTask; + } + + /// + protected override Task AttachmentsAsync() => ShowTabAsync(TabIds.Attachments); + + /// + protected override async Task PrintAsync() + { + // The preview prints what is saved: a new or changed document is saved first. + if (_section is null || Record is null || ((IsNew || IsModified) && !await SaveAsync()) || Record.Header.Id == 0) + { + return; + } + + Navigation.NavigateTo(SalesScreens.PrintUrl(_section, Record.Header.Id)); + } + + // ---- Actions ---------------------------------------------------------------------------------------------------- + + /// + protected override IEnumerable ContextActions() + { + if (Record is null || _definition is null) + { + yield break; + } + + var confirm = _definition.ConfirmAction; + if (_actions.Contains(confirm)) + { + yield return new ToolbarItem("confirm", "send", T[confirm == DocumentAction.Issue ? "Sales.Actions.Issue" : "Sales.Actions.Confirm"]) + { + Kind = ToolbarKind.Action, Primary = !IsModified, Disabled = _busy, OnClick = ConfirmAsync, + }; + } + + var targets = Targets().ToList(); + for (var i = 0; i < targets.Count; i++) + { + var target = targets[i]; + yield return new ToolbarItem("to-" + target.Code, "copy", T.Format("Sales.Actions.Create", target.Type.Description)) + { + Kind = i == 0 ? ToolbarKind.Action : ToolbarKind.Menu, Disabled = _busy || IsModified || IsNew, OnClick = () => OpenTransformAsync(target), + }; + } + } + + /// + protected override IEnumerable MenuCommands() + { + if (Record is null || _definition is null) + { + yield break; + } + + if (!IsReadOnly && Behavior.Lines.Contains(DocumentLineKind.Expense)) + { + yield return new ToolbarItem("add-expense", "plus", T["Sales.Actions.AddExpense"]) + { + Kind = ToolbarKind.Menu, OnClick = () => AddKindLineAsync(DocumentLineKind.Expense), + }; + yield return new ToolbarItem("add-discount", "minus", T["Sales.Actions.AddDiscount"]) + { + Kind = ToolbarKind.Menu, OnClick = () => AddKindLineAsync(DocumentLineKind.Discount), + }; + } + + if (IsNew) + { + yield break; + } + + if (_actions.Contains(DocumentAction.Copy)) + { + yield return new ToolbarItem("duplicate", "copy", T["Sales.Actions.Duplicate"]) + { + Kind = ToolbarKind.Menu, Disabled = _busy || IsModified, OnClick = () => OpenTransformAsync(_definition), + }; + } + + yield return new ToolbarItem("send-mail", "mail", T["Sales.Mail.Title"]) + { + Kind = ToolbarKind.Menu, Disabled = _busy || IsModified, OnClick = OpenMailAsync, + }; + + if (_actions.Contains(DocumentAction.Close)) + { + yield return new ToolbarItem("close", "check-circle", T[H.Kind == DocumentKind.Quotation ? "Sales.Actions.Refuse" : "Sales.Actions.Close"]) + { + Kind = ToolbarKind.Menu, Disabled = _busy || IsModified, OnClick = () => ChangeStateAsync(DocumentAction.Close), + }; + } + + if (_actions.Contains(DocumentAction.Reopen)) + { + yield return new ToolbarItem("reopen", "refresh", T["Sales.Actions.Reopen"]) + { + Kind = ToolbarKind.Menu, Disabled = _busy || IsModified, OnClick = () => ChangeStateAsync(DocumentAction.Reopen), + }; + } + + if (_actions.Contains(DocumentAction.Cancel)) + { + yield return new ToolbarItem("cancel-document", "x-circle", T["Sales.Actions.Cancel"]) + { + Kind = ToolbarKind.Menu, Danger = true, Disabled = _busy || IsModified, OnClick = OpenCancel, + }; + } + } + + // The sales types that can come from this document (order from a quotation, invoice from a delivery note...). + private IEnumerable Targets() + { + if (Record is null || IsNew || !_actions.Contains(DocumentAction.Copy)) + { + return []; + } + + // An order-like document gives what is left to fulfil; an issued invoice gives its notes. + var open = H.Status is DocumentStatus.Confirmed or DocumentStatus.PartiallyFulfilled; + var issued = Behavior.Lifecycle == DocumentLifecycle.Invoice && DocumentStateMachine.IsInForce(H.Status); + var preferred = SalesScreens.Sections.SelectMany(s => s.NewTypes).ToList(); + return _definitions + .Where(d => d.Behavior.Direction == DocumentDirection.Sale && d.Behavior.Fulfils(H.Kind) && preferred.Contains(d.Code) + && Session.Permissions.Allows(d.Behavior.WritePermission) + && (d.Kind is DocumentKind.CreditNote or DocumentKind.DebitNote ? issued : open)) + .OrderBy(d => Preference(H.Kind, d.Kind)) + .ThenBy(d => preferred.IndexOf(d.Code)); + } + + // The usual next step first: order after quotation, delivery note after order, deferred invoice after delivery note. + private static int Preference(DocumentKind source, DocumentKind target) => (source, target) switch + { + (DocumentKind.Quotation, DocumentKind.SalesOrder) => 0, + (DocumentKind.SalesOrder, DocumentKind.DeliveryNote) => 0, + (DocumentKind.DeliveryNote, DocumentKind.DeferredInvoice) => 0, + (DocumentKind.ProForma, DocumentKind.ImmediateInvoice) => 0, + (_, DocumentKind.CreditNote) => 0, + _ => 1, + }; + + private Task OpenTransformAsync(DocumentDefinition target) + { + if (Record is null) + { + return Task.CompletedTask; + } + + var fulfils = target.Behavior.Fulfils(H.Kind); + var lines = Record.Lines.Where(l => target.Behavior.Lines.Contains(l.Kind)).ToList(); + var selected = lines.Where(l => !fulfils || !DocumentLine.CarriesQuantity(l.Kind) || l.Residual > 0m).Select(l => l.Id).ToHashSet(); + _transform = new TransformRequest(target, T.Format("Sales.Actions.Create", target.Type.Description), + T[fulfils ? "Sales.Transform.LeadFulfil" : "Sales.Transform.LeadCopy"], lines, selected, fulfils); + StateHasChanged(); + return Task.CompletedTask; + } + + private void ToggleLine(long id, bool on) + { + if (_transform is null) + { + return; + } + + if (on) + { + _transform.Selected.Add(id); + } + else + { + _transform.Selected.Remove(id); + } + } + + private void ToggleAllLines(ChangeEventArgs e) + { + if (_transform is null) + { + return; + } + + _transform.Selected.Clear(); + if (e.Value is true) + { + _transform.Selected.UnionWith(_transform.Lines.Select(l => l.Id)); + } + } + + private async Task TransformAsync() + { + if (_transform is not { } request || Record is null || Session.Actor is not { } actor || Session.Company?.Code is not { } company) + { + return; + } + + await RunAsync(async () => + { + var all = request.Selected.Count == request.Lines.Count; + var copy = await Copies.CopyAsync(actor, company, Record.Family, H.Id, request.Target.Code, all ? null : request.Selected); + _transform = null; + Toasts.Show(ToastKind.Success, T.Format("Sales.Transform.Created", request.Target.Type.Description)); + if (SalesScreens.RecordUrl(copy.Header.Kind, copy.Header.Id) is { } url) + { + Navigation.NavigateTo(url); + } + }); + } + + private async Task ConfirmAsync() + { + if (Record is null || Session.Actor is not { } actor || Session.Company?.Code is not { } company || _definition is null) + { + return; + } + + if (IsModified && !await SaveAsync()) + { + return; + } + + var issue = _definition.ConfirmAction == DocumentAction.Issue; + if (issue && !await Dialogs.ConfirmAsync(new(T["Sales.Actions.Issue"], T["Sales.Confirm.IssueText"], T["Sales.Actions.Issue"], T["Common.Cancel"]))) + { + return; + } + + await RunAsync(async () => + { + Record = await Engine.ConfirmAsync(actor, company, Record.Family, H.Id); + await LoadSideAsync(actor, company); + Toasts.Show(ToastKind.Success, T.Format(issue ? "Sales.Confirm.Issued" : "Sales.Confirm.Confirmed", H.DocumentNumber ?? string.Empty)); + }); + } + + private async Task ChangeStateAsync(DocumentAction action) + { + if (Record is null || Session.Actor is not { } actor || Session.Company?.Code is not { } company) + { + return; + } + + await RunAsync(async () => + { + Record = action == DocumentAction.Close + ? await Engine.CloseAsync(actor, company, Record.Family, H.Id) + : await Engine.ReopenAsync(actor, company, Record.Family, H.Id); + await LoadSideAsync(actor, company); + Toasts.Show(ToastKind.Success, T["Sales.States." + H.Status]); + }); + } + + // The message proposed from the template and the e-mail of the customer. + private async Task OpenMailAsync() + { + if (Record is null || Session.Actor is not { } actor || Session.Company?.Code is not { } company) + { + return; + } + + await RunAsync(async () => + { + var draft = await Mails.DraftAsync(actor, company, Record.Family, H.Id); + (_mailTo, _mailSubject, _mailBody) = (draft.To, draft.Subject, draft.Body); + _mailValidation.Clear(); + _mailing = true; + }); + } + + private async Task SendMailAsync() + { + if (Record is null || Session.Actor is not { } actor || Session.Company?.Code is not { } company) + { + return; + } + + _mailValidation.Clear(); + _busy = true; + try + { + await Mails.SendAsync(actor, company, Record.Family, H.Id, new DocumentMailDraft(_mailTo ?? string.Empty, _mailSubject ?? string.Empty, _mailBody ?? string.Empty)); + _mailing = false; + Toasts.Show(ToastKind.Success, T["Sales.Mail.Queued"], T.Format("Sales.Mail.QueuedDetail", _mailTo ?? string.Empty)); + Record = await Engine.GetAsync(actor, company, Record.Family, H.Id) ?? Record; + await LoadSideAsync(actor, company); + } + catch (ValidationFailedException ex) + { + foreach (var error in ex.Errors) + { + var split = error.IndexOf(':', StringComparison.Ordinal); + var field = split > 0 ? error[..split] : null; + var code = error[(split + 1)..]; + if (field is null) + { + Toasts.Show(ToastKind.Error, T["Sales.Mail.Title"], T[code]); + } + else + { + _mailValidation.Add(field, T[code]); + } + } + } + catch (Exception ex) when (ex is AccessDeniedException or KeyNotFoundException) + { + Toasts.Show(ToastKind.Error, T["Sales.Mail.Title"], T[DocumentErrors.NotFound]); + } + finally + { + _busy = false; + } + } + + private Task OpenCancel() + { + _cancelReason = null; + _cancelValidation.Clear(); + _cancelling = true; + StateHasChanged(); + return Task.CompletedTask; + } + + private async Task CancelDocumentAsync() + { + if (Record is null || Session.Actor is not { } actor || Session.Company?.Code is not { } company) + { + return; + } + + _cancelValidation.Clear(); + if (Behavior.Lifecycle == DocumentLifecycle.Invoice && string.IsNullOrWhiteSpace(_cancelReason)) + { + _cancelValidation.Add("CancelReason", T[DocumentErrors.CancelReasonRequired]); + return; + } + + await RunAsync(async () => + { + Record = await Engine.CancelAsync(actor, company, Record.Family, H.Id, _cancelReason); + _cancelling = false; + await LoadSideAsync(actor, company); + Toasts.Show(ToastKind.Success, T["Sales.States." + H.Status]); + }); + } + + // Runs an action of the engine and reports its refusal. + private async Task RunAsync(Func action) + { + _busy = true; + try + { + await action(); + } + catch (ValidationFailedException ex) + { + Validation.Clear(); + Refuse(ex.Errors); + } + catch (InvalidDocumentActionException) + { + Toasts.Show(ToastKind.Error, T[InvalidDocumentActionException.Code]); + } + catch (ConcurrencyException) + { + Toasts.Show(ToastKind.Error, T["CompanyTables.NotSaved"], T["CompanyTables.Concurrency"]); + } + catch (KeyNotFoundException) + { + Toasts.Show(ToastKind.Error, T[DocumentErrors.NotFound]); + } + finally + { + _busy = false; + StateHasChanged(); + } + } + + /// + protected override void Dispose(bool disposing) + { + if (disposing) + { + _preview?.Cancel(); + _preview?.Dispose(); + } + + base.Dispose(disposing); + } + + /// The lines offered when a document becomes another one. + private sealed record TransformRequest(DocumentDefinition Target, string Title, string Lead, IReadOnlyList Lines, HashSet Selected, bool Fulfils); +} diff --git a/src/Khaemhat.Web/Components/Pages/Sales/SalesDocumentsPage.razor b/src/Khaemhat.Web/Components/Pages/Sales/SalesDocumentsPage.razor new file mode 100644 index 0000000..1d436bc --- /dev/null +++ b/src/Khaemhat.Web/Components/Pages/Sales/SalesDocumentsPage.razor @@ -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. *@ + + +@if (!_loaded) +{ +

@T["Common.Loading"]

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

@T["Sales.NoCompany"]

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

@T["Pages.NotFound.Title"]

+} +else if (!CanRead) +{ +
+ +

@T["Pages.AccessDenied.Title"]

+

@T["Pages.AccessDenied.Lead"]

+
+} +else +{ + + + @if (NewTypes.Count > 0) + { + + } + @if (_section.Segment == "fatture" && Session.Permissions.Allows("sales.invoice.write")) + { + @T["Sales.Deferred.Title"] + } + + + + + +
+ @foreach (var type in NewTypes) + { + + } +
+
+
+} + +@code { + private SalesSection? _section; + private IReadOnlyList _definitions = []; + private bool _loaded; + private bool _choosing; + + /// The radar segment, such as fatture. + [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 NewTypes => _section is null ? [] : + [.. _section.NewTypes.Select(code => _definitions.FirstOrDefault(d => d.Code == code)).OfType() + .Where(d => Session.Permissions.Allows(d.Behavior.WritePermission))]; + + private IReadOnlyList> 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 => @@StateOf(r).Text, + }, + ]; + + private IReadOnlyList QuickFilters + { + get + { + var filters = new List + { + new("status", T["Sales.Radar.State"], [new(string.Empty, T["Sales.Radar.All"]), .. States.Select(s => new KhOption(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(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((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 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]; + + /// + 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> 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([], 0, new Dictionary())); + + 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)); + } + } +} diff --git a/src/Khaemhat.Web/Components/Pages/Sales/SalesPrintPage.razor b/src/Khaemhat.Web/Components/Pages/Sales/SalesPrintPage.razor new file mode 100644 index 0000000..d6c7b9d --- /dev/null +++ b/src/Khaemhat.Web/Components/Pages/Sales/SalesPrintPage.razor @@ -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. *@ + + +@if (_model is null) +{ +
+ +

@(_missing ? T["Sales.NotFound"] : T["Common.Loading"])

+
+} +else +{ +
+
+
@_model.Title @_model.Number › @T["Sales.Print.Title"]
+

@Heading

+
+
+ + +
+
+ @if (_model.LogoAttachmentId is { } logo) + { + + } +
+
@_model.Company.Name
+ @foreach (var line in _model.Company.Lines) + { +
@line
+ } +
+
+
+
@_model.Title
+
@_model.Number
+
@_model.Date
+ @if (_model.Watermark is { } mark) + { +
@mark
+ } +
+
+ +
+
+ @foreach (var field in _model.Fields) + { +
@field.Label
+
@field.Value
+ } +
+
+
@_model.PartyLabel @_model.Party.Code
+ @_model.Party.Name + @foreach (var line in _model.Party.Lines) + { +
@line
+ } +
+
+ + + + + @for (var i = 0; i < _model.LineHeaders.Count; i++) + { + + } + + + + @foreach (var line in _model.Lines) + { + if (line.IsDescription) + { + + } + else + { + + + + + + + + + + + } + } + +
@_model.LineHeaders[i]
@line.Description
@line.Code@line.Description@line.Unit@line.Quantity@line.Price@line.Discount@line.Tax@line.Amount
+ + @foreach (var note in _model.Notes) + { +

@note

+ } + +
+
+ @if (_model.Summary is { } summary) + { + @Table(summary) + } + @if (_model.Installments is { } installments) + { + @Table(installments) + } +
+
+ @foreach (var row in _model.Totals) + { + @row.Label + @row.Value + } +
+
+ + @if (_model.Transport.Count > 0) + { +
+ @foreach (var field in _model.Transport) + { +
@field.Label
@field.Value
+ } +
+
+ @foreach (var signature in _model.Signatures) + { +
@signature
+ } +
+ } + + @if (_model.Footer is { } footer) + { +

@footer

+ } +
+} + +@code { + private SalesSection? _section; + private DocumentPrintModel? _model; + private bool _missing; + private bool _saving; + + /// The radar segment, such as fatture. + [Parameter] + public string? Segment { get; set; } + + /// The document. + [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); + + /// + 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 => + { +
+
@table.Title
+ + + + @for (var i = 0; i < table.Headers.Count; i++) + { + + } + + + + @foreach (var row in table.Rows) + { + + @for (var i = 0; i < row.Count; i++) + { + + } + + } + +
@table.Headers[i]
@row[i]
+
+ }; +} diff --git a/src/Khaemhat.Web/Documents/DocumentLookups.cs b/src/Khaemhat.Web/Documents/DocumentLookups.cs new file mode 100644 index 0000000..33244b9 --- /dev/null +++ b/src/Khaemhat.Web/Documents/DocumentLookups.cs @@ -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; + +/// +/// 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 code · description. +/// +public sealed class DocumentLookups +{ + /// No choices, before loading. + public static DocumentLookups Empty { get; } = new(); + + /// Payment terms. + public IReadOnlyList> PaymentTerms { get; private init; } = []; + + /// Payment methods. + public IReadOnlyList> PaymentMethods { get; private init; } = []; + + /// Price lists. + public IReadOnlyList> PriceLists { get; private init; } = []; + + /// Salespeople. + public IReadOnlyList> Salespeople { get; private init; } = []; + + /// The company bank accounts. + public IReadOnlyList> BankAccounts { get; private init; } = []; + + /// Warehouses. + public IReadOnlyList> Warehouses { get; private init; } = []; + + /// Carriers. + public IReadOnlyList> Carriers { get; private init; } = []; + + /// Shipping terms (porto). + public IReadOnlyList> ShippingTerms { get; private init; } = []; + + /// Reasons of transport. + public IReadOnlyList> TransportReasons { get; private init; } = []; + + /// Appearances of the goods. + public IReadOnlyList> GoodsAppearances { get; private init; } = []; + + /// VAT codes. + public IReadOnlyList> TaxCodes { get; private init; } = []; + + /// Units of measure. + public IReadOnlyList> Units { get; private init; } = []; + + /// Currencies, by code. + public IReadOnlyList> Currencies { get; private init; } = []; + + /// Reads the choices. + /// The tables. + /// Who reads. + /// The company. + /// Cancellation. + /// The choices. + public static async Task ReadAsync(TableService tables, Actor actor, string company, CancellationToken cancellationToken = default) => new() + { + PaymentTerms = await ReadAsync(tables, actor, company, false, cancellationToken).ConfigureAwait(false), + PaymentMethods = await ReadAsync(tables, actor, company, false, cancellationToken).ConfigureAwait(false), + PriceLists = await ReadAsync(tables, actor, company, false, cancellationToken).ConfigureAwait(false), + Salespeople = await ReadAsync(tables, actor, company, false, cancellationToken).ConfigureAwait(false), + BankAccounts = await ReadAsync(tables, actor, company, false, cancellationToken).ConfigureAwait(false), + Warehouses = await ReadAsync(tables, actor, company, false, cancellationToken).ConfigureAwait(false), + Carriers = await ReadAsync(tables, actor, company, false, cancellationToken).ConfigureAwait(false), + ShippingTerms = await ReadAsync(tables, actor, company, false, cancellationToken).ConfigureAwait(false), + TransportReasons = await ReadAsync(tables, actor, company, false, cancellationToken).ConfigureAwait(false), + GoodsAppearances = await ReadAsync(tables, actor, company, false, cancellationToken).ConfigureAwait(false), + TaxCodes = await ReadAsync(tables, actor, company, false, cancellationToken).ConfigureAwait(false), + Units = await ReadAsync(tables, actor, company, false, cancellationToken).ConfigureAwait(false), + Currencies = await ReadAsync(tables, actor, company, true, cancellationToken).ConfigureAwait(false), + }; + + /// The code of a choice (the part before · ). + /// The choices. + /// The id. + /// The code, or . + public static string? CodeOf(IReadOnlyList> 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]; + } + + /// The id of the choice with a code, ignoring case. + /// The choices. + /// The code typed. + /// The id, or . + public static long? IdOf(IReadOnlyList> 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>> ReadAsync(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(c.Value, c.Text))]; + } +} diff --git a/src/Khaemhat.Web/Documents/SalesScreens.cs b/src/Khaemhat.Web/Documents/SalesScreens.cs new file mode 100644 index 0000000..6f05be7 --- /dev/null +++ b/src/Khaemhat.Web/Documents/SalesScreens.cs @@ -0,0 +1,144 @@ +using System.Globalization; +using Khaemhat.Application.Localization; +using Khaemhat.Core.Documents; +using Khaemhat.Web.Ui; + +namespace Khaemhat.Web.Documents; + +/// A radar of the sales menu and the document types it holds. +/// The path segment, such as fatture. +/// The family of the documents. +/// The kinds shown. +/// The document types a user can create from the radar, the first being the usual one. +/// The icon. +/// The key of the texts under Sales.Sections. +public sealed record SalesSection(string Segment, DocumentFamily Family, IReadOnlyList Kinds, IReadOnlyList NewTypes, string Icon, string Key); + +/// +/// Addresses and labels of the sales screens (SPEC §11.3, mockups 020-030): one radar per menu entry under +/// /vendite, the record of a document under it, and the deferred invoicing. +/// +public static class SalesScreens +{ + /// The menu area. + public const string BasePath = "vendite"; + + /// The deferred invoicing of the delivery notes. + public const string DeferredInvoicingUrl = BasePath + "/fatturazione-differita"; + + /// The tab of the transport data, after Testata, for delivery notes and accompanying invoices. + public const string TransportTab = "trasporto"; + + /// The radars, in the order of the menu. + public static IReadOnlyList 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"), + ]; + + /// The radar of a path segment. + /// The segment. + /// The radar, or . + public static SalesSection? Find(string? segment) => Sections.FirstOrDefault(s => string.Equals(s.Segment, segment, StringComparison.OrdinalIgnoreCase)); + + /// The radar that holds a kind of document. + /// The kind. + /// The radar, or for a kind outside sales. + public static SalesSection? Of(DocumentKind kind) => Sections.FirstOrDefault(s => s.Kinds.Contains(kind)); + + /// The address of a radar. + /// The radar. + /// The address. + public static string RadarUrl(SalesSection section) + { + ArgumentNullException.ThrowIfNull(section); + return BasePath + "/" + section.Segment; + } + + /// The address of a document. + /// The kind. + /// The document. + /// The address, or for a kind outside sales. + public static string? RecordUrl(DocumentKind kind, long id) => + Of(kind) is { } section ? RadarUrl(section) + "/" + id.ToString(CultureInfo.InvariantCulture) : null; + + /// The address of a new document of a type. + /// The radar. + /// The document type. + /// The address. + public static string NewUrl(SalesSection section, string typeCode) => RadarUrl(section) + "/nuovo?tipo=" + Uri.EscapeDataString(typeCode); + + /// The print preview of a document. + /// The radar. + /// The document. + /// The relative URL. + public static string PrintUrl(SalesSection section, long id) + { + ArgumentNullException.ThrowIfNull(section); + return RadarUrl(section) + "/" + id.ToString(System.Globalization.CultureInfo.InvariantCulture) + "/stampa"; + } + + /// The name of a kind, such as Fattura immediata. + /// The texts. + /// The kind. + /// The name. + public static string KindName(ITexts texts, DocumentKind kind) + { + ArgumentNullException.ThrowIfNull(texts); + return texts["Sales.Kinds." + kind]; + } + + /// The label and tone of a state; a quotation shows its outcome (accepted, refused, expired). + /// The texts. + /// The kind. + /// The state. + /// Until when a quotation is valid. + /// Today. + /// The label and the tone. + 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); + } + + /// The choices of an enumeration, labelled from Sales.{group}.{value}. + /// The enumeration. + /// The texts. + /// The group of texts. + /// The choices. + public static IReadOnlyList> Choices(ITexts texts, string group) + where TEnum : struct, Enum + { + ArgumentNullException.ThrowIfNull(texts); + return [.. Enum.GetValues().Select(v => new KhOption(v.ToString(), texts["Sales." + group + "." + v]))]; + } +} diff --git a/src/Khaemhat.Web/Hosting/KhaemhatServices.cs b/src/Khaemhat.Web/Hosting/KhaemhatServices.cs index 3a0fe9d..142c091 100644 --- a/src/Khaemhat.Web/Hosting/KhaemhatServices.cs +++ b/src/Khaemhat.Web/Hosting/KhaemhatServices.cs @@ -148,6 +148,12 @@ internal static class KhaemhatServices services.AddSingleton(); services.AddSingleton(); + // The document engine (ADR 0032): one engine, the copies, a typed service per family. + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(typeof(Khaemhat.Application.Documents.DocumentService<,>)); + // Guided import and export (ADR 0031): the entities in the order of the screen. services.AddSingleton(sp => ActivatorUtilities.CreateInstance( sp, Khaemhat.Core.Parties.PartyKind.Customer)); @@ -170,6 +176,8 @@ internal static class KhaemhatServices // Companies and start. services.AddSingleton(); services.AddSingleton(sp => sp.GetRequiredService()); + services.AddSingleton(); + services.AddSingleton(sp => sp.GetRequiredService()); services.AddSingleton(); services.AddSingleton(); services.AddScoped(); @@ -220,6 +228,23 @@ internal static class KhaemhatServices services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + + // 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(); + services.AddSingleton(); + services.AddSingleton(sp => sp.GetRequiredService()); + services.AddHostedService(sp => sp.GetRequiredService()); + services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); diff --git a/src/Khaemhat.Web/Hosting/SeedCommand.cs b/src/Khaemhat.Web/Hosting/SeedCommand.cs index 80edc9a..0972cd0 100644 --- a/src/Khaemhat.Web/Hosting/SeedCommand.cs +++ b/src/Khaemhat.Web/Hosting/SeedCommand.cs @@ -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().SeedAsync(code, new CompanySeedContext(IsNew: false, Base: false, Demo: true)).ConfigureAwait(false); } } diff --git a/src/Khaemhat.Web/Resources/it-IT/Documents.json b/src/Khaemhat.Web/Resources/it-IT/Documents.json new file mode 100644 index 0000000..6ac2981 --- /dev/null +++ b/src/Khaemhat.Web/Resources/it-IT/Documents.json @@ -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." + } + } +} diff --git a/src/Khaemhat.Web/Resources/it-IT/Files.json b/src/Khaemhat.Web/Resources/it-IT/Files.json index 90ea636..80ad3fc 100644 --- a/src/Khaemhat.Web/Resources/it-IT/Files.json +++ b/src/Khaemhat.Web/Resources/it-IT/Files.json @@ -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)" diff --git a/src/Khaemhat.Web/Resources/it-IT/Parties.json b/src/Khaemhat.Web/Resources/it-IT/Parties.json index 8fbdeb5..c0508da 100644 --- a/src/Khaemhat.Web/Resources/it-IT/Parties.json +++ b/src/Khaemhat.Web/Resources/it-IT/Parties.json @@ -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", diff --git a/src/Khaemhat.Web/Resources/it-IT/Print.json b/src/Khaemhat.Web/Resources/it-IT/Print.json new file mode 100644 index 0000000..02377e6 --- /dev/null +++ b/src/Khaemhat.Web/Resources/it-IT/Print.json @@ -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." + } + } +} diff --git a/src/Khaemhat.Web/Resources/it-IT/Sales.json b/src/Khaemhat.Web/Resources/it-IT/Sales.json new file mode 100644 index 0000000..1c01d68 --- /dev/null +++ b/src/Khaemhat.Web/Resources/it-IT/Sales.json @@ -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" + } + } +} diff --git a/src/Khaemhat.Web/Resources/it-IT/Shell.json b/src/Khaemhat.Web/Resources/it-IT/Shell.json index c4de263..c52ec32 100644 --- a/src/Khaemhat.Web/Resources/it-IT/Shell.json +++ b/src/Khaemhat.Web/Resources/it-IT/Shell.json @@ -67,7 +67,8 @@ "Orders": "Ordini clienti", "DeliveryNotes": "DDT", "Invoices": "Fatture", - "CreditNotes": "Note di credito" + "CreditNotes": "Note di credito", + "DeferredInvoicing": "Fatturazione differita" }, "Purchases": { "_": "Acquisti", diff --git a/src/Khaemhat.Web/Resources/it-IT/Tables.json b/src/Khaemhat.Web/Resources/it-IT/Tables.json index ae12783..127f764 100644 --- a/src/Khaemhat.Web/Resources/it-IT/Tables.json +++ b/src/Khaemhat.Web/Resources/it-IT/Tables.json @@ -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." }, diff --git a/src/Khaemhat.Web/Shell/MenuCatalog.cs b/src/Khaemhat.Web/Shell/MenuCatalog.cs index 2c9d753..4c5b190 100644 --- a/src/Khaemhat.Web/Shell/MenuCatalog.cs +++ b/src/Khaemhat.Web/Shell/MenuCatalog.cs @@ -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", diff --git a/src/Khaemhat.Web/Tables/TableScreens.cs b/src/Khaemhat.Web/Tables/TableScreens.cs index 48dcb0c..8db0429 100644 --- a/src/Khaemhat.Web/Tables/TableScreens.cs +++ b/src/Khaemhat.Web/Tables/TableScreens.cs @@ -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) diff --git a/src/Khaemhat.Web/wwwroot/app.css b/src/Khaemhat.Web/wwwroot/app.css index c5b6f1d..469eb44 100644 --- a/src/Khaemhat.Web/wwwroot/app.css +++ b/src/Khaemhat.Web/wwwroot/app.css @@ -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; } diff --git a/tests/Khaemhat.Application.Tests/DocumentTotalsTests.cs b/tests/Khaemhat.Application.Tests/DocumentTotalsTests.cs new file mode 100644 index 0000000..075326e --- /dev/null +++ b/tests/Khaemhat.Application.Tests/DocumentTotalsTests.cs @@ -0,0 +1,169 @@ +using Khaemhat.Application.Documents; +using Khaemhat.Core.Documents; +using Khaemhat.Core.Tax; +using Khaemhat.Fiscal.Italy; + +namespace Khaemhat.Application.Tests; + +/// +/// 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. +/// +[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)); + } +} diff --git a/tests/Khaemhat.Application.Tests/Khaemhat.Application.Tests.csproj b/tests/Khaemhat.Application.Tests/Khaemhat.Application.Tests.csproj index 56cd603..8c3f051 100644 --- a/tests/Khaemhat.Application.Tests/Khaemhat.Application.Tests.csproj +++ b/tests/Khaemhat.Application.Tests/Khaemhat.Application.Tests.csproj @@ -7,6 +7,7 @@ + diff --git a/tests/Khaemhat.Core.Tests/Common/CronExpressionTests.cs b/tests/Khaemhat.Core.Tests/Common/CronExpressionTests.cs index 7ba25a2..065acb1 100644 --- a/tests/Khaemhat.Core.Tests/Common/CronExpressionTests.cs +++ b/tests/Khaemhat.Core.Tests/Common/CronExpressionTests.cs @@ -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); } } diff --git a/tests/Khaemhat.Core.Tests/Documents/DocumentRulesTests.cs b/tests/Khaemhat.Core.Tests/Documents/DocumentRulesTests.cs new file mode 100644 index 0000000..9d14106 --- /dev/null +++ b/tests/Khaemhat.Core.Tests/Documents/DocumentRulesTests.cs @@ -0,0 +1,121 @@ +using Khaemhat.Core.Documents; + +namespace Khaemhat.Core.Tests.Documents; + +/// The declarative rules of the document engine (issue #47): behaviours, states, fulfilment. +[TestClass] +public sealed class DocumentRulesTests +{ + [TestMethod] + public void EveryKind_HasABehaviour_AndFulfilsOnlyKindsOfTheSameDirection() + { + Assert.HasCount(Enum.GetValues().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(() => DocumentStateMachine.Apply(Order, DocumentStatus.PartiallyFulfilled, DocumentAction.Cancel)); + Assert.AreEqual(DocumentAction.Cancel, refused.Action); + Assert.ThrowsExactly(() => DocumentStateMachine.Apply(Order, DocumentStatus.Confirmed, DocumentAction.Delete)); + Assert.ThrowsExactly(() => DocumentStateMachine.Apply(Order, DocumentStatus.Draft, DocumentAction.Issue)); + Assert.ThrowsExactly(() => DocumentStateMachine.Apply(Order, DocumentStatus.Cancelled, DocumentAction.Reopen)); + Assert.ThrowsExactly(() => 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(() => DocumentStateMachine.Apply(DocumentLifecycle.Simple, DocumentStatus.Confirmed, DocumentAction.Close)); + } + + [TestMethod] + public void Fulfilment_SumsTheLinks_AndClosedLinesCountAsFulfilled() + { + var lines = new List + { + 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 }; +} diff --git a/tests/Khaemhat.Data.Tests/DocumentNumberingTests.cs b/tests/Khaemhat.Data.Tests/DocumentNumberingTests.cs new file mode 100644 index 0000000..f0efbde --- /dev/null +++ b/tests/Khaemhat.Data.Tests/DocumentNumberingTests.cs @@ -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; + +/// Document numbering on both engines (issue #47): concurrent confirmations never share a number. +[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().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().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(() => 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().ListAsync(Query.For().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 NumeratorAsync(TestDatabase db) + { + await new MigrationRunner(db.Context).RunAsync(db.Target, MigrationCatalog.ForCompany()); + await using var setup = await db.OpenAsync(); + return await setup.Repository().InsertAsync(new DocumentNumerator + { + Code = "FAT", + Description = "Fatture", + Kind = NumeratorKind.SalesInvoice, + Year = 2026, + Prefix = "FV", + Format = "{prefix}-{year}/{number:D4}", + }); + } +} diff --git a/tests/Khaemhat.Data.Tests/Khaemhat.Data.Tests.csproj b/tests/Khaemhat.Data.Tests/Khaemhat.Data.Tests.csproj index d595a2e..f65bb54 100644 --- a/tests/Khaemhat.Data.Tests/Khaemhat.Data.Tests.csproj +++ b/tests/Khaemhat.Data.Tests/Khaemhat.Data.Tests.csproj @@ -9,6 +9,8 @@ + + diff --git a/tests/Khaemhat.Data.Tests/MappingTests.cs b/tests/Khaemhat.Data.Tests/MappingTests.cs index c5b635d..69cc632 100644 --- a/tests/Khaemhat.Data.Tests/MappingTests.cs +++ b/tests/Khaemhat.Data.Tests/MappingTests.cs @@ -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()); } diff --git a/tests/Khaemhat.Web.Tests/Documents/DemoSalesTests.cs b/tests/Khaemhat.Web.Tests/Documents/DemoSalesTests.cs new file mode 100644 index 0000000..2d7096f --- /dev/null +++ b/tests/Khaemhat.Web.Tests/Documents/DemoSalesTests.cs @@ -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; + +/// The demo sales (SPEC §14, issue #53): every kind of sales document, in every state, made through the engine. +[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().RunAsync(company, SeedKind.Demo); + var seeder = app.Services.GetRequiredService(); + var context = new CompanySeedContext(IsNew: false, Base: false, Demo: true); + await seeder.SeedAsync(company, context); + + var editor = app.Services.GetRequiredService(); + 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().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> AllAsync(DocumentEditor editor, string company) + { + var all = new List(); + foreach (var family in new[] { DocumentFamily.SaleQuotation, DocumentFamily.SaleOrder, DocumentFamily.SaleDocument }) + { + all.AddRange((await editor.ListAsync(Root, company, family, [.. Enum.GetValues()], new ListQuery { Limit = 200 })).Items); + } + + return all; + } +} diff --git a/tests/Khaemhat.Web.Tests/Documents/DocumentEngineTests.cs b/tests/Khaemhat.Web.Tests/Documents/DocumentEngineTests.cs new file mode 100644 index 0000000..6171280 --- /dev/null +++ b/tests/Khaemhat.Web.Tests/Documents/DocumentEngineTests.cs @@ -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; + +/// The document engine on a real instance (issue #47): definitions, numbering, states, copies and fulfilment. +[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>(); + var sales = app.Services.GetRequiredService>(); + var copies = app.Services.GetRequiredService(); + 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(() => orders.SaveAsync(Root, company, order)); + Assert.AreEqual("Lines.0.Quantity:" + DocumentErrors.LineBelowFulfilled, below.Errors.Single()); + await Assert.ThrowsExactlyAsync(() => 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(() => 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(() => 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(() => sales.SaveAsync(Root, company, invoice)); + await Assert.ThrowsExactlyAsync(() => sales.DeleteAsync(Root, company, invoice.Header.Id)); + await Assert.ThrowsExactlyAsync(() => sales.CancelAsync(Root, company, first.Header.Id, null), "Fulfilled by the invoice."); + + var reason = await Assert.ThrowsExactlyAsync(() => 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(); + var sales = app.Services.GetRequiredService>(); + 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(() => 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(() => 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(() => 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(() => 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(() => 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(); + 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(); + var noKind = await Assert.ThrowsExactlyAsync(() => + 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().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> NewInvoiceAsync( + DocumentService 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> InvoiceAsync( + DocumentService sales, string company, long customer, long vat, DateOnly date) => + await sales.SaveAsync(Root, company, await NewInvoiceAsync(sales, company, customer, vat, date)); + + private static DocumentRecord Typed(DocumentRecord record) => + new() { Header = (SaleDocument)record.Header, Lines = [.. record.Lines.Cast()] }; + + private static async Task VatAsync(WebApplication app, string company) => + (await app.Services.GetRequiredService().ActiveAsync(Root, company)).Single(t => t.Code == "22").Id; + + private static async Task CustomerAsync(WebApplication app, string company) + { + var parties = app.Services.GetRequiredService(); + 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; + } +} diff --git a/tests/Khaemhat.Web.Tests/Documents/DocumentPrintMailTests.cs b/tests/Khaemhat.Web.Tests/Documents/DocumentPrintMailTests.cs new file mode 100644 index 0000000..59b3389 --- /dev/null +++ b/tests/Khaemhat.Web.Tests/Documents/DocumentPrintMailTests.cs @@ -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; + +/// Printing and sending documents (SPEC §9.4, §12.6, issue #52): the print model, the PDF, MIME, SMTP and the queue. +[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 + { + ["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 ", 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 ", 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:"); + CollectionAssert.Contains(commands, "RCPT TO:"); + CollectionAssert.Contains(commands, "RCPT TO:"); + 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(() => sender.SendAsync(new OutgoingMail(["a@example.com"], "Prova", "Testo"))); + await Assert.ThrowsExactlyAsync(() => 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(queue), CancellationToken.None); + await using (app) + { + await app.Services.GetRequiredService().RunAsync(company, SeedKind.Demo); + await app.Services.GetRequiredService().SeedAsync(company, new CompanySeedContext(IsNew: false, Base: false, Demo: true)); + var editor = app.Services.GetRequiredService(); + var engine = app.Services.GetRequiredService(); + 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().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() + .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(), 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(); + 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(() => 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(() => 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 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 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(); + 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 Mails { get; } = []; + + public bool Configured { get; set; } = true; + + public bool IsConfigured => Configured; + + public bool Enqueue(OutgoingMail mail) + { + Mails.Add(mail); + return true; + } + } +} diff --git a/tests/Khaemhat.Web.Tests/Documents/SalesFlowTests.cs b/tests/Khaemhat.Web.Tests/Documents/SalesFlowTests.cs new file mode 100644 index 0000000..9d97bdb --- /dev/null +++ b/tests/Khaemhat.Web.Tests/Documents/SalesFlowTests.cs @@ -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; + +/// +/// 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. +/// +[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(); + var editor = app.Services.GetRequiredService(); + var tables = app.Services.GetRequiredService(); + var taxes = await tables.ActiveAsync(Root, company); + var terms = await tables.ActiveAsync(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(); + var editor = app.Services.GetRequiredService(); + var copies = app.Services.GetRequiredService(); + 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 + { + 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(() => + 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(() => 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().ActiveAsync(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().Select(k => "Sales.Kinds." + k) + .Concat(Enum.GetValues().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().Select(d => "Sales.Links." + d)) + .Concat(Enum.GetValues().Select(k => "Sales.LineKinds." + k)); + var missing = keys.Where(k => !texts.Contains(k)).ToList(); + Assert.IsEmpty(missing, string.Join(", ", missing)); + } + + private static async Task 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 CustomerAsync(WebApplication app, string company, string name, string vatNumber, long? paymentTermId) + { + var parties = app.Services.GetRequiredService(); + 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; + } +}