Compare commits

..
22 Commits
Author SHA1 Message Date
Alby96andClaude Opus 5.5 cfca29d71c Merge M7 · Contabilità generale e IVA (v0.7.0) (#126)
Wiki / Publish the wiki (push) Successful in 14s
CI / PostgreSQL 16 integration (push) Successful in 1m44s
CI / Build and test (SQLite) (push) Successful in 4m3s
CI / Docker image (push) Skipped
CI / PostgreSQL 17 integration (push) Successful in 1m27s
CI / YAML check (push) Successful in 6s
Release / Image and release (push) Successful in 2m24s
General ledger, automatic posting of documents, VAT registers and settlement, withholdings, stamp duty and F24 (#62-#68). Gitea Actions created no run for this PR: build, the full suite (754) and the PostgreSQL 18 data tests (110) passed locally.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 03:49:32 +01:00
Alby96andClaude Opus 5.5 9e3ba92993 feat: general ledger, automatic posting, VAT settlement, withholdings and F24 (#62 #63 #64 #65 #66 #67 #68)
M7 adds the double-entry ledger so that the documents of M5 and M6 reach the
accounts without retyping, and the Italian VAT obligations can be prepared from
the same data.

- Chart of accounts on three levels with the Italian "PMI standard" model in the
  fiscal pack, journal templates with proposed lines, VAT registers; the chart
  import now writes the accounts and exports them (#62, ADR 0036).
- Journal entries: draft, posted, final with the libro giornale number,
  reversal; recurring entries with the nightly ledger.recurring job (#63).
- Documents post their entry inside the document transaction (PostingEngine,
  LedgerPoster) with VAT lines, open items and withholdings; a change rewrites
  the same entry, a cancellation removes or reverses it (#64, ADR 0037).
- VAT registers with final print, monthly or quarterly settlement with pro rata,
  interest, minimum and advance, confirmation with the LIQ entry, period lock
  and F24 line, LIPE file and F24 data (#65).
- Operated and suffered withholdings, CU data, stamp duty by quarter with the
  5,000 euro threshold, F24 summary with its payment entry (#66).
- Party ledgers, account ledgers, trial balance and libro giornale (#67).
- Demo accounting with the settlements of the past months confirmed and checked
  by hand in a test; wiki Contabilita, IVA, Fiscalita italiana completed with
  screenshots; CHANGELOG 0.7.0, STATUS, ADR 0036-0037 (#68).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 01:41:58 +01:00
Alby96 838362bfe1 Merge M6 · Acquisti e Magazzino (v0.6.0) (#125)
CI / YAML check (push) Failing after 58s
CI / Build and test (SQLite) (push) Successful in 4m11s
CI / PostgreSQL 16 integration (push) Skipped
CI / PostgreSQL 17 integration (push) Skipped
CI / Docker image (push) Failing after 1m19s
Purchase cycle, supplier e-invoice import, self-invoices and a warehouse posted from the documents, with the user guide in the wiki.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

No files matched your search

+6 -2
View File
@@ -152,8 +152,12 @@ jobs:
curl -fsS --max-time 5 "http://$NAME-app:8080/health"
echo
test "$(curl -s -o /dev/null -w '%{http_code}' --max-time 5 "http://$NAME-app:8080/")" = "302"
curl -fsS --max-time 5 "http://$NAME-app:8080/login" | grep -q "Accedi"
curl -fsS -D - -o /dev/null --max-time 5 "http://$NAME-app:8080/login" | grep -qi "content-security-policy"
# Read the whole response first: grep -q closes the pipe at the first match, and with pipefail the
# write error of curl (exit 23) would fail the step depending on timing.
login="$(curl -fsS --max-time 5 "http://$NAME-app:8080/login")"
grep -q "Accedi" <<<"$login"
headers="$(curl -fsS -D - -o /dev/null --max-time 5 "http://$NAME-app:8080/login")"
grep -qi "content-security-policy" <<<"$headers"
test "$(docker exec "$NAME-app" sh -c 'stat -c %u:%g /proc/1')" = "99:100"
test "$(docker exec "$NAME-app" stat -c %u:%g /data)" = "99:100"
docker exec "$NAME-app" pg_dump --version
+169
View File
@@ -7,6 +7,175 @@ un'immagine `gitea.encke-hake.ts.net/balbosoft/khaemhat:X.Y.Z`.
## [Unreleased]
## [0.7.0] - 2026-11-13
M7 - Contabilità generale e IVA. Ogni fattura, nota e autofattura si contabilizza da sola nella stessa transazione,
con le righe IVA nel suo registro, le partite aperte e la ritenuta; la prima nota in partita doppia con registrazioni
provvisorie, definitive e storni; registri IVA, liquidazione periodica con F24 e LIPE, ritenute, bollo virtuale,
partitari, mastrini e bilancio di verifica.
### Added
- Piano dei conti a tre livelli (#62, ADR 0036): mastro, conto e sottoconto (`MM.CC.SSS`), natura, tipo, voce CEE,
partitario, rilevanza IVA; modello italiano *PMI standard* di 237 conti nel pacchetto fiscale
(`ItalianLedgerTemplate`), albero con ricerca, scheda e mastrino con saldo progressivo e stampa.
- Causali contabili con righe proposte, registro IVA, apertura delle partite e causale di storno (#62): `FV`, `NCV`,
`FA`, `NCA`, `AFRC`, `CORR`, `INC`, `PAG`, `RIT`, `RITS`, `LIQ`, `F24`, `GIRO`, `SPB`, `STO` e altre.
- Prima nota (#63): registrazioni in partita doppia con cliente o fornitore sui conti con partitario, centro di
costo e righe IVA; bozza, registrata (numero per anno) e definitiva (numero del libro giornale) con *Rendi
definitive*; storno; *Chiudi lo sbilancio*; filtri e paginazione.
- Registrazioni ricorrenti (#63): copia di una registrazione modello mensile, trimestrale, semestrale o annuale fino
a una data, job di sistema `ledger.recurring` ogni giorno alle 5:00 e *Genera ora*.
- Contabilizzazione automatica dei documenti (#64, ADR 0037): fatture, note di debito, parcelle, note di credito,
fatture e note fornitore, autofatture e integrazioni scrivono la registrazione alla conferma (`PostingEngine`,
`LedgerPoster`), la riscrivono con lo stesso numero alla modifica e la tolgono o la stornano all'annullamento;
scissione dei pagamenti, IVA indetraibile sul costo, rivalsa cassa e bollo; *Contabilizza documenti* per i
documenti confermati prima.
- Registri IVA vendite, acquisti, autofatture e corrispettivi (#65) con riepilogo per aliquota, stampa di prova e
definitiva con numerazione delle pagine.
- Liquidazione IVA mensile o trimestrale (#65): IVA a debito e a credito, pro rata, credito e debito riportati,
interessi trimestrali, minimo di versamento, acconto di dicembre (storico, previsionale, effettivo); conferma con la
registrazione `LIQ`, il blocco dei periodi e il versamento F24; riapertura; file della comunicazione LIPE
(`IVP18`) e dati F24. Regole e codici tributo nel pacchetto italiano (`VatSettlementRulesIt`).
- Ritenute d'acconto operate e subite (#66): da versare quando la fattura del professionista è pagata, registrazioni
`RIT` e `RITS`, codice 1040 al 16 del mese dopo; dati della certificazione unica in CSV.
- Bollo virtuale per trimestre (#66) con soglia dei 5.000 euro, codici 2521-2524 e scadenze.
- Prospetto F24 per scadenza (#66) con export dei dati e registrazione del pagamento `F24` sulla banca
dell'azienda.
- Partitari clienti e fornitori con estratto conto e partite aperte, bilancio di verifica per mastri, conti e
sottoconti con centro di costo e risultato del periodo, libro giornale di prova e definitivo in PDF (#67).
- Menu *Contabilità*; testi in `Resources/it-IT/Ledger.json`; permessi `ledger.account.*`, `ledger.entry.*`,
`vat.register.read`, `vat.settlement.*`.
- Contabilità nei dati di esempio (#68): documenti contabilizzati, fattura del professionista pagata, noleggio
mensile della stampante come ricorrente, liquidazioni dei mesi passati confermate e F24 scaduti pagati.
- Tabelle `gl_accounts`, `gl_journal_templates`, `gl_journal_template_lines`, `gl_entries`, `gl_entry_lines`,
`gl_entry_vat`, `gl_open_items`, `gl_recurring_entries`, `vat_registers`, `vat_register_prints`,
`vat_settlements`, `vat_settlement_lines`, `tax_payments`, `withholdings` (migrazione `M20261113_002`).
- ADR 0036 e 0037; pagine wiki *Contabilità*, *IVA* e *Fiscalità italiana* complete con le schermate.
### Changed
- *Bollo virtuale* passa dal menu *Fatturazione elettronica* al menu *Contabilità*.
- Il seed di base e *Aggiorna da tabelle base* aggiungono piano dei conti, causali e registri IVA alle aziende
esistenti.
## [0.6.0] - 2026-11-12
M6 — Acquisti e Magazzino. Il ciclo passivo dall'ordine al fornitore alla fattura protocollata, le fatture
elettroniche ricevute importate in bozza, le autofatture con la loro scadenza e un magazzino che si aggiorna da solo
con i documenti: giacenze per deposito, costo medio, inventario, riordino e valorizzazione.
### Added
- Movimenti di magazzino dai documenti (#59, ADR 0035): alla conferma DDT, fatture immediate e accompagnatorie, note,
DDT e fatture fornitore, note di credito fornitore e movimenti `MM` scrivono i loro movimenti nella stessa
transazione (`inventory_entries`, `inventory_entry_lines`); l'annullamento li toglie. La causale del tipo documento
decide carico, scarico o trasferimento; la fattura di un DDT non muove di nuovo la merce, la nota di credito la
muove all'inverso. Tabella `item_balances` con giacenza per deposito, impegnato (ordini clienti) e ordinato
(ordini fornitore).
- Costo medio ponderato per articolo ricalcolato dalla storia dei movimenti a ogni modifica, anche per documenti con
data passata; ultimo costo e date di ultimo carico e scarico; il prezzo della fattura fornitore corregge il costo
dei carichi che fattura.
- Documenti del ciclo passivo nelle maschere dei documenti (#55, #56, #58): ordini fornitori, ricevimenti merce (DDT
fornitore con il numero e la data del fornitore), fatture e note di credito fornitore con **protocollo** IVA alla
conferma e rifiuto del doppio numero del fornitore nello stesso anno, autofatture e movimenti di magazzino con
causale e depositi. Menu *Acquisti* e *Magazzino*.
- Controllo dei prezzi: sulla fattura fornitore un avviso elenca le righe con un prezzo diverso dall'ordine o dal
ricevimento e la differenza totale.
- Autofatture e integrazioni: il pacchetto italiano (`SelfInvoiceRulesIt`) riconosce dalla fattura del fornitore
l'integrazione dovuta (TD16, TD17, TD18, TD19, TD28) e la scadenza; la fattura lo mostra con **Crea autofattura**,
che prepara la bozza con l'aliquota ordinaria; *Acquisti → Autofatture* elenca le integrazioni da emettere. Tipi
`AF20`-`AF29` nelle tabelle di base.
- Lettura delle fatture elettroniche ricevute (#57): `FatturaPaReader` (FPR12, FPA12, FSM10, lotti, allegati) e
lettore CMS/CAdES dei file `.p7m` con verifica dell'impronta e della firma, scritti in casa.
- Import delle fatture passive (#57): *Acquisti → Importa fatture* legge XML, P7M e ZIP, trova o crea il fornitore,
segnala doppioni, tipi non d'acquisto, totali diversi e firme non verificate, e registra in bozza fatture (TD01,
TD02, TD03, TD05, TD06, TD24-TD27) e note di credito (TD04, TD08) con articoli abbinati per codice del fornitore,
EAN e codice, codice IVA per aliquota e natura, sconti di riga e file allegato. Le regole TD stanno nel pacchetto
fiscale (`IncomingInvoiceRulesIt`).
- Giacenze e disponibilità (#60): indicatori, filtri per deposito, categoria e stato (*Disponibile*, *Da riordinare*,
*Sottoscorta*, *Esaurito*), movimenti di un articolo con saldo progressivo.
- Inventario fisico (#60): apertura per deposito, data e categoria con la giacenza contabile congelata, conteggi
scritti o importati dal file del lettore, rettifiche `INVP` e `INVN` alla data del conteggio; tabelle `stock_takes`
e `stock_take_lines`.
- Proposta di riordino (#60): articoli sotto il punto di riordino o la scorta minima, quantità dal lotto o dalla
soglia con il minimo d'ordine del fornitore, fornitore preferito con prezzo e arrivo previsto, ordini fornitore in
bozza uno per fornitore.
- Valorizzazione a data con costo medio, ultimo costo o costo standard e classi ABC; ricostruzione del magazzino da
interfaccia con avanzamento e come job di sistema `inventory.rebuild` ogni domenica alle 2:15.
- Widget *Sottoscorta* della dashboard con i dati veri.
- Dati di esempio di acquisti e magazzino (#61): esistenze iniziali, ordini ricevuti per intero e in parte, fatture
con una differenza di prezzo e una integrazione AF18 da emettere, un inventario in conteggio.
- ADR 0035; pagine wiki *Acquisti* e *Magazzino* complete con le schermate, guida all'uso aggiornata.
### Changed
- Import *Giacenze iniziali*: non è più solo verifica, scrive e conferma un movimento `APE` per deposito.
- I documenti confermati senza numero interno (DDT fornitore) si presentano come *Senza numero* invece di *Bozza*.
- *Tipi documento*: fattura immediata, fattura e nota di credito fornitore ricevono la causale di magazzino (`SCA`,
`CAR`, `RESF`); la migrazione la assegna anche nelle aziende esistenti dove manca. I tipi `AF20`-`AF29` mancanti si
aggiungono con *Aggiorna da tabelle base* o `scripts/seed.sh --base`.
## [0.5.0] - 2026-11-12
M5 — Motore documenti e Vendite. Un solo motore per tutti i documenti, con numerazione, totali, scadenze e
collegamenti riga per riga, e le maschere del ciclo attivo: dal preventivo alla fattura stampata e inviata per
e-mail, con un anno di vendite nei dati di esempio e una guida all'uso nella wiki.
### Added
- Motore documenti (#47, ADR 0032): un solo motore per vendite, acquisti e magazzino. Ogni tipo documento ha un
**genere** (17: preventivo, ordine cliente, DDT, fatture immediate, accompagnatorie, differite e di acconto, note
di credito e di debito, parcella, pro forma, autofattura, ordine fornitore, DDT fornitore, fattura e nota di credito
fornitore, movimento di magazzino) che ne decide famiglia, ciclo di vita, effetti, righe ammesse, documenti evadibili
e permessi. Tabelle `sale_quotations`, `sale_orders`, `sale_documents`, `purchase_orders`, `purchase_documents`,
`inventory_documents` con le righe e `document_links`.
- Stati e azioni ammesse per stato (`DocumentStateMachine`): ciclo *documento* (bozza, confermato, evaso in parte,
evaso, chiuso, annullato), *fattura* (bozza, emessa, XML generato, inviata, consegnata, scartata, non consegnata,
annullata) e *semplice*; fattura emessa immutabile, annullamento con motivo solo prima dell'invio allo SDI.
- Numerazione alla conferma dentro la transazione e sotto il lock del numeratore (advisory lock su PostgreSQL, lock di
scrittura su SQLite): nessun numero doppio, un rollback restituisce il numero, controllo della data fuori sequenza
sui numeratori senza buchi, numeratore dell'anno nuovo creato da solo, elenco dei numeri mancanti.
- Evasione riga per riga: copia e trasformazione dei documenti con le quantità residue, collegamenti registrati alla
conferma e tolti all'annullamento, stato evaso/evaso in parte calcolato dalle righe, chiusura e riapertura del
residuo. Servizio generico `DocumentService<THeader, TLine>` per famiglia e `DocumentCopyService`.
- Totali dei documenti (#48, ADR 0033): importo di riga con sconti a cascata, spese e righe di sconto, sconto di
piede sulle merci, prezzi IVA compresa scorporati per aliquota, castelletto IVA per codice con imposta sul totale del
gruppo, esigibilità (immediata, differita, split payment), bollo sopra 77,47 euro di operazioni senza IVA (addebitato
al cliente o no), cassa previdenza con la sua IVA, ritenuta d'acconto (anche sul 50% o 20% per gli agenti), ENASARCO,
netto a pagare. Scadenze dalle condizioni di pagamento con fine mese, giorno fisso, mesi esclusi del cliente, IVA
sulla prima rata e arrotondamento sull'ultima. Tabelle `document_tax_summaries` e `document_installments`,
ricalcolate a ogni salvataggio.
- Copia di più documenti della stessa controparte in uno solo (`MergeAsync`), con una riga di riferimento per ognuno:
la base della fatturazione differita. Le note di credito e di debito ricordano la fattura che correggono.
- Maschere delle vendite (#49, #50): radar di preventivi, ordini, DDT, fatture e note con ricerca, filtri per tipo,
stato e anno; un'unica maschera documento con intestazione, righe (articolo con F4, sconti a cascata, righe
descrittive, di spesa e di sconto), Testata, Trasporto per DDT e fatture accompagnatorie, Totali, Scadenze, Note,
Allegati, Collegamenti e Storico; azioni Conferma, Emetti, Duplica, Chiudi, Riapri, Annulla con motivo, *Segna come
rifiutato* per i preventivi e **Crea …** con la scelta delle righe e delle quantità residue.
- Fatturazione differita guidata (#51): DDT confermati e non fatturati del periodo, per tutti i clienti o uno, una
fattura differita TD24 per cliente o per DDT, in bozza o già emessa, con i riferimenti ai DDT nelle righe.
- Stampa dei documenti (#52, ADR 0034): anteprima di stampa A4 e PDF disegnati dallo stesso modello (dati
dell'azienda e logo, controparte, campi, righe, riepilogo IVA, scadenze, totali, trasporto con le firme, diciture e
filigrane), generatore *Stampa del documento in PDF* con versioni negli allegati, documento segnato come stampato.
- Invio per e-mail (#52, ADR 0034): destinatari, oggetto e testo proposti dal modello con i campi `{{Numero}}`,
`{{Cliente}}`…, PDF allegato e salvato come nuova versione, coda in background con tre tentativi, client SMTP
scritto in casa (STARTTLS, TLS, AUTH PLAIN e LOGIN) configurato da `KHAEMHAT_SMTP_*`, esito nel log *E-mail/PEC*.
- Log, sezione *Documenti* (#53): conferme ed emissioni con il numero, chiusure, riaperture, annullamenti ed
eliminazioni delle bozze.
- Dati di esempio (#53): profilo dell'azienda demo e un anno di vendite costruite con il motore (6 preventivi, 4
ordini, 5 DDT, 8 fatture e pro forma, 1 nota di credito) in tutti gli stati, idempotenti.
- Wiki: pagina [Guida all'uso](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/wiki/Guida-utente) con il percorso
completo e le schermate; [Vendite](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/wiki/Vendite) riscritta con
le schermate reali; schermate dell'accesso in *Primi passi*.
### Changed
- `README.md` è ora la guida di installazione per chi sviluppa (prerequisiti, avvio, test, migrazioni, immagine).
- L'emissione di una fattura o di una nota richiede il codice IVA su ogni riga (non descrittiva).
- *Tipi documento*: nuovo campo obbligatorio **Genere** (i tipi di base lo ricevono dalla migrazione); *Numeratori*:
nuovo campo **Data dell'ultimo numero**.
- *Clienti*, condizioni di vendita: **mesi esclusi** (due mesi senza scadenze e il giorno del mese dopo in cui slittano).
### Fixed
- `scripts/run-dev.sh` sotto Git Bash su Windows scriveva i dati in una cartella `b` sul disco invece che in
`.data/dev`.
## [0.4.0] - 2026-11-12
M4 — Tabelle, anagrafiche, articoli. Il pacchetto fiscale italiano, il profilo e le tabelle dell'azienda con i dati
+162 -39
View File
@@ -5,72 +5,195 @@
# Khaemhat
**Gestionale ERP + CRM per piccole e medie imprese italiane**, scritto da zero in C# 14 su .NET 10 con interfaccia
Blazor Server, PostgreSQL (o SQLite per demo e test) e **nessuna libreria esterna**. Si installa **solo con Docker**:
l'unico artefatto distribuito è l'immagine nel registro pacchetti di Gitea.
Blazor Server, PostgreSQL (o SQLite per demo e test) e **nessuna libreria esterna**. Si distribuisce **solo come
immagine Docker** nel registro pacchetti di Gitea.
> **Stato:** sviluppo avviato. M0 (struttura, immagine Docker, CI) consegna la versione 0.0.1 con una pagina
> "in costruzione"; le funzioni arrivano milestone dopo milestone. Vedi [`docs/STATUS.md`](docs/STATUS.md) e la
Questo file è la **guida di installazione per chi sviluppa**: come preparare il computer, compilare, avviare,
provare e pubblicare. Chi **usa** il gestionale parte dalla
[Guida all'uso](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/wiki/Guida-utente) nella wiki; chi lo **installa**
su un server da [Installazione Docker](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/wiki/Installazione-Docker)
o [Installazione Unraid](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/wiki/Installazione-Unraid).
> **Stato:** sviluppo in corso, versioni 0.x. Ultima milestone chiusa: **M5 — Motore documenti e Vendite** (0.5.0).
> Punto di ripresa in [`docs/STATUS.md`](docs/STATUS.md), piano in
> [Roadmap](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/wiki/Roadmap).
Il nome viene da Khaemhat (Mahu), scriba reale e sovrintendente al doppio granaio dell'Alto e del Basso Egitto sotto
Amenhotep III: un contabile e un magazziniere dell'antichità. Vedi
[Origine del nome](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/wiki/Origine-del-nome).
## 1. Prerequisiti
## Cosa farà
| Strumento | Versione | A cosa serve |
|---|---|---|
| **.NET SDK** | 10.0.100 o successiva della stessa *feature band* (vedi [`global.json`](global.json)) | compilare, provare, avviare |
| **Git** | qualunque recente | il repository; su Windows anche **Git Bash**, che esegue gli script `scripts/*.sh` |
| **Docker** | facoltativo | costruire e provare l'immagine; PostgreSQL e Redis per i test sui motori reali |
| **PostgreSQL** | 16 o 17, facoltativo | i test di integrazione sul motore di produzione (`KHAEMHAT_TEST_PG`) |
- Anagrafiche, articoli, listini, tabelle; vendite e acquisti con motore documenti unico; magazzino.
- Contabilità generale, IVA, F24, LIPE, ritenute, bollo, cespiti, Intrastat, chiusura e bilancio CEE.
- Scadenzario, incassi e pagamenti, RiBa/SDD/SEPA, riconciliazione bancaria, solleciti.
- Fatturazione elettronica FatturaPA con canali SDI (PEC integrata, SdICoop, intermediari).
- CRM (lead, pipeline, attività, campagne, ticket), automazioni, API REST e server MCP.
- Più aziende sulla stessa istanza (un database di sistema + un database per azienda), moduli attivabili con
licenza, temi chiaro/scuro, dashboard a widget.
Non servono Node.js, npm, bundler, IDE particolari né pacchetti NuGet oltre a quelli ammessi: un editor qualunque
va bene (Visual Studio, Rider, VS Code con C# Dev Kit). Lingua dei messaggi del compilatore: per avere gli errori in
inglese, `DOTNET_CLI_UI_LANGUAGE=en`.
## Installazione
## 2. Clonare
```bash
docker pull gitea.encke-hake.ts.net/balbosoft/khaemhat:<versione>
git clone https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat.git
```
- Qualunque host Docker: [`deploy/docker-compose.yml`](deploy/docker-compose.yml) (con PostgreSQL) e
[`deploy/.env.example`](deploy/.env.example); per una prova veloce
[`deploy/docker-compose.sqlite.yml`](deploy/docker-compose.sqlite.yml).
- Unraid: template [`deploy/unraid/khaemhat.xml`](deploy/unraid/khaemhat.xml) o
[`deploy/docker-compose.unraid.yml`](deploy/docker-compose.unraid.yml) con [`deploy/.env.example`](deploy/.env.example).
- Guide: [Installazione Unraid](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/wiki/Installazione-Unraid) ·
[Installazione Docker](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/wiki/Installazione-Docker) ·
[Primi passi](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/wiki/Primi-passi).
In rete locale anche `http://192.168.30.23:3000/BalboSoft/Khaemhat.git` o, con una chiave SSH,
`ssh://git@192.168.30.23:2222/BalboSoft/Khaemhat.git`. Il ramo principale è `main`; si lavora su rami
`feat/<n>-descrizione`, `fix/…`, `docs/…` (vedi [`docs/DEVELOPMENT.md`](docs/DEVELOPMENT.md)).
## Sviluppo
## 3. Com'è fatto il repository
Serve l'SDK .NET 10 (`global.json`); Docker solo per costruire e provare l'immagine.
| Cartella | Contenuto |
|---|---|
| `src/Khaemhat.Core` | entità, regole, macchine a stati dei documenti, nessuna dipendenza |
| `src/Khaemhat.Data`, `.Data.Sqlite`, `.Data.PostgreSql` | micro-ORM, migrazioni, provider dei due motori |
| `src/Khaemhat.Application` | servizi applicativi: sicurezza, tabelle, anagrafiche, motore documenti, stampe, seed |
| `src/Khaemhat.Infrastructure` | file (PDF, fogli di calcolo, archivi), posta SMTP, cache, licenze, sicurezza: scritti in casa |
| `src/Khaemhat.Fiscal.Abstractions`, `.Fiscal.Italy` | il pacchetto paese: tutto ciò che è italiano |
| `src/Khaemhat.Web` | host Blazor Server, componenti, pagine, risorse dei testi in `Resources/it-IT/*.json` |
| `tests/*` | MSTest, un progetto per strato |
| `tools/*` | strumenti di sviluppo: licenze (`LicenseTool`), comuni e CAP (`PlacesTool`), modello dati (`DataModelTool`) |
| `docker/`, `deploy/` | Dockerfile ed entrypoint; compose, `.env.example`, template Unraid |
| `scripts/` | build, test, avvio, seed, migrazioni, pubblicazione |
| `docs/` | specifica, ADR, architettura, mockup e la wiki (`docs/wiki/`) |
## 4. Compilare
```bash
scripts/build.sh
```
Controlla l'allowlist dei pacchetti (`scripts/check-packages.sh` su `Directory.Packages.props`) e compila
`Khaemhat.sln` in Release con **warning come errori** e gli analyzer di piattaforma. L'equivalente a mano:
```bash
dotnet build Khaemhat.sln -c Release -warnaserror
```
## 5. Avviare in locale
```bash
scripts/run-dev.sh
```
Avvia Khaemhat su <http://localhost:5080> con SQLite in `.data/dev` (ignorata da git) e queste impostazioni di
sviluppo, ognuna sovrascrivibile esportando la variabile prima di lanciare lo script:
| Variabile | Valore di sviluppo |
|---|---|
| `KHAEMHAT_DATA_DIR`, `KHAEMHAT_SYSTEM_DB` | `.data/dev`, `sqlite://…/.data/dev/system.db` |
| `KHAEMHAT_SECRET_KEY` | una chiave fissa **solo per lo sviluppo** |
| `KHAEMHAT_SUPERUSER`, `KHAEMHAT_SUPERUSER_PASSWORD` | `root` e la password iniziale scritta nello script |
| `KHAEMHAT_COMPANY_CODE`, `KHAEMHAT_COMPANY_NAME` | `DEMO`, *Khaemhat Demo S.r.l.* |
| `KHAEMHAT_LICENSE_MODE` | `test`: tutti i moduli attivi con i codici di prova |
| `KHAEMHAT_SEED_DEMO` | `true`: la prima azienda nasce con i dati di esempio (anagrafiche, articoli, un anno di vendite) |
Al primo accesso Khaemhat chiede di cambiare la password e di collegare un'app di autenticazione (il super utente
ha la verifica in due passaggi obbligatoria): conserva la chiave e i codici di recupero. Per ripartire da zero ferma
il server e cancella `.data/dev`.
Altre cose utili in sviluppo:
- **Invio di e-mail**: senza `KHAEMHAT_SMTP_HOST` e `KHAEMHAT_SMTP_FROM` l'invio è spento. Per provarlo serve un
server SMTP di prova sulla tua macchina, ad esempio
`KHAEMHAT_SMTP_HOST=127.0.0.1 KHAEMHAT_SMTP_PORT=2525 KHAEMHAT_SMTP_SECURITY=NONE KHAEMHAT_SMTP_FROM=ufficio@example.com scripts/run-dev.sh`;
l'esito di ogni invio è nel log, sezione *E-mail/PEC*.
- **Dati di base e di esempio** su un database esistente: `scripts/seed.sh --base` oppure `scripts/seed.sh --demo`
(aggiungono solo ciò che manca; meglio con il server fermo).
- **Catalogo dei componenti**: <http://localhost:5080/sviluppo/componenti> mostra i mattoni dell'interfaccia.
- **Tutte le variabili** `KHAEMHAT_*` sono in
[Installazione Docker](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/wiki/Installazione-Docker) e
[`docs/DEPLOY.md`](docs/DEPLOY.md). Una configurazione non valida ferma l'avvio con l'elenco degli errori.
Prima di ricompilare ferma il server: su Windows l'eseguibile in esecuzione blocca le DLL e la build ritenta la copia
(avviso MSB3026) fino a fallire.
## 6. Provare
```bash
scripts/test.sh
scripts/test.sh --filter "FullyQualifiedName~Documents"
```
Esegue l'allowlist e tutti i test in Release. SQLite è sempre provato; i test che avviano
l'applicazione intera usano un'istanza vera su una porta libera. I test sul **PostgreSQL** reale partono quando
`KHAEMHAT_TEST_PG` indica un ruolo con `CREATEDB` (ogni test crea e cancella il proprio database):
```bash
docker run -d --name khaemhat-pg-test -e POSTGRES_PASSWORD=prova -p 55432:5432 postgres:17
KHAEMHAT_TEST_PG="postgres://postgres:prova@localhost:55432/postgres" scripts/test.sh
```
Senza la variabile quei test risultano *saltati*. In CI (`.gitea/workflows/ci.yml`) i test girano su ogni pull request verso `main`; il job PostgreSQL
(16 e 17) sui tag e all'avvio manuale.
Regole che i test fanno rispettare: nessun pacchetto fuori allowlist, dipendenze tra progetti nel verso giusto,
nessun testo italiano scritto nei componenti (vanno nelle risorse `Resources/it-IT/*.json`), chiavi di testo
esistenti, sezione del modello dati aggiornata.
## 7. Database e migrazioni
```bash
scripts/new-migration.sh company create_sales_documents # nuova migrazione numerata
scripts/gen-datamodel.sh # rigenera la parte generata di docs/DATA-MODEL.md
scripts/gen-datamodel.sh --check # solo verifica (la fa anche un test)
```
Le migrazioni si applicano da sole all'avvio, al database di sistema e a quello di ogni azienda. Il codice non deve
dipendere dal motore: ogni query passa dal micro-ORM e gira identica su SQLite e PostgreSQL.
## 8. Immagine Docker
```bash
scripts/build.sh # allowlist dei pacchetti + build con warning come errori
scripts/test.sh # tutti i test (PostgreSQL con KHAEMHAT_TEST_PG, Redis con KHAEMHAT_TEST_REDIS)
scripts/run-dev.sh # avvio locale su http://localhost:5080 con SQLite in .data/dev
docker build -f docker/Dockerfile -t khaemhat:dev .
docker compose -f deploy/docker-compose.sqlite.yml up # prova veloce con SQLite
```
Processo, rami e Definition of Done in [`docs/DEVELOPMENT.md`](docs/DEVELOPMENT.md).
L'immagine pubblicata è `gitea.encke-hake.ts.net/balbosoft/khaemhat:<versione>` (e `:latest`, mai in produzione). La
costruisce `.gitea/workflows/release.yml` quando si spinge un tag `vX.Y.Z` (segreto `REGISTRY_TOKEN` con
`write:package`), che crea anche la release Gitea con le note del [`CHANGELOG.md`](CHANGELOG.md). Se il runner non è
disponibile:
## Documentazione
```bash
GITEA_TOKEN=… scripts/publish-image.sh v0.5.0
```
Non si producono installer, eseguibili o pacchetti `.msi/.exe/.deb`: l'unico artefatto è l'immagine
([ADR 0010](docs/adr/0010-solo-docker-nessun-installer.md)). Le versioni restano **0.x** finché il prodotto è in
sviluppo.
## 9. Documentazione e wiki
La wiki è in `docs/wiki/` e si aggiorna nella stessa unità di lavoro del codice: una funzione senza documentazione
non è finita. Il workflow `wiki.yml` la pubblica nel wiki Gitea a ogni push su `main` che la tocca; a mano:
`scripts/publish-wiki.sh`. Le schermate stanno in `docs/wiki/img/` e si fanno sull'applicazione vera con i dati di
esempio. La stessa wiki è inclusa nell'immagine e si apre con `F1` dentro il gestionale.
| Cosa | Dove |
|---|---|
| Wiki (guida utente e amministratore) | <https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/wiki> (sorgente in [`docs/wiki/`](docs/wiki/)) |
| Specifica normativa | [`docs/SPEC.md`](docs/SPEC.md) |
| Regole operative ed emendamenti | [`CLAUDE.md`](CLAUDE.md) |
| Processo di sviluppo | [`docs/DEVELOPMENT.md`](docs/DEVELOPMENT.md) |
| Processo, rami, Definition of Done | [`docs/DEVELOPMENT.md`](docs/DEVELOPMENT.md) |
| Architettura, dati, moduli, API, MCP | [`docs/ARCHITECTURE.md`](docs/ARCHITECTURE.md), [`docs/DATA-MODEL.md`](docs/DATA-MODEL.md), [`docs/MODULES.md`](docs/MODULES.md), [`docs/API.md`](docs/API.md), [`docs/MCP.md`](docs/MCP.md) |
| Installazione e sicurezza | [`docs/DEPLOY.md`](docs/DEPLOY.md), [`docs/SECURITY.md`](docs/SECURITY.md) |
| Decisioni architetturali | [`docs/adr/`](docs/adr/) |
| Mockup | [`docs/mockups/`](docs/mockups/README.md) |
| Mockup (specifica visiva) | [`docs/mockups/`](docs/mockups/README.md) |
| Novità | [`CHANGELOG.md`](CHANGELOG.md) |
| Wiki pubblicata | <https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/wiki> |
## Pianificazione
## 10. Regole del codice in breve
Il lavoro è organizzato in [issue](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/issues) raggruppate per
- C# 14 su .NET 10, `Nullable` attivo, warning come errori, `.editorconfig`; JavaScript solo come interop minimo in
`wwwroot/js`.
- **Nessuna libreria esterna**: framework Microsoft, `Npgsql`, `Microsoft.Data.Sqlite` e, nei test, MSTest.
- Codice, commenti e commit in **inglese**; interfaccia in **italiano** dalle risorse.
- Tutto ciò che è fiscale italiano sta in `Khaemhat.Fiscal.Italy`.
- Commit *Conventional Commits* che dicono cosa cambia e perché e citano l'issue (`#n`); pull request verso `main`
con `Closes #n`.
Il lavoro è organizzato in [issue](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/issues) per
[milestone](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/milestones) (M0-M14) e nei
[progetti](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/projects) *Khaemhat 1.0 — Sviluppo* e
*Khaemhat 1.1+ — Fase 2*.
[progetti](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/projects).
Il nome viene da Khaemhat (Mahu), scriba reale e sovrintendente al doppio granaio dell'Alto e del Basso Egitto sotto
Amenhotep III: vedi [Origine del nome](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/wiki/Origine-del-nome).
+1372
View File
File diff suppressed because it is too large. Load diff
+43 -13
View File
@@ -2,19 +2,24 @@
> Punto di ripresa per ogni sessione. Aggiornare a fine sessione.
**Ultimo aggiornamento:** 2026-11-12
**Milestone corrente:** M4 — Tabelle, anagrafiche, articoli: chiusa sul ramo `feat/37-tabelle-anagrafiche` (#46),
in attesa del merge in `main` con l'approvazione del titolare; poi tag `v0.4.0`, immagine e release.
**Prossimo passo:** dopo il merge, M5 — Motore documenti e Vendite (#47-#54). #35 (PNG ad alta risoluzione) resta
aperta e non blocca; #45 resta aperta solo per le banche ABI/CAB (manca una fonte con licenza compatibile).
Da recuperare: profilo dell'azienda demo (indirizzo, partita IVA) prima dei documenti di M5; misure di riferimento su PostgreSQL in `docs/DATA-MODEL.md` §6.1; indicatore di robustezza della
password (mockup 003); schede *Layout salvati* e *Notifiche* (con le e-mail, M5) del profilo; rinomina e
filtro predefinito nei radar.
**Ultimo aggiornamento:** 2026-11-13
**Milestone corrente:** M8 — Scadenzario e tesoreria (issue #69-#73), da iniziare. M7 chiusa: PR in `main`, tag
`v0.7.0`, immagine e release.
**Prossimo passo:** M8 dall'issue #69. #35 (PNG ad alta risoluzione) resta aperta e non blocca; #45 resta aperta solo
per le banche ABI/CAB (manca una fonte con licenza compatibile).
Da recuperare: misure di riferimento su PostgreSQL in `docs/DATA-MODEL.md` §6.1; indicatore di robustezza della
password (mockup 003); schede *Layout salvati* e *Notifiche* del profilo; rinomina e filtro predefinito nei radar;
logo PNG nel PDF (oggi solo JPEG, ADR 0034); coda della posta persistente e modelli e-mail per azienda (M12).
Da M6: schermata dell'import fatture con file caricati (serve un caricamento via CDP); nei movimenti di un articolo il
numero del fornitore al posto di *DDT fornitore* senza numero; FIFO e LIFO a lotti (dopo la 1.0).
Da M7: schermata del bollo virtuale (la demo non ha fatture esenti sopra 77,47 euro); import di causali e voci di
bilancio dal file `khaemhat-coa.json`; scritture delle rimanenze e libro inventari (M10); chiusura delle partite con
incassi e pagamenti e IVA per cassa (M8).
## Fatto
- Specifica normativa in `docs/SPEC.md`; `CLAUDE.md` con emendamenti E1-E7.
- ADR 0001-0031.
- ADR 0001-0037.
- Mockup in `docs/mockups/` (22 in alta risoluzione + galleria, 88 miniature, `mockup.css`, indice).
- Icone in `assets/`; deploy in `deploy/` (compose Unraid, `.env.example`, template Unraid).
- Documentazione tecnica: `ARCHITECTURE.md`, `DATA-MODEL.md` (provvisorio, sarà generato), `MODULES.md`, `API.md`,
@@ -50,7 +55,7 @@ filtro predefinito nei radar.
cestino e storico; anteprima di stampa A4; catalogo dei componenti e documento di prova per gli sviluppatori;
primi screenshot reali in `docs/wiki/img/`; ADR 0020-0024. Test: 368 verdi in locale, 21 di PostgreSQL saltati;
immagine costruita in locale e avviata da zero con SQLite.
- **M4 (chiusa, `v0.4.0`):** pacchetto fiscale `IT 2026.3` (codici IVA, nature, code list FatturaPA, motore IVA,
- **M4 (chiusa, `v0.4.0`, PR #121):** pacchetto fiscale `IT 2026.3` (codici IVA, nature, code list FatturaPA, motore IVA,
calendario, ritenute, F24; ADR 0025); validatori e `ViesClient`; 26 tabelle azienda con un'unica maschera, profilo
azienda, esercizi e cambi BCE (ADR 0026); dati di base con province e comuni ISTAT e CAP GeoNames (ADR 0028) e
`scripts/seed.sh --base|--demo`; codici automatici e compilazione automatica (ADR 0027); clienti, fornitori e
@@ -58,6 +63,31 @@ filtro predefinito nei radar.
aggiornamento massivo (ADR 0030); import/export guidato CSV/XLSX/JSON con tracciato del piano dei conti (ADR 0031);
21 anagrafiche e 120 articoli di esempio; screenshot reali nella wiki. Test: 631 verdi in locale, 21 di PostgreSQL
saltati; immagine costruita in locale e avviata da zero con SQLite e dati di esempio.
- **M5 (chiusa, `v0.5.0`, PR #124):** motore documenti (#47, ADR 0032): generi e definizioni dei tipi documento, sei famiglie
di tabelle con le righe e `document_links`, stati con azioni ammesse, numerazione atomica alla conferma (provata in
concorrenza su SQLite e su PostgreSQL 18 in locale), copia e trasformazione con evasione riga per riga; totali,
castelletto IVA, bollo, ritenute, cassa e scadenze (#48, ADR 0033); radar e maschera dei documenti di vendita con
*Crea …* (#49, #50); fatturazione differita guidata (#51); anteprima di stampa e PDF dallo stesso modello, invio per
e-mail con SMTP e coda scritti in casa (#52, ADR 0034); log *Documenti*; profilo e un anno di vendite di esempio;
wiki con la *Guida all'uso* e le schermate reali, README come guida per sviluppatori (#53). Test: 660 verdi in
locale, 23 di PostgreSQL saltati (girano in CI).
- **M6 (chiusa, `v0.6.0`, PR #125):** movimenti di magazzino dai documenti nella
stessa transazione, costo medio ponderato ricalcolato dalla storia, impegnato e ordinato, correzione del costo dalla
fattura fornitore (#59, ADR 0035); ordini fornitori, ricevimenti, fatture e note di credito fornitore con protocollo,
doppioni rifiutati, controllo dei prezzi, autofatture TD16-TD29 consigliate dal pacchetto italiano con scadenza
(#55, #56, #58); lettura FatturaPA e `.p7m` (CMS scritto in casa) e import delle fatture passive in bozza (#57);
giacenze, movimenti di un articolo, inventario fisico, proposta di riordino, valorizzazione con classi ABC,
ricostruzione anche come job settimanale, widget *Sottoscorta* (#60); giacenze iniziali da file con movimento `APE`;
acquisti e magazzino nei dati di esempio, wiki *Acquisti* e *Magazzino* con le schermate, guida all'uso (#61).
Test: 709 verdi in locale, 23 di PostgreSQL saltati (girano in CI).
- **M7 (chiusa, `v0.7.0`):** piano dei conti a tre livelli con il modello *PMI standard* di 237 conti, causali con righe
proposte (#62, ADR 0036); prima nota con bozze, registrazioni, definitive con numero del libro giornale e storni,
ricorrenti con job giornaliero (#63); contabilizzazione automatica di fatture, note, parcelle e autofatture nella
transazione del documento con righe IVA, partite e ritenute (#64, ADR 0037); registri IVA con stampa definitiva,
liquidazione mensile o trimestrale con pro rata, interessi, minimo, acconto, F24 e LIPE (#65); ritenute operate e
subite, dati CU, bollo virtuale con soglie, prospetto F24 con pagamento (#66); partitari, mastrini, bilancio di
verifica, libro giornale (#67); contabilità nei dati di esempio con la liquidazione verificata a mano in un test,
wiki *Contabilità*, *IVA* e *Fiscalità italiana* con le schermate (#68). Test: 754 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,
@@ -104,12 +134,12 @@ Emersi durante la stesura della documentazione. Si decidono con un ADR quando si
### Contabilità, IVA, e-fattura, CRM (dalla stesura delle pagine funzionali)
12. Scadenza IVA di settembre: mockup 046 la mette al 16/10/2026, mockup 047 nell'F24 del 16/11/2026 (corretto: 16/10 per i mensili).
12. Scadenza IVA di settembre: mockup 046 la mette al 16/10/2026, mockup 047 nell'F24 del 16/11/2026 (corretto: 16/10 per i mensili). **Deciso in M7: ADR 0037, il 16 del mese successivo.**
13. Bollo sulle cessioni intracomunitarie: il mockup 060 lo addebita su N3.2, ma cessioni intra-UE ed esportazioni ne sono esenti; la regola del bollo va legata al codice IVA con esclusioni.
14. Funzioni di fase 2 nelle schermate di M7: ventilazione dei corrispettivi (046) e IVA per cassa completa sono in M14 per §20.
14. Funzioni di fase 2 nelle schermate di M7: ventilazione dei corrispettivi (046) e IVA per cassa completa sono in M14 per §20. **Confermato in M7: non implementate.**
15. Moduli ambigui: bollo e dichiarazioni d'intento sotto ACCT e EINV (§8.1); export commercialista sotto ACCT e REPORT; Intrastat e LIPE nel menu e-fattura nei mockup; §10.2 senza voce Intrastat.
16. Stato "Provvisorio" dell'esercizio nel mockup 052, non previsto da SPEC (aperto / in chiusura / chiuso).
17. Codici conto incoerenti tra mockup (fornitori 05.02.001 in 040/043, 02.03.001 in 042).
17. Codici conto incoerenti tra mockup (fornitori 05.02.001 in 040/043, 02.03.001 in 042). **Deciso in M7: ADR 0036, piano PMI standard (clienti 05.01.001, fornitori 14.01.001).**
18. Regola R-005 del mockup 072 "riapre in bozza" una fattura scartata: contrasta con l'immutabilità della fattura emessa.
19. Codice campagne `CMP-…` (068) non presente nelle maschere di §11.12.
20. Codice di scarto 00327 citato in §18 senza descrizione.
+65
View File
@@ -0,0 +1,65 @@
# ADR 0032 - Motore documenti: comportamento per genere, tabelle per famiglia, numerazione alla conferma
- **Stato:** accettata
- **Data:** 2026-11-12
- **Modifica:** SPEC §11.3; milestone M5, issue #47
## Contesto
SPEC §11.3 vuole un solo motore per tutti i documenti (vendita, acquisto, magazzino), guidato da definizioni
dichiarative, con tabelle per famiglia (`sale_quotations`, `sale_orders`, `sale_documents`, `purchase_orders`,
`purchase_documents`, `inventory_documents`, ognuna con le righe), `document_links` per l'evasione, gli stati
`Draft → Confirmed → (PartiallyFulfilled | Fulfilled) → Closed`, `Cancelled` e per le fatture
`Draft → Issued → SdiGenerated → SdiSent → (SdiDelivered | SdiRejected | SdiNotDelivered)`, la numerazione alla
conferma con la data non anteriore all'ultimo numero del sezionale. Restavano aperti: dove sta il comportamento di un
tipo documento (la tabella `document_types` è modificabile dall'utente e il suo `kind` dice solo la famiglia di
numerazione), come si numera per anno quando il numeratore è per anno, quando nasce un legame di evasione, che cosa
fa la copia, quali tabelle servono già adesso.
## Decisione
1. **Genere e definizione.** Il comportamento sta in codice, per **genere** (`DocumentKind`: preventivo, ordine
cliente, DDT, fattura immediata, accompagnatoria, differita, di acconto, nota di credito, nota di debito, parcella,
pro forma, autofattura, ordine fornitore, DDT fornitore, fattura fornitore, nota di credito fornitore, movimento di
magazzino). `DocumentBehaviors` dà per ogni genere: famiglia (tabella), direzione, ciclo di vita, effetti
(magazzino, impegnato, ordinato, contabilità, scadenze, e-fattura), tipi di riga ammessi, generi da cui evade
(sorgenti) e permessi. La tabella `document_types` riceve la colonna `document_kind`: ogni tipo dell'utente
sceglie un genere e aggiunge numeratore, causale di magazzino, TD SDI, causale contabile, registro IVA, modello di
stampa. `DocumentDefinition` è l'unione dei due (tipo + comportamento) e si legge con `DocumentDefinitionService`.
I tipi seminati prendono il genere dalla migrazione e dal modello del pacchetto paese.
2. **Tre cicli di vita.** `DocumentStateMachine` conosce tre cicli: *ordine* (preventivi, ordini, DDT, pro forma:
bozza, confermato, evaso parzialmente, evaso, chiuso, annullato), *fattura* (fatture e autofatture di vendita:
bozza, emessa, XML generato, inviata, consegnata, scartata, non consegnata, annullata) e *semplice* (fatture
fornitore, movimenti: bozza, confermato, annullato). Per ogni stato dice le azioni ammesse; un'azione non ammessa
è rifiutata con `document.action.not-allowed`. Si modifica solo una bozza, oltre a ordini e preventivi confermati
non evasi; la fattura emessa è immutabile: si annulla con un motivo finché l'XML non è inviato (o se scartato),
altrimenti si fa una nota di credito. Gli stati di evasione non sono azioni: li calcola `FulfillmentCalculator`.
3. **Numerazione alla conferma.** `DocumentNumberingService` numera nella stessa transazione della conferma, sotto il
lock `numerator:<codice>:<anno>` (advisory lock di transazione su PostgreSQL, lock di scrittura su SQLite): un
rollback restituisce il numero, quindi non nascono buchi. Il numeratore del tipo vale per il suo codice; per
l'anno della data si usa la riga (codice, anno) e, se manca, si crea copiando formato, prefisso e sezionale
dell'ultima. Sui numeratori **senza buchi** (fatture, autofatture, protocollo acquisti) la data non può
precedere l'ultima numerata (`document_numerators.last_date`) e la conferma chiede il periodo aperto quando il
genere ha effetto contabile. `FindGapsAsync` elenca i numeri mancanti di un numeratore. Un documento numerato non
si elimina: si annulla e il numero resta.
4. **Tabelle.** Sei testate e sei tabelle di righe con le stesse colonne (classi base `DocumentHeader` e
`DocumentLine`), più `document_links` (riga destinazione → riga sorgente, quantità). Le tabelle del castelletto IVA
e delle rate arrivano con il calcolo dei totali (#48), i campi di trasporto sono già nella testata.
5. **Evasione.** Una riga copiata da un documento evadibile tiene la riga d'origine (`source_family`,
`source_line_id`). Il legame in `document_links` nasce alla **conferma** del documento destinazione e sparisce al
suo annullamento; dopo ogni cambio `FulfillmentCalculator` ricalcola la quantità evasa delle righe sorgente e lo
stato del documento sorgente (confermato, evaso parzialmente, evaso). Le righe con saldo forzato contano come
evase; un documento chiuso o annullato non cambia stato.
6. **Copia.** `DocumentCopyService` crea una bozza da un documento esistente verso lo stesso tipo (duplicazione) o un
altro della stessa direzione (trasformazione). Se il genere destinazione evade il genere sorgente si copiano le
quantità residue e le righe tengono l'origine, altrimenti si copiano le quantità intere senza legame.
7. **Servizio generico.** `DocumentService<THeader, TLine>` (uno per famiglia) espone crea, leggi, salva, conferma,
annulla, chiudi, riapri, elimina e copia; il lavoro su più famiglie (evasione, copia) passa da `DocumentEngine`, che
tratta testate e righe tramite le classi base.
## Conseguenze
- Un tipo documento nuovo dell'utente funziona senza codice se usa un genere esistente; un genere nuovo è codice.
- Gli effetti sono dichiarati ma si applicano con i moduli: magazzino in M6, contabilità in M7, scadenze in M8,
e-fattura in M8. Il calcolo dei totali e delle rate è #48, le maschere sono #49-#51.
- La numerazione concorrente è provata su SQLite e PostgreSQL (test dei dati, eseguiti su PostgreSQL 16 e 17 ai tag).
@@ -0,0 +1,55 @@
# ADR 0033 - Totali, castelletto IVA e scadenze dei documenti
- **Stato:** accettata
- **Data:** 2026-11-12
- **Modifica:** SPEC §11.3; milestone M5, issue #48
## Contesto
SPEC §11.3 chiede un `DocumentTotalsCalculator` (imponibile di riga, sconti a cascata, castelletto per codice IVA,
spese, sconto di piede, bollo, ritenuta, cassa previdenza, split payment, reverse charge, IVA per cassa) e un
`InstallmentGenerator` (fine mese, giorno fisso, percentuali, IVA sulla prima rata, arrotondamento sull'ultima), con
tabelle `_tax_summary` e `_installments` per ogni famiglia. Restavano aperti: dove si applica lo sconto di piede,
come si gestiscono i prezzi IVA compresa, che cosa entra nella base della ritenuta e della cassa, dove si salvano
castelletto e scadenze, quando si ricalcolano.
## Decisione
1. **Calcolo puro.** `DocumentTotalsCalculator` e `InstallmentGenerator` sono funzioni senza database, provate con
casi numerici di riferimento. L'arrotondamento e il bollo vengono da `ITaxEngine` del pacchetto paese.
2. **Riga.** Importo = quantità × prezzo × (1 − s1)(1 − s2)…, al centesimo con metà lontano da zero. Spese e sconti
senza quantità valgono una volta; le righe di sconto sono negative; le righe descrittive non contano.
3. **Sconto di piede** (formula come `10+5`): si applica a ogni riga di merce, non alle spese, e solo nel castelletto.
La riga conserva il suo importo, il documento registra quanto lo sconto ha tolto (`footer_discount_amount`).
4. **Castelletto** per codice IVA, con l'imposta calcolata sul totale del gruppo (come `DatiRiepilogo`). Con i
**prezzi IVA compresa** si somma il lordo del gruppo e si scorpora una volta sola. L'esigibilità è quella del
codice IVA, del documento (IVA per cassa) o *S* con lo **split payment**. Il reverse charge non ha bisogno di
regole: i codici N6.x hanno aliquota zero.
5. **Cassa previdenza, ritenuta, ENASARCO.** La base è la somma delle righe non escluse
(`withholding_excluded`, ad esempio le spese anticipate in nome del cliente), dopo lo sconto di piede. La cassa
entra nel castelletto con l'IVA indicata o con quella della prima riga imponibile; la ritenuta si calcola sulla
quota della base (100% per i professionisti, 50% o 20% per gli agenti), con la cassa se è soggetta. Ritenuta,
ENASARCO e IVA in split payment si tolgono dal **netto a pagare**, non dal totale.
6. **Bollo** sulle fatture e note di vendita quando gli importi senza IVA che lo richiedono superano la soglia del
pacchetto paese (77,47 euro): è sempre indicato; entra nel totale solo se addebitato al cliente.
7. **Scadenze** dal netto a pagare e dalle rate della condizione di pagamento; con *IVA sulla prima rata* l'IVA
effettivamente incassata va tutta sulla prima. Fine mese e giorno fisso: con fine mese il giorno fisso è del mese
successivo, senza fine mese è il primo giorno fisso non anteriore. I **mesi esclusi** stanno nelle condizioni di
vendita del cliente e spostano la scadenza a un giorno del mese successivo (10 se non indicato). Le scadenze
esistono per fatture, note, fatture fornitore e, come previsione, per preventivi, ordini e pro forma.
8. **Due tabelle condivise invece di dodici.** Castelletto e scadenze stanno in `document_tax_summaries` e
`document_installments` con la colonna `family`, come `document_links`: le righe non hanno vincoli verso una
sola tabella e il codice resta unico per tutte le famiglie. Diverge dalla lettera di §11.3 (una coppia di tabelle
per famiglia), non dalla sostanza.
9. **Quando.** Il motore ricalcola a ogni salvataggio (bozze e righe di documenti ancora aperti) e riscrive
castelletto e scadenze nella stessa transazione. Un documento emesso non cambia più, quindi i suoi totali restano
quelli dell'emissione. Lo scadenzario vero (partite, incassi) arriva con M8 e parte da queste righe.
10. **Revisioni dei preventivi.** Modificare un preventivo confermato aumenta il numero di revisione: il numero
del documento resta lo stesso.
## Conseguenze
- Le maschere mostrano castelletto, totali e scadenze ricalcolati durante la modifica con lo stesso codice del
salvataggio (anteprima senza scrittura).
- Il file FatturaPA (M9) troverà lo sconto di piede da ripartire sulle righe e il castelletto già pronto.
- Lo sconto cassa resta fuori: si gestirà con gli incassi (M8).
@@ -0,0 +1,47 @@
# ADR 0034 - Stampa e invio dei documenti
- **Stato:** accettata
- **Data:** 2026-11-12
- **Modifica:** SPEC §9.4, §12.6; milestone M5, issue #52
## Contesto
SPEC §9.4 chiede l'anteprima di stampa (mockup 025) e il PDF di ogni documento come allegato versionato; §12.6 l'invio
per e-mail con modelli, allegati ed esito nel log. Il vincolo di §1 esclude librerie esterne per PDF, posta e modelli.
Restavano aperti: come tenere uguali anteprima e PDF, dove stanno le diciture, quali immagini accetta il PDF, come si
invia la posta senza una libreria, che cosa succede se il server di posta non risponde.
## Decisione
1. **Un solo modello di stampa.** `DocumentPrintService` costruisce un `DocumentPrintModel` (intestazione dell'azienda
dal profilo, controparte, campi, righe, riepilogo IVA, scadenze, totali, trasporto, firme, diciture, filigrana) già
formattato con la cultura italiana. L'anteprima HTML (`SalesPrintPage`) e il PDF (`DocumentPdfGenerator`, sopra il
`PdfWriter` di M3) disegnano lo stesso modello: un campo nuovo compare in tutti e due.
2. **Diciture nelle risorse.** Etichette, diciture di legge (split payment, pro forma non valida ai fini fiscali,
fattura differita) e filigrane (*Bozza*, *Annullato*, *Dato dimostrativo*) stanno in `Resources/it-IT/Print.json`.
I modelli di stampa configurabili per tipo documento di §9.4 restano per M12; fino ad allora il tipo documento
sceglie solo quali blocchi compaiono (il trasporto e le firme per DDT e fatture accompagnatorie).
3. **Logo.** Nell'anteprima compare qualunque immagine del profilo; nel PDF solo un **JPEG**, perché il `PdfWriter`
incorpora i JPEG senza decodificarli (DCTDecode) e un decodificatore PNG scritto in casa non vale il costo ora.
Con un PNG il PDF esce senza logo.
4. **Il PDF è un allegato.** Il generatore `documents.pdf` è un `IFileGenerator`: *Salva come allegato* e l'invio per
e-mail creano una nuova versione, così resta la copia esatta di ciò che è uscito. Il documento registra i flag
*stampato* e *inviato* (con la sola permission di lettura, perché non cambiano il contenuto) e lo storico.
5. **SMTP scritto in casa.** `SmtpMailSender` parla SMTP su `TcpClient`/`SslStream`: EHLO, STARTTLS o TLS implicito,
AUTH PLAIN o LOGIN, un messaggio per connessione, timeout di 60 secondi. `MimeMessageWriter` scrive
`multipart/mixed` con testo e allegati in base64 e intestazioni non ASCII come *encoded word*. Configurazione da
`KHAEMHAT_SMTP_*` finché non c'è la pagina *Impostazioni* (M12).
6. **Coda in memoria.** `MailQueue` è un servizio in background con un canale limitato a 500 messaggi: tre tentativi
a 30 e 60 secondi, ogni passo nel log, sezione *E-mail/PEC*. Chi invia non aspetta il server. Un messaggio in coda
quando il processo si ferma si perde e il log lo dice; una coda persistente arriva se servirà con le automazioni
(M12).
7. **Modelli con campi.** Oggetto e testo vengono da `Print.Mail.*` con i campi `{{Documento}}`, `{{Numero}}`,
`{{Data}}`, `{{Cliente}}`, `{{Azienda}}`, `{{Totale}}` (`MailTemplateRenderer`; un campo sconosciuto resta
com'è, così l'errore si vede). L'utente li modifica prima di inviare; i modelli per azienda arrivano con M12.
## Conseguenze
- Anteprima e PDF non divergono e si provano insieme (il modello ha i suoi test).
- Nessuna dipendenza nuova; il client SMTP è provato contro un server finto in-process.
- Limiti noti: niente PNG nel PDF, niente coda persistente, niente modelli per azienda, niente PEC dedicata (arriva
con il canale SDI via PEC in M9).
@@ -0,0 +1,80 @@
# ADR 0035 - Magazzino e ciclo passivo
- **Stato:** accettata
- **Data:** 2026-11-12
- **Modifica:** SPEC §11.5, §11.6, §12.12; milestone M6, issue #55-#61
## Contesto
SPEC §11.6 chiede giacenze per deposito con impegnato, ordinato e disponibile aggiornati nella stessa transazione del
documento, costo medio ponderato (FIFO e LIFO predisposti), inventario fisico, proposta di riordino, valorizzazione a
data e una ricostruzione; §11.5 il ciclo passivo con protocollo IVA, import delle fatture elettroniche ricevute,
controllo dei prezzi rispetto all'ordine e autofatture TD16-TD29. Il motore documenti di M5 (ADR 0032) sa già quali
generi hanno effetto *Inventory*; restavano aperti: come si registra un movimento, come si calcola il costo quando i
documenti arrivano fuori ordine di data, come non contare due volte la merce di una fattura nata da un DDT, come
portare le novità nelle aziende create prima, dove stanno le regole italiane di autofatture e import.
## Decisione
1. **La causale decide, il genere filtra.** Ogni tipo documento ha una causale di magazzino (`inventory_reasons`:
carico, scarico, nessun effetto; flag *trasferimento* e *muove il valore*). `StockEffectMatrix` (in `Khaemhat.Core`)
dice quali generi la applicano (DDT, fatture immediate e accompagnatorie, note, DDT e fatture fornitore, note di
credito fornitore, movimenti `MM`) e quali hanno costi d'acquisto che muovono la media (DDT fornitore, fattura
fornitore, movimento con prezzo). Ordini clienti e fornitori non muovono la giacenza: il loro **residuo** è
l'impegnato e l'ordinato. Le causali di base sono 12 (`CAR`, `SCA`, `RESC`, `RESF`, `TRA`, `INVP`, `INVN`, `CVU`,
`CVR`, `OMA`, `AUTO`, `APE`).
2. **Movimenti come righe derivate.** `InventoryPoster` gira dentro la transazione del motore documenti: alla conferma
scrive un `inventory_entries` per documento con una riga per articolo e deposito (`inventory_entry_lines`, quantità
nell'unità base, con segno); all'annullamento o alla modifica di un documento in vigore lo riscrive da capo. Le righe
che vengono da un documento che ha già mosso la merce nello stesso verso (la fattura di un DDT) sono saltate;
la nota di credito di una fattura la muove all'inverso.
3. **Storia ricalcolata, non saldi incrementali.** Dopo ogni modifica la storia degli articoli toccati viene
ripercorsa per data e ordine di registrazione (`StockCostCalculator`): giacenza per deposito, costo medio ponderato
dell'articolo su tutti i depositi, ultimo costo, date di ultimo carico e scarico, e i risultati vanno in
`item_balances` e nella scheda articolo. Così un documento con una data passata dà lo stesso risultato di uno
inserito in ordine. Ogni carico con valore sposta la media; gli altri movimenti escono alla media del momento; con
giacenza a zero o negativa il carico successivo fissa la media. La giacenza negativa non blocca la conferma (non
si fermano le consegne), si vede nelle giacenze e nella dashboard.
4. **La fattura corregge il costo del carico.** Il prezzo di una fattura fornitore confermata sostituisce, per la quota
fatturata, il costo dei carichi dei DDT fornitore che fattura; la differenza di prezzo rispetto a ordine e ricevimento
è anche mostrata come avviso sulla fattura (`PurchaseService.PriceDifferencesAsync`), senza bloccare.
5. **Ricostruzione.** `InventoryService.RebuildAsync` cancella i movimenti e riposta tutti i documenti in vigore,
dal più vecchio e, a parità di data, i DDT prima delle fatture, poi ricalcola ogni articolo; gira a mano (con
avanzamento) e ogni domenica come job di sistema `inventory.rebuild`.
6. **Inventario come documento a sé.** `stock_takes` e `stock_take_lines` fotografano la giacenza contabile alla
data del conteggio; la registrazione crea due movimenti `MM` (`INVP` e `INVN`) alla stessa data. Gli articoli non
contati non vengono toccati; non c'è blocco dei movimenti durante il conteggio, perché le rettifiche sono datate
e la storia ricalcolata tiene conto dei movimenti successivi.
7. **Valorizzazione.** Costo medio ponderato, ultimo costo e costo standard a qualsiasi data, con classi ABC (80% e
95% del valore). FIFO e LIFO restano **predisposti**: il criterio è un parametro del calcolo
(`StockValuationMethod`) e i movimenti conservano data, quantità e costo di ogni carico, ma i due metodi non sono
ancora offerti perché richiedono i lotti di carico, rimandati a dopo la 1.0.
8. **Tabelle di base nelle aziende esistenti.** La migrazione `M20261113_001_CreateInventory` crea le tabelle e
assegna la causale ai tipi di base che non l'hanno (`FI` → `SCA`, `FF` → `CAR`, `NCF` → `RESF`), senza toccare una
causale scelta dall'utente. I tipi nuovi (`AF20`-`AF29`) e le causali mancanti si aggiungono con *Aggiorna da
tabelle base* o `scripts/seed.sh --base`, che aggiungono i codici mancanti senza modificare quelli esistenti
(ADR 0026). Il tracciato
*Giacenze iniziali* scrive un movimento `APE` per deposito.
9. **Regole italiane nel pacchetto fiscale.** `ISelfInvoiceRules` (`SelfInvoiceRulesIt`) decide dall'anagrafica del
fornitore (paese, UE), dal genere delle righe (beni o servizi) e dalle nature IVA quale autofattura serve (TD16,
TD17, TD18, TD19, TD28) e la scadenza (15 del mese successivo; 90 giorni per TD20 e TD29).
`IIncomingInvoiceRules` (`IncomingInvoiceRulesIt`) traduce il tipo FatturaPA nel tipo documento d'acquisto (TD01,
TD02, TD03, TD05, TD06, TD24-TD27 in `FF`; TD04 e TD08 in `NCF`; gli altri sono rifiutati). L'applicazione non
conosce i codici TD.
10. **Import delle fatture ricevute.** `PurchaseInvoiceImportService` legge XML, P7M e ZIP con il lettore di #57, trova
il fornitore per partita IVA o codice fiscale (o lo crea), rifiuta i doppioni (stesso fornitore, numero, anno),
abbina le righe per codice del fornitore, EAN e codice articolo, il codice IVA per aliquota e natura, porta gli
sconti percentuali nello sconto di riga e gli altri nel prezzo netto, e salva una bozza con il file allegato.
Totale diverso, firma non verificata e sconti sul totale sono avvisi, non errori.
## Conseguenze
- Le quantità e i costi sono sempre ricostruibili dai documenti: i movimenti sono un dato derivato e la ricostruzione
è anche la verifica di coerenza.
- Ricalcolare la storia di un articolo costa più di un aggiornamento incrementale; con le dimensioni di una PMI
(migliaia di movimenti per articolo all'anno) resta nell'ordine dei millisecondi, e i documenti toccano pochi
articoli alla volta. Se servirà, un punto di partenza annuale (chiusura del magazzino) accorcia la storia.
- I documenti fornitore senza numero interno (`DDTF`) si riconoscono dal numero del fornitore; l'interfaccia li mostra
come *Senza numero*.
- Rimandati: lotti, matricole e ubicazioni; FIFO e LIFO; libro inventari e scritture delle rimanenze (M7); XML delle
autofatture e scarico dal canale SDI (M9); report di magazzino stampabili (M13).
+65
View File
@@ -0,0 +1,65 @@
# ADR 0036 - Contabilità generale
- **Stato:** accettata
- **Data:** 2026-11-13
- **Modifica:** SPEC §11.7, §12.11; milestone M7, issue #62, #63, #67, #68
## Contesto
SPEC §11.7 chiede un piano dei conti a tre livelli con un modello italiano, causali con righe proposte, prima nota
in partita doppia con registrazioni provvisorie e definitive, registrazioni ricorrenti, partitari di clienti e
fornitori, mastrini, bilancio di verifica e libro giornale. Restavano aperti: come si numerano le registrazioni,
quando una registrazione non si può più toccare, come si correggono gli errori, dove sta il modello del piano dei
conti, come si portano piano e causali nelle aziende create prima di M7.
## Decisione
1. **Piano dei conti a tre livelli.** `gl_accounts` con codice `MM.CC.SSS` (mastro, conto, sottoconto), padre,
natura (attività, passività, costo, ricavo, ordine), tipo (generico, clienti, fornitori, banca, cassa, IVA,
tributi), voce del bilancio CEE, flag *partitario*, *rilevante IVA* e *chiusura automatica*. Si registra solo sui
sottoconti; i conti con partitario chiedono il cliente o il fornitore sulla riga. Un conto con movimenti o con
sottoconti non si elimina (si disattiva). Le regole sui codici stanno in `AccountCodes` (`Khaemhat.Core`).
2. **Il modello sta nel pacchetto fiscale.** `ILedgerTemplate` (`ItalianLedgerTemplate`) dà il piano *PMI standard*
(237 conti, da `Data/piano-dei-conti.csv`), le causali, i registri IVA, il conto di ogni ruolo contabile
(`PostingRole`: clienti, fornitori, IVA vendite e acquisti, erario, ritenute, bollo, arrotondamenti...) e quale
causale usa ogni tipo documento. L'applicazione non conosce codici di conto italiani.
3. **Causali con righe proposte.** `gl_journal_templates` e `gl_journal_template_lines`: area, registro IVA,
*apre partite*, *causale di storno*, righe con ruolo o conto, segno e descrizione. La causale di storno non ha
righe: copia quelle della registrazione stornata a segni invertiti. Una causale usata non si elimina.
4. **Tre stati e due numeri.** Una registrazione (`gl_entries`, `gl_entry_lines`, `gl_entry_vat`) nasce *Bozza*
(può non quadrare, non entra nei saldi se non lo si chiede), diventa *Registrata* quando quadra (numero di
registrazione per anno, assegnato alla registrazione) e *Definitiva* con **Rendi definitive** fino a una data: le
registrazioni ricevono il numero del libro giornale in ordine di data e non si modificano né si eliminano più. Il
comando è rifiutato se prima di quella data restano bozze, e dopo non si registra più con una data anteriore
all'ultima definitiva. Gli errori su una definitiva si correggono solo con lo
**storno** (registrazione `STO` a segni invertiti, una sola per registrazione). `JournalEntryValidator`
(`Khaemhat.Core`) controlla quadratura, sottoconti, partitari, righe IVA.
5. **Partite aperte.** Le registrazioni con una causale che *apre partite* scrivono `gl_open_items` (una per rata,
con scadenza, importo, pagato); il partitario mostra saldo, estratto conto e partite, con le scadute evidenziate.
Incassi e pagamenti che chiudono le partite arrivano con la tesoreria (M8).
6. **Ricorrenti come copia di un modello.** `gl_recurring_entries` punta a una registrazione modello e ne crea una
copia a ogni data (mensile, trimestrale, semestrale, annuale, con la fine del mese mantenuta) fino alla data di
fine; il job di sistema `ledger.recurring` gira ogni giorno alle 05:00 e il pulsante *Genera ora* lo anticipa. Le
copie sono *Registrate* con origine *Ricorrente*.
7. **Saldi calcolati dalle righe.** Mastrini, partitari e bilancio di verifica (`LedgerQueryService`) sommano le
righe del periodo, con saldo di apertura dalle righe precedenti, senza tabelle di saldi: le registrazioni toccano
poche righe e i totali restano coerenti per costruzione. Il bilancio di verifica raggruppa per mastro, conto e
sottoconto, filtra per centro di costo e mostra il risultato del periodo (ricavi meno costi).
8. **Stampe.** Libro giornale di prova o definitivo, mastrini, estratti conto e bilancio di verifica sono PDF di
`LedgerReport` sul motore di stampa di M5 (ADR 0034).
9. **Aziende esistenti.** La migrazione `M20261113_002_CreateLedger` crea le tabelle; i documenti hanno già la
colonna *contabilizzato* da M5. Piano dei conti, causali e registri arrivano da `LedgerSeeder` (seed di base, *Aggiorna da tabelle
base* o `scripts/seed.sh --base`), che aggiunge i codici mancanti senza toccare quelli esistenti (ADR 0026). La
demo (`DemoLedgerSeeder`) contabilizza i documenti demo, paga la fattura del professionista, crea il noleggio
mensile della stampante come ricorrente, conferma le liquidazioni dei mesi passati e paga gli F24 scaduti.
10. **Permessi.** `ledger.account.read/write`, `ledger.entry.read/write/finalize`; tutto dietro il modulo `ACCT`.
## Conseguenze
- Un errore su una registrazione definitiva lascia sempre traccia (registrazione originale e storno), come chiede il
libro giornale.
- Sommare le righe a ogni richiesta costa più di un saldo memorizzato; con le dimensioni di una PMI (decine di
migliaia di righe l'anno) resta sotto il secondo, e gli indici su conto e data coprono le query. La chiusura
dell'esercizio (M10) porta i saldi di apertura e accorcia la storia.
- Rimandati: chiusura e riapertura dell'esercizio, bilancio CEE riclassificato, cespiti (M10); incassi, pagamenti e
riconciliazione bancaria (M8); budget per centro di costo.
+72
View File
@@ -0,0 +1,72 @@
# ADR 0037 - Contabilizzazione dei documenti, IVA e F24
- **Stato:** accettata
- **Data:** 2026-11-13
- **Modifica:** SPEC §11.7, §11.8, §12.11; milestone M7, issue #64, #65, #66
## Contesto
SPEC §11.7 e §11.8 chiedono che fatture, note e autofatture si contabilizzino da sole, con registri IVA,
liquidazione periodica, acconto, comunicazione LIPE, ritenute d'acconto, certificazione unica, bollo virtuale e
prospetto F24. Restavano aperti: quando si scrive la registrazione di un documento, come si corregge, come si
calcola la liquidazione, cosa succede se la si riapre, dove stanno codici tributo e scadenze italiane.
## Decisione
1. **Contabilizzazione nella transazione del documento.** `LedgerPoster` gira nel motore documenti, come
`InventoryPoster` (ADR 0035), e solo con il modulo `ACCT` attivo. Fatture (immediate, accompagnatorie,
differite, di acconto), note di debito e parcelle sono *vendite*; la nota di credito è una vendita a segni
invertiti; fattura e nota fornitore sono *acquisti*; autofatture e integrazioni vanno in entrambi i registri. La
modifica di un documento in vigore riscrive la sua registrazione **con lo stesso numero**; l'annullamento la
elimina o, se è definitiva, la storna. Una registrazione che viene da un documento non si modifica a mano: si
corregge il documento. I documenti confermati prima della licenza si contabilizzano in blocco
(`LedgerService.PostPendingAsync`, pulsante *Contabilizza documenti*).
2. **Regole di registrazione in `PostingEngine`** (`Khaemhat.Core`, senza accesso ai dati): vendita = cliente Dare
per il totale, ricavi Avere per conto dell'articolo o della riga, rivalsa cassa e bollo addebitato Avere, IVA
vendite Avere; scissione dei pagamenti = l'IVA torna dal cliente al conto dell'erario; acquisto = fornitore Avere,
costi Dare con l'IVA indetraibile sommata al costo, IVA acquisti Dare; autofattura = IVA acquisti Dare e IVA
vendite Avere. Sconti di testata e arrotondamenti vanno sulla riga più grande, così la registrazione quadra sempre
al centesimo. Un conto mancante blocca la conferma con un errore che dice quale ruolo configurare.
3. **Righe IVA e partite dal documento.** Il castelletto del documento diventa `gl_entry_vat` nel registro della
causale (`VEN1`, `VEN-RC`, `ACQ1`, `ACQ-RC`, `CORR`) con protocollo, data IVA, esigibilità e quota indetraibile;
le rate diventano partite aperte; la ritenuta del documento diventa una riga di `withholdings`.
4. **Registri e stampa definitiva.** I registri IVA si leggono per periodo con il riepilogo per aliquota; la stampa
definitiva (`vat_register_prints`) parte dal giorno dopo l'ultima stampa definitiva e continua la numerazione delle
pagine dell'anno. Il blocco del periodo viene dalla liquidazione (punto 5), non dalla stampa.
5. **Liquidazione in `VatSettlementCalculator`** (`Khaemhat.Core`): IVA a debito delle vendite e dei corrispettivi
esigibili (l'esigibilità differita resta fuori), IVA a credito degli acquisti al netto dell'indetraibile e del pro
rata, credito o debito del periodo precedente, acconto di dicembre, interessi dell'1% sul trimestrale (anche sul
quarto, versato a marzo con il codice 6099), minimo di versamento sotto il quale il debito passa al periodo dopo. Periodicità dal profilo
azienda. La liquidazione si **calcola** quante volte si vuole e si **conferma** in ordine: la conferma scrive la
registrazione `LIQ` (IVA vendite Dare, IVA acquisti Avere, interessi Dare, erario c/liquidazione Avere), segna i
periodi fiscali come liquidati (da lì documenti e registrazioni con IVA in quelle date sono rifiutati, ADR 0026
sui periodi) e crea il versamento F24 se c'è da pagare. La si può **riaprire** finché il suo F24
non è pagato e nessuna liquidazione successiva è confermata.
6. **Regole italiane nel pacchetto fiscale.** `IVatSettlementRules` (`VatSettlementRulesIt`) dà minimo (25,82),
interessi trimestrali, acconto (88%, minimo 103,29, metodi storico, previsionale ed effettivo), codici tributo
(6001-6012, 6031-6033, 6099 con rateazione 0101, 6013 e 6035 per l'acconto, 1040 per le ritenute, 2521-2524 per il
bollo), scadenze (16 del mese, agosto al 20, acconto al 27 dicembre, giorno lavorativo successivo) e soglie del
bollo virtuale (5.000 euro sul primo e secondo trimestre). `IPeriodicVatReturnWriter` (`LipeWriter`) scrive il
file LIPE (fornitura `IVP18`); `ITaxPaymentFormExporter` esporta i dati F24 in CSV.
7. **Tributi come versamenti.** `tax_payments` raccoglie ogni riga da versare (IVA, acconto, ritenute, bollo) con
codice, periodo e scadenza; il prospetto F24 le raggruppa per scadenza. *Registra pagamento* scrive la
registrazione `F24` (erario Dare per origine, banca Avere) e segna le righe come pagate; si annulla eliminando o
stornando quella registrazione.
8. **Ritenute.** Quelle *operate* nascono dalle fatture dei professionisti: in attesa finché la fattura non è
pagata, poi da versare (registrazione `RIT`, riga F24 al 16 del mese dopo); quelle *subite* nascono dalle
parcelle emesse (registrazione `RITS`, credito per ritenute). I dati della certificazione unica si esportano in
CSV per anno e percipiente.
9. **Nessun invio telematico.** Khaemhat prepara LIPE, dati F24 e dati CU; l'invio resta all'utente o
all'intermediario con i servizi dell'Agenzia delle Entrate.
10. **Permessi.** `vat.register.read`, `vat.settlement.read/confirm`, oltre a quelli di ADR 0036.
## Conseguenze
- Documenti e contabilità non divergono: la registrazione è un dato derivato, scritto nella stessa transazione, e
una contabilizzazione in blocco la ricostruisce.
- Correggere un documento di un periodo già liquidato è rifiutato dal blocco dei periodi: si corregge con una nota
di variazione, come prevede la norma, oppure si riapre la liquidazione.
- La verifica a mano della demo è un test (`DemoLedgerTests`): la prima liquidazione con IVA è ricalcolata dai
registri e confrontata con quella confermata.
- Rimandati: dichiarazione IVA annuale, Intrastat, F24 telematico, plafond e dichiarazioni d'intento, IVA per cassa
con chiusura automatica delle partite (con gli incassi di M8).
+122 -121
View File
@@ -1,178 +1,179 @@
# Acquisti
> **Stato:** bozza · **Ultima revisione:** 2026-11-10 · **Versione software:** non ancora rilasciata (milestone M6)
> **Modulo di licenza:** CORE (XML delle autofatture e canale SDI con EINV, registrazione con ACCT) · **Permessi principali:** famiglia `purchases.*` (codici esatti definiti in sviluppo) · **Specifica:** SPEC §11.3, §11.5
> **Stato:** completa per la versione 0.6 · **Ultima revisione:** 2026-11-12 · **Versione software:** 0.6.0 (M6)
> **Modulo di licenza:** CORE (XML delle autofatture con EINV, registrazione contabile con ACCT) · **Permessi principali:** `purchases.order.*` (ordini fornitore), `inventory.entry.*` (DDT fornitore), `purchases.invoice.*` (fatture, note di credito, import, autofatture) · **Specifica:** SPEC §11.3, §11.5, ADR 0035
Il modulo **Acquisti** copre il ciclo passivo: **ordini ai fornitori** (anche generati dalla proposta di riordino),
**DDT di carico** con controllo delle quantità ricevute, **fatture di acquisto** con protocollo IVA e conti per riga,
**note di credito** dei fornitori, **import delle fatture passive** XML/P7M ricevute dallo SDI e le **autofatture e
integrazioni** (TD16-TD29) per reverse charge e acquisti dall'estero.
Il modulo **Acquisti** copre il ciclo passivo: **ordini ai fornitori** (anche dalla proposta di riordino),
**ricevimento della merce** con il DDT del fornitore, **fatture e note di credito dei fornitori** con il protocollo
IVA, **import delle fatture elettroniche** ricevute (XML, P7M, ZIP) e le **autofatture e integrazioni** (TD16-TD29)
per inversione contabile e acquisti dall'estero.
> **In questa versione** ci sono ordini, ricevimenti, fatture e note di credito fornitore con protocollo, carico a
> magazzino e costo medio, controllo dei prezzi rispetto a ordine e ricevimento, import delle fatture elettroniche e
> autofatture in bozza con la loro scadenza. Dalla 0.7 le fatture e le note fornitore **si contabilizzano** da sole
> con i registri IVA (vedi [Contabilità](Contabilita) e [IVA](IVA)). Arrivano più avanti: i **pagamenti** e lo scadenzario (M8), il **file XML** delle autofatture e lo scarico dal canale SDI (M9).
## Dove si trova
Menu **Acquisti** → *Ordini fornitori*, *DDT di carico*, *Fatture di acquisto*, *Import XML SDI*, *Autofatture*.
Menu **Acquisti** → *Ordini fornitori*, *Ricevimenti merce*, *Fatture passive*, *Importa fatture*, *Autofatture*.
Le maschere sono quelle comuni a tutti i documenti (toolbar, intestazione, schede, righe con castelletto e totali):
vedi [Interfaccia e scorciatoie](Interfaccia-e-scorciatoie) e [Vendite](Vendite) per il motore documenti.
Le maschere sono quelle comuni a tutti i documenti (toolbar, intestazione, schede, righe con castelletto e totali,
trasformazioni, stampa, allegati): vedi [Vendite](Vendite) per il funzionamento del motore documenti e
[Interfaccia e scorciatoie](Interfaccia-e-scorciatoie) per la tastiera.
```
Proposta di riordino ──► Ordine fornitore ──ricevi merce──► DDT di carico ──registra fattura──► Fattura di acquisto
▲
Fattura passiva XML/P7M (SDI) ──import──┘ (abbinamento all'ordine o al DDT)
Proposta di riordino ──► Ordine fornitore ──Crea DDT fornitore (carico)──► Ricevimento ──Crea Fattura fornitore──► Fattura
▲
Fattura elettronica XML / P7M / ZIP ──Importa fatture──► Fattura in bozza ─┘
Fattura di un fornitore estero o in reverse charge ──Crea autofattura──► Autofattura / integrazione (TD16-TD29)
```
## Ordini fornitori
![031 · Ordine fornitore generato dalla proposta di riordino](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/mockups/thumbs/031-ordine-fornitore.png)
*Mockup 031 — ordine fornitore confermato, nato dalla proposta di riordino, con il pannello Origine del fabbisogno (anteprima ridotta).*
Un **ordine fornitore** (`OF`) dice al fornitore che cosa ti serve; non muove il magazzino ma, una volta
**confermato**, aumenta l'**ordinato** degli articoli finché non arriva la merce (vedi [Magazzino](Magazzino)).
Azioni: **Invia al fornitore** (e-mail con il PDF dell'ordine), **Ricevi merce (DDT carico)**, **Chiudi residuo**.
- Scegliendo il fornitore si applicano le sue condizioni (pagamento, banca, porto, valuta).
- Scegliendo un articolo, Khaemhat propone il **prezzo del fornitore** dalla scheda articolo (*Fornitori*).
- Gli ordini nascono a mano, dalla **proposta di riordino** (un ordine in bozza per fornitore, vedi
[Magazzino](Magazzino#proposta-di-riordino)) o copiando un altro documento.
- Quando la merce arriva, **Crea DDT fornitore (carico)** porta le righe ancora da ricevere nel ricevimento: puoi scegliere
righe e quantità, così un ordine può essere ricevuto in più volte. Lo stato diventa *Evaso in parte* ed *Evaso*;
**Chiudi** chiude un residuo che non arriverà più.
- L'intestazione mostra la **data prevista** di consegna, calcolata come data dell'ordine + **lead time** del
fornitore, e lo stato di ricevimento (*Ricevuto 0%*…).
- Le righe riportano il **codice del fornitore** per l'articolo; il prezzo proposto è quello del fornitore.
- Il pannello **Origine del fabbisogno** spiega perché si ordina: sottoscorta, impegni da ordini clienti, lotto di
riordino.
- Schede: *Righe*, *Testata*, *Totali*, *Ricevimenti*, *Note*, *Allegati*, *Collegamenti*.
- Un ordine confermato aggiorna l'**ordinato** degli articoli (vedi [Magazzino](Magazzino)).
![Khaemhat 0.6.0 · ricevimento della merce](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/acquisti-ricevimento.png)
Gli ordini nascono a mano, dalla **proposta di riordino** (un ordine in bozza per fornitore, vedi
[Magazzino](Magazzino)) o dall'azione **Ordina a fornitore** di un ordine cliente.
## Ricevimenti merce (DDT fornitore)
## DDT di carico
Il **DDT fornitore (carico)** (`DDTF`) registra la merce arrivata. Non ha un numero interno: nella testata scrivi il
**numero e la data del DDT del fornitore**, che lo identificano (nell'elenco compare come *Senza numero*).
![032 · DDT di carico con controllo quantità ricevute](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/mockups/thumbs/032-ddt-di-carico.png)
*Mockup 032 — ricevimento con confronto ordinato/ricevuto, riga con 20 pezzi mancanti e aggiornamento del costo medio (anteprima ridotta).*
1. Dall'ordine premi **Crea DDT fornitore (carico)**, oppure crea un ricevimento e richiama l'ordine.
2. Controlla le **quantità ricevute** riga per riga e il **deposito** di arrivo.
3. **Conferma**: la merce viene **caricata a magazzino** con la causale `CAR` e aggiorna **costo medio** e **ultimo
costo** degli articoli; l'ordine segna le quantità evase.
Il **DDT di carico** registra la merce ricevuta. Azioni: **Registra fattura da questo DDT**, **Stampa etichette**,
**Riapri**.
Un ricevimento confermato resta modificabile finché non è fatturato; dal ricevimento **Crea Fattura fornitore**
prepara la fattura con le stesse righe.
1. Dall'ordine fornitore premi **Ricevi merce** oppure crea un DDT di carico e usa **Evadi da…** per richiamare
l'ordine.
2. Indica numero e data del **DDT del fornitore**.
3. Conta la merce: per ogni riga inserisci la quantità **ricevuta**; si può **scansionare l'EAN o il codice
fornitore** per contare. La colonna *Controllo* segnala le differenze (*OK*, *Mancanti 20*…).
4. **Conferma**: la merce viene **caricata a magazzino** (causale *Carico da fornitore*, deposito indicato), si
aggiornano **ultimo costo** e **costo medio ponderato** dell'articolo.
## Fatture passive
Se arriva meno del previsto, il **residuo** resta aperto sull'ordine; se non arriverà più si chiude con **Chiudi
residuo**. Un messaggio sotto le righe riassume differenze e variazioni del costo medio.
![Khaemhat 0.6.0 · fattura fornitore con differenza di prezzo](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/acquisti-fattura-differenze.png)
## Fatture di acquisto
![033 · Fattura di acquisto da XML con conti e centri di costo per riga](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/mockups/thumbs/033-fattura-di-acquisto.png)
*Mockup 033 — fattura di acquisto in bozza nata da XML, con protocollo, flag Verifica prezzi, righe con conto e centro di costo, castelletto con IVA detraibile (anteprima ridotta).*
Azioni: **Registra (protocolla)**, **Contabilizza**, **Confronta con ordine**, **Apri XML**.
La **fattura fornitore** (`FF`) e la **nota di credito fornitore** (`NCF`) registrano i documenti del fornitore.
| Dato | Descrizione |
|---|---|
| **Data di registrazione** e **data/numero del documento** del fornitore | la registrazione determina il periodo IVA |
| **Protocollo** | numero progressivo del registro IVA acquisti (es. `ACQ/2026/000613`), assegnato alla registrazione |
| **Conto e centro di costo per riga** | ogni riga ha il proprio conto di costo e centro di costo (proposti da articolo, categoria o fornitore) |
| **Indetraibilità** | codici IVA con indetraibilità parziale o totale (es. telefonia 50%): il castelletto mostra imponibile, imposta e quota **detraibile** |
| **Ritenute e cassa** | per i professionisti: ritenuta d'acconto, cassa previdenza; il totale mostra il **netto a pagare** |
| **Registrazione contabile** | scheda con l'anteprima della registrazione (con modulo Contabilità) |
| **N. documento fornitore** e **data** | numero e data scritti dal fornitore (nella testata) |
| **Data** | data di registrazione: decide il periodo IVA |
| **Protocollo** | numero progressivo del registro IVA acquisti (numeratore `PRA`), assegnato alla **conferma**; nell'elenco compare nella colonna *Protocollo* |
| **Righe** | articoli, righe descrittive e spese con il codice IVA di ogni riga; per i professionisti ritenuta d'acconto e cassa come nelle vendite |
| **Scadenze** | calcolate dal pagamento del fornitore |
Schede: *Righe*, *Testata*, *Totali*, *Scadenze*, *Ritenute e cassa*, *Registrazione contabile*, *Note*,
*Allegati*, *Collegamenti*.
La fattura nasce dal ricevimento (**Crea Fattura fornitore**), dall'ordine (per servizi o merce senza DDT), dall'**import
della fattura elettronica** (vedi sotto) o a mano. **Conferma** assegna il protocollo e la rende definitiva; una
fattura confermata si corregge con una **nota di credito fornitore** (**Crea Nota di credito fornitore**).
**Registra (protocolla)** assegna il protocollo e rende la fattura definitiva; **Contabilizza** crea la registrazione
(automatica alla conferma o in batch, secondo le preferenze). La fattura può nascere:
**Magazzino.** Una fattura di merce senza DDT carica il magazzino alla conferma; una fattura nata da un ricevimento
non carica di nuovo, ma il suo **prezzo corregge il costo** del carico. La nota di credito fornitore scarica la merce
resa (causale `RESF`).
- dal **DDT di carico** (**Registra fattura da questo DDT**), che la collega ai carichi;
- dall'**import XML** (vedi sotto);
- a mano, ad esempio per fatture cartacee o estere.
**Controllo dei prezzi.** Se una riga della fattura ha un prezzo diverso da quello dell'ordine o del ricevimento da
cui viene, sopra le righe compare un avviso con la differenza totale e, riga per riga, il prezzo atteso e quello
fatturato. È un avviso: decidi tu se registrare la fattura o chiedere una nota di credito.
Le **note di credito dei fornitori** si registrano allo stesso modo e chiudono le partite collegate.
## Importare le fatture elettroniche
## Import delle fatture passive XML/P7M
![Khaemhat 0.6.0 · import delle fatture passive](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/acquisti-importa-fatture.png)
![034 · Import fatture passive XML/P7M](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/mockups/thumbs/034-import-xml-sdi.png)
*Mockup 034 — quattro file in import (pronto, con ritenuta e cassa, fornitore da creare, duplicato) e mappatura delle righe sull'ordine con differenza di prezzo (anteprima ridotta).*
**Acquisti → Importa fatture** (o il link nell'elenco delle fatture passive) registra in bozza le fatture ricevute
dallo SDI o dal tuo intermediario.
1. Carica i file con **Carica XML / P7M / ZIP**, oppure **Leggi inbox** (cartella di ingresso dell'istanza) o
**Scarica dal canale SDI** (con il modulo Fatturazione elettronica).
2. Per ogni file Khaemhat legge fornitore, numero, data, tipo documento (TD) e totale e mostra un **esito**:
*Pronto*, *Fornitore da creare*, *Duplicato*, oppure avvisi (ad esempio *Ritenuta 20% · cassa 4%*).
3. Il **fornitore** viene riconosciuto da **partita IVA o codice fiscale**; se non esiste si crea al volo dai dati
dell'XML.
4. **Mappatura righe**: ogni riga XML viene abbinata a un articolo cercando, in ordine, il **codice del fornitore**,
l'**EAN** e la **descrizione** (ricerca approssimata). Le righe non abbinate diventano descrittive o si abbinano a
mano.
5. **Abbina a ordine**: confronta prezzi e quantità con l'ordine fornitore; le differenze sono evidenziate (es.
*+3,4%*).
6. **Salva bozza** o **Registra fattura di acquisto**. Se ci sono differenze la fattura nasce **in bozza** con il
flag *Verifica prezzi*.
1. **Caricamento**: scegli uno o più file: **XML FatturaPA**, file firmati **.p7m** o archivi **ZIP** che li
contengono (fino a 50 MB per file). I file che non sono fatture elettroniche leggibili sono elencati a parte con il
motivo.
2. **Controllo**: per ogni fattura vedi fornitore (nuovo o già in anagrafica), numero, data, tipo, totale e un esito:
*Pronta*, oppure *Già registrata* (stesso fornitore, stesso numero, stesso anno), *Non è un acquisto* (per esempio
un'autofattura emessa dall'azienda stessa), *Totale diverso* (il totale del file non torna con le righe), *Firma non
verificata*, *Sconto sul totale*. **Leggi** mostra righe, riepilogo IVA e pagamento del file.
3. **Registrazione**: spunta le fatture e premi **Registra in bozza**. Per ognuna Khaemhat:
- trova il **fornitore** dalla partita IVA o dal codice fiscale, o lo **crea** dai dati del file;
- crea una **fattura fornitore** (tipi TD01, TD02, TD03, TD05, TD06, TD24-TD27) o una **nota di credito fornitore**
(TD04, TD08) in bozza, con numero e data del fornitore e la causale nelle note;
- abbina ogni riga a un **articolo** cercando il **codice del fornitore** (scheda articolo, *Fornitori*), poi l'**EAN**,
poi il **codice articolo**; le righe non abbinate diventano righe libere con descrizione, prezzo e IVA;
- riporta gli **sconti** percentuali come sconto di riga e gli altri nel prezzo netto;
- sceglie il **codice IVA** dell'azienda con la stessa aliquota e natura;
- **allega il file** originale alla fattura (scheda *Allegati*, tipo *Fattura elettronica*).
L'**XML originale** viene allegato alla fattura; per i file **P7M** la **firma CAdES** viene verificata. I file già
importati sono riconosciuti come duplicati.
Le fatture importate restano **in bozza**: controllale e confermale per protocollarle. Se un codice IVA manca (per
esempio una natura non usata finora), aggiungilo in [Tabelle azienda](Tabelle-azienda) → *Codici IVA* e ripeti
l'import.
## Autofatture e integrazioni (TD16-TD29)
![035 · Autofattura / integrazione reverse charge](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/mockups/thumbs/035-autofattura-integrazione.png)
*Mockup 035 — integrazione TD17 per servizi da un fornitore estero: IVA integrata, effetto neutro, registri RC vendite e acquisti, scadenza di invio allo SDI (anteprima ridotta).*
![Khaemhat 0.6.0 · integrazione da emettere su una fattura intracomunitaria](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/acquisti-fattura-autofattura.png)
Quando l'IVA è dovuta dall'acquirente (inversione contabile) l'azienda deve **integrare** la fattura ricevuta o
emettere un'**autofattura**, trasmettendola allo SDI. In Khaemhat questi documenti stanno in **Acquisti →
Autofatture** e nascono dalla fattura di acquisto d'origine.
Quando l'IVA è dovuta da chi compra (inversione contabile, acquisti dall'estero) l'azienda deve **integrare** la
fattura ricevuta o emettere un'**autofattura** e trasmetterla allo SDI. Khaemhat lo riconosce da solo dalla fattura
fornitore (paese del fornitore, beni o servizi, natura IVA delle righe) e mostra sopra le righe quale documento serve e **entro quando**:
| Codice | Documento | Quando si usa |
| Tipo | Quando | Scadenza |
|---|---|---|
| **TD16** | Integrazione fattura reverse charge interno | acquisti nazionali in inversione contabile (art. 17 c.6 DPR 633/72, es. subappalto edile) |
| **TD17** | Integrazione/autofattura per acquisto di servizi dall'estero | servizi da fornitori UE ed extra-UE |
| **TD18** | Integrazione per acquisto di beni intracomunitari | beni da fornitori UE |
| **TD19** | Integrazione/autofattura per acquisto di beni ex art. 17 c.2 DPR 633/72 | beni già in Italia acquistati da soggetti non residenti |
| **TD20** | Autofattura per regolarizzazione e integrazione delle fatture | regolarizzazione nei casi previsti (definizione aggiornata dalle specifiche v1.9) |
| **TD21** | Autofattura per splafonamento | acquisti oltre il plafond dell'esportatore abituale |
| **TD22** | Estrazione beni da deposito IVA | |
| **TD23** | Estrazione beni da deposito IVA con versamento dell'IVA | |
| **TD28** | Acquisti da San Marino con IVA | fatture cartacee con IVA da operatori sammarinesi |
| **TD29** | Comunicazione per omessa o irregolare fatturazione | introdotto con le specifiche v1.9 (dal 1° aprile 2025) |
| **AF16** (TD16) | inversione contabile interna: righe con natura N6.x (subappalti, rottami, cellulari…) | 15 del mese dopo il ricevimento |
| **AF17** (TD17) | servizi da un fornitore estero, UE o extra UE | 15 del mese dopo |
| **AF18** (TD18) | beni da un fornitore di un altro Paese UE | 15 del mese dopo |
| **AF19** (TD19) | beni già in Italia comprati da un soggetto non residente (art. 17 c.2) | 15 del mese dopo |
| **AF28** (TD28) | acquisti da San Marino con IVA in fattura | 15 del mese dopo |
| **AF20**, **AF29** | regolarizzazione di una fattura non ricevuta o irregolare | 90 giorni |
| AF21, AF22, AF23 | splafonamento, estrazione da deposito IVA | a mano, quando servono |
Come funziona (esempio TD17, mockup 035):
![Khaemhat 0.6.0 · integrazioni da emettere](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/acquisti-autofatture-in-attesa.png)
1. La fattura estera viene registrata negli acquisti.
2. Si crea l'integrazione: le righe sono **riprese dalla fattura estera** con imponibile e aliquota; Khaemhat
calcola l'**IVA integrata**.
3. **Conferma e genera XML**: nell'XML il **fornitore estero** compare come cedente/prestatore e la **nostra azienda**
come cessionario/committente.
4. La registrazione va contemporaneamente nel **registro IVA vendite RC** e nel **registro IVA acquisti RC**: l'effetto
è **neutro** (IVA a debito = IVA a credito, salvo indetraibilità). Il pannello *Effetto contabile* mostra le due
righe.
5. L'XML va inviato **entro il 15 del mese successivo**: Khaemhat mostra la scadenza nel documento e un promemoria
nella dashboard.
**Acquisti → Autofatture** elenca in alto le **integrazioni da emettere**, la scadenza più vicina per prima. **Crea
autofattura** (qui o nella fattura fornitore) prepara il documento in bozza: le righe della fattura con il **codice IVA
ordinario** al posto della natura, il numero e la data della fattura del fornitore come documento collegato, la data
di oggi. Controllalo ed **emettilo**: prende il numero dal numeratore `AUT` delle autofatture.
Schede: *Righe*, *Testata*, *Registrazione IVA*, *XML SDI*, *Collegamenti*. Le definizioni ufficiali dei codici sono
in [Fiscalità italiana](Fiscalita-italiana).
Il **file XML** dell'autofattura (con il fornitore come cedente e l'azienda come cessionario) e l'invio allo SDI
arrivano con la [Fatturazione elettronica](Fatturazione-elettronica) (M9); la doppia registrazione nei registri IVA
vendite e acquisti si fa da sola alla conferma dell'autofattura (dalla 0.7, vedi [IVA](IVA)). Le definizioni ufficiali dei codici TD sono in
[Fiscalità italiana](Fiscalita-italiana).
## Fatture da fornitori forfettari
Le fatture dei fornitori in **regime forfettario** non hanno IVA (natura N2.2 nell'XML del fornitore) e riportano il
**bollo** quando dovuto; non sono soggette a ritenuta d'acconto. Nella scheda del fornitore il flag *Regime
forfettario* (gruppo *Ritenute e contributi*) indica questa situazione; i controlli automatici sulla fattura
importata saranno definiti in sviluppo.
Le fatture dei fornitori in **regime forfettario** non hanno IVA (natura N2.2) e riportano il **bollo** quando dovuto;
non sono soggette a ritenuta. All'import la riga prende il codice IVA dell'azienda con natura N2.2; non serve
nessuna autofattura.
## Stati
Ordini e DDT di carico seguono gli stati del motore documenti: *Bozza*, *Confermato*, *Ricevuto parzialmente* /
*Ricevuto*, *Chiuso*, *Annullato*. Le fatture di acquisto sono *Bozza* finché non vengono **registrate
(protocollate)**; i badge indicano anche *Da XML SDI*, *Verifica prezzi*, *Caricato a magazzino*, *Da fatturare*.
| Documento | Stati |
|---|---|
| Ordine fornitore, ricevimento | *Bozza*, *Confermato*, *Evaso in parte*, *Evaso*, *Chiuso*, *Annullato* |
| Fattura e nota di credito fornitore | *Bozza*, *Confermato* (protocollata), *Annullato* |
| Autofattura | *Bozza*, *Emessa* e, con la fatturazione elettronica, gli stati dello SDI |
## Permessi e licenza
Ordini, carichi, fatture di acquisto e import da file sono nel modulo **CORE**. La generazione e l'invio dell'XML
delle autofatture e lo scarico dal canale SDI richiedono **EINV**; la registrazione contabile e i registri IVA
**ACCT**; i pagamenti **FIN**. Costi e margini sono visibili solo a chi ha il permesso `items.cost.read`.
Ordini, ricevimenti, fatture, import e autofatture sono nel modulo **CORE**. Gli ordini richiedono
`purchases.order.read`/`write`; i ricevimenti, che muovono il magazzino, `inventory.entry.read`/`write` (e
`inventory.entry.post` per confermarli); fatture, note di credito, import e autofatture `purchases.invoice.read`/`write`.
L'XML delle autofatture richiederà **EINV**, la registrazione contabile **ACCT**, i pagamenti **FIN**. Costi e margini
sono visibili solo con `items.cost.read`.
## Domande frequenti
- **L'import segna "Duplicato".** La fattura risulta già importata: non va registrata una seconda volta (il
criterio esatto di riconoscimento sarà definito in sviluppo).
- **Una riga dell'XML non trova l'articolo.** Aggiungi il codice del fornitore nella scheda articolo (*Fornitori*):
la volta successiva l'abbinamento sarà automatico.
- **Ho ricevuto meno merce di quella ordinata.** Conferma il DDT con la quantità ricevuta: il residuo resta aperto
sull'ordine.
- **L'import dice "Già registrata".** Lo stesso fornitore ha già un documento con quel numero nello stesso anno: non
va registrata due volte.
- **Una riga dell'XML non trova l'articolo.** Aggiungi il codice che usa il fornitore nella scheda articolo
(*Fornitori*, codice fornitore): dalla volta successiva l'abbinamento è automatico.
- **Ho ricevuto meno merce di quella ordinata.** Conferma il ricevimento con la quantità arrivata: il residuo resta
aperto sull'ordine e l'ordinato degli articoli lo tiene in conto.
- **La fattura ha un prezzo diverso dall'ordine.** L'avviso sopra le righe lo segnala; se la fattura è giusta
confermala e il costo medio si allinea al prezzo fatturato.
- **Non vedo l'avviso dell'autofattura.** Compare sulle fatture di fornitori esteri o con righe in natura N6.x,
finché non c'è un'autofattura collegata. L'elenco *Integrazioni da emettere* mostra solo le fatture **confermate**.
## Pagine correlate
+6 -1
View File
@@ -1,6 +1,6 @@
# Allegati e file
> **Stato:** completa per M3 (invio e-mail e scanner con M5) · **Ultima revisione:** 2026-11-11 · **Versione software:** 0.3.0 (milestone M3)
> **Stato:** completa per M5 (acquisizione da scanner con M13) · **Ultima revisione:** 2026-11-12 · **Versione software:** 0.5.0
> **Modulo di licenza:** CORE · **Permessi principali:** `attachments.read`, `attachments.write`, `attachments.delete` · **Specifica:** SPEC §9.4
Ogni documento e ogni anagrafica può avere **allegati**: file caricati dall'utente (l'ordine del cliente in PDF, una
@@ -79,6 +79,11 @@ La sezione **Genera file** del pannello elenca le uscite disponibili per il docu
**Rigenera** non sovrascrive mai: crea la versione successiva (`v2`, `v3`…) e lascia consultabili le precedenti.
**In 0.5.0** i documenti di vendita (preventivi, ordini, DDT, fatture, note, pro forma) hanno il generatore **Stampa
del documento in PDF**: lo stesso disegno dell'anteprima di stampa (vedi [Vendite](Vendite#stampa-e-pdf)). Lo usano
anche **Salva come allegato** dell'anteprima e **Invia per e-mail**, che allega al messaggio la versione appena
creata: così tra gli allegati resta sempre la copia esatta di ciò che è stato stampato o inviato.
Anche i **report** producono file (XLSX, CSV, PDF) scaricabili e, se pianificati, inviati per e-mail come allegati.
Le **stampe massive** (ad esempio tutte le fatture del mese) producono un unico **ZIP** scaricato direttamente,
senza file temporanei.
+9 -7
View File
@@ -1,6 +1,6 @@
# Articoli e listini
> **Stato:** completa · **Ultima revisione:** 2026-11-12 · **Versione software:** 0.4.0 (milestone M4; giacenze e costi dai movimenti con il magazzino, M6)
> **Stato:** completa · **Ultima revisione:** 2026-11-12 · **Versione software:** 0.4.0 (milestone M4; giacenze e costi dai movimenti dalla 0.6.0, M6)
> **Modulo di licenza:** CORE · **Permessi principali:** `items.item.read` (consultare), `items.item.write` (inserire, modificare, disattivare, prezzi), `items.item.delete` (eliminare), `items.cost.read` (vedere costi e margini) · **Specifica:** SPEC §11.2, §11.3 (prezzi), §14 · **Decisioni:** ADR 0030
L'**articolo** descrive ciò che l'azienda vende o compra: merci, servizi, spese, righe descrittive e cespiti. Nella
@@ -75,18 +75,20 @@ salvataggio.
### Costi
- **Costo standard**: valore scritto a mano.
- **Ultimo costo** e **costo medio**: li aggiornano i carichi di magazzino (DDT di carico, fatture di acquisto) che
arrivano con il magazzino (M6); fino ad allora sono valorizzati solo nei dati di esempio. Il costo medio è il
criterio di valorizzazione del magazzino (vedi [Magazzino](Magazzino)).
- **Ultimo costo** e **costo medio**: li calcolano i carichi di magazzino (DDT fornitore, fatture fornitore, esistenze
iniziali, movimenti di carico) dalla versione 0.6.0. Il costo medio è il criterio di valorizzazione del magazzino
(vedi [Magazzino](Magazzino#costo-medio-e-valorizzazione)).
- Il **margine** è calcolato sul prezzo: (prezzo - costo) / prezzo.
- Chi non ha il permesso `items.cost.read` non vede i costi (né nella scheda né nell'elenco né nei listini) e,
quando salva, i costi in archivio restano quelli di prima.
### Giacenze e riordino
Con **Gestito a magazzino** l'articolo parteciperà a movimenti, giacenze per deposito (*Giacenza, Impegnato,
Ordinato, Disponibile, Valore*) e **proposta di riordino**: questi arrivano con il magazzino (M6). Scorta minima,
punto e lotto di riordino si possono già compilare.
Con **Gestito a magazzino** l'articolo partecipa a movimenti, giacenze per deposito (*Giacenza, Impegnato,
Ordinato, Disponibile, Valore*) e **proposta di riordino** (vedi [Magazzino](Magazzino)). **Scorta minima**, **punto
di riordino** e **lotto di riordino** decidono lo stato dell'articolo nelle giacenze e la quantità proposta; il
**fornitore preferito** della scheda *Fornitori*, con prezzo, minimo d'ordine e lead time, è quello a cui la
proposta ordina.
### Controlli al salvataggio
+5 -1
View File
@@ -137,13 +137,17 @@ il dettaglio dell'ultima. Le esecuzioni sono registrate nel database di sistema.
## Job di sistema
Nella versione 0.2.0 i job di sistema sono questi (orari nel fuso `Europe/Rome`):
Nella versione 0.7.0 i job di sistema sono questi (orari nel fuso `Europe/Rome`):
| Codice | Cosa fa | Quando |
|---|---|---|
| `system.sessions-cleanup` | elimina le sessioni scadute o revocate da più di 30 giorni, nel database di sistema e in ogni azienda non disattivata | al minuto 15 di ogni ora |
| `system.license-check` | ricalcola la licenza; avvisa gli amministratori a 30, 14, 7, 3 e 1 giorno dalla scadenza e quando è scaduta | ogni ora |
| `system.log-retention` | elimina gli eventi di log più vecchi della retention del loro livello | ogni notte alle 03:30 |
| `system.attachments-trash` | svuota il cestino degli allegati oltre i giorni di conservazione | ogni notte alle 03:45 |
| `system.ecb-rates` | scarica i cambi di riferimento della BCE (richiede la rete) | nei giorni feriali alle 16:30 |
| `inventory.rebuild` | ricostruisce il magazzino di ogni azienda attiva dai documenti in vigore (vedi [Magazzino](Magazzino#ricostruzione)) | la domenica alle 02:15 |
| `ledger.recurring` | crea le registrazioni ricorrenti arrivate alla loro data in ogni azienda con la contabilità (vedi [Contabilità](Contabilita)) | ogni giorno alle 05:00 |
Oltre alle attività degli amministratori, Khaemhat esegue sempre alcuni **job di sistema**: pulizia (log e sessioni
secondo la retention), controllo della licenza, aggiornamento dei cambi BCE, lettura dell'inbox e dei canali SDI,
+4 -1
View File
@@ -1,6 +1,6 @@
# Changelog
> **Stato:** completa per 0.4.0 · **Ultima revisione:** 2026-11-12
> **Stato:** completa per 0.7.0 · **Ultima revisione:** 2026-11-13
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,9 @@ Le novità di ogni versione sono nel file
| Versione | Data | Contenuto |
|---|---|---|
| 0.7.0 | 2026-11-13 | M7 — Contabilità generale e IVA: piano dei conti PMI a tre livelli, causali, prima nota con registrazioni provvisorie, definitive e storni, ricorrenti; contabilizzazione automatica di fatture, note e autofatture con righe IVA, partite e ritenute; registri IVA con stampa definitiva, liquidazione mensile o trimestrale con acconto, F24 e LIPE; ritenute d'acconto e dati CU; bollo virtuale; partitari, mastrini, bilancio di verifica e libro giornale; contabilità nei dati di esempio. |
| 0.6.0 | 2026-11-12 | M6 — Acquisti e Magazzino: ordini fornitori, ricevimenti, fatture e note di credito fornitore con protocollo e controllo dei prezzi; import delle fatture elettroniche XML, P7M e ZIP con fornitore e articoli abbinati; autofatture e integrazioni TD16-TD29 con la loro scadenza; giacenze per deposito con impegnato, ordinato e costo medio ponderato, movimenti e trasferimenti, inventario fisico, proposta di riordino, valorizzazione con classi ABC, ricostruzione; giacenze iniziali da file; acquisti e magazzino nei dati di esempio. |
| 0.5.0 | 2026-11-12 | M5 — Motore documenti e Vendite: preventivi, ordini, DDT, fatture, note di credito, pro forma e parcelle con numerazione senza buchi, castelletto IVA, bollo, ritenute e scadenze; documenti collegati riga per riga e *Crea …* per passare dall'uno all'altro; fatturazione differita guidata; anteprima di stampa e PDF salvato tra gli allegati; invio per e-mail con SMTP interno; un anno di vendite nei dati di esempio; [Guida all'uso](Guida-utente) con le schermate. |
| 0.4.0 | 2026-11-12 | M4 — Tabelle, anagrafiche, articoli: pacchetto fiscale italiano, profilo azienda, esercizi e cambi, 26 tabelle azienda con province, comuni e CAP, clienti, fornitori e contatti con controlli e VIES, articoli e listini con prezzi a validità, codici automatici, import/export guidato (anche del piano dei conti, per ora solo verifica) e dati di esempio. |
| 0.3.0 | 2026-11-11 | M3 — Framework UI: la finestra di Khaemhat con menu, schede e barra di stato, la dashboard a widget, *Il mio profilo* con temi e colori, ricerca globale, aiuto in app, notifiche, componenti per maschere e liste, allegati e anteprima di stampa (provati su un documento di prova, le maschere gestionali arrivano da 0.4.0). |
| 0.2.0 | 2026-11-11 | M2 — Sistema e sicurezza: avvio da variabili d'ambiente, super utente e prima azienda, accesso con password e verifica in due passaggi, utenti, ruoli e permessi, licenze e moduli con codici di prova, log per sezioni, attività programmate. |
+275 -227
View File
@@ -1,272 +1,320 @@
# Contabilità generale
> **Stato:** bozza · **Ultima revisione:** 2026-11-10 · **Versione software:** non ancora rilasciata (milestone M7; chiusura esercizio e bilancio CEE in M10)
> **Modulo di licenza:** ACCT · **Permessi principali:** `ledger.entry.write`, `ledger.entry.finalize`, `ledger.entry.reopen`, `ledger.account.write`, `ledger.closing.run`, `ledger.export` · **Specifica:** SPEC §11.7, §11.1, §14
> **Stato:** completa per la versione 0.7 · **Ultima revisione:** 2026-11-13 · **Versione software:** 0.7.0 (M7)
> **Modulo di licenza:** ACCT · **Permessi principali:** `ledger.account.read`/`write` (piano dei conti e causali), `ledger.entry.read`/`write` (prima nota, partitari, bilancio), `ledger.entry.finalize` (registrazioni definitive) · **Specifica:** SPEC §11.7, §14, ADR 0036, ADR 0037
## A cosa serve
Il modulo **Contabilità** tiene la **contabilità generale in partita doppia** dell'azienda: piano dei conti, causali,
prima nota, registrazioni ricorrenti, partitari di clienti e fornitori, mastrini, bilancio di verifica e libro
giornale. È collegato al resto del gestionale: ogni fattura, nota di credito o autofattura confermata scrive da sola
la sua registrazione, con le righe IVA e le partite.
Il modulo Contabilità tiene la **contabilità generale in partita doppia** dell'azienda: piano dei conti, causali,
prima nota, partitari e mastrini, esercizi e periodi, chiusura dell'esercizio e bilancio. È collegato al resto del
gestionale: ogni documento confermato (fattura di vendita o di acquisto, nota di credito, incasso, pagamento,
ammortamento…) genera da solo la propria registrazione partendo dalla **causale contabile** del tipo di documento.
La parte fiscale (registri IVA, liquidazione, acconto, F24, LIPE, ritenute d'acconto, bollo virtuale) è descritta
nella pagina [IVA](IVA); le regole italiane usate (piano dei conti modello, codici tributo, scadenze) in
[Fiscalità italiana](Fiscalita-italiana).
La parte IVA (registri, liquidazione, F24, LIPE, ritenute, bollo, dichiarazioni d'intento) è descritta nella pagina
[IVA](IVA); i cespiti nella pagina [Cespiti](Cespiti); partite, incassi e banche nello [Scadenzario](Scadenzario).
> **In questa versione** ci sono il piano dei conti modello *PMI standard* con voci CEE, le causali contabili, la
> prima nota manuale con castelletto IVA, la **contabilizzazione automatica** di fatture, note e autofatture, le
> registrazioni ricorrenti, lo storno, le registrazioni definitive con il numero di libro giornale, i partitari con
> estratto conto e partite, i mastrini, il bilancio di verifica e le stampe del bilancio e del libro giornale.
> Arrivano più avanti: **scadenzario**, incassi e pagamenti bancari e riconciliazione (M8), **chiusura
> dell'esercizio**, ratei e risconti, **bilancio CEE** riclassificato e **cespiti** (M10). Non ci sono ancora
> l'import del piano dei conti da file e l'export per il commercialista.
## Dove si trova
Menu laterale **Contabilità**, con le voci **Prima nota**, **Piano dei conti**, **Causali contabili**, **Registri IVA**,
**Liquidazione IVA**, **Ritenute**, **Chiusura esercizio**, **Bilancio**. Esercizi e periodi si gestiscono da
**Tabelle azienda → Esercizi** (mockup 052). Le voci compaiono solo se il modulo ACCT è licenziato e l'utente ha i
permessi (vedi [Licenze e moduli](Licenze-e-moduli) e [Utenti e permessi](Utenti-e-permessi)).
Menu **Contabilità** → *Prima nota*, *Piano dei conti*, *Causali*, *Partitari*, *Registri IVA*, *Liquidazione IVA*,
*Ritenute e F24*, *Bollo virtuale*, *Bilancio*. Le ultime quattro voci fiscali sono spiegate in [IVA](IVA).
## Schermate
Il menu compare solo se la licenza dell'azienda comprende il modulo **ACCT** e l'utente ha i permessi (vedi
[Licenze e moduli](Licenze-e-moduli) e [Utenti e permessi](Utenti-e-permessi)). Esercizi e periodi si gestiscono da
**Tabelle azienda → Esercizi** (vedi [Tabelle azienda](Tabelle-azienda)); periodicità IVA e pro rata sono nel
**profilo azienda**.
![040 · Prima nota](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/mockups/thumbs/040-prima-nota.png)
*Mockup 040 — registrazione di prima nota generata da una fattura di acquisto: intestazione con causale FA, stato *Provvisoria* e *Quadrata*, righe in partita doppia con centro di costo e partita, riquadro delle righe IVA (anteprima ridotta)*
![041 · Prima nota manuale non quadrata](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/mockups/thumbs/041-prima-nota-manuale-non-quadrata.png)
*Mockup 041 — giroconto manuale in bozza con sbilancio di € 300,00 evidenziato e suggerimento "Ctrl+D quadra sull'ultima riga" (anteprima ridotta)*
![042 · Piano dei conti](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/mockups/thumbs/042-piano-dei-conti.png)
*Mockup 042 — albero dei conti con saldi, dettaglio del sottoconto (natura, tipo, conto padre, voce CEE, riclassificato, flag) e mastrino sotto (anteprima ridotta)*
![043 · Causali contabili](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/mockups/thumbs/043-causali-contabili.png)
*Mockup 043 — elenco delle causali con area, registro IVA e "genera partita"; sotto, il modello righe della causale FA con ruoli, segno e base d'importo (anteprima ridotta)*
![044 · Partitario](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/mockups/thumbs/044-partitario-estratto-conto.png)
*Mockup 044 — partitario di un cliente con saldo iniziale, dare/avere del periodo, saldo e scaduto; movimenti con saldo progressivo e stato della partita (anteprima ridotta)*
![050 · Chiusura esercizio](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/mockups/png/050-chiusura-esercizio.png)
*Mockup 050 — procedura guidata di chiusura in nove passi raggruppati in cinque fasi (Controlli, Assestamento, Chiusura, Apertura, Stampe), con esito e autore di ogni passo*
![051 · Bilancio CEE](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/mockups/png/051-bilancio-cee.png)
*Mockup 051 — bilancio CEE con stato patrimoniale espandibile e conto economico a confronto con l'esercizio precedente (Δ %); viste Verifica, CEE, Riclassificato, Indici*
![052 · Esercizi e periodi](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/mockups/png/052-esercizi-periodi.png)
*Mockup 052 — elenco degli esercizi con stato, registrazioni e ultimo periodo IVA liquidato; sotto, i periodi mensili con stato (Aperto, Liquidato, Bloccato) e interruttore di blocco*
## Piano dei conti
Il piano dei conti ha tre livelli con codice **`MM.CC.SSS`** (mastro, conto, sottoconto; per esempio `01.04.001`
*Clienti Italia*). Alla creazione dell'azienda viene **precaricato un piano standard per PMI** con le voci di bilancio
CEE già associate (nel mockup 042 l'intestazione mostra la versione del modello caricato).
| Campo | Significato |
|---|---|
| **Codice** | `MM.CC.SSS`, gerarchico; il conto padre è il livello superiore |
| **Descrizione** | obbligatoria |
| **Natura** | patrimoniale (attività/passività), economica (costi/ricavi), d'ordine |
| **Tipo** | mastro, conto, sottoconto |
| **Voce CEE** | voce dello schema di stato patrimoniale (art. 2424 c.c.) o conto economico (art. 2425 c.c.) |
| **Riclassificato** | voce del riclassificato finanziario/gestionale (es. *Crediti commerciali*) |
| **Partitario clienti/fornitori** | il conto si articola per controparte (vedi sotto) |
| **Rilevante IVA** | il conto entra nei controlli IVA |
| **Chiusura automatica** | il conto viene chiuso dalla procedura di fine esercizio |
| **Movimentabile** | si possono registrare movimenti (di norma solo i sottoconti) |
| **Attivo** | i conti disattivati restano nello storico ma non si propongono |
Selezionando un conto nell'albero si vedono a destra i suoi dati e sotto il **mastrino** (data, registrazione,
descrizione, dare, avere, saldo); il pulsante **Mastrino completo** apre la vista intera con i filtri.
### Importare un piano dei conti
Non esiste in Italia un formato standard per scambiare il piano dei conti, quindi Khaemhat accetta tre formati:
| Formato | Uso | Contenuto |
|---|---|---|
| **CSV** (separatore `;`) | import da altri gestionali o da foglio di calcolo | colonne `codice;descrizione;livello;padre;natura;tipo;voce_cee;riclassifica;flag` |
| **XLSX** | come il CSV | stesso tracciato, una riga per conto |
| **JSON** (`khaemhat-coa.json`) | export/import completo fra installazioni Khaemhat | conti, voci di bilancio, causali e mappature |
1. Apri **Contabilità → Piano dei conti** e premi **Importa piano dei conti** (oppure usa la procedura guidata di
[Import-Export](Import-Export)).
2. Scegli il file e verifica la **mappatura delle colonne**.
3. Controlla l'**anteprima**: Khaemhat verifica la coerenza gerarchica (ogni conto ha un padre esistente, il livello
corrisponde al codice, le voci CEE esistono) e segnala le righe errate.
4. Conferma. Il risultato e gli eventuali errori restano nel report dell'importazione.
I valori ammessi nelle colonne `natura`, `tipo` e `flag` saranno fissati in sviluppo e riportati qui.
## Causali contabili e ruoli
Una **causale contabile** è il modello di una registrazione. Ogni causale ha **righe modello** che non indicano un
conto fisso ma un **ruolo**; il ruolo viene risolto nel conto reale al momento della registrazione (il conto del
cliente, il conto di ricavo dell'articolo o della sua categoria, il conto IVA del codice IVA…).
| Ruolo | Esempio di conto risolto |
|---|---|
| cliente / fornitore | sottoconto del partitario della controparte |
| ricavo / costo | conto della riga, dell'articolo o della categoria |
| IVA vendite / IVA acquisti | conti IVA del codice IVA |
| banca / cassa | conto collegato al conto bancario o alla cassa |
| Erario ritenute, cassa previdenza, bollo | conti configurati per azienda |
| abbuoni, contropartita | conti configurati o indicati a mano |
Per ogni riga si indicano anche **dare/avere**, la base dell'importo (totale documento, imponibile riga, IVA
detraibile, IVA indetraibile, ritenuta, cassa…), il **registro IVA** e se la riga **genera una partita** nello
scadenzario. Il pulsante **Prova su documento** mostra la registrazione che la causale produrrebbe su un documento
esistente, senza salvarla.
Causali di base precaricate: **FV** fattura di vendita, **NCV** nota di credito a cliente, **FA** fattura di
acquisto, **NCA** nota di credito da fornitore, **AFRC** integrazione reverse charge (autofatture TD16-TD19),
**CORR** corrispettivi, **INC** incasso, **PAG** pagamento, **INS** insoluto, **GIRO** giroconto, **AMM**
ammortamenti, **RAT** ratei e risconti, **RIM** rimanenze, chiusura e apertura, **F24**, ritenute versate, stipendi
(da import), interessi e commissioni.
```
Fattura / nota / autofattura ──Conferma──► Registrazione "Da documento" (righe, castelletto IVA, partite)
Registrazione manuale ──Registra──► Registrata ──Rendi definitive──► Definitiva (n. libro giornale) ──Storna──► Storno
Ricorrente ──ogni notte alle 5:00──► Registrazione "Ricorrente" alla data prevista
```
## Prima nota
Ogni registrazione ha un numero per esercizio (es. `2026/001205`), data di registrazione, data di competenza,
causale, descrizione, documento d'origine, registro IVA e protocollo, stato, periodo e fonte.
![Khaemhat 0.7.0 · prima nota con le registrazioni dell'esercizio](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/contabilita-prima-nota.png)
*La prima nota dell'azienda demo: fatture di vendita (FV) e di acquisto (FA), nota di credito (NCV), liquidazioni IVA
(LIQ), versamenti F24, ritenuta (RIT) e il noleggio mensile ricorrente, tutte nello stato* Registrata.
### Registrare a mano
**Contabilità → Prima nota** elenca le registrazioni dell'esercizio, la più recente per prima, con numero, data,
causale, descrizione, documento, cliente o fornitore, importo e stato. In alto la ricerca (descrizione, numero o
documento) e i filtri **Dal**, **Al** e **Stato**; in fondo la paginazione. Un clic sul numero apre la registrazione.
1. **Contabilità → Prima nota**, premi **+** (Ctrl+N) e scegli la causale.
2. Nella scheda **Righe contabili** inserisci conto (F4 apre il piano dei conti), descrizione, controparte, dare o
avere, centro di costo, commessa e partita. Ctrl+↓ aggiunge una riga.
3. Se la registrazione ha IVA, compila la scheda **Righe IVA** (codice IVA, imponibile, aliquota, imposta, % di
indetraibilità, detraibile, natura).
4. Controlla la **quadratura** nell'intestazione: Dare, Avere e **Sbilancio**. Se c'è uno sbilancio, **Ctrl+D**
lo assegna all'ultima riga.
5. **Salva** (Ctrl+S). La registrazione resta *provvisoria*; quando è corretta premi **Rendi definitiva**.
La scheda **Registrazioni** contiene l'elenco; la scheda **Ricorrenti** le registrazioni che si ripetono (vedi
[sotto](#registrazioni-ricorrenti)). I pulsanti della barra:
Una registrazione che non quadra si può salvare **solo come bozza** (mockup 041: badge rosso con lo sbilancio) e non
può mai diventare definitiva.
### Stati e regole
| Stato | Cosa significa | Cosa si può fare |
| Pulsante | Cosa fa | Permesso |
|---|---|---|
| **Bozza / Provvisoria** | in lavorazione, entra nei saldi ma non sul libro giornale definitivo | modificare, eliminare, rendere definitiva (solo se quadra) |
| **Definitiva** | numerata in modo continuo sul libro giornale | **immutabile**: si corregge solo con uno **storno** collegato |
| **Nuova registrazione** | apre una registrazione vuota | `ledger.entry.write` |
| **Contabilizza documenti** | registra in prima nota i documenti di vendita e acquisto confermati di un periodo che non sono ancora contabilizzati | `ledger.entry.write` |
| **Rendi definitive** | rende definitive tutte le registrazioni fino a un giorno | `ledger.entry.finalize` |
- Le registrazioni **generate da un documento** si modificano solo stornando o correggendo il documento d'origine
(pulsante **Documento origine** per aprirlo).
- Le date sono ammesse solo in **periodi aperti**: un periodo liquidato o bloccato e un esercizio chiuso rifiutano
nuove registrazioni con data interna.
- **Storna** crea la registrazione inversa collegata all'originale (campo *storno di*).
- **Registrazioni ricorrenti**: da una registrazione manuale **Salva modello ricorrente** crea un modello riusabile
(affitti, canoni, stipendi…).
- **Valuta**: le righe possono essere in valuta estera con il cambio; le differenze cambio si rilevano alla chiusura
della partita (vedi [Scadenzario](Scadenzario)).
### Gli stati di una registrazione
| Stato | Significato | Cosa si può fare |
|---|---|---|
| **Bozza** | in lavorazione, senza numero; può non quadrare; non entra nei saldi | modificare, registrare, eliminare |
| **Registrata** | numerata (per esempio `2026/00011`), quadrata, entra nei saldi e nei registri IVA | modificare ed eliminare (se manuale), stornare, rendere definitiva |
| **Definitiva** | ha il numero di **libro giornale** | solo **stornare**: non si modifica né si elimina |
Ogni registrazione indica anche la sua **origine**: *Manuale*, *Da documento*, *Liquidazione IVA*, *Versamento F24*,
*Ricorrente*, *Storno*, *Ritenuta*.
## Registrare a mano
![Khaemhat 0.7.0 · registrazione generata da una fattura di acquisto](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/contabilita-registrazione-fattura.png)
*La registrazione di una fattura di acquisto intracomunitaria: causale FA, registro ACQ1, fornitore in Avere e merci
in Dare; nel castelletto IVA il codice NI41 (natura N3.2). La striscia in alto riassume Dare, Avere, Sbilancio e
righe.*
1. **Contabilità → Prima nota → Nuova registrazione**.
2. Nella **Testata** scegli la **data** e la **causale**: la causale propone le righe con conti e segni e il
**registro IVA**. Scrivi la **descrizione** e, se serve, **numero** e **data del documento**.
3. Nelle **Righe** completa per ogni riga il **conto** (si registra solo sui **sottoconti**), il **cliente o
fornitore** (obbligatorio sui conti con partitario, come *Clienti Italia* e *Fornitori Italia*), la descrizione,
il **centro di costo** e l'importo in **Dare** oppure in **Avere**. **Aggiungi riga** e il cestino aggiungono e
tolgono righe.
4. Se la registrazione ha IVA, compila il **Castelletto IVA** con **Aggiungi aliquota**: codice IVA, imponibile,
imposta e parte indetraibile. Con righe IVA serve un registro IVA.
5. Controlla la striscia in alto: **Dare**, **Avere**, **Sbilancio** e numero di **righe**. **Chiudi lo
sbilancio** mette la differenza sull'ultima riga senza importo (o su una nuova riga, a cui dai il conto).
6. **Salva bozza** conserva il lavoro anche se non quadra; **Registra** salva la registrazione, che deve quadrare, e
le assegna il numero.
Una registrazione con righe IVA non si può datare in un periodo già **liquidato** (vedi [IVA](IVA#liquidazione-iva));
nessuna registrazione si può datare in un periodo **bloccato**, in un esercizio chiuso o **prima dell'ultima
registrazione definitiva**.
### Registrazioni che vengono dai documenti
Le registrazioni *Da documento* non si modificano né si eliminano dalla prima nota: si corregge il **documento** e
Khaemhat riscrive la registrazione con lo stesso numero. Se il documento viene annullato, la registrazione sparisce
oppure, se era già definitiva, viene stornata.
### Stornare ed eliminare
- **Storna** chiede la **data dello storno** e crea una nuova registrazione con Dare e Avere invertiti, collegata
all'originale (che diventa *Stornata*). Si stornano solo le registrazioni registrate o definitive, una volta sola.
- **Elimina** toglie una registrazione manuale non definitiva. Una registrazione usata come modello di una ricorrente
si elimina solo dopo aver tolto la ricorrente.
### Rendere definitive le registrazioni
**Rendi definitive** chiede un giorno e rende definitive tutte le registrazioni registrate fino a quel giorno: ognuna
riceve il **numero di libro giornale**, in ordine di data, e da quel momento si corregge solo con uno storno.
L'operazione non si annulla ed è rifiutata se nel periodo ci sono ancora **bozze** (registrale o eliminale prima).
Dopo, nessuna nuova registrazione può avere una data anteriore all'ultima definitiva.
## Contabilizzazione automatica dei documenti
Alla conferma di un documento (o in un secondo momento con la procedura **Contabilizzazione documenti**, vedi
[Automazioni](Automazioni)) Khaemhat applica la causale contabile del **tipo documento** e genera la registrazione
con le righe IVA e le partite di scadenzario, nella stessa transazione del documento. Il documento mostra il flag
*contabilizzato* e il collegamento alla registrazione; la registrazione mostra il documento d'origine.
Con il modulo ACCT attivo, quando **confermi** (o emetti) uno di questi documenti Khaemhat scrive la sua registrazione
**nella stessa operazione**, con le righe IVA nel suo registro, le **partite** dalle rate di scadenza e l'eventuale
**ritenuta d'acconto**:
## Partitari, mastrini ed estratti conto
Il **partitario** (mockup 044) mostra per un cliente o fornitore: saldo iniziale, dare e avere del periodo, saldo,
di cui scaduto e l'elenco dei movimenti con saldo progressivo e stato della partita. Filtri per periodo, conto,
stato e "solo definitive". Da qui:
- **Estratto conto**: genera il PDF da inviare al cliente (resta come allegato, vedi [Allegati e file](Allegati-e-file));
- **Sollecito**: apre i solleciti dello [Scadenzario](Scadenzario).
Il **drill-down** è completo: dal bilancio al conto, dal conto al mastrino, dal mastrino alla registrazione, dalla
registrazione al documento.
## Esercizi e periodi
In **Tabelle azienda → Esercizi** (mockup 052) ogni esercizio ha inizio, fine, stato, numero di registrazioni,
ultimo periodo IVA liquidato, data di blocco, prima pagina del libro giornale e ultima registrazione definitiva.
| Esercizio | Periodo (mese o trimestre) |
|---|---|
| **Aperto** — si registra normalmente | **Aperto** — accetta registrazioni |
| **In chiusura** — è in corso la procedura di chiusura | **Liquidato** — la liquidazione IVA è stata confermata |
| **Chiuso** — sola lettura | **Bloccato** — rifiuta ogni registrazione con data interna |
**Nuovo esercizio** crea l'esercizio successivo; di norma lo crea la chiusura stessa, in stato provvisorio, per
permettere di registrare nel nuovo anno prima di aver chiuso il vecchio. I periodi si bloccano e sbloccano con
l'interruttore **Blocco** (permesso di riapertura richiesto).
## Chiusura dell'esercizio guidata
**Contabilità → Chiusura esercizio** (mockup 050) guida la chiusura in nove passi. Ogni passo è **ripetibile e
annullabile**; le registrazioni generate sono marcate con la fonte `closing/<passo>` e restano provvisorie fino alle
stampe definitive.
| # | Passo | Cosa fa |
| Documento | Causale | Registro IVA |
|---|---|---|
| 1 | Controlli preliminari | nessuna registrazione provvisoria, partite quadrate, IVA liquidata, numerazioni continue |
| 2 | Ammortamenti | quote civilistiche e fiscali dei [Cespiti](Cespiti) |
| 3 | Ratei e risconti | da competenze dei documenti e inserimenti manuali (**Verifica ratei/risconti**) |
| 4 | Rimanenze finali | valorizzazione del [Magazzino](Magazzino) al 31/12 e storno delle iniziali |
| 5 | Accantonamenti | svalutazione crediti, TFR (da import) |
| 6 | Chiusura conti economici | giroconto a Conto economico e rilevazione del risultato |
| 7 | Chiusura conti patrimoniali | giroconto a Stato patrimoniale finale |
| 8 | Apertura nuovo esercizio | riporto dei saldi e delle partite aperte |
| 9 | Stampe definitive | libro giornale, libro inventari, registri IVA, registro cespiti |
| Fattura immediata, accompagnatoria, differita, di acconto; nota di debito; parcella | `FV` | `VEN1` |
| Nota di credito a cliente | `NCV` | `VEN1` |
| Fattura fornitore | `FA` | `ACQ1` |
| Nota di credito fornitore | `NCA` | `ACQ1` |
| Autofatture e integrazioni (AF16-AF29) | `AFRC` | `VEN-RC` e `ACQ-RC` |
1. Apri la procedura e premi **Esegui passo N**: il passo mostra il numero di registrazioni prodotte e l'esito
(*Superato*, *Eseguito*, *Da verificare*, *In attesa*).
2. Controlla i risultati con l'icona di anteprima e, se serve, torna indietro di un passo.
3. Dopo le stampe definitive premi **Blocca esercizio**: l'esercizio diventa **chiuso**, in sola lettura, e le date
precedenti al nuovo esercizio vengono rifiutate.
Come si formano le righe:
La chiusura è anche nel catalogo delle procedure ([Automazioni](Automazioni)).
- **Vendita**: il **cliente** in Dare per il totale; i **ricavi** in Avere, raggruppati per conto; la **rivalsa
della cassa previdenziale** e il **bollo addebitato** al cliente in Avere; l'**IVA vendite** in Avere. Con lo
**split payment** l'IVA viene subito tolta al cliente (il cliente paga solo l'imponibile).
- **Acquisto**: il **fornitore** in Avere; i **costi** in Dare, con l'**IVA indetraibile** aggiunta al costo;
l'**IVA acquisti** in Dare.
- **Autofattura e integrazione**: **IVA acquisti** in Dare e **IVA vendite** in Avere, senza cliente né fornitore;
il documento compare in entrambi i registri RC, con effetto neutro sulla liquidazione.
- **Note di credito**: le stesse righe con i segni invertiti.
- Lo **sconto in calce** e gli **arrotondamenti** si ripartiscono sulle righe; i centesimi di differenza vanno sulla
riga più grande.
## Bilancio
**Quale conto.** Per ogni riga Khaemhat usa il **Conto ricavi** o **Conto costi** dell'articolo (scheda articolo),
per gli acquisti il **Conto di costo** del fornitore, poi il conto del codice IVA e, se manca, quello della causale
(`30.01.001` *Ricavi per vendita di merci*, `20.01.001` *Merci c/acquisti*). Il cliente e il fornitore usano il
**Conto cliente** o **Conto fornitore** della loro scheda, altrimenti `05.01.001` *Clienti Italia* e `14.01.001`
*Fornitori Italia*. Se manca un conto la conferma del documento si ferma con un messaggio che lo dice.
**Contabilità → Bilancio** (mockup 051) offre quattro viste:
**Contabilizza documenti.** I documenti confermati quando ACCT non era attivo (o prima della versione 0.7) si
registrano in blocco: **Prima nota → Contabilizza documenti**, scegli **Dal** e **Al** e premi **Contabilizza**. La
casella *Ricontabilizza anche i documenti già registrati* riscrive anche le registrazioni esistenti, purché non
siano definitive.
| Vista | Contenuto |
## Registrazioni ricorrenti
![Khaemhat 0.7.0 · la scheda Ricorrenti della prima nota](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/contabilita-ricorrenti.png)
*Il noleggio mensile della stampante dei dati demo: frequenza mensile, prossima data, registrazione modello e stato.*
Affitti, canoni, noleggi: una registrazione **ricorrente** copia una **registrazione modello** alle date previste.
1. Registra una volta la scrittura da ripetere (per esempio *Noleggi* in Dare e *Banca c/c* in Avere).
2. **Prima nota → Ricorrenti → Nuova ricorrente**: descrizione, **numero della registrazione modello** (il numero di
prima nota, per esempio `2026/00018`), **frequenza** (*Mensile*, *Trimestrale*, *Semestrale*, *Annuale*),
**prossima data**, data **Fino al** facoltativa, casella **Sospesa**.
3. Ogni notte alle **5:00** l'attività di sistema *Registrazioni ricorrenti* (vedi
[Attività programmate](Attivita-programmate)) scrive le registrazioni arrivate a scadenza, con origine
*Ricorrente*, e sposta in avanti la prossima data. **Genera ora** fa lo stesso subito.
Una data di fine mese resta di fine mese (31/01, poi 28/02, poi 31/03). **Apri il modello** apre la registrazione da
copiare; eliminando una ricorrente le registrazioni già generate restano.
## Piano dei conti
![Khaemhat 0.7.0 · piano dei conti con il mastrino di Clienti Italia](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/contabilita-piano-dei-conti.png)
*L'albero dei 237 conti del modello PMI standard, il dettaglio del sottoconto 05.01.001 Clienti Italia (sottoconto,
attività, tipo Clienti, voce CEE C.II.1, con partitario) e il suo mastrino con il saldo progressivo.*
Il piano dei conti ha tre livelli con codice **`MM.CC.SSS`**: **mastro** (`05` *Crediti verso clienti*), **conto**
(`05.01` *Clienti*) e **sottoconto** (`05.01.001` *Clienti Italia*). Si registra solo sui sottoconti. Con le tabelle
di base dell'azienda viene caricato il modello **PMI standard** del pacchetto fiscale: 237 conti con le voci di
bilancio CEE già associate (vedi [Fiscalità italiana](Fiscalita-italiana#piano-dei-conti-modello)).
| Campo | Significato |
|---|---|
| **Verifica** | bilancio di verifica per conto (dare, avere, saldo); bilancini per centro di costo e commessa |
| **CEE** | schema civilistico **ordinario**, **abbreviato** o **micro**, con confronto con l'esercizio precedente e Δ % |
| **Riclassificato** | riclassificato finanziario e gestionale |
| **Indici** | indici di bilancio |
| **Codice** | mastro, conto e sottoconto separati da punti; il conto padre deve esistere |
| **Descrizione** | obbligatoria |
| **Natura** | *Attività*, *Passività*, *Costo*, *Ricavo*, *Conto d'ordine* |
| **Tipo** | *Generico*, *Clienti*, *Fornitori*, *Banca*, *Cassa*, *IVA*, *Tributi*: dice alle registrazioni automatiche che cosa cercare |
| **Voce di bilancio CEE** | voce dello schema civilistico (art. 2424 e 2425 c.c.), per esempio `C.II.1` |
| **Riclassificazione** | voce del riclassificato, facoltativa |
| **Partitario** | le righe indicano il cliente o il fornitore |
| **Rilevante IVA** | il conto entra nelle registrazioni con IVA |
| **Chiuso in automatico a fine esercizio** | il conto sarà chiuso dalla procedura di fine esercizio (M10) |
| **Disattivato** | il conto resta nello storico ma non si usa più |
L'intestazione indica la data di situazione (anche **infrannuale**) e se include le registrazioni provvisorie.
Doppio clic su una voce apre i conti, poi il mastrino, la registrazione e il documento. Il bilancio si stampa e si
esporta in XLSX e PDF; la **nota integrativa** è prodotta in bozza. Il formato XBRL è previsto in fase 2
([Roadmap](Roadmap)).
A sinistra l'**albero** con la ricerca per codice o descrizione; a destra i dati del conto scelto e, per i
sottoconti, il **mastrino**: i movimenti del periodo (**Dal**, **Al**) con saldo iniziale, Dare, Avere, **saldo
progressivo**, totali e paginazione. **Stampa** scarica il mastrino in PDF; il numero della registrazione la apre.
## Export per il commercialista
**Nuovo conto**, **Modifica** ed **Elimina** richiedono `ledger.account.write`. Un conto con **movimenti** non si
elimina (disattivalo); un conto con **sottoconti** si elimina solo dopo di loro.
Pacchetto **ZIP mensile** con libro giornale, registri IVA, partitari e bilancio in XLSX, CSV e PDF. Si genera a mano
o in automatico con la procedura **Export per il commercialista** pianificata ogni mese (vedi [Automazioni](Automazioni)
e [Attività programmate](Attivita-programmate)).
## Causali contabili
## Report del modulo
![Khaemhat 0.7.0 · causali contabili, la causale FA con le righe proposte](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/contabilita-causali.png)
*Le causali di base con il loro registro IVA; a destra la causale FA Fattura di acquisto: area Acquisti, registro
ACQ1, apre partite, e le righe proposte con ruolo, segno e conto.*
Libro giornale, mastrini, bilancini per centro di costo e commessa, registri IVA, liquidazioni, scadenzario IVA,
elenco clienti e fornitori per fatturato, riepilogo per natura IVA, dati dei quadri VE/VF, estratti conto, export per
il commercialista. Vedi [Report](Report).
Una **causale** è il modello di una registrazione: propone conti, segni e registro IVA. Ogni causale ha:
## Scorciatoie
| Tasto | Azione |
| Campo | Significato |
|---|---|
| Ctrl+N / Ctrl+S | nuova registrazione / salva |
| Ctrl+D | quadra la registrazione sull'ultima riga |
| F4 | ricerca nel piano dei conti dalla cella *Conto* |
| Ctrl+↓ | nuova riga |
| Ctrl+↑ / Ctrl+↓ (fuori dalla griglia) | registrazione precedente / successiva |
| Alt+1…9 | cambia scheda |
| **Codice**, **Descrizione** | per esempio `FA` *Fattura di acquisto* |
| **Area** | *Generale*, *Vendite*, *Acquisti*, *Tesoreria*, *Imposte*, *Chiusura esercizio* |
| **Registro IVA** | il registro delle registrazioni con IVA |
| **Apre partite** | le registrazioni aprono partite di clienti o fornitori |
| **Causale di storno** | note di credito: i segni del documento si invertono |
| **Disattivato** | la causale non si propone più |
| **Righe proposte** | per ogni riga **ruolo** (*Cliente*, *Fornitore*, *Ricavo*, *Costo*, *IVA vendite*, *IVA acquisti*, *Banca*, *Cassa*, *Ritenute da versare*, *Ritenute subite*, *Contributo cassa*, *Bollo*, *Arrotondamenti*, *Erario c/IVA*, *IVA split payment* o *Conto indicato*), **segno** Dare o Avere, **conto** e descrizione |
Elenco completo in [Interfaccia e scorciatoie](Interfaccia-e-scorciatoie).
Causali di base: **FV** fattura di vendita, **NCV** nota di credito a cliente, **FA** fattura di acquisto, **NCA**
nota di credito da fornitore, **AFRC** autofattura e integrazione reverse charge, **CORR** corrispettivi giornalieri,
**INC** incasso da cliente, **PAG** pagamento a fornitore, **RIT** ritenuta d'acconto operata, **RITS** ritenuta
d'acconto subita, **LIQ** liquidazione IVA periodica, **F24** versamento con modello F24, **GIRO** giroconto, **SPB**
spese e commissioni bancarie, **STO** storno di scrittura.
Le causali dei documenti, della liquidazione, delle ritenute e dell'F24 sono usate dalle registrazioni automatiche:
cambiarne i conti cambia le registrazioni future. Una causale usata da registrazioni non si elimina: disattivala.
Per un'azienda creata con una versione precedente, conti, causali e registri mancanti si aggiungono con
`scripts/seed.sh --base` (vedi [Dati di base e di esempio](Dati-di-base-e-esempio)).
## Partitari ed estratto conto
![Khaemhat 0.7.0 · partitario clienti, estratto conto e partite](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/contabilita-partitari.png)
*Il partitario clienti con Dare, Avere, saldo e partite aperte; a destra l'estratto conto di Edilizia Moderna S.p.A. e
le sue partite, con le scadenze passate in rosso.*
**Contabilità → Partitari** ha due schede, **Clienti** e **Fornitori**. L'elenco mostra per ogni soggetto con
movimenti Dare, Avere, **Saldo** e numero di partite **aperte**, con ricerca per nome o codice e il **saldo
complessivo**.
Scegliendo un soggetto si vedono:
- l'**estratto conto** del periodo (**Dal**, **Al**): saldo iniziale, movimenti con documento e saldo progressivo,
totali; **Stampa** lo scarica in PDF;
- le **partite**: una per rata di ogni documento, con data documento, numero della rata, **scadenza**, importo,
pagato e **residuo**; le scadenze superate sono in rosso. *Mostra anche le partite chiuse* aggiunge quelle saldate.
In questa versione le partite nascono dai documenti; gli incassi e i pagamenti che le chiudono, i solleciti e lo
scadenzario arrivano con lo [Scadenzario](Scadenzario) (M8).
## Bilancio di verifica e libro giornale
![Khaemhat 0.7.0 · bilancio di verifica](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/contabilita-bilancio.png)
*Il bilancio di verifica dell'azienda demo al livello dei sottoconti, con i totali di conti e mastri; la striscia
riassume Dare, Avere, quadratura e risultato del periodo.*
**Contabilità → Bilancio** mostra i saldi di tutti i conti in un periodo:
- filtri **Dal** e **Al**, **Centro di costo** (tutti o uno), **Dettaglio** (*Mastri*, *Conti*, *Sottoconti*) e
**Comprendi le bozze**;
- per ogni conto **saldo iniziale**, **Dare**, **Avere**, **Saldo Dare** o **Saldo Avere**, con i totali di conti e
mastri;
- la striscia con i totali **Dare** e **Avere**, la **Quadratura** (*Dare e Avere quadrano* o no) e il **Risultato
del periodo** (ricavi meno costi: *Utile* o *Perdita*).
Le stampe sono file PDF da scaricare:
| Pulsante | Contenuto |
|---|---|
| **Stampa bilancio** | il bilancio di verifica del periodo e del centro di costo scelti |
| **Libro giornale di prova** | registrazioni registrate e definitive del periodo, in ordine di data, con le righe |
| **Libro giornale definitivo** | solo le registrazioni definitive, con il numero di libro giornale e le pagine numerate dall'inizio dell'anno |
Il bilancio CEE (stato patrimoniale e conto economico civilistici), il riclassificato e gli indici arrivano con la
chiusura dell'esercizio (M10).
## Dati demo
Con i dati di esempio (`scripts/seed.sh --demo`) la contabilità parte già popolata: i documenti demo sono
contabilizzati, la fattura del professionista *Studio Rag. Neri Paola* è pagata e la sua ritenuta è da versare, il
noleggio mensile della stampante (45 euro, conto `22.01.003` *Noleggi* contro la banca) è una registrazione
ricorrente, le liquidazioni IVA dei mesi già finiti sono confermate e gli F24 già scaduti sono pagati. Vedi
[Dati di base e di esempio](Dati-di-base-e-esempio).
## Permessi e licenza
Serve il modulo **ACCT**. Il permesso `ledger.entry.finalize` è necessario per rendere definitiva una registrazione;
gli altri codici indicati in testa seguono la convenzione `modulo.entità.azione` (SPEC §7.2) e saranno fissati in
sviluppo. Il ruolo predefinito **Contabilità** li comprende. Senza licenza ACCT le voci del menu non compaiono, ma i
dati restano conservati.
Serve il modulo **ACCT**: senza, il menu Contabilità non compare, i documenti non vengono contabilizzati (si
recuperano dopo con **Contabilizza documenti**) e i dati già registrati restano conservati.
## Attenzione
| Permesso | Cosa consente |
|---|---|
| `ledger.account.read` | vedere piano dei conti e causali |
| `ledger.account.write` | creare, modificare ed eliminare conti e causali |
| `ledger.entry.read` | prima nota, mastrini, partitari, bilancio e stampe del libro giornale |
| `ledger.entry.write` | registrazioni manuali, storni, ricorrenti, contabilizzazione dei documenti |
| `ledger.entry.finalize` | rendere definitive le registrazioni |
- Una registrazione **definitiva** non si modifica: va stornata. Usa lo stato provvisorio finché non hai controllato.
- Confermare una liquidazione IVA blocca il periodo: correzioni successive richiedono la riapertura (permesso
dedicato) e vanno ricalcolate.
- I numeri del libro giornale definitivo sono continui; la procedura di chiusura verifica che non ci siano buchi.
I permessi della parte IVA (`vat.register.read`, `vat.settlement.read`, `vat.settlement.confirm`) sono in [IVA](IVA).
## Domande frequenti
- **Il pulsante Registra è spento.** Dare e Avere non quadrano: guarda lo *Sbilancio* nella striscia, correggi gli
importi o usa **Chiudi lo sbilancio**. Intanto puoi usare **Salva bozza**.
- **"Si registra solo sui sottoconti".** Hai scelto un mastro o un conto: scegli un sottoconto (codice a tre parti).
- **"Le righe su clienti e fornitori indicano il soggetto".** Il conto ha il partitario: indica il cliente o il
fornitore nella riga.
- **Non riesco a modificare la registrazione di una fattura.** Viene dal documento: correggi la fattura e la
registrazione si aggiorna. Se è già definitiva, la correzione del documento la storna e la riscrive.
- **"Manca un conto per contabilizzare il documento".** Una causale o il piano dei conti non hanno il conto che
serve (per esempio dopo aver cancellato un sottoconto): controlla la causale del documento e il conto dell'articolo.
- **La data è rifiutata.** Il periodo è liquidato (solo per registrazioni con IVA), bloccato, l'esercizio è chiuso o
c'è già una registrazione definitiva successiva.
- **La ricorrente non ha generato nulla.** È sospesa, la data *Fino al* è passata o la prossima data è nel futuro;
**Genera ora** mostra l'eventuale problema.
## Pagine correlate
[IVA](IVA) · [Cespiti](Cespiti) · [Scadenzario](Scadenzario) · [Vendite](Vendite) · [Acquisti](Acquisti) ·
[Magazzino](Magazzino) · [Tabelle azienda](Tabelle-azienda) · [Report](Report) · [Automazioni](Automazioni) ·
[Import-Export](Import-Export) · [Fiscalità italiana](Fiscalita-italiana) · [Glossario](Glossario)
[IVA](IVA) · [Fiscalità italiana](Fiscalita-italiana) · [Vendite](Vendite) · [Acquisti](Acquisti) ·
[Scadenzario](Scadenzario) · [Cespiti](Cespiti) · [Tabelle azienda](Tabelle-azienda) ·
[Attività programmate](Attivita-programmate) · [Dati di base e di esempio](Dati-di-base-e-esempio) ·
[Glossario](Glossario)
+1 -1
View File
@@ -56,7 +56,7 @@ magazzino* M6, *CRM* M11), senza numeri finti.
| **Attività CRM** | le attività del giorno (chiamate, riunioni, visite) | richiede il modulo CRM |
| **Promemoria personali** | note libere, visibili solo a te | |
| **Scorciatoie** | pulsanti configurabili verso maschere e azioni frequenti | |
| **Sottoscorta** | articoli sotto la scorta minima | |
| **Sottoscorta** | gli articoli più urgenti da riordinare (esauriti, sottoscorta, sotto il punto di riordino) con disponibile e scorta; un clic apre i movimenti dell'articolo, **Riordina** la proposta di riordino | dalla 0.6.0 |
| **Pipeline CRM** | valore delle opportunità per fase | richiede il modulo CRM |
| **Ultimi documenti** | ultimi documenti aperti o creati | |
| **Stato del sistema** | versione, database, cache, licenza, aziende aperte, attività programmate di oggi, ognuno con un pallino verde, giallo o rosso | solo account di istanza |
+29 -2
View File
@@ -1,6 +1,6 @@
# Dati di base e di esempio
> **Stato:** completa per M4 · **Ultima revisione:** 2026-11-12 · **Versione software:** 0.4.0 (dati di esempio di documenti e contabilità con i moduli, completi in M9)
> **Stato:** completa per M5 · **Ultima revisione:** 2026-11-12 · **Versione software:** 0.6.0 (dati di esempio di contabilità con il modulo, completi in M9)
> **Modulo di licenza:** CORE · **Livello richiesto:** amministratore (rimozione dati di esempio: super utente) · **Specifica:** SPEC §6, §12.11, §14
## A cosa serve
@@ -133,7 +133,34 @@ i controlli; non si verificano sul VIES (ADR 0029). Gli agenti di esempio non so
Ci sono poi **120 articoli** in dieci categorie con i listini *Pubblico* e *Rivenditori* derivati dal base, prezzi
dell'anno precedente, fornitori abituali, UM e codici alternativi, sostitutivi e i prezzi netti e i codici di un
cliente (ADR 0030, vedi [Articoli e listini](Articoli-e-listini)). I codici a barre di esempio iniziano con `200`,
prefisso riservato all'uso interno. Il resto della tabella arriva con le milestone dei rispettivi moduli.
prefisso riservato all'uso interno.
**Da M5** l'azienda di esempio ha anche il **profilo** compilato (indirizzo, partita IVA, REA, nota a piè di
pagina delle stampe) e **un anno di vendite** costruite con il motore dei documenti, con date dal 1° gennaio a oggi:
| Documenti | Stati |
|---|---|
| 6 preventivi | 2 trasformati in ordine, 1 rifiutato, 1 con la validità scaduta, 1 in attesa di risposta, 1 in bozza |
| 4 ordini clienti | 3 evasi (uno in due consegne), 1 ancora da consegnare |
| 5 DDT | 2 già fatturati in differita, 3 da fatturare (prova la [fatturazione differita](Vendite#fatturazione-differita)) |
| 8 fatture | 5 immediate (una in bozza), 2 differite, 1 pro forma |
| 1 nota di credito | reso di un articolo difettoso, collegata alla fattura |
Le fatture e la nota condividono il numeratore (`1/2026` … `7/2026`), senza buchi e in ordine di data. Tutti i
documenti sono marcati come dimostrativi e la stampa lo scrive in evidenza. Il caricamento non si ripete se
l'azienda ha già documenti di vendita.
**Da M6** ci sono anche **acquisti e magazzino**, costruiti allo stesso modo:
| Documenti | Che cosa mostrano |
|---|---|
| 1 movimento di esistenze iniziali al 1° gennaio (`APE`) | la giacenza di partenza di ogni articolo; un articolo su cinque parte con poca merce, così le vendite lo portano sotto scorta e la [proposta di riordino](Magazzino#proposta-di-riordino) ha qualcosa da proporre |
| 2 ordini fornitori | uno ricevuto per intero, uno ricevuto in parte (il resto è nell'*ordinato*) |
| 2 ricevimenti merce | i carichi dei due ordini |
| 3 fatture fornitore | una dal ricevimento con un prezzo più alto dell'ordine (vedi l'avviso sulle differenze), la parcella del commercialista, la fattura di un fornitore tedesco che aspetta la sua **integrazione AF18** |
| 1 inventario aperto | 12 articoli già contati, due con una differenza |
Il caricamento non si ripete se l'azienda ha già documenti di acquisto o di magazzino. Il resto della tabella arriva con le milestone dei rispettivi moduli.
I dati sono costruiti con gli stessi motori del programma (documenti, contabilità): ogni quadratura torna, e lo
stesso caricamento è usato come prova automatica di correttezza.
+153 -49
View File
@@ -1,21 +1,29 @@
# Fiscalità italiana
> **Stato:** bozza · **Ultima revisione:** 2026-11-11 · **Versione software:** 0.4.0 (codici e regole di base; il resto con M5-M10)
> **Modulo di licenza:** CORE, ACCT, EINV, INTRA · **Specifica:** SPEC §11.1, §11.3-§11.9, §14
> **Stato:** completa per la versione 0.7 · **Ultima revisione:** 2026-11-13 · **Versione software:** 0.7.0 (M7)
> **Modulo di licenza:** CORE, ACCT, EINV, INTRA · **Specifica:** SPEC §11.1, §11.3-§11.9, §14, ADR 0036, ADR 0037
Questa pagina raccoglie in un solo posto i **codici e le regole fiscali italiane** che Khaemhat usa: tipi documento
SDI, nature IVA, modalità e condizioni di pagamento, regimi fiscali, codici tributo F24 e scadenze. Serve come
riferimento rapido mentre si compilano anagrafiche, codici IVA e documenti.
SDI, nature IVA, modalità e condizioni di pagamento, regimi fiscali, il **piano dei conti modello**, i **codici
tributo F24** con le scadenze, la **LIPE**, le **ritenute d'acconto** e il **bollo virtuale**. Serve come riferimento
rapido mentre si compilano anagrafiche, codici IVA e documenti e mentre si liquida l'IVA.
Tutte queste tabelle sono **caricate dai dati di base** (pacchetto dati, per esempio `IT 2026.3`) e si aggiornano da
**Amministrazione → Dati di base e di esempio** con **Aggiorna tabelle di base**. Le descrizioni ufficiali complete
sono quelle delle *specifiche tecniche della fattura elettronica* dell'Agenzia delle Entrate, caricate nel seed: in
caso di dubbio fa fede il testo mostrato dal programma, non questa pagina.
Tutto ciò che è italiano sta nel **pacchetto fiscale Italia** del programma: le tabelle sono **caricate dai dati di
base** (pacchetto dati, per esempio `IT 2026.3`) e si aggiornano da **Amministrazione → Dati di base e di esempio**
con **Aggiorna tabelle di base** (o con `scripts/seed.sh --base`). Le descrizioni ufficiali complete sono quelle
delle *specifiche tecniche della fattura elettronica* dell'Agenzia delle Entrate, caricate nel seed: in caso di dubbio
fa fede il testo mostrato dal programma, non questa pagina.
> **Attenzione.** Khaemhat calcola e prepara i dati (F24, LIPE, Intrastat, bollo) ma **non sostituisce il
> commercialista** né invia F24 e LIPE: l'invio telematico avviene tramite intermediario o home banking, come
> indicato nella maschera della liquidazione. Le norme cambiano: la versione delle specifiche SDI supportata è
> indicata nel programma ed è verificata a ogni rilascio.
> **In questa versione** sono in uso i codici dei documenti, delle nature, dei pagamenti e dei regimi (dalla 0.4),
> e con la 0.7 il piano dei conti *PMI standard*, i registri IVA, le regole della liquidazione e dell'acconto, i
> codici tributo e le scadenze dell'F24, il tracciato LIPE, le ritenute d'acconto e il bollo virtuale. Le parti su
> notifiche SDI, dichiarazioni d'intento, Intrastat e cespiti descrivono regole che il programma userà con la
> [Fatturazione elettronica](Fatturazione-elettronica) (M9) e con [Cespiti](Cespiti) e [Intrastat](Intrastat) (M10).
> **Attenzione.** Khaemhat calcola e prepara i dati (F24, LIPE, Certificazione Unica, bollo) ma **non sostituisce il
> commercialista** né invia F24, LIPE e CU: l'invio telematico avviene con i servizi dell'Agenzia delle Entrate,
> l'home banking o l'intermediario, come ricordato nelle maschere. Le norme cambiano: la versione delle specifiche SDI
> supportata è indicata nel programma ed è verificata a ogni rilascio.
## Dove si trovano questi codici nel programma
@@ -25,10 +33,12 @@ caso di dubbio fa fede il testo mostrato dal programma, non questa pagina.
| Nature IVA (N…) | **Tabelle azienda → Codici IVA** | [Tabelle-azienda](Tabelle-azienda), [IVA](IVA) |
| Modalità di pagamento (MP) | **Tabelle azienda → Metodi di pagamento** | [Tabelle-azienda](Tabelle-azienda) |
| Regime fiscale (RF) | **Tabelle azienda → Profilo azienda**, scheda fornitore | [Tabelle-azienda](Tabelle-azienda), [Anagrafiche](Anagrafiche) |
| Codici tributo F24 | liquidazione IVA, ritenute, bollo virtuale | [IVA](IVA), [Contabilita](Contabilita) |
| Piano dei conti, causali, registri IVA | **Contabilità → Piano dei conti**, *Causali*, *Registri IVA* | [Contabilita](Contabilita), [IVA](IVA) |
| Codici tributo F24 | liquidazione IVA, acconto, ritenute, bollo virtuale | [IVA](IVA) |
| Tipi di ritenuta (RT) e casse (TC) | scheda fiscale del fornitore e del cliente, parcelle, fatture dei professionisti | [Anagrafiche](Anagrafiche), [IVA](IVA#ritenute-dacconto) |
![076 · Codici IVA con nature SDI](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/mockups/thumbs/076-codici-iva.png)
*Mockup 076 — tabella dei codici IVA con aliquota, natura SDI, riferimento normativo ed esigibilità; sotto, il dettaglio del codice selezionato (anteprima ridotta).*
![Khaemhat · codici IVA con natura SDI](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/tabelle-codici-iva.png)
*La tabella dei codici IVA dell'azienda in Tabelle azienda: ogni codice porta aliquota o natura SDI.*
## Tipi documento SDI (TD)
@@ -172,58 +182,149 @@ fatture passive. Il codice RF03 non esiste più nelle specifiche correnti.
I dettagli operativi sono in [Fatturazione-elettronica](Fatturazione-elettronica).
## Piano dei conti modello
Il pacchetto fiscale porta il piano dei conti **PMI standard**: **237 conti** in tre livelli con codice `MM.CC.SSS`
(mastro, conto, sottoconto), ognuno con natura, tipo e voce dello schema di bilancio civilistico (art. 2424 e 2425
c.c.). Si carica con le tabelle di base dell'azienda e si modifica liberamente da **Contabilità → Piano dei conti**
(vedi [Contabilità](Contabilita#piano-dei-conti)).
| Mastri | Natura | Contenuto |
|---|---|---|
| `01`-`09` | Attività | immobilizzazioni immateriali, materiali e finanziarie, rimanenze, crediti verso clienti, altri crediti (IVA, tributi), disponibilità liquide, ratei e risconti attivi, fondi di ammortamento |
| `10`-`17` | Passività | patrimonio netto, fondi rischi, TFR, debiti verso banche, fornitori, debiti tributari e previdenziali, altri debiti, ratei e risconti passivi |
| `20`-`29` | Costi | acquisti, servizi, godimento di beni di terzi, personale, ammortamenti, variazioni delle rimanenze, accantonamenti, oneri diversi, oneri finanziari, imposte sul reddito |
| `30`-`32` | Ricavi | vendite e prestazioni, altri ricavi e proventi, proventi finanziari |
| `90` | Conti d'ordine | conti di apertura e chiusura |
I conti usati dalle registrazioni automatiche:
| Conto | Uso |
|---|---|
| `05.01.001` Clienti Italia | cliente delle fatture di vendita (se la scheda cliente non indica un altro conto) |
| `14.01.001` Fornitori Italia | fornitore delle fatture di acquisto |
| `30.01.001` Ricavi per vendita di merci, `30.02.001` Resi e sconti su vendite | ricavi delle fatture e delle note di credito senza conto sull'articolo |
| `20.01.001` Merci c/acquisti, `20.02.001` Resi e sconti su acquisti | costi delle fatture e note di credito fornitore senza conto sull'articolo o sul fornitore |
| `06.02.001` IVA su acquisti, `15.01.001` IVA su vendite | IVA dei registri acquisti e vendite |
| `15.01.002` Erario c/liquidazione IVA | saldo della liquidazione periodica e suo versamento |
| `15.02.001` Erario c/ritenute lavoro autonomo, `06.03.001` Erario c/ritenute subite | ritenute operate e subite |
| `31.01.002` Rimborso spese di bollo, `27.01.002` Imposta di bollo | bollo addebitato al cliente (ricavo) e bollo a carico dell'azienda (costo) |
| `31.01.003` Rivalsa contributi previdenziali | rivalsa della cassa previdenziale sulle parcelle |
| `27.01.003` IVA indetraibile | IVA indetraibile delle autofatture e del pro rata |
| `28.01.003` Interessi sulla liquidazione IVA trimestrale | interessi dei contribuenti IVA trimestrali |
| `07.01.001` Banca c/c, `07.02.001` Cassa contanti | banca predefinita per i versamenti F24, cassa dei corrispettivi |
**Registri IVA di base:** `VEN1` fatture emesse, `ACQ1` fatture acquisti, `CORR` corrispettivi, `VEN-RC` e `ACQ-RC`
per autofatture e integrazioni. **Causali di base:** FV, NCV, FA, NCA, AFRC, CORR, INC, PAG, RIT, RITS, LIQ, F24,
GIRO, SPB, STO (vedi [Contabilità](Contabilita#causali-contabili)). Fatture, note di debito e parcelle si registrano
con FV su VEN1, le note di credito con NCV, le fatture fornitore con FA su ACQ1, le note di credito fornitore con NCA,
le autofatture AF16-AF29 con AFRC su VEN-RC e ACQ-RC.
## Codici tributo F24
Khaemhat propone il codice tributo e prepara i **dati F24** da passare a intermediario o home banking.
Khaemhat propone il codice tributo e prepara i **dati F24** da passare all'home banking o all'intermediario (vedi
[IVA](IVA#prospetto-f24-e-pagamento)).
| Codice | Uso | Maschera |
| Codice | Uso | Dove nasce |
|---|---|---|
| 6001 … 6012 | IVA mensile, da gennaio (6001) a dicembre (6012) | Liquidazione IVA (046) |
| 6031 … 6034 | IVA trimestrale, dal 1° (6031) al 4° trimestre (6034, contribuenti trimestrali "speciali") | Liquidazione IVA |
| 6013 | Acconto IVA mensili | Liquidazione IVA (acconto di dicembre) |
| 6035 | Acconto IVA trimestrali | Liquidazione IVA (acconto di dicembre) |
| 6099 | IVA dovuta in base alla dichiarazione annuale | Liquidazione IVA |
| 1040 | Ritenute su redditi di lavoro autonomo | Ritenute (047) |
| 1038 | Ritenute su provvigioni | Ritenute (047) |
| 2521 … 2524 | Imposta di bollo sulle fatture elettroniche, dal 1° (2521) al 4° trimestre (2524) | Bollo virtuale (060) |
| 6001 … 6012 | IVA mensile, da gennaio (6001) a dicembre (6012) | Liquidazione IVA |
| 6031, 6032, 6033 | IVA trimestrale del 1°, 2° e 3° trimestre | Liquidazione IVA |
| 6099, rateazione `0101` | saldo IVA del 4° trimestre dei trimestrali, versato con la dichiarazione annuale | Liquidazione IVA |
| 6013 | Acconto IVA mensili | Acconto IVA |
| 6035 | Acconto IVA trimestrali | Acconto IVA |
| 1040 | Ritenute su redditi di lavoro autonomo | Ritenute |
| 1038 | Ritenute su provvigioni | Ritenute |
| 1019 | Ritenute del 4% operate dal condominio | tabella dei codici |
| 1001 | Ritenute su retribuzioni e pensioni | tabella dei codici |
| 2521 … 2524 | Imposta di bollo sulle fatture elettroniche, dal 1° (2521) al 4° trimestre (2524) | Bollo virtuale |
![046 · Liquidazione IVA, F24, LIPE](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/mockups/png/046-liquidazione-iva.png)
*Mockup 046 — liquidazione periodica: registri del periodo con controlli, calcolo dell'IVA da versare, riquadro Versamento con codice tributo, scadenza e termine della LIPE.*
Il codice 6034 (4° trimestre dei trimestrali "speciali") non è usato: per i trimestrali ordinari il saldo del 4°
trimestre si versa con il 6099. Il file **Dati F24** è un CSV con separatore `;`: una riga di intestazione (scadenza,
codice fiscale e denominazione dell'azienda), poi una riga per codice della sezione Erario con rateazione o mese,
anno di riferimento, importo a debito, importo a credito e descrizione, e in fondo il saldo. Il tracciato telematico
degli intermediari non viene prodotto.
![047 · Ritenute, casse previdenza, prospetto F24](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/mockups/png/047-ritenute-parcelle-f24.png)
*Mockup 047 — ritenute operate su parcelle e provvigioni con cassa previdenziale ed ENASARCO; in basso il prospetto F24 con i codici 1040, 1038 e IVA.*
## Liquidazione e acconto IVA
| Regola | Valore in Khaemhat | Riferimento |
|---|---|---|
| Periodicità | mensile o trimestrale, dal profilo azienda | |
| Versamento minimo | se il dovuto (con gli interessi) è sotto **25,82 euro** non si versa e passa al periodo dopo | art. 1 c. 4 DPR 100/1998 |
| Interessi dei trimestrali | **1%** sul saldo a debito di ogni trimestre | |
| Pro rata | percentuale di detraibilità del profilo azienda, applicata all'IVA detraibile degli acquisti | art. 19-bis DPR 633/72 |
| Esigibilità differita e split payment | l'IVA resta fuori dal debito del periodo | |
| Acconto di dicembre | **88%** della base con i metodi storico e previsionale, tutto l'importo con il metodo effettivo (operazioni fino al 20 dicembre); non dovuto sotto **103,29 euro**; versamento entro il **27 dicembre** | L. 405/1990 |
## Comunicazione LIPE
La **comunicazione delle liquidazioni periodiche IVA** (art. 21-bis DL 78/2010) si prepara come file XML nel
tracciato **IVP18** dell'Agenzia delle Entrate: un file per trimestre, con un modulo per ogni mese (o uno per il
trimestre). Ogni modulo riporta totale delle operazioni attive e passive, IVA esigibile e detratta, IVA dovuta o a
credito, debito e credito del periodo precedente, interessi, acconto e importo da versare o a credito. Gli importi
hanno la virgola e due decimali. Il file si chiama `IT<codice fiscale>_LI_<anno>_T<trimestre>.xml`; va firmato e
inviato con i servizi dell'Agenzia o dall'intermediario.
| Trimestre | Scadenza della LIPE |
|---|---|
| 1° | 31 maggio |
| 2° | 16 settembre |
| 3° | 30 novembre |
| 4° | fine febbraio dell'anno dopo |
## Ritenute d'acconto e casse previdenziali
| Tipo | Aliquota | Su | Codice F24 | Tipo e causale nell'XML |
|---|---|---|---|---|
| Lavoro autonomo professionale | 20% | tutto il compenso | 1040 | RT01, causale A |
| Lavoro autonomo occasionale | 20% | tutto il compenso | 1040 | RT01, causale M |
| Provvigioni ad agenti e rappresentanti | 23% | 50% della provvigione | 1038 | RT01, causale R |
| Provvigioni ad agenti con dipendenti o terzi | 23% | 20% della provvigione | 1038 | RT01, causale R |
I tipi di ritenuta della fattura elettronica sono **RT01** (persone fisiche), **RT02** (persone giuridiche),
**RT03**-**RT06** (contributi INPS, ENASARCO, ENPAM, altri); le casse previdenziali vanno da **TC01** (avvocati) a
**TC22** (per esempio **TC04** ingegneri e architetti). La ritenuta operata diventa dovuta quando si **paga** la
fattura del professionista (criterio di cassa) e si versa entro il **16 del mese successivo** al pagamento. I dati
della **Certificazione Unica** (compenso lordo, somme non soggette, imponibile, ritenute per percipiente e causale)
si esportano in CSV; la CU si invia con i servizi dell'Agenzia o dall'intermediario.
## Imposta di bollo
| Regola | Valore |
|---|---|
| Quando | fatture senza IVA (esenti, non imponibili, fuori campo) sopra **77,47 euro** |
| Importo | **2,00 euro** per fattura |
| Nature che contano | N1, N2.1, N2.2, N3.5, N3.6, N4, N5; non contano esportazioni (N3.1), cessioni intracomunitarie (N3.2), San Marino (N3.3), operazioni assimilate (N3.4), inversione contabile (N6.x) e N7 |
| Versamento | per trimestre: 1° entro il **31 maggio** (2521), 2° entro il **30 settembre** (2522), 3° entro il **30 novembre** (2523), 4° entro **fine febbraio** dell'anno dopo (2524) |
| Importi bassi | se il bollo del 1° trimestre non supera **5.000 euro** si versa con il 2°; se 1° e 2° insieme non superano 5.000 euro, con il 3° (DM 4/12/2023) |
## Scadenze e regole principali
| Adempimento | Regola | Note in Khaemhat |
|---|---|---|
| Liquidazione IVA mensile | versamento entro il **16 del mese successivo** | la conferma della liquidazione **blocca il periodo** |
| Liquidazione IVA trimestrale | versamento entro il 16 del secondo mese successivo al trimestre (per il secondo trimestre vale la proroga estiva di agosto), con **interessi dell'1%**; il quarto trimestre si versa con il saldo annuale entro il 16 marzo | interessi calcolati in automatico |
| Liquidazione IVA mensile | versamento entro il **16 del mese successivo** | la conferma della liquidazione segna il periodo come **liquidato** |
| Liquidazione IVA trimestrale | 1°-3° trimestre entro il 16 del secondo mese successivo al trimestre, con **interessi dell'1%**; il 4° trimestre entro il **16 marzo** con il codice 6099 | interessi calcolati in automatico |
| Scadenze in agosto e nei festivi | i versamenti fra il 1° e il 20 agosto slittano al **20 agosto**; una scadenza di sabato, domenica o festivo slitta al primo giorno lavorativo | festivi nazionali, Pasquetta e, dal 2026, il 4 ottobre |
| Versamento minimo | importo fino a **€ 25,82** non versato e riportato al periodo successivo | valore della specifica; da verificare in sviluppo rispetto alla norma vigente |
| Acconto IVA | entro il **27 dicembre**; metodo **storico**, **previsionale** o **analitico** | scelta del metodo nella liquidazione di dicembre |
| LIPE | 1° trimestre entro 31 maggio, 2° entro 16 settembre, 3° entro 30 novembre, 4° entro fine febbraio (o nella dichiarazione annuale) | XML LIPE generato dalla liquidazione |
| Ritenute d'acconto operate | versamento entro il **16 del mese successivo** al pagamento della parcella (1040/1038) | la ritenuta nasce al pagamento della fattura |
| Imposta di bollo | **€ 2,00** se le operazioni esenti, non imponibili o fuori campo superano **€ 77,47** | contano le nature N1, N2.1, N2.2, N3.5, N3.6, N4, N5; non contano esportazioni (N3.1), cessioni intracomunitarie (N3.2), San Marino (N3.3), operazioni assimilate (N3.4), inversione contabile (N6.x) e N7 |
| Bollo virtuale | versamento trimestrale: 1° trimestre entro 31 maggio, 2° entro 30 settembre, 3° entro 30 novembre, 4° entro fine febbraio; con importi bassi i primi trimestri possono slittare (soglia di € 5.000) | elenco da confrontare con quello proposto dall'Agenzia |
| Autofatture e integrazioni (TD16-TD19) | XML da trasmettere **entro il 15 del mese successivo** | promemoria nella dashboard |
| Versamento minimo IVA | importo sotto **25,82 euro** non versato e riportato al periodo successivo | *debito sotto la soglia* nella liquidazione |
| Acconto IVA | entro il **27 dicembre**; metodo **storico**, **previsionale** o **effettivo**; non dovuto sotto 103,29 euro | riquadro *Acconto IVA* della liquidazione |
| LIPE | 1° trimestre entro 31 maggio, 2° entro 16 settembre, 3° entro 30 novembre, 4° entro fine febbraio | file XML dalla liquidazione |
| Ritenute d'acconto operate | versamento entro il **16 del mese successivo** al pagamento della fattura (1040/1038) | la ritenuta diventa dovuta con **Fattura pagata** |
| Bollo virtuale | versamento trimestrale (vedi sopra), con la soglia dei 5.000 euro | elenco da confrontare con quello proposto dall'Agenzia |
| Autofatture e integrazioni (TD16-TD19) | XML da trasmettere **entro il 15 del mese successivo** | promemoria nelle autofatture |
| Fattura differita (TD24) | emissione entro il 15 del mese successivo a quello delle consegne documentate da DDT | procedura **Fatturazione differita** |
| Interessi di mora | D.Lgs. 231/2002 per i ritardi nelle transazioni commerciali | calcolati nei solleciti |
![060 · Bollo virtuale trimestrale](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/mockups/png/060-bollo-virtuale.png)
*Mockup 060 — imposta di bollo del trimestre: fatture con bollo, importo, codice tributo 2524 e scadenza; in fondo la regola dei € 77,47.*
| Interessi di mora | D.Lgs. 231/2002 per i ritardi nelle transazioni commerciali | con i solleciti dello scadenzario (M8) |
## Altri riferimenti usati dal programma
| Tema | Regola | Pagina |
|---|---|---|
| Split payment | IVA versata dalla PA cessionaria (esigibilità **S**) | [Vendite](Vendite) |
| Split payment | IVA versata dalla PA cessionaria (esigibilità **S**): in contabilità l'IVA viene tolta subito al cliente | [Vendite](Vendite), [Contabilita](Contabilita) |
| Reverse charge interno | IVA a carico del cessionario, registri RC vendite e acquisti (IVA neutra) | [Acquisti](Acquisti), [IVA](IVA) |
| Dichiarazione d'intento | operazioni non imponibili N3.5 con controllo di plafond, utilizzato e residuo | [Fatturazione-elettronica](Fatturazione-elettronica) |
| Ritenuta e cassa previdenza | parcelle TD06: cassa (ad esempio 4%) e ritenuta d'acconto; ENASARCO per gli agenti | [Contabilita](Contabilita) |
| Cespiti | coefficienti del DM 31/12/1988, primo anno al 50%, limiti per le autovetture, beni sotto € 516,46 | [Cespiti](Cespiti) |
| Intrastat | elenchi INTRA cessioni e acquisti, periodicità da soglie, nomenclatura NC8 | [Intrastat](Intrastat) |
| Bilancio | schemi CEE art. 2424 (stato patrimoniale) e 2425 (conto economico), ordinario/abbreviato/micro | [Contabilita](Contabilita) |
| Dichiarazione d'intento | operazioni non imponibili N3.5 con controllo di plafond, utilizzato e residuo (M10) | [Fatturazione-elettronica](Fatturazione-elettronica) |
| Ritenuta e cassa previdenza | parcelle TD06: cassa (ad esempio 4%) e ritenuta d'acconto | [IVA](IVA#ritenute-dacconto) |
| Cespiti | coefficienti del DM 31/12/1988, primo anno al 50%, limiti per le autovetture, beni sotto € 516,46 (M10) | [Cespiti](Cespiti) |
| Intrastat | elenchi INTRA cessioni e acquisti, periodicità da soglie, nomenclatura NC8 (M10) | [Intrastat](Intrastat) |
| Bilancio | schemi CEE art. 2424 (stato patrimoniale) e 2425 (conto economico): le voci sono già sui conti, gli schemi arrivano con M10 | [Contabilita](Contabilita) |
## Domande frequenti
@@ -233,7 +334,10 @@ SDI: è registrata nel programma e aggiornata con i rilasci.
**Una natura o un codice non c'è nella tabella.** Lancia **Aggiorna tabelle di base**: il pacchetto dati porta i
codici correnti. Se manca ancora, segnalalo: le code list sono parte del pacchetto fiscale italiano.
**Khaemhat invia l'F24?** No: prepara i dati e la stampa; l'invio passa da intermediario o home banking.
**Posso usare un mio piano dei conti?** Sì: il modello *PMI standard* si modifica, si ampliano i sottoconti e si
disattivano quelli che non servono. L'import di un piano dei conti da file non c'è ancora.
**Khaemhat invia l'F24?** No: prepara i dati e il file; l'invio passa da home banking o intermediario.
## Pagine correlate
+195
View File
@@ -0,0 +1,195 @@
# Guida all'uso
> **Stato:** completa per la versione 0.7 · **Ultima revisione:** 2026-11-13 · **Versione software:** 0.7.0 (M7)
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.7.0 | Arriva con |
|---|---|---|
| Accesso e sicurezza | password, verifica in due passaggi, codici di recupero, blocco dopo i tentativi sbagliati | — |
| Interfaccia | menu, schede, ricerca globale, notifiche, aiuto F1, dashboard a widget, temi e colori | — |
| Tabelle azienda | profilo azienda, esercizi, cambi, codici IVA, pagamenti, banche, depositi, tipi documento, numeratori e le altre tabelle di base | — |
| Anagrafiche | clienti, fornitori, contatti, controlli di partita IVA e codice fiscale, VIES | CRM (lead, opportunità): M11 |
| Articoli | articoli, categorie, listini con prezzi a validità, prezzi netti per cliente, costo medio e ultimo costo dai movimenti | — |
| Vendite | preventivi, ordini, DDT, fatture, note, pro forma, fatturazione differita, stampa PDF, invio per e-mail, scarico del magazzino e impegno, registrazione contabile automatica | incassi e scadenzario M8, XML SDI M9 |
| Acquisti | ordini fornitori, ricevimenti, fatture e note di credito fornitore con protocollo, controllo dei prezzi, import delle fatture elettroniche XML/P7M/ZIP, autofatture e integrazioni in bozza con scadenza, registrazione contabile e registri IVA | pagamenti M8, XML delle autofatture M9 |
| Magazzino | giacenze per deposito, impegnato e ordinato, costo medio, movimenti e trasferimenti, inventario fisico, proposta di riordino, valorizzazione con classi ABC, ricostruzione | scritture delle rimanenze e libro inventari con la chiusura dell'esercizio M10 |
| Contabilità | piano dei conti, causali, prima nota, contabilizzazione automatica dei documenti, registrazioni ricorrenti e definitive, partitari, mastrini, bilancio di verifica, libro giornale | chiusura dell'esercizio, bilancio CEE e cespiti M10 |
| IVA | registri IVA, liquidazione con F24, acconto, file LIPE, ritenute d'acconto con prospetto F24 e dati CU, bollo virtuale | dichiarazioni d'intento M10 |
| Scadenzario | partite aperte dai documenti, visibili nei partitari | incassi, pagamenti, banche e solleciti M8 |
| Fatturazione elettronica | — | M9 |
| Import ed export | clienti, fornitori, articoli, prezzi e giacenze iniziali da CSV, Excel e JSON; esportazione dai radar | import del piano dei conti: più avanti |
| Amministrazione da interfaccia | utenti e licenze da variabili e riga di comando | pagine di amministrazione: M12 |
Le voci di menu delle aree non ancora pronte aprono una pagina che dice che cosa conterranno.
## 1. Entrare
![Pagina di accesso](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/accesso-login.png)
Scegli l'**azienda**, scrivi **nome utente** e **password** e premi **Accedi**. Se il tuo account ha la verifica in
due passaggi, Khaemhat chiede il codice a 6 cifre dell'app di autenticazione (o un codice di recupero). Al primo
accesso può chiederti di cambiare la password. Vedi [Primi passi](Primi-passi) e
[Utenti e permessi](Utenti-e-permessi).
## 2. Orientarsi
![La Home](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/interfaccia-home.png)
- **Barra superiore**: logo e versione, l'**azienda** su cui lavori (si cambia da qui), la **ricerca globale**
(`Ctrl+K`), cronologia, **notifiche**, tema chiaro o scuro, **aiuto** (`F1`) e il menu del tuo profilo.
- **Menu a sinistra**: le aree del gestionale; si comprime per avere più spazio.
- **Schede**: ogni maschera si apre in una scheda; puoi tenerne aperte più insieme e passare dall'una all'altra.
- **Barra di stato** in basso: azienda, esercizio, utente, stato della connessione e versione.
La **Home** è una dashboard a widget che ognuno personalizza. Le scorciatoie da tastiera sono elencate in
[Interfaccia e scorciatoie](Interfaccia-e-scorciatoie#tabella-completa-delle-scorciatoie); la dashboard in
[Dashboard](Dashboard).
![Ricerca globale](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/interfaccia-ricerca.png)
## 3. Preparare l'azienda
![Codici IVA](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/tabelle-codici-iva.png)
Prima dei documenti controlla in **Tabelle azienda**:
1. **Profilo azienda**: ragione sociale, partita IVA, indirizzo, REA, contatti, logo e la nota a piè di pagina delle
stampe. Questi dati compaiono su ogni documento stampato.
2. **Esercizi e periodi**: l'esercizio dell'anno deve essere aperto, altrimenti i documenti non si confermano.
3. **Pagamenti**, **banche**, **codici IVA**, **depositi**: le tabelle di base sono già caricate; aggiungi le tue.
4. **Tipi documento** e **numeratori**: il formato dei numeri (`7/2026`, `OC-2026-0004`) e i sezionali.
5. **Codici automatici**: come si numerano clienti, fornitori e articoli.
Dettagli in [Tabelle azienda](Tabelle-azienda) e [Dati di base e di esempio](Dati-di-base-e-esempio).
## 4. Clienti e fornitori
![Radar dei clienti](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/anagrafiche-radar.png)
**Anagrafiche → Clienti** apre il **radar**, l'elenco con ricerca, filtri, colonne a scelta e viste salvate.
`Ctrl+N` crea un cliente; un doppio clic apre la scheda.
![Scheda cliente](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/anagrafiche-scheda.png)
Nella scheda compili i dati anagrafici e fiscali (partita IVA e codice fiscale sono controllati; la partita IVA UE si
verifica sul VIES), gli indirizzi di consegna, i contatti e le **condizioni commerciali**: pagamento, listino,
agente, banca. I documenti di vendita le propongono da soli. Vedi [Anagrafiche](Anagrafiche).
## 5. Articoli e prezzi
![Scheda articolo](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/articoli-scheda.png)
**Anagrafiche → Articoli**: codice, descrizione, categoria, unità di misura, codice IVA, prezzo, codici a barre,
fornitori abituali. **Listini** gestisce i prezzi per listino con date di validità; nella scheda del cliente puoi
fissare prezzi netti. Vedi [Articoli e listini](Articoli-e-listini).
![Griglia dei listini](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/listini-griglia.png)
## 6. Vendere
![Radar delle fatture](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/vendite-fatture-radar.png)
Il menu **Vendite** raccoglie preventivi, ordini, DDT, fatture e note di credito. Il percorso tipico:
1. **Preventivo** → **Crea Ordine cliente** quando il cliente accetta.
2. **Ordine** → **Crea DDT** a ogni consegna (anche parziale) oppure **Crea Fattura immediata**.
3. **Fatturazione differita** a fine mese: tutti i DDT del periodo diventano fatture, una per cliente.
4. **Nota di credito** dalla fattura per un reso o una correzione.
![Fattura emessa](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/vendite-documento.png)
Nella maschera del documento scegli il cliente, inserisci le righe (`F4` cerca l'articolo) e controlla castelletto
IVA, scadenze e totali; **Conferma** (o **Emetti** per le fatture) assegna il numero. I documenti restano collegati
riga per riga, così Khaemhat sa che cosa resta da consegnare o da fatturare.
![Fatturazione differita](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/vendite-fatturazione-differita.png)
Tutto il ciclo è spiegato in [Vendite](Vendite).
## 7. Stampare e inviare
![Anteprima di stampa](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/vendite-stampa.png)
La **stampante** della toolbar (`Ctrl+P`) apre l'anteprima: **Stampa** con la stampante del computer, **Apri PDF** o
**Scarica PDF**, **Salva come allegato** per conservarne una copia.
![Invio per e-mail](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/vendite-email.png)
Dal menu **⋯** del documento, **Invia per e-mail** propone destinatario, oggetto e testo; il PDF parte in allegato e
l'esito finisce nel log. Vedi [Vendite](Vendite#invio-per-e-mail).
## 8. Comprare
![Fattura fornitore con differenza di prezzo](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/acquisti-fattura-differenze.png)
Il ciclo passivo usa le stesse maschere delle vendite. In **Acquisti → Ordini fornitori** prepari l'ordine (il prezzo
è quello del fornitore nella scheda articolo); quando arriva la merce **Crea DDT fornitore (carico)** registra il
ricevimento, anche in più volte, e alla conferma carica il magazzino. **Crea Fattura fornitore** prepara la fattura:
alla conferma prende il **protocollo** IVA. Se il prezzo fatturato è diverso da quello dell'ordine o del ricevimento,
un avviso sopra le righe lo segnala.
![Import delle fatture passive](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/acquisti-importa-fatture.png)
Le fatture elettroniche ricevute si caricano da **Acquisti → Importa fatture**: XML, P7M o ZIP, anche molti file
insieme. Khaemhat trova o crea il fornitore, abbina gli articoli, scarta i doppioni e registra le fatture in bozza con
il file allegato. Per le fatture di fornitori esteri o in inversione contabile indica quale **autofattura** serve ed
entro quando; **Acquisti → Autofatture** le elenca tutte. Vedi [Acquisti](Acquisti).
## 9. Il magazzino
![Giacenze e disponibilità](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/magazzino-giacenze.png)
**Magazzino → Giacenze** mostra per ogni articolo giacenza, impegnato, ordinato, disponibile, costo medio e valore,
con lo stato rispetto a scorta minima e punto di riordino; apri una riga per vedere i movimenti. I documenti
confermati muovono il magazzino da soli: non serve registrare a parte carichi e scarichi.
![Proposta di riordino](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/magazzino-riordino.png)
**Proposte di riordino** calcola che cosa ordinare e a quale fornitore e crea gli ordini in bozza, uno per fornitore.
**Inventario** guida il conteggio fisico (anche dal file del lettore di codici a barre) e registra le rettifiche;
**Valorizzazione** calcola il valore del magazzino a una data con le classi ABC. Vedi [Magazzino](Magazzino).
## 10. Allegati
![Pannello allegati](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/allegati-pannello.png)
Ogni anagrafica e ogni documento ha la scheda **Allegati**: carichi file dal computer, li vedi in anteprima, scarichi tutto in un archivio ZIP. I PDF che Khaemhat genera sono **versionati**: ogni stampa salvata o
e-mail inviata aggiunge una versione e le precedenti restano. Vedi [Allegati e file](Allegati-e-file).
## 11. Importare ed esportare
![Mappatura delle colonne](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/import-export-mappatura.png)
**Amministrazione → Import/Export** porta in Khaemhat clienti, fornitori, articoli, prezzi di listino e giacenze iniziali da un file
CSV, Excel o JSON: scegli il file, abbini le colonne, guarda l'anteprima con gli errori riga per riga e conferma. Ogni radar
esporta le righe visibili. Vedi [Import/Export](Import-Export).
## 12. Personalizzare
![Il mio profilo](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/preferenze-profilo.png)
Dal menu del tuo nome, **Il mio profilo**: tema chiaro, scuro o automatico, colore d'accento, densità e carattere,
dati personali, password e verifica in due passaggi, sessioni aperte e pagina iniziale. Le preferenze dell'azienda (ad esempio i decimali dei
prezzi) sono in **Tabelle azienda → Preferenze**. Vedi [Preferenze utente](Preferenze-utente).
![Tema scuro](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/design-tema-scuro.png)
## Se qualcosa non va
- **`F1`** apre l'aiuto della pagina in cui sei: la pagina di questa wiki, anche senza connessione a Gitea.
- La pagina di errore riporta un **codice di traccia**: comunicalo all'amministratore, che lo ritrova nel
[Log](Log).
- Le domande più comuni sono in [FAQ](FAQ); i termini del gestionale nel [Glossario](Glossario).
## Pagine correlate
[Primi passi](Primi-passi) · [Interfaccia e scorciatoie](Interfaccia-e-scorciatoie) · [Anagrafiche](Anagrafiche) ·
[Articoli e listini](Articoli-e-listini) · [Tabelle azienda](Tabelle-azienda) · [Vendite](Vendite) ·
[Acquisti](Acquisti) · [Magazzino](Magazzino) · [Contabilità](Contabilita) · [IVA](IVA) ·
[Allegati e file](Allegati-e-file) · [Import/Export](Import-Export) · [Preferenze utente](Preferenze-utente)
+5 -1
View File
@@ -1,6 +1,6 @@
# Khaemhat
> **Stato:** bozza · **Ultima revisione:** 2026-11-12 · **Versione software:** 0.4.0 (M4; sviluppo in corso)
> **Stato:** completa per 0.7.0 · **Ultima revisione:** 2026-11-13 · **Versione software:** 0.7.0 (M7; 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) |
+230 -142
View File
@@ -1,199 +1,287 @@
# IVA
> **Stato:** bozza · **Ultima revisione:** 2026-11-10 · **Versione software:** non ancora rilasciata (milestone M7; dichiarazioni d'intento in M10)
> **Modulo di licenza:** ACCT (bollo virtuale e dichiarazioni d'intento anche con EINV) · **Permessi principali:** `vat.settlement.confirm`, `vat.register.print`, `vat.withholding.write`, `vat.intent.write` · **Specifica:** SPEC §11.7, §11.9, §11.3, §14
> **Stato:** completa per la versione 0.7 · **Ultima revisione:** 2026-11-13 · **Versione software:** 0.7.0 (M7)
> **Modulo di licenza:** ACCT · **Permessi principali:** `vat.register.read` (registri IVA), `vat.settlement.read` (liquidazione, ritenute, bollo, F24), `vat.settlement.confirm` (conferme, versamenti, stampe definitive) · **Specifica:** SPEC §11.7, §11.9, §14, ADR 0037
## A cosa serve
Questa pagina descrive l'IVA e i versamenti collegati, tutti nel menu **Contabilità**:
Questa pagina descrive tutto ciò che riguarda l'IVA e i versamenti collegati:
- **registri IVA** con protocollo, stampa di prova e stampa definitiva;
- **liquidazione periodica** mensile o trimestrale, con credito e debito riportati, pro rata, interessi trimestrali e
minimo di versamento; **acconto di dicembre**; file della **comunicazione LIPE** e dati del modello **F24**;
- **ritenute d'acconto** operate e subite, **prospetto F24** con il suo pagamento e dati per la **Certificazione
Unica**;
- **imposta di bollo virtuale** sulle fatture elettroniche, per trimestre.
- **registri IVA** con protocollo e stampe definitive;
- **liquidazione periodica** con esigibilità differita, IVA per cassa, pro-rata, acconto di dicembre, interessi,
minimo di versamento, **dati F24** e **LIPE**;
- **ritenute d'acconto** e **casse previdenziali**, con prospetto F24 e dati per la **CU**;
- **imposta di bollo virtuale** sulle fatture elettroniche;
- **dichiarazioni d'intento** ricevute ed emesse, con plafond.
> **Khaemhat non trasmette nulla.** Prepara i file della LIPE, i dati dell'F24 e i dati della Certificazione Unica;
> l'invio telematico si fa con i servizi dell'Agenzia delle Entrate, con l'home banking o tramite l'intermediario.
Khaemhat **non trasmette** F24, LIPE e CU: prepara i dati, i file e le stampe; l'invio telematico avviene tramite
intermediario o home banking (avviso presente nel mockup 046).
> **In questa versione** ci sono i cinque registri IVA con stampe di prova e definitive, la liquidazione con la sua
> registrazione e il versamento F24, l'acconto IVA, il file LIPE, le ritenute con il prospetto F24 e il pagamento, i
> dati della CU e il bollo virtuale. Arrivano più avanti: i **pagamenti delle fatture** dallo scadenzario, che oggi
> per le ritenute si registrano a mano (M8), le **dichiarazioni d'intento** e il plafond e l'**Intrastat** (M10),
> l'**IVA per cassa** completa (fase 2). Non ci sono ancora la **dichiarazione IVA annuale** e l'**invio
> telematico** di F24, LIPE e CU.
## Dove si trova
- **Contabilità → Registri IVA**, **Contabilità → Liquidazione IVA**, **Contabilità → Ritenute**.
- **Fatturazione elettronica → Bollo virtuale**, **→ Dichiarazioni d'intento**, **→ LIPE**.
Menu **Contabilità** → *Registri IVA*, *Liquidazione IVA*, *Ritenute e F24*, *Bollo virtuale*. La **periodicità**
IVA (mensile o trimestrale) e la **percentuale di pro rata** si impostano nel **profilo azienda** (vedi
[Tabelle azienda](Tabelle-azienda)). Le registrazioni che queste pagine scrivono sono in **Prima nota** (vedi
[Contabilità](Contabilita)).
## Schermate
![045 · Registri IVA](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/mockups/thumbs/045-registri-iva.png)
*Mockup 045 — registro Vendite 1 del mese con protocolli, imponibile, aliquota o natura, imposta ed esigibilità; in alto l'ultima stampa definitiva (anteprima ridotta)*
![046 · Liquidazione IVA](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/mockups/png/046-liquidazione-iva.png)
*Mockup 046 — liquidazione mensile provvisoria: parametri, registri del periodo con i controlli superati, calcolo dell'IVA da versare e riquadro del versamento (codice tributo, scadenza, export F24, scadenza LIPE)*
![047 · Ritenute e F24](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/mockups/png/047-ritenute-parcelle-f24.png)
*Mockup 047 — ritenute operate e subite con cassa previdenziale, periodo e stato del versamento; sotto, il prospetto F24 del 16 del mese con i tributi 1040, 1038 e 6009*
![060 · Bollo virtuale](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/mockups/png/060-bollo-virtuale.png)
*Mockup 060 — fatture del trimestre soggette a bollo con natura, importo esente e addebito; riquadri con importo, codice tributo, scadenza e trimestre precedente*
![061 · Dichiarazioni d'intento](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/mockups/png/061-dichiarazioni-intento.png)
*Mockup 061 — dichiarazioni d'intento ricevute con protocollo AdE, plafond, utilizzato, residuo e stato (attiva, avviso al 97 %, esaurita)*
```
Documenti confermati ──► Registri IVA ──Calcola──► Liquidazione ──Conferma──► registrazione LIQ + riga F24
Fattura del professionista ──Fattura pagata──► Ritenuta da versare ──► riga F24 (1040)
Fatture con bollo del trimestre ──Metti in F24──► riga F24 (2521-2524)
Righe F24 della scadenza ──► Prospetto F24 ──Registra pagamento──► registrazione F24
```
## Registri IVA
Registri previsti: **vendite**, **acquisti**, **corrispettivi**, **vendite reverse charge**, **acquisti reverse
charge** e i **sezionali** che servono (es. `VEN1`, `ACQ1`, `VEN-RC`, `ACQ-RC`, `ACQ-SP` per lo split payment,
`CORR`). Ogni documento registrato riceve un **protocollo** progressivo nel suo registro.
![Khaemhat 0.7.0 · registro IVA delle fatture emesse](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/contabilita-registri-iva.png)
*Il registro VEN1 di ottobre: una scheda per registro, la striscia con tipo, imponibile, imposta, ultima stampa
definitiva e ultima pagina, le righe con protocollo e il riepilogo per aliquota.*
La griglia mostra protocollo, data di registrazione, documento, data del documento, controparte, P.IVA o codice
fiscale, imponibile, aliquota o natura, imposta, totale ed **esigibilità** (`I` immediata, `D` differita, `S`
scissione dei pagamenti).
**Contabilità → Registri IVA** ha una scheda per registro:
**Stampe**
| Stampa | Effetto |
| Registro | Contenuto |
|---|---|
| **Provvisoria** | in qualunque momento, senza effetti |
| **Stampa definitiva** del periodo | pagine numerate, totali per aliquota e natura; aggiorna "ultima stampa definitiva" |
| **Riepilogo aliquote** | totali del periodo per codice IVA e natura |
| **VEN1** Registro fatture emesse | fatture, note di debito, parcelle e note di credito di vendita |
| **VEN-RC** Registro fatture emesse - autofatture e integrazioni | il lato *vendite* delle autofatture e integrazioni (TD16-TD29) |
| **ACQ1** Registro fatture acquisti | fatture e note di credito dei fornitori |
| **ACQ-RC** Registro fatture acquisti - autofatture e integrazioni | il lato *acquisti* delle stesse autofatture |
| **CORR** Registro dei corrispettivi | le registrazioni dei corrispettivi (causale `CORR`) |
Le autofatture reverse charge (TD16-TD19) sono annotate sia nel registro vendite RC sia nel registro acquisti RC,
Scegli il periodo con **Dal** e **Al**. Ogni riga mostra **protocollo** (il link apre la registrazione), **data di
registrazione IVA**, documento e data, cliente o fornitore, **aliquota** o natura, **imponibile**, **imposta**,
**indetraibile** ed **esigibilità** (*Immediata*, *Differita*, *Scissione dei pagamenti*). Sotto, il **riepilogo per
aliquota** e il totale del registro.
Le autofatture e integrazioni compaiono in **VEN-RC** e in **ACQ-RC** con la stessa imposta: a debito e a credito,
con effetto neutro sulla liquidazione.
## Liquidazione IVA periodica
### Stampe
| Stampa | Effetto | Permesso |
|---|---|---|
| **Stampa di prova** | PDF del registro nel periodo scelto, in qualunque momento, senza effetti | `vat.register.read` |
| **Stampa definitiva** | PDF dal giorno dopo l'ultima stampa definitiva fino al giorno scelto, con le pagine numerate di seguito all'ultima pagina dell'anno | `vat.settlement.confirm` |
La stampa definitiva non si annulla: la striscia mostra la data dell'**ultima stampa definitiva** e l'**ultima
pagina**, e la stampa successiva riparte da lì (la prima dell'anno parte dal 1° gennaio e dalla pagina 1). La stampa
definitiva **non blocca** le registrazioni: a bloccare il periodo è la conferma della liquidazione (vedi sotto).
## Liquidazione IVA
![Khaemhat 0.7.0 · liquidazione IVA di ottobre confermata](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/contabilita-liquidazione-iva.png)
*La liquidazione mensile di ottobre 2026 confermata: registri del periodo, calcolo con il credito di settembre,
riquadro del versamento (codice 6010, scadenza 16/11/2026, trimestre LIPE) e l'elenco delle liquidazioni dell'anno.*
### Come si fa
1. **Contabilità → Liquidazione IVA**. Controlla i parametri: **Periodicità** (mensile o trimestrale, dal profilo
azienda), **Periodo**, **Data liquidazione**, **Credito precedente**, **Pro-rata**.
2. Premi **Calcola**. Khaemhat esegue i **controlli preliminari** (mostrati con il segno di spunta sopra i registri):
numerazione continua, nessuna bozza, date coerenti, periodo precedente confermato.
3. Controlla la tabella **Registri del periodo** (documenti, imponibile, IVA, indetraibile, note come *neutra* per il
reverse charge) e il riquadro **Calcolo**.
4. Premi **Conferma**: la liquidazione diventa definitiva e il **periodo viene bloccato** (vedi
[Contabilità](Contabilita), esercizi e periodi). Serve il permesso `vat.settlement.confirm`.
5. Premi **Dati F24** per esportare i dati del versamento e **LIPE XML** per il file della comunicazione.
1. **Contabilità → Liquidazione IVA**. La **periodicità** viene dal profilo azienda; scegli **Anno** e **Periodo**
(mese o trimestre).
2. Premi **Calcola** (serve `vat.settlement.read`). Khaemhat legge i registri del periodo e mostra la tabella
**Registri del periodo** (documenti, imponibile, imposta, indetraibile, esigibilità differita), il riquadro
**Calcolo** e il riquadro **Versamento** con codice tributo, anno, importo, scadenza e trimestre LIPE. Puoi
ricalcolare quante volte vuoi finché la liquidazione non è confermata.
3. Premi **Conferma liquidazione** (serve `vat.settlement.confirm`). Le liquidazioni si confermano in ordine: se un
periodo precedente è calcolato ma non confermato, va confermato prima. Alla conferma Khaemhat:
- scrive in prima nota la registrazione **LIQ**: *IVA su vendite* in Dare, *IVA su acquisti* in Avere, gli
interessi trimestrali in Dare, l'eventuale IVA resa indetraibile dal pro rata a costo, e la differenza su
*Erario c/liquidazione IVA*;
- segna i periodi dell'esercizio come **liquidati**;
- se c'è da versare, aggiunge la riga del modello **F24** con codice tributo e scadenza (vedi
[Prospetto F24](#prospetto-f24-e-pagamento)).
4. **Dati F24** scarica i dati del modello F24 della scadenza; **Comunicazione LIPE** scarica il file del trimestre
(vedi [sotto](#comunicazione-lipe)).
**Riapri** annulla la conferma: la registrazione LIQ viene eliminata (o stornata, se è già definitiva), la riga F24
viene tolta e i periodi tornano aperti. Non si riapre se l'F24 della liquidazione è già **pagato** (annulla prima il
pagamento) né se una liquidazione **successiva** è confermata (riapri prima quella).
**Periodi liquidati.** Dopo la conferma, documenti e registrazioni **con IVA** datati nei periodi liquidati sono
rifiutati: per correggere bisogna riaprire la liquidazione. Le registrazioni senza IVA restano libere.
### Le voci del calcolo
| Voce | Regola |
| Voce | Regola in Khaemhat |
|---|---|
| IVA a debito | dai registri vendite e corrispettivi del periodo (esigibilità immediata) |
| IVA a credito | dai registri acquisti, al netto dell'**indetraibile** e del **pro-rata** |
| Esigibilità differita | l'IVA delle fatture a esigibilità differita entra quando si incassa (o alla scadenza di legge) |
| IVA per cassa | con il regime dell'IVA per cassa attivo nel profilo azienda, debito e credito seguono incassi e pagamenti; il regime completo è previsto in fase 2 ([Roadmap](Roadmap)) |
| Credito del periodo precedente | riportato automaticamente |
| Acconto versato | sottratto nella liquidazione di dicembre (o del 4° trimestre) |
| Interessi 1 % | maggiorazione dell'1 % per i contribuenti **trimestrali** |
| Minimo di versamento | se l'IVA dovuta non supera **€ 25,82** non si versa e si **riporta** al periodo successivo |
| **IVA a debito sulle vendite** | imposta dei registri vendite e corrispettivi del periodo, tolta quella a esigibilità differita e in scissione dei pagamenti |
| **IVA a credito sugli acquisti** | imposta dei registri acquisti, tolta la parte **indetraibile** dei codici IVA, poi ridotta dal **pro rata** del profilo azienda |
| **IVA indetraibile** | indetraibile per codice IVA più la parte tolta dal pro rata |
| **IVA a esigibilità differita** | mostrata a parte: non entra nel debito del periodo |
| **Credito / debito periodo precedente** | riportati dalla liquidazione confermata precedente |
| **Acconto versato** | l'acconto di dicembre registrato, tolto nell'ultima liquidazione dell'anno (dicembre o 4° trimestre) |
| **Interessi trimestrali 1%** | per i contribuenti trimestrali, sul saldo a debito |
| **Da versare** | se il totale (con gli interessi) è sotto **25,82 euro** non si versa: diventa *debito sotto la soglia* e passa al periodo dopo; se il saldo è a credito diventa *credito da riportare* |
### Acconto di dicembre
### Codici tributo e scadenze
L'acconto si calcola con uno dei tre metodi: **storico**, **previsionale**, **analitico**. Khaemhat propone gli
importi di tutti e tre e l'utente sceglie. Percentuali e scadenza seguono le regole in vigore (al momento della
stesura: 88 % per storico e previsionale, liquidazione al 20 dicembre per l'analitico, versamento entro il 27
dicembre) e sono aggiornate con il pacchetto fiscale. Codici tributo: **6013** (mensili) e **6035** (trimestrali).
| Periodo | Codice | Scadenza |
|---|---|---|
| Mese (gennaio-dicembre) | **6001**-**6012** | 16 del mese dopo |
| 1°, 2°, 3° trimestre | **6031**, **6032**, **6033** | 16 del secondo mese dopo il trimestre (16/5, 20/8, 16/11) |
| 4° trimestre | **6099**, rateazione **0101** | 16 marzo dell'anno dopo, con il saldo annuale |
### Codici tributo F24
Le scadenze di sabato, domenica o festivo passano al primo giorno lavorativo; i versamenti dal 1° al 20 agosto
passano al **20 agosto**. Codici e calendario sono in [Fiscalità italiana](Fiscalita-italiana#codici-tributo-f24).
| Codice | Versamento |
### Acconto IVA di dicembre
Il riquadro **Acconto IVA** (sotto l'elenco delle liquidazioni, con `vat.settlement.confirm`) calcola l'acconto da
versare entro il **27 dicembre** (primo giorno lavorativo successivo se festivo) con il codice **6013** (mensili) o
**6035** (trimestrali).
| Metodo | Base di calcolo | Acconto |
|---|---|---|
| **Storico** | l'IVA dell'ultimo periodo dell'anno prima (dicembre o 4° trimestre), al lordo dell'acconto di allora e senza interessi | 88% della base |
| **Previsionale** | l'IVA che prevedi per l'ultimo periodo dell'anno: la scrivi tu | 88% della base |
| **Effettivo** | l'IVA dall'inizio dell'ultimo periodo al **20 dicembre** | tutta la base |
1. Scegli il **metodo**: la **base di calcolo** si compila con il valore che Khaemhat conosce (il riquadro *Basi di
calcolo* mostra storico ed effettivo; **Ricalcola le basi** le rilegge). Per il previsionale scrivila tu.
2. **Registra acconto** aggiunge la riga F24 dell'acconto. Sotto **103,29 euro** l'acconto non è dovuto e non viene
registrato. Finché non è pagato puoi registrarlo di nuovo con un altro metodo: la riga si aggiorna.
L'acconto registrato viene tolto nella liquidazione di dicembre o del 4° trimestre.
### Comunicazione LIPE
**Comunicazione LIPE** scarica il file XML della **comunicazione delle liquidazioni periodiche IVA** di un trimestre,
nel tracciato **IVP18** dell'Agenzia delle Entrate: un modulo per ogni mese (o per il trimestre), con operazioni
attive e passive, IVA esigibile e detratta, debiti e crediti riportati, interessi, acconto e importo da versare o a
credito. Il pulsante si accende quando è confermata la liquidazione dell'ultimo mese del trimestre (o del trimestre).
Il file si chiama `IT<codice fiscale>_LI_<anno>_T<trimestre>.xml` e va firmato e inviato con i servizi dell'Agenzia
o dall'intermediario. Le scadenze sono in [Fiscalità italiana](Fiscalita-italiana#comunicazione-lipe).
## Ritenute d'acconto
![Khaemhat 0.7.0 · ritenute operate e prospetto F24](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/contabilita-ritenute.png)
*La ritenuta operata sulla fattura dello Studio Rag. Neri Paola (RT01, causale A, cassa TC04, 20% di 450 euro) già
pagata e da versare; sotto, il prospetto F24 della scadenza del 16/11/2026 con l'IVA di ottobre.*
**Contabilità → Ritenute e F24** elenca le ritenute dei documenti di un **anno**, nelle schede **Operate**, **Subite**
e **Tutte**:
- **operate**: quelle che l'azienda trattiene sulle **fatture dei professionisti** e degli agenti (fatture fornitore
con ritenuta);
- **subite**: quelle che i clienti trattengono sulle **parcelle** e fatture emesse dall'azienda con ritenuta.
Le ritenute nascono da sole quando il documento viene contabilizzato. Per ognuna: documento (il link apre la
registrazione), data, cliente o fornitore, **tipo** e causale di pagamento (per esempio `RT01 · A`), imponibile,
**cassa** previdenziale e contributo, **aliquota** (con la quota dell'imponibile, per esempio *20% su 50%* per gli
agenti), importo, data di pagamento della fattura e **stato**:
| Stato | Significato |
|---|---|
| 6001 … 6012 | IVA mensile, da gennaio (6001) a dicembre (6012) |
| 6031 … 6034 | IVA trimestrale, dal 1° (6031) al 4° trimestre (6034); il 6034 riguarda i trimestrali "speciali", per gli altri il saldo del 4° trimestre si versa con la dichiarazione annuale (6099) |
| 6013 / 6035 | acconto IVA mensili / trimestrali |
| 6099 | IVA da dichiarazione annuale |
| 1040 | ritenute su redditi di lavoro autonomo |
| 1038 | ritenute su provvigioni (agenti e rappresentanti) |
| *In attesa del pagamento* | ritenuta operata su una fattura non ancora pagata |
| *Da versare* | la fattura è pagata: la ritenuta va versata con l'F24 |
| *Versata* | l'F24 che la contiene è pagato |
| *Subita* | ritenuta trattenuta dal cliente su una fattura dell'azienda |
I codici sono caricati con i dati di base ([Dati di base e di esempio](Dati-di-base-e-esempio)) e riepilogati in
[Fiscalità italiana](Fiscalita-italiana).
### Registrare il pagamento della fattura
### LIPE
La ritenuta operata diventa dovuta **quando paghi la fattura** del professionista (criterio di cassa). Finché i
pagamenti non arrivano con lo [Scadenzario](Scadenzario) (M8), si registra a mano:
La **Comunicazione delle liquidazioni periodiche IVA** si genera come file XML nel tracciato dell'Agenzia delle
Entrate dalle liquidazioni confermate del trimestre (voce di menu **Fatturazione elettronica → LIPE** o pulsante
**LIPE XML**). Il riquadro **Versamento** mostra il trimestre di riferimento e la scadenza.
1. Sulla riga della ritenuta premi **Fattura pagata** e indica la data di pagamento.
2. Khaemhat scrive la registrazione **RIT** (*fornitore* in Dare, *Erario c/ritenute lavoro autonomo* in Avere) e
aggiunge la ritenuta alla riga F24 del suo codice tributo (**1040** lavoro autonomo, **1038** provvigioni) e del
mese di pagamento, con scadenza il **16 del mese dopo**. Le ritenute dello stesso codice e mese si sommano.
3. Per una ritenuta **subita**, **Fattura pagata** chiede la data in cui il cliente ha pagato e scrive la registrazione
**RITS** (*Erario c/ritenute subite* in Dare, *cliente* in Avere): è un credito d'imposta.
## Ritenute d'acconto e casse previdenziali
Il pulsante con la freccia annulla il pagamento della fattura (e la sua registrazione) finché l'F24 non è pagato.
**Contabilità → Ritenute** (mockup 047) elenca le ritenute **operate** (sulle parcelle e provvigioni che paghiamo) e
quelle **subite** (sulle nostre fatture, ad esempio verso la PA), con i filtri **Operate / Subite / Tutte**.
### Dati per la Certificazione Unica
| Colonna | Significato |
|---|---|
| Tipo | professionista TD06, agente ENASARCO, ritenuta subita… |
| Imponibile, Cassa, Importo cassa | contributo previdenziale (es. 4 % INPS di rivalsa, 4 % cassa professionale) |
| Ritenuta | aliquota (es. 20 %; per gli agenti l'aliquota si applica a una quota della provvigione) |
| Periodo → F24 | mese di pagamento della fattura e data del modello F24 in cui confluisce |
| Stato | *Da versare*, *In F24*, *Versata*, *Subita* |
**Dati Certificazione Unica** scarica un file CSV con i **percipienti** dell'anno: una riga per professionista e
causale con codice fiscale, denominazione, causale, anno, compenso lordo, somme non soggette, imponibile, ritenute,
codice tributo e documenti. Contiene le ritenute operate sulle fatture pagate nell'anno. La CU si compila e si invia
con i servizi dell'Agenzia delle Entrate o dall'intermediario.
Regole:
## Prospetto F24 e pagamento
- La ritenuta nasce come **debito verso l'Erario al pagamento** della fattura (criterio di cassa) e confluisce nel
prospetto F24 del mese successivo (tributi **1040** e **1038**).
- Sulle **parcelle (TD06)** cassa previdenziale, ritenuta e netto a pagare sono calcolati in automatico; **ENASARCO**
si applica agli agenti con i relativi massimali.
- **Registra versamento** registra il pagamento del modello F24 e chiude le ritenute versate.
- **CU export** produce i dati della Certificazione Unica da consegnare all'intermediario.
Il riquadro **Prospetto F24** (nella pagina *Ritenute e F24*) raccoglie tutto ciò che va versato con l'F24: IVA della
liquidazione, acconto IVA, ritenute operate, bollo virtuale.
Il **Prospetto F24** del giorno di scadenza riepiloga tributi, periodi e importi (ritenute e IVA) con il totale.
1. Scegli la **scadenza** nell'elenco (si apre sulla prima non pagata).
2. Il prospetto mostra una riga per **codice tributo** e periodo con descrizione, periodo di riferimento, importo a
debito e a credito, e il **saldo** dell'F24.
3. **Dati F24** scarica un file CSV (separatore `;`, sezione Erario) con intestazione, una riga per codice tributo e il
saldo, da passare all'home banking o all'intermediario.
4. Pagato l'F24, **Registra pagamento** chiede la data: Khaemhat scrive la registrazione **F24** (*Erario
c/liquidazione IVA*, *Erario c/ritenute* e *imposta di bollo* in Dare secondo le righe, la **banca** in Avere) e
segna versate le righe e le ritenute. La banca è quella predefinita dell'azienda (il suo *conto contabile*), o
`07.01.001` *Banca c/c*.
**Annulla pagamento** toglie la registrazione del pagamento (o la storna, se è definitiva) e riporta le righe da
versare.
## Imposta di bollo virtuale
Sulle fatture con operazioni **esenti, non imponibili o fuori campo IVA** di importo **superiore a € 77,47** si
applica il bollo di **€ 2,00**, calcolato in automatico sul documento e indicato nell'XML (`DatiBollo`).
Sulle fatture elettroniche **senza IVA** (operazioni esenti, non imponibili o fuori campo) di importo **superiore a
77,47 euro** si applica il bollo di **2 euro**. Khaemhat lo calcola già sul documento di vendita (vedi
[Vendite](Vendite)), che dice anche se è **addebitato al cliente** o **a carico dell'azienda**.
**Fatturazione elettronica → Bollo virtuale** (mockup 060) mostra le fatture del trimestre con il bollo, la natura
IVA, l'importo esente e l'**addebito** (*addebitato al cliente*, *a carico azienda*; per le fatture ricevute *a
carico fornitore*). I riquadri riportano numero di fatture, importo, codice tributo del trimestre (**2521-2524**),
scadenza e stato del trimestre precedente.
**Contabilità → Bollo virtuale** riepiloga il bollo per **anno** e **trimestre**:
1. A fine trimestre controlla l'elenco e confrontalo con quello messo a disposizione dall'Agenzia delle Entrate.
2. **Esporta per F24** produce i dati del versamento.
3. A pagamento avvenuto premi **Segna versato**.
- la striscia del trimestre: numero di **fatture**, **importo**, **codice tributo**, **scadenza** e lo stato del
**trimestre precedente**;
- l'elenco delle fatture del trimestre con il bollo: documento (il link lo apre), data, cliente, imponibile, bollo e
**addebito**;
- il riepilogo dei quattro trimestri dell'anno con fatture, importo, scadenza e stato (*Da mettere in F24*, *In F24*,
*pagato il*).
> **Attenzione:** alcune operazioni non imponibili sono escluse dal bollo per legge (per esempio le cessioni
> intracomunitarie e le esportazioni). L'esclusione sarà gestita sul codice IVA; la regola precisa sarà verificata in
> sviluppo con la normativa vigente.
| Trimestre | Codice | Scadenza |
|---|---|---|
| 1° | **2521** | 31 maggio |
| 2° | **2522** | 30 settembre |
| 3° | **2523** | 30 novembre |
| 4° | **2524** | fine febbraio dell'anno dopo |
## Dichiarazioni d'intento e plafond
Se il bollo del **1° trimestre** non supera **5.000 euro** si versa con il 2° (30 settembre); se quello del 1° e del
2° insieme non supera 5.000 euro si versa con il 3° (30 novembre). Le scadenze festive passano al primo giorno
lavorativo.
**Fatturazione elettronica → Dichiarazioni d'intento** (mockup 061) gestisce:
- **Ricevute**: dichiarazioni degli esportatori abituali nostri clienti (numero, data, cliente, **protocollo AdE**,
plafond, utilizzato, residuo, anno, stato);
- **Emesse (plafond nostro)**: dichiarazioni che l'azienda presenta ai propri fornitori.
Regole:
- Il plafond si aggiorna a ogni fattura con codice IVA **N3.5** (non imponibile a seguito di dichiarazione d'intento).
- Al **90 %** di utilizzo compare un avviso (e la regola di automazione predefinita *Avviso plafond* avvisa
l'amministrazione, vedi [Automazioni](Automazioni)); al **100 %** la fattura è bloccata.
- Il protocollo della dichiarazione è riportato nell'XML della fattura (blocco `AltriDatiGestionali`).
- **Registro cronologico** stampa il registro delle dichiarazioni.
La dichiarazione è collegata alla scheda fiscale del cliente ([Anagrafiche](Anagrafiche)).
1. Scegli il trimestre e confronta l'elenco con quello che l'Agenzia delle Entrate mette a disposizione nell'area
riservata.
2. **Metti in F24** (serve `vat.settlement.confirm`) aggiunge la riga del bollo al prospetto F24 della scadenza. Se
il bollo del trimestre cambia (una fattura in più), premilo di nuovo: finché non è pagata la riga si aggiorna.
3. **Dati F24** scarica i dati dell'F24 di quella scadenza; il pagamento si registra dal
[Prospetto F24](#prospetto-f24-e-pagamento).
## Permessi e licenza
- Registri, liquidazione, F24, LIPE, ritenute: modulo **ACCT**.
- Bollo virtuale e dichiarazioni d'intento: compaiono nel menu Fatturazione elettronica e la specifica li elenca sia
in ACCT sia in EINV; l'abbinamento definitivo sarà fissato in sviluppo.
- `vat.settlement.confirm` è richiesto per confermare la liquidazione; gli altri codici in testa sono indicativi
(convenzione `modulo.entità.azione`, SPEC §7.2).
Tutto è nel modulo **ACCT**.
| Permesso | Cosa consente |
|---|---|
| `vat.register.read` | vedere i registri IVA e farne la stampa di prova |
| `vat.settlement.read` | calcolare e vedere le liquidazioni, ritenute, bollo, prospetto F24; scaricare LIPE, dati F24 e CU |
| `vat.settlement.confirm` | confermare e riaprire le liquidazioni, registrare acconto, pagamenti delle fatture, pagamenti F24, bollo in F24, stampa definitiva dei registri |
## Domande frequenti
**Ho trovato un errore in un periodo già liquidato.** Il periodo è bloccato: un utente con il permesso di
riapertura sblocca il periodo, si corregge, si ricalcola e si conferma di nuovo. Se l'F24 è già stato versato, la
differenza va gestita nella liquidazione successiva o con ravvedimento (fuori da Khaemhat).
**Khaemhat invia l'F24?** No. Prepara dati e stampe; l'invio è dell'intermediario o dell'home banking.
**Dove imposto la periodicità IVA e il pro-rata?** Nel profilo azienda ([Tabelle azienda](Tabelle-azienda)).
- **"Conferma prima la liquidazione del periodo precedente".** Un mese (o trimestre) precedente è calcolato ma non
confermato: confermalo prima. Il credito e il debito si riportano solo da una liquidazione confermata.
- **Ho trovato un errore in un periodo già liquidato.** Riapri la liquidazione (e prima quelle successive, se
confermate), correggi il documento, ricalcola e conferma di nuovo. Se l'F24 è già pagato, annulla prima il
pagamento; se l'hai davvero versato, la differenza va gestita nella liquidazione successiva o con il ravvedimento,
fuori da Khaemhat.
- **Il pulsante Comunicazione LIPE è spento.** Il trimestre non è finito o la liquidazione del suo ultimo mese non è
confermata.
- **La ritenuta non compare nel prospetto F24.** È *In attesa del pagamento*: registra **Fattura pagata**. La ritenuta
va nella scadenza del 16 del mese dopo il pagamento.
- **La stampa definitiva del registro è rifiutata.** Deve partire dal giorno dopo l'ultima stampa definitiva: la
striscia del registro mostra quale.
- **Khaemhat invia F24, LIPE o CU?** No: prepara i dati e i file; l'invio è dell'home banking, dei servizi
dell'Agenzia delle Entrate o dell'intermediario.
- **Dove imposto periodicità e pro rata?** Nel profilo azienda, in [Tabelle azienda](Tabelle-azienda).
## Pagine correlate
[Contabilità](Contabilita) · [Fatturazione elettronica](Fatturazione-elettronica) · [Vendite](Vendite) ·
[Acquisti](Acquisti) · [Intrastat](Intrastat) · [Scadenzario](Scadenzario) · [Fiscalità italiana](Fiscalita-italiana) ·
[Automazioni](Automazioni) · [Report](Report)
[Contabilità](Contabilita) · [Fiscalità italiana](Fiscalita-italiana) · [Vendite](Vendite) · [Acquisti](Acquisti) ·
[Scadenzario](Scadenzario) · [Fatturazione elettronica](Fatturazione-elettronica) · [Tabelle azienda](Tabelle-azienda) ·
[Glossario](Glossario)
+18 -12
View File
@@ -1,6 +1,6 @@
# Import/Export
> **Stato:** completa per M4 · **Ultima revisione:** 2026-11-12 · **Versione software:** 0.4.0 (scrittura di giacenze iniziali in M6, piano dei conti in M7; saldi e partite di apertura in M7 e M9)
> **Stato:** completa per M4 · **Ultima revisione:** 2026-11-12 · **Versione software:** 0.4.0 (giacenze iniziali dalla 0.6.0, piano dei conti dalla 0.7.0; saldi e partite di apertura più avanti)
> **Modulo di licenza:** CORE (piano dei conti: ACCT) · **Livello richiesto:** amministratore, oppure permesso di scrittura o di export dell'entità · **Specifica:** SPEC §11.7, §12.12 · **Decisione:** ADR 0031
## A cosa serve
@@ -94,13 +94,16 @@ obbligatoria. Unità alternative, codici alternativi, fornitori e sostitutivi re
netto), non entrambi. Stesso articolo, listino o cliente e data: il prezzo si sostituisce; una data nuova aggiunge
un prezzo che vale da quel giorno, come nella griglia dei listini. Le righe senza errori si scrivono tutte insieme.
### Giacenze iniziali (solo verifica fino a M6)
### Giacenze iniziali
`articolo`\*, `deposito` (vuoto: il deposito dell'articolo), `quantita`\* (maggiore di zero), `costo_unitario`.
L'articolo deve essere merce gestita a magazzino. Il controllo serve a preparare il file: la scrittura del movimento
di apertura arriva con il [Magazzino](Magazzino).
`articolo`\*, `deposito` (vuoto: il deposito dell'articolo, poi quello predefinito), `quantita`\* (maggiore di zero),
`costo_unitario` (vuoto: costo medio, standard o ultimo costo dell'articolo). L'articolo deve essere merce gestita a
magazzino e non può comparire due volte nello stesso deposito. Dalla 0.6.0 l'import scrive **un movimento di
magazzino per deposito** con la causale `APE` (esistenza iniziale) alla data dell'import e lo conferma: giacenze e
costo medio partono da lì (vedi [Magazzino](Magazzino#esistenze-iniziali)). Se la causale `APE` manca, le righe sono
saltate con un messaggio: aggiungila con *Aggiorna da tabelle base*.
### Piano dei conti (solo verifica fino a M7)
### Piano dei conti
Vedi il tracciato più sotto.
@@ -113,7 +116,7 @@ Vedi il tracciato più sotto.
| Opzione | Valori | Entità |
|---|---|---|
| **Se il codice esiste** | *Aggiorna* (le celle piene cambiano il record, le vuote lasciano ciò che c'è) oppure *Salta la riga* (avviso) | clienti, fornitori, articoli, prezzi |
| **Se il codice esiste** | *Aggiorna* (le celle piene cambiano il record, le vuote lasciano ciò che c'è) oppure *Salta la riga* (avviso) | clienti, fornitori, articoli, prezzi, piano dei conti |
| **Codice mancante** | *Genera automatico* con le regole dei codici automatici (vedi [Tabelle azienda](Tabelle-azienda)) oppure *Errore sulla riga* | clienti, fornitori, articoli |
| **Verifica P.IVA su VIES (UE)** | controlla su VIES le partite IVA dei soggetti UE durante l'import (più lento) | clienti, fornitori |
| **Completa comune da CAP** | completa comune e provincia da un CAP con un solo comune, o il CAP da un comune con un solo CAP (avviso) | clienti, fornitori |
@@ -158,8 +161,10 @@ farla sull'azienda reale.
## Tracciato del piano dei conti
In Italia non esiste uno standard per lo scambio del piano dei conti, perciò Khaemhat definisce il proprio
tracciato. Il piano standard per PMI sarà **precaricato** con la contabilità (M7); l'importazione serve a chi vuole
usare il piano del proprio commercialista o del gestionale precedente. Fino a M7 il file si **verifica** soltanto.
tracciato. Il piano standard per PMI è **precaricato** con la contabilità (dalla 0.7, vedi [Contabilità](Contabilita));
l'importazione serve a chi vuole usare il piano del proprio commercialista o del gestionale precedente. I conti nuovi
si aggiungono; quelli che esistono si aggiornano se l'opzione **Se il codice esiste** è *Aggiorna*, altrimenti si
saltano. Lo stesso tracciato si usa per esportare il piano dell'azienda.
### CSV e XLSX
@@ -210,7 +215,8 @@ Per lo scambio **completo** fra installazioni Khaemhat:
```
`accounts` ha le stesse colonne del CSV. Voci di bilancio (`statementLines`), causali (`journalTemplates`) e
mappature (`mappings`) si contano già nella mappatura e si importano con la contabilità (M7).
mappature (`mappings`) si contano nella mappatura ma non si importano ancora: le causali si gestiscono in
*Contabilità → Causali*.
### Controlli
@@ -231,8 +237,8 @@ Il riquadro **Esporta e modelli** usa l'entità scelta in alto:
(nome `clienti-2026-11-12.csv`). I codici delle tabelle sono esportati come codici.
L'export richiede il flag utente **Può esportare dati** e il permesso di export dell'entità (per le anagrafiche
*Esportare anagrafiche*) (vedi [Utenti e permessi](Utenti-e-permessi)). Giacenze e piano dei conti hanno per ora solo
il modello. Le griglie esportano anche dal proprio menu (CSV/XLSX).
*Esportare anagrafiche*) (vedi [Utenti e permessi](Utenti-e-permessi)). Le giacenze hanno per ora solo il
modello; il piano dei conti si esporta per intero. Le griglie esportano anche dal proprio menu (CSV/XLSX).
## Domande frequenti
+14
View File
@@ -55,6 +55,20 @@ Khaemhat invia e-mail (inviti, recupero password, documenti, report, avvisi) tra
I valori iniziali possono arrivare dalle variabili `KHAEMHAT_SMTP_HOST`, `_PORT`, `_USER`, `_PASSWORD`, `_FROM`,
`_SECURITY`; quelli salvati qui li sovrascrivono.
> **In 0.5.0** la pagina *Impostazioni* non c'è ancora (arriva con M12): il server SMTP si configura **solo con le
> variabili d'ambiente** e serve all'invio dei documenti per e-mail (vedi [Vendite](Vendite#invio-per-e-mail)).
>
> | Variabile | Valore |
> |---|---|
> | `KHAEMHAT_SMTP_HOST` | nome del server; senza, l'invio è spento |
> | `KHAEMHAT_SMTP_FROM` | indirizzo del mittente (solo l'indirizzo, ad esempio `ufficio@azienda.it`); obbligatorio insieme all'host |
> | `KHAEMHAT_SMTP_SECURITY` | `STARTTLS` (predefinito), `SSL` (o `TLS`, connessione cifrata dall'inizio) oppure `NONE` (solo su reti fidate) |
> | `KHAEMHAT_SMTP_PORT` | predefinita 587, oppure 465 con `SSL` |
> | `KHAEMHAT_SMTP_USER`, `KHAEMHAT_SMTP_PASSWORD` | credenziali, se il server le chiede (AUTH PLAIN o LOGIN); la password anche come `KHAEMHAT_SMTP_PASSWORD_FILE` |
>
> Il client SMTP è scritto in Khaemhat, senza librerie esterne: un messaggio per connessione, tre tentativi, l'esito
> nel [Log](Log), sezione *E-mail / PEC*.
**Prova:** premi **Invia e-mail di prova** dopo aver salvato: arriva un messaggio all'indirizzo indicato. L'esito
compare anche in [Stato sistema](Stato-sistema) (controllo *SMTP*) e nel [Log](Log), sezione *E-mail / PEC*.
+2 -2
View File
@@ -59,7 +59,7 @@ Ogni modulo scrive nella **propria sezione**. Il pannello a sinistra le elenca c
| **Autenticazione** | accessi, errori di password, blocchi, 2FA, nuovi dispositivi |
| **Database** | connessioni, manutenzione |
| **Migrazioni** | migrazioni applicate e loro esito |
| **Documenti** | creazione, emissione, annullamento di documenti |
| **Documenti** | conferma ed emissione con il numero assegnato, chiusura, riapertura, annullamento, eliminazione delle bozze (da 0.5.0) |
| **Contabilità** | registrazioni, liquidazioni, chiusure |
| **Magazzino** | movimenti, ricostruzioni |
| **SDI / e-invoicing** | generazione XML, invii, notifiche, scarti |
@@ -68,7 +68,7 @@ Ogni modulo scrive nella **propria sezione**. Il pannello a sinistra le elenca c
| **Attività programmate** | inizio, fine, durata, esito di ogni esecuzione |
| **Backup** | backup, copie remote, verifiche, ripristini |
| **API / MCP** | chiamate API e strumenti MCP |
| **E-mail / PEC** | invii e letture di posta |
| **E-mail / PEC** | invii e letture di posta: da 0.5.0 ogni messaggio messo in coda, inviato, ritentato o fallito, con la risposta del server SMTP |
| **Integrazioni** | VIES, cambi BCE, intermediari SDI |
| **UI / circuiti** | errori dell'interfaccia con lo stack completo |
| **Prestazioni** | query oltre 500 ms, richieste lente, garbage collection |
+136 -90
View File
@@ -1,148 +1,194 @@
# Magazzino
> **Stato:** bozza · **Ultima revisione:** 2026-11-10 · **Versione software:** non ancora rilasciata (milestone M6)
> **Modulo di licenza:** CORE · **Permessi principali:** `inventory.entry.post`, `items.cost.read`, famiglia `inventory.*` · **Specifica:** SPEC §11.6, §22
> **Stato:** completa per la versione 0.6 · **Ultima revisione:** 2026-11-12 · **Versione software:** 0.6.0 (M6)
> **Modulo di licenza:** CORE · **Permessi principali:** `inventory.stock.read` (giacenze), `inventory.entry.*` (movimenti, inventario), `inventory.entry.post` (conferma, rettifiche, ricostruzione), `items.cost.read` (costi e valori) · **Specifica:** SPEC §11.6, ADR 0035
Il **magazzino** tiene la quantità e il valore di ogni articolo in ogni **deposito**. Le giacenze si aggiornano da
sole con i documenti (DDT, fatture accompagnatorie, carichi, resi) e con i movimenti manuali; da qui si fanno
trasferimenti tra depositi, inventari fisici, la proposta di riordino e la valorizzazione.
sole quando confermi un documento che muove la merce (DDT, fatture accompagnatorie, carichi dai fornitori, resi,
movimenti manuali); da qui consulti giacenze e movimenti, fai l'**inventario fisico**, generi la **proposta di
riordino** e calcoli la **valorizzazione** a una data.
> **In questa versione** ci sono giacenze per deposito, impegnato e ordinato, costo medio ponderato, movimenti per
> articolo, movimenti manuali e trasferimenti, inventario fisico con import dei conteggi, proposta di riordino,
> valorizzazione con analisi ABC e ricostruzione. Arrivano più avanti: le **scritture contabili** delle rimanenze e il
> **libro inventari** con la chiusura dell'esercizio (M10), i report di magazzino stampabili (M13), FIFO e LIFO a lotti (dopo la 1.0).
## Dove si trova
Menu **Magazzino** → *Giacenze*, *Movimenti*, *Inventario fisico*, *Sottoscorta* (proposta di riordino),
*Trasferimenti*. I depositi e le causali di magazzino sono in [Tabelle azienda](Tabelle-azienda).
Menu **Magazzino** → *Giacenze*, *Movimenti*, *Inventario*, *Proposte di riordino*. I **depositi** e le **causali
di magazzino** sono in [Tabelle azienda](Tabelle-azienda); scorta minima, punto e lotto di riordino e fornitori
abituali sono nella scheda dell'articolo (vedi [Articoli e listini](Articoli-e-listini)).
## Le quattro quantità
## Le quantità
| Quantità | Significato | Da dove nasce |
|---|---|---|
| **Giacenza** | merce fisicamente presente nel deposito | carichi e scarichi confermati |
| **Impegnato** | merce riservata a ordini clienti confermati e non ancora evasi | ordini clienti, trasferimenti in bozza |
| **Ordinato** | merce in arrivo dai fornitori | ordini fornitore confermati e non ancora ricevuti |
| **Disponibile** | **giacenza - impegnato** | calcolata |
| **Giacenza** | merce presente nel deposito | movimenti dei documenti confermati |
| **Impegnato** | merce riservata a ordini clienti confermati e non ancora evasi | residuo degli ordini clienti |
| **Ordinato** | merce in arrivo dai fornitori | residuo degli ordini fornitore confermati |
| **Disponibile** | giacenza meno impegnato | calcolata |
Il sistema registra anche la merce **in transito** e il **valore medio** per articolo e deposito. Tutte queste
quantità sono aggiornate **nella stessa transazione** del documento che le muove: non c'è mai un momento in cui il
documento è confermato e la giacenza no.
Tutte si aggiornano **nella stessa operazione** che conferma il documento: non c'è mai un momento in cui il documento
è confermato e la giacenza no. Se annulli il documento, i suoi movimenti spariscono e le quantità tornano come prima.
## Quali documenti muovono il magazzino
Ogni tipo documento ha una **causale di magazzino** (in *Tabelle azienda → Tipi documento*) che decide se carica,
scarica o trasferisce. Con i tipi di base:
| Documento | Causale | Effetto |
|---|---|---|
| DDT, fattura immediata, fattura accompagnatoria | `SCA` scarico per vendita | scarica al costo medio |
| DDT fornitore (carico), fattura fornitore | `CAR` carico da acquisto | carica e aggiorna il costo medio |
| Nota di credito fornitore | `RESF` reso a fornitore | scarica |
| Movimento di magazzino (`MM`) | quella scelta nel movimento | carico, scarico o trasferimento |
| Ordini clienti e fornitori, preventivi, fatture differite | nessuna | solo impegnato e ordinato |
Una fattura nata da un DDT **non muove di nuovo** la merce: le sue righe trovano il carico o lo scarico già fatto
dal DDT. Il prezzo della fattura fornitore però **corregge il costo** del carico: se il fornitore fattura a un prezzo
diverso da quello del DDT, il costo medio viene ricalcolato con il prezzo fatturato.
Le causali di base sono: `CAR` carico da acquisto, `SCA` scarico per vendita, `RESC` reso da cliente, `RESF` reso a
fornitore, `TRA` trasferimento tra depositi, `INVP` e `INVN` rettifiche inventariali, `CVU` e `CVR` uscita e rientro
in conto visione (solo quantità), `OMA` omaggio, `AUTO` autoconsumo, `APE` esistenza iniziale. Per un'azienda creata
con una versione precedente le causali e i tipi documento mancanti si aggiungono con **Aggiorna da tabelle base** nel
menu `…` della tabella (vedi [Tabelle azienda](Tabelle-azienda)) o, per tutte le tabelle, con `scripts/seed.sh --base`.
## Giacenze e disponibilità
![036 · Giacenze, disponibilità, sottoscorta](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/mockups/thumbs/036-giacenze.png)
*Mockup 036 — striscia di indicatori (valore magazzino, articoli gestiti, sottoscorta, sotto riordino, in arrivo) e griglia giacenze con stato (anteprima ridotta).*
![Khaemhat 0.6.0 · giacenze e disponibilità](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/magazzino-giacenze.png)
In alto una **striscia di indicatori**: valore del magazzino, articoli gestiti, articoli **sottoscorta**, articoli
**sotto il punto di riordino**, valore **in arrivo** (ordinato).
In alto la striscia degli indicatori: **articoli in giacenza**, **sottoscorta**, **esauriti**, **articoli in
arrivo** (con ordini fornitore aperti) e **valore di magazzino** (visibile solo con `items.cost.read`).
La griglia mostra per ogni articolo: categoria, UM, **giacenza**, **impegnato**, **ordinato**, **disponibile**,
**scorta minima**, **punto di riordino**, **costo medio**, **valore** e uno **stato**:
Sotto, il filtro **Deposito** (tutti o uno solo) e la casella **Anche gli articoli senza giacenza**; poi il radar
con ricerca per codice o descrizione e i filtri rapidi **Categoria** e **Stato**. Per ogni articolo: categoria, unità,
giacenza, impegnato, ordinato, disponibile, scorta minima, costo medio, valore e uno **stato**:
| Stato | Quando |
|---|---|
| *OK* | disponibilità sopra il punto di riordino |
| *Sotto riordino* | disponibilità sotto il punto di riordino |
| *Sottoscorta* | disponibilità sotto la scorta minima (riga evidenziata) |
| *Esaurito · in arrivo* | giacenza a zero con ordini fornitore aperti |
| *Disponibile* | il disponibile più l'ordinato supera il punto di riordino |
| *Da riordinare* | disponibile più ordinato pari o sotto il punto di riordino |
| *Sottoscorta* | disponibile sotto la scorta minima |
| *Esaurito* | disponibile sotto zero, o a zero per un articolo con scorta minima o punto di riordino |
Filtri: ricerca (articolo, EAN, descrizione), **Deposito**, **Categoria**, **Mostra** (*Solo gestiti a magazzino*),
chip *Evidenzia sottoscorta*. Azioni: **Proposta di riordino**, **Inventario**. Il dettaglio per deposito di un
singolo articolo è anche nella scheda articolo (vedi [Articoli e listini](Articoli-e-listini)).
Le colonne *Ultimo carico* e *Ultimo scarico* si aggiungono dal selettore delle colonne del radar. I pulsanti
portano alla **proposta di riordino** e all'**inventario**, aprono la **valorizzazione** e la **ricostruzione**.
## Movimenti e trasferimenti
## Movimenti di un articolo
![037 · Movimento di magazzino manuale (trasferimento)](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/mockups/thumbs/037-movimento-magazzino.png)
*Mockup 037 — trasferimento in bozza dal deposito SEDE al deposito furgone, con disponibilità all'origine e valore (anteprima ridotta).*
![Khaemhat 0.6.0 · movimenti di un articolo](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/magazzino-movimenti-articolo.png)
I **movimenti manuali** servono per tutto ciò che non passa da un documento di vendita o acquisto: carichi e scarichi
rettificativi, omaggi interni, consumi, **trasferimenti** tra depositi. Ogni movimento ha una **causale di
magazzino** che ne stabilisce l'effetto (carico, scarico, trasferimento).
Apri una riga delle giacenze (doppio clic o **Invio**) per vedere i movimenti dell'articolo in ordine di data: il
documento che li ha generati (il link lo apre), la causale, il cliente o fornitore, il deposito, la quantità, il
costo unitario e il **saldo progressivo**. **Apri l'articolo** porta alla scheda. Il widget *Sottoscorta* della
[Dashboard](Dashboard) apre direttamente questa finestra sull'articolo scelto.
Per un trasferimento:
## Movimenti manuali e trasferimenti
1. **Magazzino → Trasferimenti** (o *Movimenti*), **Nuovo**.
2. Scegli la causale di trasferimento, il **deposito di origine** e quello di **destinazione**.
3. Inserisci le righe: la colonna *Disp. origine* mostra quanto è disponibile nel deposito di partenza.
4. Se serve, **Stampa lista prelievo** per chi prepara la merce.
5. **Conferma**.
Per tutto ciò che non passa da un documento di vendita o acquisto (rettifiche, omaggi, autoconsumi, conto visione,
trasferimenti) usa **Magazzino → Movimenti** e crea un **Movimento di magazzino**: è un documento come gli altri
(vedi [Vendite](Vendite) per la maschera), con in più la **causale** e il **deposito**.
Un trasferimento genera **due movimenti collegati** (scarico dall'origine e carico nella destinazione) nella stessa
transazione. Finché il movimento è in bozza la merce dell'origine risulta **impegnata**.
1. Scegli la **causale**: decide se il movimento carica, scarica o trasferisce.
2. Indica il **deposito**; per un trasferimento anche il **deposito di destinazione**, diverso dall'origine.
3. Inserisci le righe con articolo e quantità; nei carichi il prezzo è il costo unitario.
4. **Conferma**: il magazzino si aggiorna. Un trasferimento scarica l'origine e carica la destinazione al costo medio,
senza cambiare il valore complessivo.
Un movimento confermato si può annullare: i suoi movimenti vengono tolti e le giacenze ricalcolate.
## Inventario fisico
![038 · Inventario fisico con conteggi e rettifiche](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/mockups/thumbs/038-inventario-fisico.png)
*Mockup 038 — inventario guidato in cinque passi, griglia con giacenza teorica, contato, differenza, valore e rettifica (anteprima ridotta).*
![Khaemhat 0.6.0 · inventario fisico in conteggio](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/magazzino-inventario.png)
L'inventario è una procedura guidata:
L'inventario confronta la merce contata con la **giacenza contabile** e trasforma le differenze in rettifiche.
1. **Preparazione**: scegli il **deposito**, la **data** e il criterio di **valorizzazione** (es. costo medio);
l'opzione **Blocca movimenti durante il conteggio** congela le giacenze del deposito.
2. **Conteggio**: **Stampa liste di conteggio** (anche per ubicazione e squadra) e inserisci i quantitativi contati
nella griglia oppure **Importa conteggi CSV**.
3. **Verifica differenze**: la griglia confronta **giacenza teorica** e **contato** e mostra differenza e valore;
il filtro *Solo differenze e da contare* aiuta a chiudere il lavoro.
4. **Rettifiche**: **Genera rettifiche** crea i movimenti di carico o scarico per allineare la giacenza al contato.
5. **Chiusura**: sblocca il deposito.
1. **Apertura**: in **Magazzino → Inventario** scegli il **deposito**, la **data del conteggio**, se vuoi una
**categoria** e una descrizione, poi **Apri inventario**. Khaemhat fotografa la giacenza contabile di ogni articolo
gestito a magazzino a quella data.
2. **Conteggio**: scrivi le quantità contate nella colonna *Contato* e premi **Salva conteggi**, oppure **Importa
conteggi** da un file CSV o di testo del lettore di codici a barre: una riga per articolo con *codice articolo* e
*quantità*, separati da punto e virgola, tabulazione o virgola (con la virgola la quantità usa il punto decimale).
Una riga di intestazione viene saltata; i codici non in lista sono segnalati.
3. **Verifica differenze**: il filtro **Mostra** (*Tutti*, *Da contare*, *Con differenze*) aiuta a chiudere il
lavoro; le righe con differenza sono evidenziate e la striscia in alto riassume articoli contati, differenze e
valore delle differenze.
4. **Registrazione**: **Registra rettifiche** crea alla data del conteggio un movimento `INVP` per le eccedenze e uno
`INVN` per gli ammanchi, e chiude l'inventario. Gli articoli **non contati restano come sono**.
**Annulla inventario** lo chiude senza muovere il magazzino; i conteggi restano consultabili. I movimenti successivi
alla data del conteggio non disturbano: le rettifiche sono alla data del conteggio e la giacenza di oggi tiene conto
di entrambi.
## Proposta di riordino
![039 · Proposta di riordino fornitori dal sottoscorta](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/mockups/thumbs/039-proposta-di-riordino.png)
*Mockup 039 — proposta di riordino: indicatori, criterio di calcolo, quantità proposta modificabile e fornitore per riga (anteprima ridotta).*
![Khaemhat 0.6.0 · proposta di riordino](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/magazzino-riordino.png)
La proposta elenca gli articoli sotto il punto di riordino con giacenza, impegnato, ordinato, disponibile, scorta
minima, punto e **lotto** di riordino, **quantità proposta** (modificabile), **fornitore** abituale, lead time,
prezzo e valore. In alto gli indicatori: articoli sotto riordino, proposte, valore, fornitori coinvolti, articoli
già coperti da ordini.
La proposta elenca gli articoli il cui **disponibile più ordinato** non copre più il **punto di riordino** (o, se manca,
la **scorta minima**). Per ogni articolo propone:
1. Scegli **deposito**, **fornitore** (o tutti) e il **criterio di calcolo** (es. *disponibile + ordinato < punto
di riordino*, con o senza l'impegnato).
2. **Ricalcola**, controlla e correggi le quantità proposte, togli la spunta alle righe da non ordinare.
3. **Genera ordini fornitore**: Khaemhat crea **un ordine in bozza per fornitore** (vedi [Acquisti](Acquisti)).
- la **quantità**: il **lotto di riordino** dell'articolo se c'è, altrimenti quanto riporta al punto di riordino (o
alla scorta minima); mai meno del **minimo d'ordine** del fornitore;
- il **fornitore abituale** (il preferito nella scheda articolo, *Fornitori*) con il suo prezzo e la **data di arrivo
prevista** dal lead time.
Il mockup indica come fabbisogno il maggiore tra il lotto e la differenza fra punto di riordino e disponibile più
ordinato; la formula definitiva (compresi gli arrotondamenti al lotto) sarà fissata in sviluppo. La proposta può
anche essere eseguita da una procedura pianificata o alimentata da una regola di automazione (evento *articolo sotto
il punto di riordino*, vedi [Automazioni](Automazioni)).
Correggi le quantità, cambia il fornitore di una riga o togli la spunta alle righe da non ordinare; **Ricalcola**
rilegge le giacenze. **Genera ordini fornitore** crea **un ordine in bozza per fornitore** con prezzi e condizioni del
fornitore: controllali e confermali da **Acquisti → Ordini fornitori** (vedi [Acquisti](Acquisti)). Le righe senza
fornitore non vengono ordinate.
## Costo medio e valorizzazione
- Il criterio di valorizzazione è il **costo medio ponderato**: a ogni carico il nuovo costo medio è
(valore della giacenza esistente + valore del carico) / (giacenza esistente + quantità caricata). FIFO e LIFO sono
predisposti ma non attivi.
- Il **valore** di una giacenza è quantità x costo medio.
- La **valorizzazione a data** ricostruisce quantità e valore a una data passata (ad esempio al 31 dicembre).
- Le **rimanenze finali** valorizzate alimentano la chiusura dell'esercizio e il **libro inventari** (vedi
[Contabilità](Contabilita)); sono disponibili le **scritture ausiliarie di magazzino** e l'**analisi ABC**.
![Khaemhat 0.6.0 · valorizzazione con classi ABC](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/magazzino-valorizzazione.png)
- Il criterio è il **costo medio ponderato** per articolo, su tutti i depositi: a ogni carico con valore il nuovo
costo medio è (valore della giacenza + valore del carico) / (giacenza + quantità caricata). Scarichi, trasferimenti
e conto visione escono al costo medio del momento e non lo cambiano.
- La scheda articolo mostra **costo medio** e **ultimo costo** calcolati dai movimenti.
- La **valorizzazione** (pulsante nelle giacenze) calcola quantità e valore **a una data** qualsiasi, anche passata,
con il criterio scelto: *costo medio ponderato*, *ultimo costo* o *costo standard*. Divide gli articoli in **classi
ABC**: A gli articoli che fanno l'80% del valore, B fino al 95%, C il resto.
- FIFO e LIFO sono previsti con la gestione a lotti; le rimanenze alimenteranno la chiusura dell'esercizio e il libro
inventari con la chiusura dell'esercizio (M10).
## Ricostruzione
Se le giacenze risultassero non allineate (ad esempio dopo un ripristino o un import), la **ricostruzione** ricalcola
giacenze, impegnato, ordinato e costi medi ripercorrendo tutti i movimenti. È una procedura eseguibile a mano o da
attività programmata e non modifica i documenti. Vedi [Automazioni](Automazioni) e
[Attività programmate](Attivita-programmate).
Se le giacenze sembrano non tornare (dopo un ripristino, un import diretto nel database, un cambio di causale su un
tipo documento), **Ricostruisci** nelle giacenze riscrive tutti i movimenti dai documenti in vigore, dal più vecchio,
e ricalcola giacenze, impegnato, ordinato e costi. I documenti non cambiano e i dati restano consultabili durante il
lavoro, che mostra l'avanzamento. Richiede `inventory.entry.post`.
## Stati dei movimenti
La stessa ricostruzione gira ogni **domenica alle 2:15** come attività di sistema *Ricostruzione del magazzino* (vedi
[Attività programmate](Attivita-programmate)), su tutte le aziende attive.
| Stato | Effetto |
|---|---|
| **Bozza** | nessun effetto sulla giacenza (nei trasferimenti l'origine è impegnata) |
| **Confermato** | giacenze aggiornate; righe non più modificabili |
| **Annullato** | movimenti stornati |
## Esistenze iniziali
Per partire con le giacenze di un altro gestionale importa il tracciato **Giacenze iniziali** da
[Import ed export](Import-Export): articolo, deposito, quantità e costo unitario. Khaemhat crea e conferma un
movimento con causale `APE` per deposito, alla data dell'import.
## Permessi e licenza
Il magazzino è nel modulo **CORE**. Confermare un movimento richiede `inventory.entry.post`; vedere costi e valori
richiede `items.cost.read`.
Il magazzino è nel modulo **CORE**. Vedere giacenze e movimenti richiede `inventory.stock.read`; scrivere movimenti
e conteggi `inventory.entry.write`; confermare i movimenti, registrare le rettifiche e ricostruire
`inventory.entry.post`. Costi, valori e valorizzazione sono visibili solo con `items.cost.read`.
## Domande frequenti
- **Il disponibile è negativo.** Gli ordini clienti confermati impegnano più merce di quella in giacenza: ordina al
fornitore o rivedi le consegne.
- **Il costo medio è cambiato dopo un carico.** È il comportamento previsto del costo medio ponderato; il messaggio
sul DDT di carico indica il vecchio e il nuovo valore.
- **Durante l'inventario non riesco a scaricare merce dal deposito.** È attivo il blocco dei movimenti: termina la
procedura o disattiva il blocco.
- **La giacenza è negativa.** È stato confermato uno scarico senza merce a sufficienza (Khaemhat non lo blocca, per
non fermare le consegne): registra il carico mancante o fai un inventario.
- **Il costo medio è cambiato dopo una fattura fornitore.** Il prezzo fatturato era diverso da quello del DDT di
carico: il costo del carico viene corretto con il prezzo della fattura.
- **Un articolo non compare nelle giacenze.** Non ha movimenti: spunta *Anche gli articoli senza giacenza*. Se non
compare comunque, nella scheda non è *gestito a magazzino* o non è un bene.
- **L'articolo non è nella proposta di riordino.** Non ha punto di riordino né scorta minima, oppure l'ordinato già
lo copre.
## Pagine correlate
[Articoli e listini](Articoli-e-listini) · [Acquisti](Acquisti) · [Vendite](Vendite) ·
[Tabelle azienda](Tabelle-azienda) · [Report](Report) · [Contabilità](Contabilita) · [Automazioni](Automazioni)
[Tabelle azienda](Tabelle-azienda) · [Import ed export](Import-Export) · [Dashboard](Dashboard) ·
[Attività programmate](Attivita-programmate)
+16 -6
View File
@@ -1,6 +1,6 @@
# Primi passi
> **Stato:** parziale (passi 1-4 completi) · **Ultima revisione:** 2026-11-11 · **Versione software:** 0.2.0 (passi 1-4), passi successivi M3-M5
> **Stato:** parziale (passi 1-4, 7, 10 e 12 completi; amministrazione da interfaccia con M12) · **Ultima revisione:** 2026-11-12 · **Versione software:** 0.5.0
> **Modulo di licenza:** CORE · **Livello richiesto:** super utente, poi amministratore · **Specifica:** SPEC §5.4, §7, §8, §12, §14
Questa pagina accompagna chi ha appena installato Khaemhat dal primo avvio del container fino alla prima fattura
@@ -57,6 +57,10 @@ disattivata al primo cambio password.
*Mockup 001 — pagina di accesso: a sinistra marca e funzioni principali, a destra il modulo con azienda, nome utente,
password e l'avviso della modalità Trial (anteprima ridotta).*
![Khaemhat 0.5.0 · pagina di accesso](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/accesso-login.png)
*La pagina di accesso di Khaemhat 0.5.0.*
1. Nel campo **Azienda** lascia la prima azienda, già proposta (quella creata dal container, ad esempio
*Khaemhat Demo S.r.l.*). Il super utente e gli amministratori possono anche scegliere **Nessuna (account di
istanza)** per lavorare solo sulle pagine di amministrazione dell'istanza.
@@ -111,6 +115,10 @@ telefono. Non c'è un codice QR, perché generarlo richiederebbe una libreria es
*Mockup 002 — verifica in due passaggi: sei caselle per il codice, pulsante Verifica e nota sul codice che cambia
ogni 30 secondi (anteprima ridotta).*
![Khaemhat 0.5.0 · verifica in due passaggi](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/accesso-verifica.png)
*La verifica in due passaggi di Khaemhat 0.5.0: il codice dell'app oppure un codice di recupero.*
Agli accessi successivi, dopo la password, compare la schermata **Verifica in due passaggi**: scrivi le 6 cifre
mostrate dall'app e premi **Verifica**. Il codice cambia ogni 30 secondi.
@@ -275,12 +283,14 @@ Con l'azienda configurata puoi emettere la prima fattura:
4. Scegli il cliente: pagamento, listino e agente vengono proposti dalla sua scheda.
5. Nella scheda **Righe** aggiungi l'articolo (`F4` apre la ricerca), la quantità e controlla prezzo e IVA.
6. Premi **Salva** (`Ctrl+S`): la fattura è in *bozza*.
7. Premi **Conferma ed emetti**: la fattura riceve il numero, diventa immutabile e, con il modulo ACCT attivo,
viene contabilizzata.
8. Dalla toolbar genera il PDF o l'XML FatturaPA: ogni file generato diventa un allegato della fattura.
7. Premi **Emetti**: la fattura riceve il numero e diventa immutabile.
8. Premi la **stampante** (`Ctrl+P`): l'anteprima di stampa offre il PDF e **Salva come allegato**; dal menu **⋯**
**Invia per e-mail** manda il PDF al cliente (serve il server SMTP, vedi [Impostazioni](Impostazioni#e-mail-smtp)).
La guida completa è in [Vendite](Vendite); l'invio allo SDI richiede il modulo EINV (vedi
[Fatturazione elettronica](Fatturazione-elettronica)).
![Khaemhat 0.5.0 · una fattura emessa](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/vendite-documento.png)
La guida completa è in [Vendite](Vendite). Dalla 0.7 la fattura confermata è già in [Contabilità](Contabilita); l'XML FatturaPA per lo SDI con M9
(modulo EINV, vedi [Fatturazione elettronica](Fatturazione-elettronica)).
## Domande frequenti
+1 -1
View File
@@ -13,7 +13,7 @@ Il lavoro di dettaglio è nelle issue di Gitea, raggruppate per
Finché il prodotto è in sviluppo le versioni restano **0.x**, anche dopo M13: la **1.0.0** sarà pubblicata solo
quando verrà deciso esplicitamente.
**Completate:** M0 (0.0.1), M1 (0.1.0), M2 (0.2.0), M3 (0.3.0), M4 (0.4.0). **In corso:** M5.
**Completate:** M0 (0.0.1), M1 (0.1.0), M2 (0.2.0), M3 (0.3.0), M4 (0.4.0), M5 (0.5.0), M6 (0.6.0), M7 (0.7.0). **Prossima:** M8.
| # | Milestone | Contenuto principale | Versione |
|---|---|---|---|
+10 -3
View File
@@ -81,7 +81,7 @@ liquidazione IVA (*provvisoria*, *confermata*), registrazioni, interruttore **Bl
Indirizzo: `/tabelle/esercizi`. **Nuovo esercizio** crea l'anno successivo all'ultimo con i suoi dodici mesi. Il
pulsante **Blocca** di un mese impedisce nuove registrazioni con date in quel mese; **Sblocca** chiede conferma. Un
mese *liquidato* si sblocca solo annullando la liquidazione IVA (M7).
mese *liquidato* si sblocca solo riaprendo la liquidazione IVA (vedi [IVA](IVA)).
Regola fondamentale: **si possono registrare documenti e movimenti contabili solo con data in un periodo aperto**. Un
periodo bloccato rifiuta ogni registrazione con data al suo interno; la conferma della liquidazione IVA blocca il
@@ -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
+276 -212
View File
@@ -1,288 +1,352 @@
# Vendite
> **Stato:** bozza · **Ultima revisione:** 2026-11-10 · **Versione software:** non ancora rilasciata (milestone M5)
> **Modulo di licenza:** CORE (XML SDI con EINV, contabilizzazione con ACCT, partite con FIN) · **Permessi principali:** `sales.invoice.issue`, `sales.deliverynote.reopen`, famiglia `sales.*` · **Specifica:** SPEC §11.3, §11.4
> **Stato:** completa per la versione 0.5 · **Ultima revisione:** 2026-11-12 · **Versione software:** 0.5.0 (M5)
> **Modulo di licenza:** CORE (XML SDI con EINV, contabilizzazione con ACCT, partite con FIN) · **Permessi principali:** `sales.quote.*`, `sales.order.*`, `sales.delivery.*`, `sales.invoice.*` (emissione `sales.invoice.issue`) · **Specifica:** SPEC §9.4, §11.3, §11.4, §12.6
Il modulo **Vendite** gestisce l'intero ciclo attivo: **preventivi**, **ordini clienti**, **DDT**, **fatture**
(immediate, accompagnatorie, differite, acconti, semplificate), **note di credito e di debito**, **pro-forma**,
**parcelle**, la **fatturazione differita** guidata e i corrispettivi registrati a mano. Tutti i documenti usano lo
stesso motore e la stessa maschera.
Il modulo **Vendite** gestisce il ciclo attivo: **preventivi**, **ordini clienti**, **DDT**, **fatture** (immediate,
accompagnatorie, differite, di acconto, parcelle), **note di credito e di debito**, **pro forma** e la
**fatturazione differita** dei DDT. Tutti i documenti usano lo stesso motore e la stessa maschera, si stampano in PDF
e si inviano per e-mail.
> **In questa versione** i documenti hanno numeri, totali, castelletto IVA, bollo, ritenute, scadenze, collegamenti
> riga per riga, stampa ed e-mail. Dalla 0.6 i documenti **muovono il magazzino** (DDT e fatture
> accompagnatorie scaricano, gli ordini impegnano: vedi [Magazzino](Magazzino)). Dalla 0.7 fatture e note
> **si contabilizzano** da sole (vedi [Contabilità](Contabilita)). Arrivano più avanti: gli **incassi** e il controllo
> del fido (M8), il **file XML** per lo
> SDI (M9) e il collegamento alle opportunità del **CRM** (M11). I pulsanti di queste funzioni compaiono quando la
> funzione c'è.
## Dove si trova
Menu **Vendite** → *Preventivi*, *Ordini clienti*, *DDT*, *Fatture*, *Note di credito*, *Fatturazione differita*.
Le pro forma, le fatture di acconto e le parcelle stanno nell'elenco *Fatture*; le note di debito in *Note di credito*.
## Il motore dei documenti in sintesi
## Un giro completo in cinque minuti
Ogni tipo di documento è descritto da una definizione che stabilisce: numeratore e sezionale, causale di magazzino
(se il documento carica o scarica merce), **effetti** (impegno, scarico, partite, registrazione contabile), da quali
documenti può essere **evaso** (ad esempio un DDT da un ordine), tipo documento SDI (TD), causale contabile, registro
IVA e modello di stampa.
Con l'azienda di esempio (vedi [Dati di base e di esempio](Dati-di-base-e-esempio)) trovi già un anno di vendite in
tutti gli stati. Per provare il ciclo da zero:
1. **Vendite → Preventivi → Nuovo preventivo** (`Ctrl+N`): scegli il cliente, aggiungi due righe, **Conferma**.
2. Sul preventivo premi **Crea Ordine cliente**: le righe passano all'ordine, collegate al preventivo.
3. Sull'ordine confermato premi **Crea DDT**: puoi consegnare solo una parte delle quantità.
4. **Vendite → Fatturazione differita**: indica il mese, **Cerca i DDT**, **Genera fatture**.
5. Apri la fattura, premi la **stampante** (`Ctrl+P`) per l'anteprima e il PDF, poi **⋯ → Invia per e-mail**.
## Gli elenchi (radar)
![Khaemhat 0.5.0 · radar delle fatture di vendita](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/vendite-fatture-radar.png)
*Le fatture dell'azienda di esempio: numero, data, tipo, cliente, riferimento, imponibile, totale e stato. Le bozze
non hanno ancora un numero.*
Ogni voce del menu apre un **radar** (vedi [Interfaccia e scorciatoie](Interfaccia-e-scorciatoie#radar)): cerca per
numero, riferimento o cliente, filtra per **tipo**, **stato** e **anno**, ordina, scegli le colonne e salva la vista.
Un doppio clic (o `Invio`) apre il documento in una nuova scheda.
![Khaemhat 0.5.0 · radar dei preventivi](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/vendite-preventivi-radar.png)
*I preventivi: quelli evasi sono diventati ordini, uno è stato rifiutato, uno è in bozza.*
**Nuovo** chiede il tipo quando l'elenco ne raccoglie più d'uno (ad esempio fattura immediata, accompagnatoria,
differita, di acconto, parcella o pro forma):
![Khaemhat 0.5.0 · scelta del tipo di fattura](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/vendite-nuovo-tipo.png)
## La maschera del documento
![Khaemhat 0.5.0 · fattura immediata, scheda Righe](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/vendite-documento.png)
*Una fattura emessa: toolbar, intestazione con tipo, numero, stato, cliente e totale; righe; castelletto IVA,
scadenze e totali.*
- **Toolbar**: nuovo, salva (`Ctrl+S`), annulla le modifiche, elimina (solo bozze), **stampa** (`Ctrl+P`),
**allegati**, le azioni del documento (*Conferma*, *Emetti*, *Crea …*) e il menu **⋯** con *Duplica*, *Chiudi*,
*Riapri*, *Annulla documento*, *Invia per e-mail*. A destra il **radar** e i pulsanti per il documento precedente e
successivo.
- **Intestazione**: tipo e numero (in bozza *Numero alla conferma*), data, stato, badge *Dato dimostrativo* per i dati
di esempio; cliente con codice, località e partita IVA, condizioni proposte (pagamento, listino, agente); il totale
del documento con imponibile e IVA.
- **Schede**: *Righe* (si apre lì), *Testata*, *Trasporto* (DDT e fatture accompagnatorie), *Totali*, *Scadenze*,
*Note*, *Allegati*, *Collegamenti*, *Storico*. Il numero accanto al nome della scheda conta righe, rate o
collegamenti.
### Righe
Ogni riga ha articolo (`F4` per cercarlo), descrizione, unità di misura, quantità, prezzo, sconti a cascata (`10+3`),
codice IVA e importo. Scegliendo l'articolo Khaemhat propone descrizione, unità, codice IVA e prezzo secondo l'ordine
*prezzo netto del cliente → listino del cliente → listino base → prezzo dell'articolo* (vedi
[Articoli e listini](Articoli-e-listini)). Oltre alle righe di merce ci sono le righe **descrittive** (solo testo),
le righe di **spesa** (trasporto, incasso) e le righe di **sconto**; i DDT non accettano spese né sconti.
Sotto le righe: **castelletto IVA** (imponibile e imposta per codice IVA), **scadenze** (le rate della condizione di
pagamento) e **totali**.
### Testata
![Khaemhat 0.5.0 · fattura, scheda Testata](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/vendite-documento-testata.png)
*La Testata con i gruppi Documento, Cliente, Condizioni e Dati fiscali.*
| Gruppo | Campi |
|---|---|
| **Documento** | tipo, numero (alla conferma), **data** *, validità (preventivi), data di consegna (ordini), revisione, riferimento e data del cliente, documento rettificato (note) |
| **Cliente** | **cliente** *, agente, valuta, listino |
| **Condizioni** | pagamento, modalità, banca, sconto di piede, prezzi IVA inclusa |
| **Dati fiscali** | esigibilità IVA, split payment, bollo a carico del cliente, CIG e CUP per la PA |
| **Ritenuta, cassa previdenza, ENASARCO** | per parcelle e provvigioni: aliquote, base, tipo e causale della ritenuta, cassa |
| **Note** | note stampate sul documento |
Scegliendo il cliente Khaemhat propone destinazione, listino, pagamento, agente e banca dalle sue **condizioni
commerciali** (vedi [Anagrafiche](Anagrafiche)). Per emettere una fattura ogni riga (tranne le descrittive) deve
avere il codice IVA.
### Trasporto (DDT e fatture accompagnatorie)
![Khaemhat 0.5.0 · DDT, scheda Trasporto](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/vendite-ddt-trasporto.png)
*Causale del trasporto, trasporto a cura del mittente, del destinatario o del vettore, porto, aspetto dei beni,
colli, pesi, inizio del trasporto.*
I dati di trasporto finiscono nella stampa insieme agli spazi per le **firme** del conducente, del vettore e del
destinatario.
### Collegamenti
![Khaemhat 0.5.0 · ordine cliente, scheda Collegamenti](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/vendite-collegamenti.png)
*Un ordine evaso: da quale preventivo nasce e quali DDT lo hanno evaso, con le quantità.*
I documenti sono **collegati riga per riga**: quando un DDT evade un ordine, ogni riga del DDT ricorda la riga
d'ordine di origine e la quantità evasa. Così Khaemhat calcola i **residui**, permette di riaprirli e scrive nel file
XML della fattura i riferimenti all'ordine (*DatiOrdineAcquisto*) e ai DDT (*DatiDDT*).
d'ordine e la quantità evasa. Così Khaemhat calcola i **residui** e lo stato (*Evaso in parte*, *Evaso*). Il
collegamento vale dalla **conferma** del documento che evade: una bozza non toglie nulla al residuo, un documento
annullato lo restituisce. Una nota di credito mostra qui la fattura che rettifica.
## Dal preventivo alla fattura: Crea …
```
Preventivo ──trasforma──► Ordine cliente ──evadi──► DDT ──fattura differita──► Fattura TD24
└────────────── evadi ──────────────► Fattura immediata TD01
Preventivo ──Crea Ordine──► Ordine cliente ──Crea DDT──► DDT ──Fatturazione differita──► Fattura differita (TD24)
└──────────── Crea Fattura immediata ─────────────► Fattura immediata (TD01)
Fattura ──Crea Nota di credito──► Nota di credito (TD04)
```
Alla **conferma**, in un'unica operazione indivisibile, il documento riceve il numero, muove il magazzino, genera
le scadenze e le partite, crea la registrazione contabile e gli allegati: o riesce tutto o non cambia nulla.
![Khaemhat 0.5.0 · Crea ordine dal preventivo](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/vendite-trasforma.png)
*Crea Ordine cliente da un preventivo: si scelgono le righe; per un documento che evade, la quantità proposta è
quella ancora da evadere.*
## La maschera di un documento di vendita
I pulsanti **Crea …** della toolbar elencano i documenti che si possono generare da quello aperto. Se il nuovo tipo
**evade** il vecchio (preventivo → ordine, ordine → DDT o fattura, DDT → fattura differita) le righe prendono solo le
**quantità residue**, che puoi ridurre, e restano collegate; altrimenti (ad esempio fattura → nota di credito) le
righe si **copiano**. Il nuovo documento nasce in **bozza** e si apre in una nuova scheda. **Duplica** crea invece un
documento dello stesso tipo con la data di oggi.
![020 · Fattura di vendita · righe](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/mockups/thumbs/020-fattura-vendita-righe.png)
*Mockup 020 — fattura in bozza: toolbar con Conferma ed emetti, XML SDI, Contabilizza, Evadi da…; intestazione; righe con riga descrittiva; castelletto IVA, scadenze e totali (anteprima ridotta).*
## Preventivi
![021 · Fattura di vendita · testata](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/mockups/thumbs/021-fattura-vendita-testata.png)
*Mockup 021 — scheda Testata con i gruppi Documento, Controparte, Condizioni, Magazzino e trasporto (anteprima ridotta).*
Il preventivo ha una **validità** (giorni o data) che compare nella stampa. Quando il cliente accetta, **Crea Ordine
cliente**; se rifiuta, **⋯ → Segna come rifiutato** (il preventivo passa a *Chiuso*). Un preventivo trasformato in
ordine risulta *Evaso*.
![022 · Fattura di vendita · tema scuro](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/mockups/thumbs/022-fattura-vendita-tema-scuro.png)
*Mockup 022 — la stessa fattura in tema scuro con accento Malachite (anteprima ridotta).*
## Ordini clienti
La struttura è quella descritta in [Interfaccia e scorciatoie](Interfaccia-e-scorciatoie): toolbar, intestazione a
tre blocchi, schede **Righe** (si apre lì), *Testata*, *Totali*, *Trasporto*, *Scadenze*, *Dati SDI/PA*, *Note*,
*Allegati*, *Collegamenti*, *Storico*.
L'ordine raccoglie gli impegni presi con il cliente. Da un ordine confermato si creano **DDT** o **fatture
immediate**, anche più di uno, finché resta un residuo; la scheda *Collegamenti* mostra chi ha evaso cosa. **⋯ →
Chiudi** chiude il residuo che non verrà consegnato, **Riapri** lo riporta aperto. Per la PA la Testata raccoglie CIG
e CUP, riportati nella stampa.
| Gruppo della Testata | Campi |
## DDT (documenti di trasporto)
Il DDT accompagna la merce: si compila la scheda *Trasporto* e si stampa con gli spazi per le firme. Un DDT confermato
non ancora fatturato compare nella **fatturazione differita**; un DDT fatturato risulta *Evaso*. Finché non è
fatturato le righe si possono ancora correggere; **Annulla documento** lo annulla con un motivo. Alla conferma il DDT
**scarica il magazzino** (causale `SCA`); la fattura differita che lo fattura non scarica di nuovo.
## Fatture
1. **Vendite → Fatture → Nuova fattura**, scegli il tipo, oppure parti da un ordine con **Crea Fattura immediata**.
2. Scegli il cliente: condizioni, listino, agente e destinazione vengono proposti.
3. Inserisci le righe e controlla castelletto IVA, scadenze e totali.
4. **Emetti** (permesso `sales.invoice.issue`): assegna il numero e blocca il documento.
Una fattura **emessa non si modifica**. Per correggerla si emette una **nota di credito**; finché il file XML non è
stato inviato allo SDI si può **annullare** indicando il motivo (il numero resta usato).
## Note di credito (TD04) e di debito (TD05)
![Khaemhat 0.5.0 · nota di credito](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/vendite-nota-credito.png)
*Una nota di credito che storna un articolo difettoso: l'intestazione indica la fattura rettificata.*
Si crea dalla fattura con **Crea Nota di credito** (le righe si copiano e si tolgono quelle che non vanno stornate) o
da **Vendite → Note di credito → Nuova nota**. Usa lo stesso numeratore delle fatture.
## Pro forma e parcelle
La **pro forma** è un documento **non fiscale** (ad esempio per chiedere un anticipo): stessa maschera della fattura,
numerazione propria (`PF-2026-0001`), nessun file XML e nessun effetto contabile; si trasforma in fattura quando
serve. La **parcella** (TD06) calcola la **cassa previdenza** e la **ritenuta d'acconto** e mostra il **netto a
pagare**; gli acconti su parcella usano TD03.
## Fatturazione differita
![Khaemhat 0.5.0 · fatturazione differita](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/vendite-fatturazione-differita.png)
*Ottobre: tre DDT da fatturare, uno per cliente; a destra la fattura in cui finirà ciascuno.*
1. **Periodo e cliente**: *DDT dal* e *DDT al*, un cliente (vuoto per tutti), la **data delle fatture** e il
**raggruppamento** (*una fattura per cliente* o *una fattura per DDT*). Spunta *Emetti subito le fatture* per
numerarle subito; altrimenti restano in bozza da controllare. Premi **Cerca i DDT**.
2. **Scelta dei DDT**: l'elenco mostra i DDT confermati e non ancora fatturati con la fattura che verrà generata;
togli la spunta a quelli da fatturare più avanti.
3. **Genera fatture**: crea una fattura differita (TD24) per gruppo, con i riferimenti ai DDT nelle righe; i DDT
diventano *Evasi*. Il riepilogo indica quante fatture sono state create; un clic le apre.
Con *una fattura per cliente* i DDT dello stesso cliente finiscono in una sola fattura, che prende pagamento,
banca e condizioni dal primo DDT; se un cliente ha DDT con condizioni diverse scegli *una fattura per DDT*. La fattura differita va emessa entro il giorno 15 del mese successivo a quello delle consegne.
## Stampa e PDF
![Khaemhat 0.5.0 · anteprima di stampa di una fattura](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/vendite-stampa.png)
*L'anteprima di stampa: intestazione dell'azienda, cliente, righe, riepilogo IVA, scadenze e totali.*
La **stampante** della toolbar (`Ctrl+P`) salva il documento se serve e apre l'**anteprima di stampa**:
| Pulsante | Che cosa fa |
|---|---|
| **Documento** | Tipo documento, Sezionale/Numero, **Data** *, Registro IVA, Competenza IVA, Valuta, Cambio, Vostro riferimento |
| **Controparte** | **Cliente** *, Destinazione, Fatturare a, Agente, Listino |
| **Condizioni** | Pagamento, Inizio rate (es. fine mese), Banca azienda, Sconto piede %, Spese incasso, Bollo (automatico) |
| **Magazzino e trasporto** | Causale magazzino, Deposito, Vettore, Porto, Colli |
| **Stampa** | la stampa del browser (scegli la stampante o *Salva come PDF*) |
| **Apri PDF** / **Scarica PDF** | il PDF disegnato da Khaemhat, identico all'anteprima |
| **Salva come allegato** | conserva il PDF tra gli **allegati** del documento come nuova versione e segna il documento come *stampato* |
| 75% · 100% · 125% | lo zoom dell'anteprima |
Scegliendo il cliente, Khaemhat propone destinazione, listino, pagamento, agente e banca dalle sue condizioni
commerciali; dal tipo documento propone causale e deposito.
La stampa riporta i dati dell'azienda dal **profilo azienda** (ragione sociale, indirizzo, partita IVA, REA, capitale
sociale, contatti e la nota a piè di pagina; vedi [Tabelle azienda](Tabelle-azienda)), il logo (nel PDF se è un
JPEG), il cliente, i campi utili (pagamento, banca, riferimento, validità, agente, CIG e CUP), le righe, il
**riepilogo IVA**, le **scadenze**, i totali con bollo e ritenuta e le diciture previste (split payment, pro forma non
valida ai fini fiscali, fattura differita con i DDT). Le bozze, i documenti annullati e i dati dimostrativi portano
una scritta in evidenza. Il DDT ha in più il riquadro del trasporto e le firme:
Le **righe** hanno: articolo, descrizione, UM, quantità, prezzo, sconti (anche `5+2`), codice IVA, importo, deposito,
data di consegna. Le righe descrittive (solo testo) servono per riferimenti e note. Sotto la griglia: **castelletto
IVA** (imponibile e imposta per codice IVA, esigibilità), **scadenze** (rate con data, metodo e importo) e
**totali**.
![Khaemhat 0.5.0 · anteprima di stampa di un DDT](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/vendite-stampa-ddt.png)
Ogni PDF salvato diventa un **allegato versionato** (vedi [Allegati e file](Allegati-e-file)): nella scheda
*Allegati* si vedono tutte le versioni, con chi le ha create e quando. Il generatore si chiama *Stampa del documento
in PDF*.
## Invio per e-mail
![Khaemhat 0.5.0 · invio di una fattura per e-mail](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/vendite-email.png)
*Destinatario dall'anagrafica del cliente, oggetto e testo dal modello; il PDF parte in allegato.*
**⋯ → Invia per e-mail** (su un documento salvato) propone:
- **Destinatari**: l'e-mail del cliente; più indirizzi separati da virgola o punto e virgola.
- **Oggetto** e **Messaggio** dal modello, con i campi `{{Documento}}`, `{{Numero}}`, `{{Data}}`, `{{Cliente}}`,
`{{Azienda}}` e `{{Totale}}` già compilati. Puoi cambiare tutto prima di inviare.
**Invia** salva il PDF tra gli allegati come nuova versione, lo allega al messaggio, mette il messaggio **in coda** e
segna il documento come *inviato*. Il messaggio parte in background: tre tentativi a distanza crescente; l'esito (o
l'errore del server) è nel [Log](Log), sezione **E-mail/PEC**. La coda vive in memoria: un messaggio ancora in attesa
quando Khaemhat si ferma non parte, e il log lo dice.
L'invio richiede un **server SMTP** configurato dall'amministratore con le variabili `KHAEMHAT_SMTP_*` (vedi
[Impostazioni](Impostazioni#e-mail-smtp)); senza, la finestra lo segnala e il pulsante *Invia* è spento.
## Tipi di documento e codici TD
| Documento | Codice TD (SDI) | Note |
|---|---|---|
| Fattura immediata | **TD01** | emessa contestualmente alla cessione o prestazione |
| Fattura accompagnatoria | **TD01** | fattura con i dati di trasporto, fa anche da documento di trasporto e scarica il magazzino |
| Fattura accompagnatoria | **TD01** | fattura con i dati di trasporto, fa anche da documento di trasporto |
| Fattura di acconto/anticipo su fattura | **TD02** | |
| Fattura di acconto/anticipo su parcella | **TD03** | |
| Nota di credito | **TD04** | riferita alla fattura da stornare |
| Nota di debito | **TD05** | |
| Parcella | **TD06** | con ritenuta d'acconto e cassa previdenza |
| Fattura semplificata | **TD07** | per importi fino a 400 euro |
| Nota di credito semplificata | **TD08** | |
| Nota di debito semplificata | **TD09** | |
| Nota di credito / di debito semplificata | **TD08** / **TD09** | |
| Fattura differita (beni con DDT, servizi documentati) | **TD24** | art. 21, comma 4, lett. a) DPR 633/72 |
| Fattura differita (triangolazioni interne) | **TD25** | art. 21, comma 4, terzo periodo, lett. b) |
| Cessione di beni ammortizzabili e passaggi interni | **TD26** | anche dalle dismissioni dei cespiti |
| Cessione di beni ammortizzabili e passaggi interni | **TD26** | |
| Autoconsumo o cessioni gratuite senza rivalsa (omaggi) | **TD27** | |
| Pro-forma | — | non è un documento fiscale: niente numerazione fiscale né XML |
| Pro forma | — | non è un documento fiscale: niente numerazione fiscale né XML |
Le autofatture e le integrazioni (TD16-TD29) sono negli [Acquisti](Acquisti). L'elenco completo dei codici è in
[Fiscalità italiana](Fiscalita-italiana).
## Preventivi
![026 · Preventivo / offerta con revisioni](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/mockups/thumbs/026-preventivo-offerta.png)
*Mockup 026 — preventivo inviato, revisione 2 di 2, collegato a un'opportunità CRM; azioni Trasforma in ordine, Nuova revisione, Accettato, Rifiutato (anteprima ridotta).*
Il preventivo (offerta) ha una **validità** (es. 30 giorni, con data di scadenza) e uno stato (*Bozza*, *Inviato*,
*Accettato*, *Rifiutato*). Le schede sono *Righe*, *Testata*, *Totali*, *Condizioni e note*, *Revisioni*, *Allegati*,
*CRM*; sotto le righe il pannello **Revisioni** elenca le versioni con data, totale ed esito (*Superata*, *Inviata*).
1. Crea il preventivo, inserisci le righe e invialo per e-mail.
2. Se il cliente chiede modifiche usa **Nuova revisione**: la versione precedente resta consultabile come
*superata*.
3. Segna l'esito con **Accettato** o **Rifiutato**.
4. **Trasforma in ordine** crea l'ordine cliente con le stesse righe e collega i due documenti.
Con il modulo CRM il preventivo è collegato all'**opportunità** e ne aggiorna valore e fase (vedi [CRM](CRM)).
L'intestazione mostra anche il **margine** a chi può vedere i costi.
## Ordini clienti
![027 · Ordine cliente · evasione e residui](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/mockups/thumbs/027-ordine-cliente.png)
*Mockup 027 — ordine di una PA con split payment, evaso al 38%: righe con ordinato, evaso, residuo, disponibile e stato; documenti collegati (anteprima ridotta).*
Azioni contestuali: **Genera DDT**, **Genera fattura**, **Impegna**, **Ordina a fornitore**, **Chiudi residuo**.
- **Evasione**: la griglia *Righe e stato di evasione* mostra per ogni riga quantità ordinata, evasa, residua e
disponibile, con uno stato (*Evaso*, *Parziale*, *Impegnato*, *Da ordinare*, *Aperto*) e una barra di avanzamento.
Il pannello **Documenti collegati** elenca DDT e fatture già generati e gli ordini fornitore nati dall'ordine.
- **Impegnato**: un ordine confermato **impegna** la merce, che resta in giacenza ma non è più disponibile per altri.
- **Residui**: le quantità non evase restano aperte finché non vengono consegnate o chiuse con **Chiudi residuo**.
- **Ordina a fornitore**: per le righe non disponibili crea un ordine fornitore.
- **Fido e scaduto**: se il cliente supera il fido o ha pagamenti scaduti, la conferma è bloccata; chi ha il
permesso di forzatura può procedere indicando il motivo.
- **Dati PA**: per la pubblica amministrazione la scheda *Dati PA (CIG/CUP)* raccoglie CIG, CUP e riferimenti alla
determina, riportati poi nell'XML della fattura.
## DDT (documenti di trasporto)
![028 · DDT · dati di trasporto, colli, firme](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/mockups/thumbs/028-ddt-trasporto.png)
*Mockup 028 — DDT confermato e scaricato, da fatturare: scheda Trasporto con causale, vettore, porto, colli e pesi, firme (anteprima ridotta).*
Il DDT accompagna la merce e **scarica il magazzino** alla conferma. Azioni: **Stampa 3 copie**, **Fattura questo
DDT**, **Etichette colli**, **Riapri**.
| Gruppo (scheda Trasporto) | Campi |
|---|---|
| **Trasporto** | Causale del trasporto (vendita, reso, conto visione…), Trasporto a mezzo (mittente, destinatario, vettore), Vettore, Porto, resa (Incoterms), Inizio trasporto (data e ora), Targa, Annotazioni |
| **Colli e pesi** | Aspetto esteriore dei beni, Numero colli, Peso lordo, Peso netto, Volume, Pallet, Tracking |
| **Firme** | Conducente, Vettore, Destinatario (firme sulla stampa) |
Il DDT si stampa in **tre copie**. Un DDT confermato ha le righe non modificabili; **Riapri** (permesso
`sales.deliverynote.reopen`) storna lo scarico e lo rigenera alla nuova conferma. I **resi** da cliente si
registrano con un DDT con causale di reso, che ricarica il magazzino.
## Fatture
1. **Vendite → Fatture**, **Nuovo** (`Ctrl+N`) oppure parti da un ordine o da un DDT con **Evadi da…**.
2. Scegli il cliente (F4 per cercare): condizioni, listino, agente e destinazione vengono proposti.
3. Inserisci le righe: il prezzo segue l'ordine *netto cliente → listino cliente → listino base → prezzo articolo*
(vedi [Articoli e listini](Articoli-e-listini)).
4. Controlla castelletto IVA, scadenze e totali.
5. **Conferma ed emetti**: assegna il numero, blocca il documento, scarica il magazzino (accompagnatoria), genera
scadenze e registrazione contabile.
6. **XML SDI** genera il file FatturaPA, che si invia dal canale configurato (vedi
[Fatturazione elettronica](Fatturazione-elettronica)).
Una fattura **emessa non si modifica**. Per correggerla si emette una **nota di credito**; se l'XML non è ancora
stato inviato allo SDI si può **annullare** indicando il motivo.
## Note di credito (TD04)
![029 · Nota di credito TD04](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/mockups/thumbs/029-nota-di-credito.png)
*Mockup 029 — nota di credito che storna una riga della fattura per reso merce difettosa, con rientro a magazzino e compensazione della partita (anteprima ridotta).*
La nota di credito indica la **fattura stornata**, il **motivo** e la causale (ad esempio *reso da cliente*); se
c'è un reso la merce **rientra a magazzino**. Il pannello **Partite** mostra l'effetto sulla partita della fattura
(ad esempio *chiude parzialmente la rata 1/1*). L'XML è di tipo TD04 e riporta il riferimento alla fattura
d'origine. La nota di debito (TD05) funziona allo stesso modo per gli addebiti integrativi.
## Pro-forma
Documento **non fiscale** (ad esempio per chiedere un anticipo): stessa maschera della fattura, senza numerazione
fiscale, senza XML e senza registrazione contabile. Si trasforma in fattura quando serve.
## Parcelle (TD06)
Per le aziende o gli studi che emettono parcelle: la parcella calcola la **cassa previdenza** (contributo
integrativo, con IVA propria) e la **ritenuta d'acconto** che il cliente tratterrà, e mostra il **netto a pagare**.
Gli acconti su parcella usano TD03.
## Fatturazione differita guidata
![030 · Fatturazione differita · procedura guidata](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/mockups/thumbs/030-fatturazione-differita.png)
*Mockup 030 — procedura in quattro passi: parametri, selezione dei DDT non fatturati nel periodo, anteprima delle fatture, generazione (anteprima ridotta).*
1. **Parametri**: DDT dal… al…, **data fattura**, **sezionale**, tipo (*Fattura differita TD24*), **raggruppa**
(*per cliente, rispettando la preferenza* di raggruppamento del cliente), *Genera XML SDI*, *Invia e-mail al
cliente*.
2. **Selezione DDT**: elenco dei DDT non fatturati nel periodo con la fattura che verrà generata; togli la spunta
ai DDT da escludere.
3. **Anteprima fatture**: numero di fatture e totale.
4. **Generazione**: numera le fatture, le contabilizza e, se richiesto, genera l'XML. I riferimenti ai DDT sono
riportati in riga e nell'XML (*DatiDDT*).
La fattura differita va emessa entro il giorno 15 del mese successivo a quello delle consegne. La stessa procedura
è eseguibile da attività programmata (vedi [Automazioni](Automazioni)).
[Fiscalità italiana](Fiscalita-italiana). I tipi, i numeratori e i sezionali si configurano in *Tipi documento* (vedi
[Tabelle azienda](Tabelle-azienda)).
## Stati
| Documenti (preventivi, ordini, DDT) | Significato |
| Preventivi, ordini, DDT, pro forma | Significato |
|---|---|
| **Bozza** | modificabile, senza numero definitivo, nessun effetto |
| **Confermato** | numerato, effetti applicati (impegno, scarico) |
| **Evaso parzialmente** / **Evaso** | una parte o tutto è passato al documento successivo |
| **Chiuso** | concluso (anche con residuo chiuso a mano) |
| **Annullato** | annullato con motivo |
| **Bozza** | modificabile, senza numero, nessun effetto |
| **Confermato** | numerato; le righe si possono ancora cambiare finché non sono evase |
| **Evaso in parte** / **Evaso** | una parte o tutto è passato al documento successivo |
| **Chiuso** | concluso, anche con residuo chiuso a mano (o preventivo rifiutato) |
| **Annullato** | annullato con motivo; il numero resta usato |
| Fatture e note | Significato |
|---|---|
| **Bozza** | modificabile |
| **Emessa** | numerata, contabilizzata, immutabile |
| **XML generato** | file FatturaPA pronto |
| **Inviata allo SDI** | in attesa di esito |
| **Consegnata** | recapitata al cliente |
| **Scartata** | rifiutata dallo SDI: va corretta e rigenerata |
| **Non consegnata** | impossibile recapitarla: è disponibile nell'area riservata del cliente |
| **Emessa** | numerata e immutabile |
| **XML generato**, **Inviata allo SdI**, **Consegnata**, **Scartata**, **Non consegnata** | gli stati della fatturazione elettronica (M9) |
Altri badge indicano lo stato contabile (*Non contabilizzata*), del magazzino (*Scaricato*) o della fatturazione
(*Da fatturare*).
Che cosa si può fare:
- Si **modifica** una bozza; di ordini, preventivi, DDT e pro forma confermati si possono ancora cambiare le righe
finché non sono evasi del tutto, ma una quantità non scende sotto quella già evasa e una riga evasa non si toglie.
- Si **elimina** solo una bozza, che non ha mai avuto un numero.
- Si **annulla** un documento confermato non ancora evaso: il numero resta e le quantità che aveva evaso tornano ai
documenti d'origine. Una fattura si annulla **con un motivo** finché il file non è stato inviato allo SDI; dopo, si
fa una nota di credito.
- Si **chiude** il residuo di un documento evaso in parte; **Riapri** lo riporta allo stato che dicono le sue righe.
- Si **duplica** o si **crea** un altro documento da uno in qualunque stato.
## Numerazione
- Formato `{prefisso}/{anno}/{numero a 6 cifre}`, ad esempio `FT/2026/000418`, per **sezionale** (FT, NC, DDT…) e
anno, configurato nei numeratori (vedi [Tabelle azienda](Tabelle-azienda)).
- Il numero è assegnato **alla conferma**, in modo atomico: le bozze non consumano numeri.
- Per fatture e note di credito **non sono ammessi buchi** e la data non può essere anteriore a quella dell'ultimo
documento numerato nello stesso sezionale.
- La data deve cadere in un **periodo fiscale aperto** (vedi esercizi e periodi in [Tabelle azienda](Tabelle-azienda)).
- Il formato è quello del numeratore del tipo documento, per **sezionale** e anno: ad esempio `{number}/{year}` per
fatture, note e DDT (`7/2026`), `OC-{year}-{number:D4}` per gli ordini (`OC-2026-0004`), `PRE-{year}-{number:D4}`
per i preventivi.
- Il numero è assegnato **alla conferma**, in modo atomico: le bozze non consumano numeri, due conferme contemporanee
non ricevono mai lo stesso numero e una conferma non riuscita restituisce il numero. Fatture, note di credito e note
di debito condividono il numeratore delle fatture.
- Per fatture e note **non sono ammessi buchi** e la data non può essere anteriore a quella dell'ultimo documento
numerato nello stesso numeratore.
- La data deve cadere in un **esercizio aperto** (vedi [Tabelle azienda](Tabelle-azienda)); con il primo documento
di un anno nuovo la numerazione riparte da 1.
## Calcolo dei totali
| Elemento | Regola |
|---|---|
| **Imponibile di riga** | quantità x prezzo x (1 - sconto 1) x (1 - sconto 2)…, arrotondato a 2 decimali (arrotondamento commerciale) |
| **Imponibile di riga** | quantità × prezzo × (1 − sconto 1) × (1 − sconto 2)…, arrotondato a 2 decimali (arrotondamento commerciale) |
| **Castelletto IVA** | imponibili raggruppati per codice IVA; imposta calcolata per aliquota sul totale del gruppo |
| **Spese** | trasporto, incasso ecc. con il proprio codice IVA |
| **Sconto piede** | ripartito sulle righe |
| **Bollo** | 2,00 euro automatici se le operazioni esenti, non imponibili o fuori campo IVA superano 77,47 euro; la scheda del cliente indica se è a carico del cliente |
| **Sconto di piede** | ripartito sulle righe |
| **Bollo** | 2,00 euro automatici se le operazioni esenti, non imponibili o fuori campo IVA superano 77,47 euro; la scheda del cliente indica se è a suo carico |
| **Ritenuta d'acconto** | sulle parcelle, calcolata sull'imponibile previsto; il netto a pagare la esclude |
| **Cassa previdenza** | contributo sulle parcelle, con IVA propria |
| **Split payment** | per PA e soggetti obbligati: l'IVA è esposta ma versata dal cliente all'Erario; il totale *da versare* è il solo imponibile (esigibilità **S**) |
| **Split payment** | per PA e soggetti obbligati: l'IVA è esposta ma versata dal cliente all'Erario (esigibilità **S**) |
| **Reverse charge** | fattura senza IVA con natura N6.x: l'imposta la integra il cliente |
| **IVA per cassa** | esigibilità differita al pagamento per chi ha aderito al regime (gestione completa prevista in fase 2) |
**Scadenze**: generate dalla condizione di pagamento (rate, giorni, fine mese, giorno fisso, percentuali, IVA sulla
prima rata, sconto cassa); l'eventuale differenza di arrotondamento va sull'ultima rata.
## Stampa, PDF ed e-mail
![025 · Anteprima di stampa / PDF](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/mockups/thumbs/025-anteprima-stampa-pdf.png)
*Mockup 025 — anteprima di stampa della fattura: modello, copie, lingua, zoom (anteprima ridotta).*
`Ctrl+P` apre l'**anteprima di stampa** in una nuova scheda: si scelgono **modello**, numero di **copie** e
**lingua**, si ingrandisce (50%, 100%, adatta) e si stampa, si scarica il PDF o lo si invia. La stampa contiene le
diciture di legge previste ed è sempre in tema chiaro. Ogni PDF generato diventa un **allegato versionato** del
documento (vedi [Allegati e file](Allegati-e-file)).
L'invio per **e-mail o PEC** allega il PDF (e, se richiesto, l'XML o la copia di cortesia ZIP) usando i modelli
e-mail dell'azienda; il canale preferito è nelle condizioni del cliente.
## Collegamenti, duplicazione e corrispettivi
- **Collegamenti**: la scheda omonima mostra i documenti di origine e quelli generati (ordine → DDT → fattura) con
le quantità; l'icona *Collegamenti* della toolbar apre lo stesso elenco.
- **Duplica** crea un nuovo documento in bozza con le stesse righe; la **trasformazione** cambia tipo mantenendo i
collegamenti (preventivo → ordine).
- **Corrispettivi**: le vendite al dettaglio si registrano a mano come corrispettivi giornalieri.
## Report
Giornale vendite, fatturato per cliente, agente, categoria e articolo (vedi [Report](Report)), DDT da fatturare,
ordini aperti, provvigioni agenti, margini (con il modulo REPORT).
prima rata); l'eventuale differenza di arrotondamento va sull'ultima rata.
## Permessi e licenza
Le vendite sono nel modulo **CORE**. Emettere una fattura richiede `sales.invoice.issue`; riaprire un DDT
`sales.deliverynote.reopen`; forzare un blocco di fido un permesso di tipo `override`. La generazione e l'invio
dell'XML richiedono **EINV**, la registrazione contabile **ACCT**, partite e incassi **FIN**.
Le vendite sono nel modulo **CORE**. Ogni famiglia ha due permessi, lettura (`.read`) e scrittura (`.write`):
`sales.quote`, `sales.order`, `sales.delivery`, `sales.invoice` (fatture, note e pro forma). La scrittura vale per
creare, modificare, confermare, chiudere, riaprire e annullare; per le fatture e le note **emettere** e annullare
richiede in più `sales.invoice.issue` ed eliminare una bozza `sales.invoice.delete`. Stampare richiede la sola
lettura. Vedi [Utenti e permessi](Utenti-e-permessi).
## Domande frequenti
- **Non riesco a confermare la fattura: "data anteriore all'ultima numerata".** Nello stesso sezionale esiste una
fattura con data successiva: correggi la data o usa un altro sezionale.
- **Il bollo non viene calcolato.** Il bollo è automatico solo se la parte esente, non imponibile o fuori campo
supera 77,47 euro; controlla i codici IVA delle righe.
- **Devo correggere una fattura già inviata.** Emetti una nota di credito (TD04) e una nuova fattura.
- **"Indica il codice IVA" su una riga.** Fatture e note si emettono solo con il codice IVA su ogni riga di merce,
spesa o sconto: sceglilo nella riga o nella scheda dell'articolo.
- **Il bollo non viene calcolato.** È automatico solo se la parte esente, non imponibile o fuori campo supera 77,47
euro; controlla i codici IVA delle righe.
- **Un DDT non compare nella fatturazione differita.** Deve essere *Confermato*, non già fatturato e con data nel
periodo; se hai indicato un cliente, deve essere suo.
- **"Invia per e-mail" è spento.** Il documento ha modifiche non salvate: salvalo. Se la finestra dice che manca il
server SMTP, chiedi all'amministratore di configurarlo.
- **Ho inviato l'e-mail ma il cliente non l'ha ricevuta.** Guarda il [Log](Log), sezione *E-mail/PEC*: c'è la
risposta del server per ogni tentativo.
- **Devo correggere una fattura già inviata allo SDI.** Emetti una nota di credito (TD04) e una nuova fattura.
## Pagine correlate
[Anagrafiche](Anagrafiche) · [Articoli e listini](Articoli-e-listini) · [Magazzino](Magazzino) ·
[Allegati e file](Allegati-e-file) · [Fatturazione elettronica](Fatturazione-elettronica) ·
[Contabilità](Contabilita) · [Scadenzario](Scadenzario) · [CRM](CRM) · [Fiscalità italiana](Fiscalita-italiana)
[Anagrafiche](Anagrafiche) · [Articoli e listini](Articoli-e-listini) · [Tabelle azienda](Tabelle-azienda) ·
[Allegati e file](Allegati-e-file) · [Log](Log) · [Magazzino](Magazzino) ·
[Fatturazione elettronica](Fatturazione-elettronica) · [Contabilità](Contabilita) · [Scadenzario](Scadenzario) ·
[Fiscalità italiana](Fiscalita-italiana)
+3
View File
@@ -1,5 +1,8 @@
**[Khaemhat](Home)**
**Guida**
- [Guida all'uso](Guida-utente)
**Installazione**
- [Primi passi](Primi-passi)
- [Unraid](Installazione-Unraid)
Binary file not shown.

After

Width:  |  Height:  |  Size: 188 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 182 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 74 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 113 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 121 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 69 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 119 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 165 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 118 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 174 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 115 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 149 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 190 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 100 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 97 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 73 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 97 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 177 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 178 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 199 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 166 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 220 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 90 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 99 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 145 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 118 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 102 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 92 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 99 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 105 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 109 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 87 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 115 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 124 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 121 KiB

+6 -2
View File
@@ -3,7 +3,8 @@
# Any KHAEMHAT_* variable already set in the shell wins over the defaults below.
set -euo pipefail
root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
# Under Git Bash on Windows, pwd -W gives B:/... instead of /b/..., which .NET would read as a folder b on the drive.
root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && (pwd -W 2>/dev/null || pwd))"
cd "$root"
data_dir="$root/.data/dev"
@@ -11,7 +12,10 @@ mkdir -p "$data_dir"
export ASPNETCORE_ENVIRONMENT="${ASPNETCORE_ENVIRONMENT:-Development}"
export KHAEMHAT_DATA_DIR="${KHAEMHAT_DATA_DIR:-$data_dir}"
export KHAEMHAT_SYSTEM_DB="${KHAEMHAT_SYSTEM_DB:-sqlite://$data_dir/system.db}"
# sqlite:///home/... on Linux and macOS, sqlite:///B:/... on Windows.
db_path="$data_dir"
[[ "$db_path" == /* ]] || db_path="/$db_path"
export KHAEMHAT_SYSTEM_DB="${KHAEMHAT_SYSTEM_DB:-sqlite://$db_path/system.db}"
# Development-only key: never use it outside this script.
export KHAEMHAT_SECRET_KEY="${KHAEMHAT_SECRET_KEY:-a2hhZW1oYXQtZGV2ZWxvcG1lbnQtb25seS1ub3QtYS1zZWNyZXQ=}"
export KHAEMHAT_SUPERUSER="${KHAEMHAT_SUPERUSER:-root}"
@@ -105,7 +105,7 @@ public static class WidgetCatalog
new(WidgetIds.CrmActivities, "Dashboard.Widgets.CrmActivities.Title", "target", 6, ModuleCodes.Crm, "crm.lead.read", Milestone: "M11"),
new(WidgetIds.Notes, "Dashboard.Widgets.Notes.Title", "edit", 4, ModuleCodes.Core),
new(WidgetIds.Shortcuts, "Dashboard.Widgets.Shortcuts.Title", "zap", 4, ModuleCodes.Core),
new(WidgetIds.Understock, "Dashboard.Widgets.Understock.Title", "box", 6, ModuleCodes.Core, "inventory.stock.read", Milestone: "M6"),
new(WidgetIds.Understock, "Dashboard.Widgets.Understock.Title", "box", 6, ModuleCodes.Core, "inventory.stock.read"),
new(WidgetIds.Pipeline, "Dashboard.Widgets.Pipeline.Title", "target", 6, ModuleCodes.Crm, "crm.lead.read", Milestone: "M11"),
new(WidgetIds.RecentDocuments, "Dashboard.Widgets.RecentDocuments.Title", "file", 6, ModuleCodes.Core, "sales.invoice.read", Milestone: "M5"),
new(WidgetIds.SystemStatus, "Dashboard.Widgets.System.Title", "shield", 4, ModuleCodes.Core, InstanceOnly: true),
@@ -0,0 +1,201 @@
using Khaemhat.Core.Documents;
using Khaemhat.Core.Parties;
using Khaemhat.Core.Tables;
using Khaemhat.Data;
using Khaemhat.Data.Querying;
using Khaemhat.Fiscal.Abstractions;
namespace Khaemhat.Application.Documents;
/// <summary>The totals of a stored document: its tax summary and installments, as written by the last save.</summary>
/// <param name="Summary">The tax summary.</param>
/// <param name="Installments">The installments.</param>
public sealed record DocumentFigures(IReadOnlyList<DocumentTaxSummary> Summary, IReadOnlyList<DocumentInstallment> Installments)
{
/// <summary>No figures.</summary>
public static DocumentFigures Empty { get; } = new([], []);
}
/// <summary>
/// Applies <see cref="DocumentTotalsCalculator"/> and <see cref="InstallmentGenerator"/> to a document being saved:
/// writes the line amounts and header totals, then replaces its tax summary and installments (issue #48).
/// </summary>
internal static class DocumentCalculation
{
/// <summary>Computes the totals of a document in place.</summary>
/// <param name="uow">The unit of work.</param>
/// <param name="engine">The country's tax engine.</param>
/// <param name="behavior">The behaviour of the document.</param>
/// <param name="record">The document.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The tax summary and installments to write once the document has its id.</returns>
public static async Task<DocumentFigures> ApplyAsync(IUnitOfWork uow, ITaxEngine engine, DocumentBehavior behavior, DocumentRecord record, CancellationToken cancellationToken)
{
var header = record.Header;
var taxCodes = await TaxCodesAsync(uow, record, cancellationToken).ConfigureAwait(false);
var options = new TotalsOptions
{
PricesIncludeTax = header.PricesIncludeTax,
FooterDiscount = header.FooterDiscount,
Exigibility = header.Exigibility,
SplitPayment = header.SplitPayment,
StampDutyApplies = behavior.Direction == DocumentDirection.Sale && behavior.Has(DocumentEffects.EInvoice),
StampDutyCharged = header.StampDutyCharged,
WithholdingRate = header.WithholdingRate,
WithholdingBasePercent = header.WithholdingBasePercent <= 0m ? 100m : header.WithholdingBasePercent,
SocialSecurityRate = header.SocialSecurityRate,
SocialSecurityTax = header.SocialSecurityTaxCodeId is { } id && taxCodes.TryGetValue(id, out var own) ? own : null,
SocialSecurityWithheld = header.SocialSecurityWithheld,
EnasarcoRate = header.EnasarcoRate,
};
var lines = record.Lines
.Select(l => new TotalsLine(l.Kind, l.Quantity, l.Price, l.DiscountFormula,
l.TaxCodeId is { } t && taxCodes.TryGetValue(t, out var tax) ? tax : null, l.WithholdingExcluded))
.ToList();
var totals = DocumentTotalsCalculator.Compute(lines, options, engine);
for (var i = 0; i < record.Lines.Count; i++)
{
record.Lines[i].TaxableAmount = totals.LineAmounts[i];
}
header.TaxableAmount = totals.Taxable;
header.TaxAmount = totals.Tax;
header.TotalAmount = totals.Total;
header.ExpensesAmount = totals.Expenses;
header.FooterDiscountAmount = totals.FooterDiscountAmount;
header.StampDuty = totals.StampDuty;
header.WithholdingAmount = totals.Withholding;
header.SocialSecurityAmount = totals.SocialSecurity;
header.EnasarcoAmount = totals.Enasarco;
header.NetAmount = totals.Net;
var summary = totals.Summary.Select(s => new DocumentTaxSummary
{
Family = record.Family,
TaxCodeId = s.Tax.TaxCodeId,
Rate = s.Tax.Rate,
Nature = s.Tax.Nature,
Exigibility = s.Tax.Exigibility,
NonDeductiblePercent = s.Tax.NonDeductiblePercent,
LegalReference = s.Tax.LegalReference,
Taxable = s.Taxable,
Tax = s.TaxAmount,
NonDeductibleTax = s.NonDeductibleTax,
}).ToList();
var installments = new List<DocumentInstallment>();
if (behavior.Has(DocumentEffects.Installments) || behavior.Kind is DocumentKind.ProForma or DocumentKind.SalesOrder or DocumentKind.Quotation)
{
installments = await InstallmentsAsync(uow, engine, behavior, record, totals, cancellationToken).ConfigureAwait(false);
}
return new DocumentFigures(summary, installments);
}
/// <summary>Replaces the tax summary and installments of a document.</summary>
/// <param name="uow">The unit of work.</param>
/// <param name="family">The family.</param>
/// <param name="documentId">The document.</param>
/// <param name="figures">The new rows.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
public static async Task WriteAsync(IUnitOfWork uow, DocumentFamily family, long documentId, DocumentFigures figures, CancellationToken cancellationToken)
{
var summaries = uow.Repository<DocumentTaxSummary, long>();
var installments = uow.Repository<DocumentInstallment, long>();
var where = SqlFragment.Of($"family = {family.ToString()} AND document_id = {documentId}");
foreach (var old in (await summaries.ListAsync(Query.For<DocumentTaxSummary>().Where(where), cancellationToken).ConfigureAwait(false)).Items)
{
await summaries.DeleteAsync(old.Id, cancellationToken).ConfigureAwait(false);
}
foreach (var old in (await installments.ListAsync(Query.For<DocumentInstallment>().Where(where), cancellationToken).ConfigureAwait(false)).Items)
{
await installments.DeleteAsync(old.Id, cancellationToken).ConfigureAwait(false);
}
foreach (var row in figures.Summary)
{
row.Id = 0;
row.Family = family;
row.DocumentId = documentId;
await summaries.InsertAsync(row, cancellationToken).ConfigureAwait(false);
}
foreach (var row in figures.Installments)
{
row.Id = 0;
row.Family = family;
row.DocumentId = documentId;
await installments.InsertAsync(row, cancellationToken).ConfigureAwait(false);
}
}
/// <summary>Reads the tax summary and installments of a document.</summary>
/// <param name="uow">The unit of work.</param>
/// <param name="family">The family.</param>
/// <param name="documentId">The document.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The rows.</returns>
public static async Task<DocumentFigures> ReadAsync(IUnitOfWork uow, DocumentFamily family, long documentId, CancellationToken cancellationToken)
{
var where = SqlFragment.Of($"family = {family.ToString()} AND document_id = {documentId}");
var summary = await uow.Repository<DocumentTaxSummary, long>()
.ListAsync(Query.For<DocumentTaxSummary>().Where(where).OrderByDescending(s => s.Rate), cancellationToken).ConfigureAwait(false);
var installments = await uow.Repository<DocumentInstallment, long>()
.ListAsync(Query.For<DocumentInstallment>().Where(where).OrderBy(s => s.Number), cancellationToken).ConfigureAwait(false);
return new DocumentFigures(summary.Items, installments.Items);
}
private static async Task<Dictionary<long, TotalsTax>> TaxCodesAsync(IUnitOfWork uow, DocumentRecord record, CancellationToken cancellationToken)
{
var ids = record.Lines.Where(l => l.TaxCodeId is not null).Select(l => l.TaxCodeId!.Value).ToHashSet();
if (record.Header.SocialSecurityTaxCodeId is { } own)
{
ids.Add(own);
}
if (ids.Count == 0)
{
return [];
}
var list = ids.ToList();
var codes = await uow.Repository<TaxCode, long>().ListAsync(Query.For<TaxCode>().Where(c => list.Contains(c.Id)), cancellationToken).ConfigureAwait(false);
return codes.Items.ToDictionary(c => c.Id, c => new TotalsTax(c.Id, c.Rate, string.IsNullOrWhiteSpace(c.Nature) ? null : c.Nature,
c.Exigibility, c.NonDeductiblePercent, c.LegalReference));
}
private static async Task<List<DocumentInstallment>> InstallmentsAsync(
IUnitOfWork uow, ITaxEngine engine, DocumentBehavior behavior, DocumentRecord record, DocumentTotals totals, CancellationToken cancellationToken)
{
var header = record.Header;
PaymentTerm? term = null;
IReadOnlyList<PaymentTermLine> termLines = [];
if (header.PaymentTermId is { } termId)
{
term = await uow.Repository<PaymentTerm, long>().GetAsync(termId, cancellationToken).ConfigureAwait(false);
termLines = (await uow.Repository<PaymentTermLine, long>()
.ListAsync(Query.For<PaymentTermLine>().Where(l => l.PaymentTermId == termId).OrderBy(l => l.Number), cancellationToken).ConfigureAwait(false)).Items;
}
ExcludedMonths? excluded = null;
if (behavior.Direction == DocumentDirection.Sale && header.PartyId is { } partyId)
{
var terms = await uow.Repository<PartySalesTerms, long>()
.FindAsync(Query.For<PartySalesTerms>().Where(t => t.PartyId == partyId), cancellationToken).ConfigureAwait(false);
if (terms is { } t && (t.ExcludedMonth1 is not null || t.ExcludedMonth2 is not null))
{
excluded = new ExcludedMonths(t.ExcludedMonth1, t.ExcludedMonth2, t.ExcludedMonthsDay ?? 10);
}
}
var paidTax = totals.Tax - totals.SplitPaymentTax;
var dues = InstallmentGenerator.Generate(
header.DocumentDate, totals.Net, paidTax,
[.. termLines.Select(l => new InstallmentRule(l.Days, l.EndOfMonth, l.FixedDay, l.Percent))],
term?.VatOnFirstInstallment ?? false, excluded, engine.Round);
var method = header.PaymentMethodId ?? term?.PaymentMethodId;
return [.. dues.Select(d => new DocumentInstallment { Number = d.Number, DueDate = d.DueDate, Amount = d.Amount, PaymentMethodId = method })];
}
}
@@ -0,0 +1,257 @@
using System.Globalization;
using Khaemhat.Application.Security;
using Khaemhat.Core.Documents;
using Khaemhat.Data;
namespace Khaemhat.Application.Documents;
/// <summary>
/// Makes a new draft from an existing document (SPEC §11.3, ADR 0032): a duplicate of the same type, or a
/// transformation to another type of the same direction. When the new kind fulfils the old one (order to delivery note,
/// delivery note to deferred invoice) the lines take what is left to fulfil and remember where they come from; the
/// link is recorded when the new document is confirmed.
/// </summary>
public sealed class DocumentCopyService
{
private readonly DocumentEngine _engine;
private readonly PermissionService _permissions;
private readonly TimeProvider _clock;
/// <summary>Creates the service.</summary>
/// <param name="engine">The engine.</param>
/// <param name="permissions">The permissions.</param>
/// <param name="clock">The clock.</param>
public DocumentCopyService(DocumentEngine engine, PermissionService permissions, TimeProvider clock)
{
ArgumentNullException.ThrowIfNull(engine);
ArgumentNullException.ThrowIfNull(permissions);
ArgumentNullException.ThrowIfNull(clock);
_engine = engine;
_permissions = permissions;
_clock = clock;
}
/// <summary>Copies a document into a new draft and saves it.</summary>
/// <param name="actor">Who copies.</param>
/// <param name="companyCode">The company.</param>
/// <param name="family">The family of the source.</param>
/// <param name="id">The source.</param>
/// <param name="targetTypeCode">The type of the new document, such as <c>DDT</c>.</param>
/// <param name="lineIds">The lines to copy; all when empty.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The new draft.</returns>
/// <exception cref="ValidationFailedException">The copy is not possible.</exception>
public Task<DocumentRecord> CopyAsync(
Actor actor, string companyCode, DocumentFamily family, long id, string targetTypeCode, IReadOnlyCollection<long>? lineIds = null,
CancellationToken cancellationToken = default) =>
MergeAsync(actor, companyCode, family, [id], targetTypeCode, null, lineIds, cancellationToken);
/// <summary>
/// Copies several documents of the same party into one new draft and saves it (deferred invoice from delivery
/// notes, delivery note from several orders): the header comes from the first, each source adds a reference line
/// and its lines.
/// </summary>
/// <param name="actor">Who copies.</param>
/// <param name="companyCode">The company.</param>
/// <param name="family">The family of the sources.</param>
/// <param name="ids">The sources, in order.</param>
/// <param name="targetTypeCode">The type of the new document.</param>
/// <param name="date">The date of the new document; today when empty.</param>
/// <param name="lineIds">The lines to copy; all when empty.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The new draft.</returns>
/// <exception cref="ValidationFailedException">The copy is not possible.</exception>
public async Task<DocumentRecord> MergeAsync(
Actor actor, string companyCode, DocumentFamily family, IReadOnlyList<long> ids, string targetTypeCode, DateOnly? date = null,
IReadOnlyCollection<long>? lineIds = null, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(actor);
ArgumentNullException.ThrowIfNull(ids);
if (ids.Count == 0)
{
throw new ValidationFailedException([":" + DocumentErrors.CopyNothingLeft]);
}
var sources = new List<DocumentRecord>();
foreach (var id in ids)
{
sources.Add(await _engine.GetAsync(actor, companyCode, family, id, cancellationToken).ConfigureAwait(false)
?? throw new KeyNotFoundException(DocumentErrors.NotFound));
}
var company = CompanyCodes.Normalize(companyCode);
DocumentDefinition target;
await using (var uow = await _engine.Factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false))
{
target = await DocumentDefinitionService.GetAsync(uow, targetTypeCode, cancellationToken).ConfigureAwait(false);
}
await _permissions.DemandAsync(actor, target.Behavior.WritePermission, cancellationToken).ConfigureAwait(false);
if (sources.Select(s => s.Header.PartyId).Distinct().Count() > 1)
{
throw new ValidationFailedException([":" + DocumentErrors.CopyParties]);
}
var copy = new DocumentRecord
{
Family = target.Family,
Header = Header(sources[0], target, date ?? DateOnly.FromDateTime(_clock.GetLocalNow().DateTime)),
};
var wanted = lineIds is { Count: > 0 } ? lineIds.ToHashSet() : null;
var anyFulfils = false;
foreach (var source in sources)
{
var sourceBehavior = DocumentBehaviors.Of(source.Header.Kind);
DocumentStateMachine.Apply(sourceBehavior.Lifecycle, source.Header.Status, DocumentAction.Copy);
if (sourceBehavior.Direction != target.Behavior.Direction)
{
throw new ValidationFailedException([nameof(DocumentHeader.DocumentTypeId) + ":" + DocumentErrors.CopyDirection]);
}
var fulfils = target.Behavior.Fulfils(source.Header.Kind);
anyFulfils |= fulfils;
if (fulfils && (source.Header.Status is DocumentStatus.Draft or DocumentStatus.Closed or DocumentStatus.Cancelled))
{
throw new ValidationFailedException([":" + DocumentErrors.CopySourceNotOpen]);
}
var lines = new List<DocumentLine>();
foreach (var line in source.Lines.Where(l => wanted is null || wanted.Contains(l.Id)))
{
if (!target.Behavior.Lines.Contains(line.Kind))
{
continue;
}
var quantity = line.Quantity;
if (fulfils && DocumentLine.CarriesQuantity(line.Kind))
{
quantity = line.Residual;
if (quantity <= 0)
{
continue;
}
}
lines.Add(Line(line, target.Family, quantity, fulfils ? source.Family : null));
}
if (sources.Count > 1 && lines.Count > 0 && source.Header.DocumentNumber is { } number
&& target.Behavior.Lines.Contains(DocumentLineKind.Description))
{
var reference = DocumentStores.Of(target.Family).NewLine();
reference.Kind = DocumentLineKind.Description;
reference.Description = ReferenceLabel(source.Header.Kind) + " " + number + " del "
+ source.Header.DocumentDate.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture);
copy.Lines.Add(reference);
}
copy.Lines.AddRange(lines);
}
if (anyFulfils && !copy.Lines.Any(l => l.SourceLineId is not null))
{
throw new ValidationFailedException([":" + DocumentErrors.CopyNothingLeft]);
}
return await _engine.SaveAsync(actor, company, copy, cancellationToken).ConfigureAwait(false);
}
// The reference printed before the lines of each source (the documents are written in Italian).
private static string ReferenceLabel(DocumentKind kind) => kind switch
{
DocumentKind.DeliveryNote or DocumentKind.PurchaseDeliveryNote => "Rif. DDT n.",
DocumentKind.SalesOrder or DocumentKind.PurchaseOrder => "Rif. ordine n.",
DocumentKind.Quotation => "Rif. preventivo n.",
_ => "Rif. documento n.",
};
private static DocumentHeader Header(DocumentRecord record, DocumentDefinition target, DateOnly today)
{
var source = record.Header;
var header = DocumentStores.Of(target.Family).NewHeader();
header.DocumentTypeId = target.Type.Id;
header.Kind = target.Kind;
header.Status = DocumentStatus.Draft;
header.IsDemo = source.IsDemo;
header.DocumentDate = today;
header.Year = today.Year;
header.PartyId = source.PartyId;
header.DestinationId = source.DestinationId;
header.CurrencyCode = source.CurrencyCode;
header.ExchangeRate = source.ExchangeRate;
header.PriceListId = source.PriceListId;
header.PaymentTermId = source.PaymentTermId;
header.PaymentMethodId = source.PaymentMethodId;
header.BankAccountId = source.BankAccountId;
header.SalespersonId = source.SalespersonId;
header.WarehouseId = source.WarehouseId;
header.InventoryReasonId = target.Type.InventoryReasonId ?? source.InventoryReasonId;
header.TransportReasonId = source.TransportReasonId;
header.ShippingTermId = source.ShippingTermId;
header.CarrierId = source.CarrierId;
header.GoodsAppearanceId = source.GoodsAppearanceId;
header.DeliveryDate = source.DeliveryDate;
header.FooterDiscount = source.FooterDiscount;
header.Notes = source.Notes;
header.ExternalReference = source.ExternalReference;
header.ExternalDate = source.ExternalDate;
header.PricesIncludeTax = source.PricesIncludeTax;
header.Exigibility = source.Exigibility;
header.SplitPayment = source.SplitPayment;
header.StampDutyCharged = source.StampDutyCharged;
header.WithholdingRate = source.WithholdingRate;
header.WithholdingBasePercent = source.WithholdingBasePercent;
header.WithholdingType = source.WithholdingType;
header.WithholdingReason = source.WithholdingReason;
header.SocialSecurityFund = source.SocialSecurityFund;
header.SocialSecurityRate = source.SocialSecurityRate;
header.SocialSecurityTaxCodeId = source.SocialSecurityTaxCodeId;
header.SocialSecurityWithheld = source.SocialSecurityWithheld;
header.EnasarcoRate = source.EnasarcoRate;
header.Cig = source.Cig;
header.Cup = source.Cup;
header.TransportBy = source.TransportBy;
if (target.Kind is DocumentKind.CreditNote or DocumentKind.DebitNote or DocumentKind.PurchaseCreditNote
&& DocumentBehaviors.Of(source.Kind).Lifecycle != DocumentLifecycle.Order && record.Family == target.Family)
{
// A note refers to the invoice it corrects (DatiFattureCollegate).
header.RelatedDocumentId = source.Id;
header.RelatedNumber = source.DocumentNumber;
header.RelatedDate = source.DocumentDate;
}
return header;
}
private static DocumentLine Line(DocumentLine source, DocumentFamily family, decimal quantity, DocumentFamily? sourceFamily)
{
var line = DocumentStores.Of(family).NewLine();
line.Kind = source.Kind;
line.ItemId = source.ItemId;
line.Description = source.Description;
line.UnitOfMeasureId = source.UnitOfMeasureId;
line.Quantity = quantity;
line.Price = source.Price;
line.PriceSource = source.PriceSource;
line.DiscountFormula = source.DiscountFormula;
line.TaxCodeId = source.TaxCodeId;
line.TaxableAmount = source.Quantity == 0 || quantity == source.Quantity
? source.TaxableAmount
: Math.Round(source.TaxableAmount * quantity / source.Quantity, 2, MidpointRounding.AwayFromZero);
line.WarehouseId = source.WarehouseId;
line.DeliveryDate = source.DeliveryDate;
line.AccountCode = source.AccountCode;
line.CostCenterId = source.CostCenterId;
line.JobId = source.JobId;
line.Notes = source.Notes;
line.WithholdingExcluded = source.WithholdingExcluded;
if (sourceFamily is not null && DocumentLine.CarriesQuantity(source.Kind))
{
line.SourceFamily = sourceFamily;
line.SourceLineId = source.Id;
}
return line;
}
}
@@ -0,0 +1,97 @@
using Khaemhat.Application.Security;
using Khaemhat.Core.Documents;
using Khaemhat.Core.Tables;
using Khaemhat.Data;
using Khaemhat.Data.Querying;
namespace Khaemhat.Application.Documents;
/// <summary>
/// A document type of the company with the behaviour of its kind (SPEC §11.3, ADR 0032): code, kind, direction,
/// numerator, warehouse reason, effects, sources for fulfilment, SDI type, journal template, VAT register, print
/// template.
/// </summary>
/// <param name="Type">The row of <c>document_types</c>.</param>
/// <param name="Behavior">The behaviour of its kind.</param>
public sealed record DocumentDefinition(DocumentType Type, DocumentBehavior Behavior)
{
/// <summary>The code of the type.</summary>
public string Code => Type.Code;
/// <summary>The kind.</summary>
public DocumentKind Kind => Behavior.Kind;
/// <summary>The family (tables).</summary>
public DocumentFamily Family => Behavior.Family;
/// <summary>The life cycle.</summary>
public DocumentLifecycle Lifecycle => Behavior.Lifecycle;
/// <summary>The action that confirms the documents: issue for invoices, confirm for the others.</summary>
public DocumentAction ConfirmAction => Lifecycle == DocumentLifecycle.Invoice ? DocumentAction.Issue : DocumentAction.Confirm;
}
/// <summary>Reads the definitions of the company's document types.</summary>
public static class DocumentDefinitionService
{
/// <summary>Error: the document type does not exist.</summary>
public const string TypeMissing = "document.type.missing";
/// <summary>Error: the document type has no kind.</summary>
public const string TypeWithoutKind = "document.type.no-kind";
/// <summary>Error: the document type is disabled.</summary>
public const string TypeDisabled = "document.type.disabled";
/// <summary>The definition of a document type.</summary>
/// <param name="uow">A company unit of work.</param>
/// <param name="typeId">The type.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The definition.</returns>
/// <exception cref="ValidationFailedException">The type is missing or has no kind.</exception>
public static async Task<DocumentDefinition> GetAsync(IUnitOfWork uow, long typeId, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(uow);
var type = await uow.Repository<DocumentType, long>().GetAsync(typeId, cancellationToken).ConfigureAwait(false)
?? throw new ValidationFailedException([nameof(DocumentHeader.DocumentTypeId) + ":" + TypeMissing]);
return Of(type);
}
/// <summary>The definition of a document type by code.</summary>
/// <param name="uow">A company unit of work.</param>
/// <param name="code">The code, such as <c>FI</c>.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The definition.</returns>
/// <exception cref="ValidationFailedException">The type is missing or has no kind.</exception>
public static async Task<DocumentDefinition> GetAsync(IUnitOfWork uow, string code, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(uow);
var normalized = (code ?? string.Empty).Trim().ToUpperInvariant();
var type = await uow.Repository<DocumentType, long>().FindAsync(Query.For<DocumentType>().Where(t => t.Code == normalized), cancellationToken).ConfigureAwait(false)
?? throw new ValidationFailedException([nameof(DocumentHeader.DocumentTypeId) + ":" + TypeMissing]);
return Of(type);
}
/// <summary>The definitions of every usable type (enabled, with a kind), by code.</summary>
/// <param name="uow">A company unit of work.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The definitions.</returns>
public static async Task<IReadOnlyList<DocumentDefinition>> ListAsync(IUnitOfWork uow, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(uow);
var types = await uow.Repository<DocumentType, long>().ListAsync(Query.For<DocumentType>().OrderBy(t => t.Code), cancellationToken).ConfigureAwait(false);
return [.. types.Items.Where(t => !t.Disabled && t.DocumentKind is not null).Select(Of)];
}
/// <summary>The definition of a type row.</summary>
/// <param name="type">The row.</param>
/// <returns>The definition.</returns>
/// <exception cref="ValidationFailedException">The type has no kind.</exception>
public static DocumentDefinition Of(DocumentType type)
{
ArgumentNullException.ThrowIfNull(type);
return type.DocumentKind is { } kind
? new DocumentDefinition(type, DocumentBehaviors.Of(kind))
: throw new ValidationFailedException([nameof(DocumentHeader.DocumentTypeId) + ":" + TypeWithoutKind]);
}
}
@@ -0,0 +1,445 @@
using Khaemhat.Application.Items;
using Khaemhat.Application.Querying;
using Khaemhat.Application.Security;
using Khaemhat.Application.Tables;
using Khaemhat.Core.Documents;
using Khaemhat.Core.Items;
using Khaemhat.Core.Parties;
using Khaemhat.Core.Tables;
using Khaemhat.Core.Tax;
using Khaemhat.Data;
using Khaemhat.Data.Querying;
namespace Khaemhat.Application.Documents;
/// <summary>A document in a radar.</summary>
/// <param name="Id">The document.</param>
/// <param name="Family">The family.</param>
/// <param name="Kind">The kind.</param>
/// <param name="TypeCode">The code of the document type.</param>
/// <param name="DocumentNumber">The number as printed; empty for drafts.</param>
/// <param name="Date">The date.</param>
/// <param name="PartyId">The party.</param>
/// <param name="PartyCode">The code of the party.</param>
/// <param name="PartyName">The name of the party.</param>
/// <param name="Status">The state.</param>
/// <param name="Taxable">The taxable amount.</param>
/// <param name="Total">The total.</param>
/// <param name="Net">The amount to pay.</param>
/// <param name="Reference">The reference of the other side.</param>
/// <param name="DeliveryDate">The delivery date.</param>
/// <param name="ValidUntil">Until when a quotation is valid.</param>
/// <param name="Revision">The revision of a quotation.</param>
/// <param name="IsDemo">Demo data.</param>
public sealed record DocumentRow(
long Id, DocumentFamily Family, DocumentKind Kind, string TypeCode, string? DocumentNumber, DateOnly Date, long? PartyId, string? PartyCode,
string? PartyName, DocumentStatus Status, decimal Taxable, decimal Total, decimal Net, string? Reference, DateOnly? DeliveryDate,
DateOnly? ValidUntil, int Revision, bool IsDemo);
/// <summary>A document linked to another one.</summary>
/// <param name="Family">The family.</param>
/// <param name="Id">The document.</param>
/// <param name="Kind">The kind.</param>
/// <param name="DocumentNumber">The number.</param>
/// <param name="Date">The date.</param>
/// <param name="Status">The state.</param>
/// <param name="Total">The total.</param>
/// <param name="Direction">Where it stands: before (source), after (fulfils it) or corrected (note).</param>
/// <param name="Quantity">The quantity fulfilled between the two.</param>
public sealed record LinkedDocument(
DocumentFamily Family, long Id, DocumentKind Kind, string? DocumentNumber, DateOnly Date, DocumentStatus Status, decimal Total,
LinkDirection Direction, decimal Quantity);
/// <summary>How a linked document relates to the one shown.</summary>
public enum LinkDirection
{
/// <summary>The document shown fulfils it (an order of a delivery note).</summary>
Source = 0,
/// <summary>It fulfils the document shown (a delivery note of an order).</summary>
Target = 1,
/// <summary>The invoice a note corrects, or a note that corrects the invoice shown.</summary>
Related = 2,
}
/// <summary>An open document with something left to fulfil, for the guided fulfilment and the deferred invoicing.</summary>
/// <param name="Row">The document.</param>
/// <param name="Lines">The lines with a residual.</param>
public sealed record OpenDocument(DocumentRow Row, IReadOnlyList<DocumentLine> Lines);
/// <summary>
/// What the document screens need besides the engine (SPEC §11.3-§11.4): radars, the values proposed by the party and
/// by the item, totals computed while editing, the documents linked and the open documents to fulfil.
/// </summary>
public sealed class DocumentEditor
{
private readonly IUnitOfWorkFactory _factory;
private readonly PermissionService _permissions;
private readonly CompanyFiscalContext _packs;
/// <summary>Creates the service.</summary>
/// <param name="factory">The units of work.</param>
/// <param name="permissions">The permissions.</param>
/// <param name="packs">The fiscal packs.</param>
public DocumentEditor(IUnitOfWorkFactory factory, PermissionService permissions, CompanyFiscalContext packs)
{
ArgumentNullException.ThrowIfNull(factory);
ArgumentNullException.ThrowIfNull(permissions);
ArgumentNullException.ThrowIfNull(packs);
_factory = factory;
_permissions = permissions;
_packs = packs;
}
/// <summary>A page of documents of some kinds of a family.</summary>
/// <param name="actor">Who reads.</param>
/// <param name="companyCode">The company.</param>
/// <param name="family">The family.</param>
/// <param name="kinds">The kinds; all of the family when empty.</param>
/// <param name="query">The request; the search also looks at the code and name of the party.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The page.</returns>
public async Task<ListPage<DocumentRow>> ListAsync(
Actor actor, string companyCode, DocumentFamily family, IReadOnlyCollection<DocumentKind> kinds, ListQuery query, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(kinds);
ArgumentNullException.ThrowIfNull(query);
var wanted = kinds.Count > 0 ? kinds : DocumentBehaviors.KindsOf(family);
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, DocumentBehaviors.Of(wanted.First()).ReadPermission, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
var conditions = new List<SqlFragment>
{
SqlFragment.Literal("kind IN (") + SqlFragment.Join(", ", wanted.Select(k => SqlFragment.Parameter(k.ToString()))) + SqlFragment.Literal(")"),
};
var list = query;
if (!string.IsNullOrWhiteSpace(query.Search))
{
var pattern = "%" + query.Search.Trim().ToLowerInvariant() + "%";
var parties = await uow.Repository<Party, long>().ListAsync(
Query.For<Party>().Where(SqlFragment.Of($"(LOWER(name) LIKE {pattern} OR LOWER(code) LIKE {pattern})")).Take(500), cancellationToken).ConfigureAwait(false);
var any = new List<SqlFragment>
{
SqlFragment.Of($"LOWER(document_number) LIKE {pattern}"),
SqlFragment.Of($"LOWER(external_reference) LIKE {pattern}"),
};
if (parties.Items.Count > 0)
{
any.Add(SqlFragment.Literal("party_id IN (") + SqlFragment.Join(", ", parties.Items.Select(p => SqlFragment.Parameter(p.Id))) + SqlFragment.Literal(")"));
}
conditions.Add(SqlFragment.Join(" OR ", any).Parenthesize());
list = query with { Search = null };
}
var page = await DocumentStores.Of(family).ListAsync(uow, list, conditions, cancellationToken).ConfigureAwait(false);
return new ListPage<DocumentRow>(await RowsAsync(uow, family, page.Items, cancellationToken).ConfigureAwait(false), page.Total, page.Totals);
}
/// <summary>
/// Proposes the values of a party on a draft (SPEC §11.3): destination, price list, payment, bank, agent, carrier,
/// warehouse, currency, split payment, stamp duty, withholding and social security; the VAT code of the lines when
/// the party has its own (declaration of intent, exemption).
/// </summary>
/// <param name="actor">Who edits.</param>
/// <param name="companyCode">The company.</param>
/// <param name="record">The document, changed in place.</param>
/// <param name="partyId">The party; none clears it.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
public async Task ApplyPartyAsync(Actor actor, string companyCode, DocumentRecord record, long? partyId, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(record);
var behavior = DocumentBehaviors.Of(record.Header.Kind);
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, behavior.WritePermission, cancellationToken).ConfigureAwait(false);
var header = record.Header;
header.PartyId = partyId;
header.DestinationId = null;
if (partyId is not { } id)
{
return;
}
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
var party = await uow.Repository<Party, long>().GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException("party.not-found");
var fiscal = await uow.Repository<PartyFiscal, long>().FindAsync(Query.For<PartyFiscal>().Where(f => f.PartyId == id), cancellationToken).ConfigureAwait(false);
header.CurrencyCode = party.CurrencyCode;
header.SalespersonId = party.SalespersonId ?? header.SalespersonId;
if (behavior.Direction == DocumentDirection.Sale)
{
var terms = await uow.Repository<PartySalesTerms, long>().FindAsync(Query.For<PartySalesTerms>().Where(t => t.PartyId == id), cancellationToken).ConfigureAwait(false);
header.PriceListId = terms?.PriceListId;
header.PaymentTermId = terms?.PaymentTermId ?? header.PaymentTermId;
header.BankAccountId = terms?.CompanyBankAccountId ?? header.BankAccountId;
header.CarrierId = terms?.CarrierId ?? header.CarrierId;
header.ShippingTermId = terms?.ShippingTermId ?? header.ShippingTermId;
header.WarehouseId = terms?.WarehouseId ?? header.WarehouseId;
var addresses = await uow.Repository<PartyAddress, long>()
.ListAsync(Query.For<PartyAddress>().Where(a => a.PartyId == id && a.Kind == PartyAddressKind.Delivery), cancellationToken).ConfigureAwait(false);
header.DestinationId = (addresses.Items.FirstOrDefault(a => a.IsDefault) ?? (addresses.Items.Count == 1 ? addresses.Items[0] : null))?.Id;
if (header.BankAccountId is null)
{
var profile = await uow.Repository<CompanyProfile, long>().FindAsync(Query.For<CompanyProfile>(), cancellationToken).ConfigureAwait(false);
header.BankAccountId = profile?.DefaultBankAccountId;
}
}
else
{
var terms = await uow.Repository<PartyPurchaseTerms, long>().FindAsync(Query.For<PartyPurchaseTerms>().Where(t => t.PartyId == id), cancellationToken).ConfigureAwait(false);
header.PaymentTermId = terms?.PaymentTermId ?? header.PaymentTermId;
header.ShippingTermId = terms?.ShippingTermId ?? header.ShippingTermId;
}
header.PaymentMethodId = header.PaymentTermId is { } termId
? (await uow.Repository<PaymentTerm, long>().GetAsync(termId, cancellationToken).ConfigureAwait(false))?.PaymentMethodId
: null;
header.SplitPayment = fiscal?.SplitPayment ?? false;
header.StampDutyCharged = fiscal?.StampDutyCharged ?? true;
header.Exigibility = fiscal?.Exigibility?.Trim().ToUpperInvariant() switch
{
"D" => TaxExigibility.Deferred,
"S" => TaxExigibility.SplitPayment,
_ => null,
};
var withholding = fiscal is { Withholding: true } && behavior.Kind != DocumentKind.DeliveryNote;
header.WithholdingRate = withholding ? fiscal!.WithholdingRate ?? 20m : null;
header.WithholdingBasePercent = 100m;
header.WithholdingType = withholding ? "RT01" : null;
header.WithholdingReason = withholding ? fiscal!.WithholdingReason ?? "A" : null;
header.SocialSecurityFund = string.IsNullOrWhiteSpace(fiscal?.PensionFund) ? null : fiscal.PensionFund;
header.SocialSecurityRate = header.SocialSecurityFund is null ? null : fiscal!.PensionFundRate;
header.SocialSecurityWithheld = header.SocialSecurityFund == "TC22";
header.EnasarcoRate = behavior.Direction == DocumentDirection.Purchase && fiscal is { Enasarco: true } ? 8.5m : null;
if (PartyTaxCode(fiscal, header.DocumentDate) is { } taxCode)
{
foreach (var line in record.Lines.Where(l => l.Kind != DocumentLineKind.Description))
{
line.TaxCodeId = taxCode;
}
}
}
/// <summary>
/// Fills a line from an item: description, unit, VAT, price and discounts (net price of the party, list, base list,
/// item) and quantity one when empty.
/// </summary>
/// <param name="actor">Who edits.</param>
/// <param name="companyCode">The company.</param>
/// <param name="record">The document.</param>
/// <param name="line">The line, changed in place.</param>
/// <param name="itemId">The item.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
public async Task FillLineAsync(Actor actor, string companyCode, DocumentRecord record, DocumentLine line, long itemId, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(record);
ArgumentNullException.ThrowIfNull(line);
var behavior = DocumentBehaviors.Of(record.Header.Kind);
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, behavior.WritePermission, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
var item = await uow.Repository<Item, long>().GetAsync(itemId, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(ItemService.NotFound);
line.Kind = DocumentLineKind.Item;
line.ItemId = item.Id;
line.Description = item.Description;
line.UnitOfMeasureId = item.UnitOfMeasureId;
if (line.Quantity == 0m)
{
line.Quantity = 1m;
}
PartyFiscal? fiscal = null;
if (record.Header.PartyId is { } partyId)
{
fiscal = await uow.Repository<PartyFiscal, long>().FindAsync(Query.For<PartyFiscal>().Where(f => f.PartyId == partyId), cancellationToken).ConfigureAwait(false);
}
if (behavior.Direction == DocumentDirection.Purchase)
{
line.TaxCodeId = PartyTaxCode(fiscal, record.Header.DocumentDate) ?? item.PurchaseTaxCodeId;
var supplier = record.Header.PartyId is { } supplierId
? await uow.Repository<ItemSupplier, long>().FindAsync(Query.For<ItemSupplier>().Where(s => s.ItemId == item.Id && s.PartyId == supplierId), cancellationToken).ConfigureAwait(false)
: null;
line.Price = supplier?.Price ?? item.LastCost ?? item.StandardCost ?? 0m;
line.PriceSource = supplier?.Price is not null ? PriceSource.PartyNet : PriceSource.Item;
line.DiscountFormula = null;
return;
}
line.TaxCodeId = PartyTaxCode(fiscal, record.Header.DocumentDate) ?? item.SalesTaxCodeId;
var (price, discounts) = await PriceListService.QuoteAsync(uow, item.Id, record.Header.PartyId, record.Header.PriceListId, record.Header.DocumentDate, cancellationToken)
.ConfigureAwait(false);
line.Price = price.Price ?? 0m;
line.PriceSource = price.Source;
line.DiscountFormula = discounts.Formula;
if (price.VatIncluded && !record.Header.PricesIncludeTax && line.TaxCodeId is { } taxId
&& await uow.Repository<TaxCode, long>().GetAsync(taxId, cancellationToken).ConfigureAwait(false) is { Rate: > 0m } tax)
{
// A list with VAT on a document without: the net price, to four decimals like the lists.
line.Price = Math.Round(line.Price * 100m / (100m + tax.Rate), 4, MidpointRounding.AwayFromZero);
}
}
/// <summary>
/// Computes the totals of a document being edited, without saving: line amounts and header totals change in place.
/// </summary>
/// <param name="actor">Who edits.</param>
/// <param name="companyCode">The company.</param>
/// <param name="record">The document.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The tax summary and installments the save would write.</returns>
public async Task<DocumentFigures> PreviewAsync(Actor actor, string companyCode, DocumentRecord record, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(record);
var behavior = DocumentBehaviors.Of(record.Header.Kind);
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, behavior.ReadPermission, cancellationToken).ConfigureAwait(false);
var pack = await _packs.PackOfAsync(company, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
return await DocumentCalculation.ApplyAsync(uow, pack.TaxEngine, behavior, record, cancellationToken).ConfigureAwait(false);
}
/// <summary>The documents linked to one: the ones it fulfils, the ones that fulfil it, the invoice a note corrects.</summary>
/// <param name="actor">Who reads.</param>
/// <param name="companyCode">The company.</param>
/// <param name="record">The document.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The linked documents.</returns>
public async Task<IReadOnlyList<LinkedDocument>> LinksAsync(Actor actor, string companyCode, DocumentRecord record, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(record);
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, DocumentBehaviors.Of(record.Header.Kind).ReadPermission, cancellationToken)
.ConfigureAwait(false);
if (record.Header.Id == 0)
{
return [];
}
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
var family = record.Family.ToString();
var id = record.Header.Id;
var links = (await uow.Repository<DocumentLink, long>().ListAsync(
Query.For<DocumentLink>().Where(SqlFragment.Of(
$"((target_family = {family} AND target_document_id = {id}) OR (source_family = {family} AND source_document_id = {id}))")),
cancellationToken).ConfigureAwait(false)).Items;
var wanted = new Dictionary<(DocumentFamily, long), (LinkDirection Direction, decimal Quantity)>();
foreach (var link in links)
{
var (key, direction) = link.TargetFamily == record.Family && link.TargetDocumentId == id
? ((link.SourceFamily, link.SourceDocumentId), LinkDirection.Source)
: ((link.TargetFamily, link.TargetDocumentId), LinkDirection.Target);
wanted[key] = (direction, wanted.GetValueOrDefault(key).Quantity + link.Quantity);
}
if (record.Header.RelatedDocumentId is { } related)
{
wanted.TryAdd((record.Family, related), (LinkDirection.Related, 0m));
}
var notes = await DocumentStores.Of(record.Family).ListAsync(uow, new ListQuery { Limit = 100 },
[SqlFragment.Of($"related_document_id = {id}")], cancellationToken).ConfigureAwait(false);
foreach (var note in notes.Items)
{
wanted.TryAdd((record.Family, note.Id), (LinkDirection.Related, 0m));
}
var result = new List<LinkedDocument>();
foreach (var group in wanted.GroupBy(w => w.Key.Item1))
{
var headers = await DocumentStores.Of(group.Key).ManyAsync(uow, [.. group.Select(g => g.Key.Item2)], cancellationToken).ConfigureAwait(false);
foreach (var header in headers)
{
var (direction, quantity) = wanted[(group.Key, header.Id)];
result.Add(new LinkedDocument(group.Key, header.Id, header.Kind, header.DocumentNumber, header.DocumentDate, header.Status, header.TotalAmount,
direction, quantity));
}
}
return [.. result.OrderBy(r => r.Direction).ThenBy(r => r.Date).ThenBy(r => r.DocumentNumber, StringComparer.Ordinal)];
}
/// <summary>
/// The confirmed documents of some kinds with something left to fulfil, for a party or for all, up to a date: what
/// a new delivery note can take from the orders, or a deferred invoice from the delivery notes.
/// </summary>
/// <param name="actor">Who reads.</param>
/// <param name="companyCode">The company.</param>
/// <param name="family">The family of the sources.</param>
/// <param name="kinds">The kinds of the sources.</param>
/// <param name="partyId">The party; all when empty.</param>
/// <param name="from">The first date; none when empty.</param>
/// <param name="to">The last date; none when empty.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The documents, by party and date.</returns>
public async Task<IReadOnlyList<OpenDocument>> OpenAsync(
Actor actor, string companyCode, DocumentFamily family, IReadOnlyCollection<DocumentKind> kinds, long? partyId, DateOnly? from, DateOnly? to,
CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(kinds);
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, DocumentBehaviors.Of(kinds.First()).ReadPermission, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
var conditions = new List<SqlFragment>
{
SqlFragment.Literal("kind IN (") + SqlFragment.Join(", ", kinds.Select(k => SqlFragment.Parameter(k.ToString()))) + SqlFragment.Literal(")"),
SqlFragment.Of($"status IN ({nameof(DocumentStatus.Confirmed)}, {nameof(DocumentStatus.PartiallyFulfilled)})"),
};
if (partyId is { } party)
{
conditions.Add(SqlFragment.Of($"party_id = {party}"));
}
if (from is { } first)
{
conditions.Add(SqlFragment.Of($"document_date >= {first}"));
}
if (to is { } last)
{
conditions.Add(SqlFragment.Of($"document_date <= {last}"));
}
var store = DocumentStores.Of(family);
var page = await store.ListAsync(uow, new ListQuery { Limit = ListQuery.MaxLimit, Sort = [new ListSort("date"), new ListSort("number")] }, conditions, cancellationToken)
.ConfigureAwait(false);
var rows = await RowsAsync(uow, family, page.Items, cancellationToken).ConfigureAwait(false);
var result = new List<OpenDocument>();
foreach (var row in rows)
{
var lines = (await store.LinesAsync(uow, row.Id, cancellationToken).ConfigureAwait(false)).Where(l => l.Residual > 0m).ToList();
if (lines.Count > 0)
{
result.Add(new OpenDocument(row, lines));
}
}
return [.. result.OrderBy(r => r.Row.PartyName, StringComparer.CurrentCulture).ThenBy(r => r.Row.Date).ThenBy(r => r.Row.DocumentNumber, StringComparer.Ordinal)];
}
private static long? PartyTaxCode(PartyFiscal? fiscal, DateOnly date) =>
fiscal switch
{
{ IntentActive: true, IntentTaxCodeId: { } intent } when (fiscal.IntentFrom is null || fiscal.IntentFrom <= date) && (fiscal.IntentTo is null || fiscal.IntentTo >= date) => intent,
{ TaxCodeId: { } own } => own,
_ => null,
};
private static async Task<IReadOnlyList<DocumentRow>> RowsAsync(IUnitOfWork uow, DocumentFamily family, IReadOnlyList<DocumentHeader> headers, CancellationToken cancellationToken)
{
var partyIds = headers.Where(h => h.PartyId is not null).Select(h => h.PartyId!.Value).Distinct().ToList();
var parties = partyIds.Count == 0
? new Dictionary<long, Party>()
: (await uow.Repository<Party, long>().ListAsync(Query.For<Party>().Where(p => partyIds.Contains(p.Id)), cancellationToken).ConfigureAwait(false)).Items.ToDictionary(p => p.Id);
var typeIds = headers.Select(h => h.DocumentTypeId).Distinct().ToList();
var types = typeIds.Count == 0
? new Dictionary<long, DocumentType>()
: (await uow.Repository<DocumentType, long>().ListAsync(Query.For<DocumentType>().Where(t => typeIds.Contains(t.Id)), cancellationToken).ConfigureAwait(false)).Items.ToDictionary(t => t.Id);
return
[
.. headers.Select(h =>
{
var party = h.PartyId is { } p ? parties.GetValueOrDefault(p) : null;
return new DocumentRow(h.Id, family, h.Kind, types.GetValueOrDefault(h.DocumentTypeId)?.Code ?? string.Empty, h.DocumentNumber, h.DocumentDate, h.PartyId,
party?.Code, party?.Name, h.Status, h.TaxableAmount, h.TotalAmount, h.NetAmount, h.ExternalReference, h.DeliveryDate, h.ValidUntil, h.Revision, h.IsDemo);
}),
];
}
}
@@ -0,0 +1,936 @@
using Khaemhat.Application.Audit;
using Khaemhat.Application.Inventory;
using Khaemhat.Application.Security;
using Khaemhat.Application.Tables;
using Khaemhat.Core.Documents;
using Khaemhat.Data;
using Khaemhat.Data.Querying;
using Microsoft.Extensions.Logging;
namespace Khaemhat.Application.Documents;
/// <summary>A document with its lines, whatever the family.</summary>
public sealed class DocumentRecord
{
/// <summary>The family.</summary>
public DocumentFamily Family { get; init; }
/// <summary>The header.</summary>
public required DocumentHeader Header { get; init; }
/// <summary>The lines, in order.</summary>
public List<DocumentLine> Lines { get; init; } = [];
/// <summary>The tax summary and installments written by the last save.</summary>
public DocumentFigures Figures { get; init; } = DocumentFigures.Empty;
}
/// <summary>The error codes of the document engine; the interface translates them (<c>Documents.json</c>).</summary>
public static class DocumentErrors
{
/// <summary>The document does not exist.</summary>
public const string NotFound = "document.not-found";
/// <summary>A customer or supplier is needed.</summary>
public const string PartyRequired = "document.party.required";
/// <summary>The date is missing.</summary>
public const string DateRequired = "document.date.required";
/// <summary>The date of a numbered document cannot change.</summary>
public const string DateNumbered = "document.date.numbered";
/// <summary>The type belongs to another family of documents.</summary>
public const string TypeFamily = "document.type.family";
/// <summary>The type of a confirmed document cannot change.</summary>
public const string TypeLocked = "document.type.locked";
/// <summary>The document has no lines.</summary>
public const string LinesRequired = "document.lines.required";
/// <summary>The kind of line is not accepted by the document.</summary>
public const string LineKindNotAllowed = "document.line.kind-not-allowed";
/// <summary>A line without description.</summary>
public const string LineDescriptionRequired = "document.line.description-required";
/// <summary>An item line without item.</summary>
public const string LineItemRequired = "document.line.item-required";
/// <summary>A quantity below what later documents already fulfilled.</summary>
public const string LineBelowFulfilled = "document.line.below-fulfilled";
/// <summary>A line fulfilled by later documents cannot be removed.</summary>
public const string LineFulfilledRemoved = "document.line.fulfilled-removed";
/// <summary>The line to fulfil does not exist or belongs to a kind the document does not fulfil.</summary>
public const string LineSourceInvalid = "document.line.source-invalid";
/// <summary>A cancelled invoice needs a reason.</summary>
public const string CancelReasonRequired = "document.cancel.reason-required";
/// <summary>Later documents fulfil this one: cancel them first.</summary>
public const string CancelHasFollowers = "document.cancel.has-followers";
/// <summary>A copy changes direction (sale to purchase).</summary>
public const string CopyDirection = "document.copy.direction";
/// <summary>Nothing is left to fulfil.</summary>
public const string CopyNothingLeft = "document.copy.nothing-left";
/// <summary>A closed or cancelled document cannot be fulfilled.</summary>
public const string CopySourceNotOpen = "document.copy.source-not-open";
/// <summary>Error: documents of different parties cannot go into one document.</summary>
public const string CopyParties = "document.copy.parties";
/// <summary>Error: a discount formula that cannot be read.</summary>
public const string LineDiscountInvalid = "document.line.discount-invalid";
/// <summary>Error: a line of an invoice without its VAT code.</summary>
public const string LineTaxRequired = "document.line.tax-required";
/// <summary>A supplier invoice needs the number and date the supplier gave it.</summary>
public const string SupplierNumberRequired = "document.purchase.number-required";
/// <summary>The same supplier already has a document of the kind with that number in that year.</summary>
public const string SupplierDuplicate = "document.purchase.duplicate";
/// <summary>The VAT date comes before the date of the supplier document.</summary>
public const string VatDateBefore = "document.purchase.vat-date-before";
}
/// <summary>
/// The document engine (SPEC §11.3, ADR 0032): one implementation of create, save, confirm or issue, cancel, close,
/// reopen and delete for every family, with the numbering and the fulfilment links. The typed entry points are
/// <see cref="DocumentService{THeader, TLine}"/> and <see cref="DocumentCopyService"/>.
/// </summary>
public sealed partial class DocumentEngine
{
private readonly IUnitOfWorkFactory _factory;
private readonly PermissionService _permissions;
private readonly AuditTrail _audit;
private readonly FiscalYearService _fiscal;
private readonly CompanyFiscalContext _packs;
private readonly TimeProvider _clock;
private readonly ILogger<DocumentEngine> _logger;
private readonly Ledger.LedgerPoster _ledger;
/// <summary>Creates the engine.</summary>
/// <param name="factory">The units of work.</param>
/// <param name="permissions">The permissions.</param>
/// <param name="audit">The history.</param>
/// <param name="fiscal">The fiscal calendar (open periods).</param>
/// <param name="packs">The fiscal pack of each company (tax rounding, stamp duty).</param>
/// <param name="clock">The clock.</param>
/// <param name="logger">The log (section Documenti): confirmations, changes of state, deletions.</param>
/// <param name="ledger">Posts the documents to the ledger (module ACCT).</param>
public DocumentEngine(
IUnitOfWorkFactory factory, PermissionService permissions, AuditTrail audit, FiscalYearService fiscal, CompanyFiscalContext packs, TimeProvider clock,
ILogger<DocumentEngine> logger, Ledger.LedgerPoster ledger)
{
ArgumentNullException.ThrowIfNull(ledger);
_ledger = ledger;
ArgumentNullException.ThrowIfNull(logger);
_logger = logger;
ArgumentNullException.ThrowIfNull(packs);
_packs = packs;
ArgumentNullException.ThrowIfNull(factory);
ArgumentNullException.ThrowIfNull(permissions);
ArgumentNullException.ThrowIfNull(audit);
ArgumentNullException.ThrowIfNull(fiscal);
ArgumentNullException.ThrowIfNull(clock);
_factory = factory;
_permissions = permissions;
_audit = audit;
_fiscal = fiscal;
_clock = clock;
}
internal IUnitOfWorkFactory Factory => _factory;
internal AuditTrail Audit => _audit;
/// <summary>The definitions of the usable document types.</summary>
/// <param name="actor">Who asks.</param>
/// <param name="companyCode">The company.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The definitions the actor can see.</returns>
public async Task<IReadOnlyList<DocumentDefinition>> DefinitionsAsync(Actor actor, string companyCode, CancellationToken cancellationToken = default)
{
var company = Company(actor, companyCode);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
var result = new List<DocumentDefinition>();
foreach (var definition in await DocumentDefinitionService.ListAsync(uow, cancellationToken).ConfigureAwait(false))
{
if ((await _permissions.CheckAsync(actor, definition.Behavior.ReadPermission, cancellationToken).ConfigureAwait(false)).Allowed)
{
result.Add(definition);
}
}
return result;
}
/// <summary>A new draft of a type, not saved: today's date and the defaults of the type.</summary>
/// <param name="actor">Who creates.</param>
/// <param name="companyCode">The company.</param>
/// <param name="typeCode">The document type, such as <c>FI</c>.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The draft.</returns>
public async Task<DocumentRecord> NewAsync(Actor actor, string companyCode, string typeCode, CancellationToken cancellationToken = default)
{
var company = Company(actor, companyCode);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
var definition = await DocumentDefinitionService.GetAsync(uow, typeCode, cancellationToken).ConfigureAwait(false);
await _permissions.DemandAsync(actor, definition.Behavior.WritePermission, cancellationToken).ConfigureAwait(false);
var header = DocumentStores.Of(definition.Family).NewHeader();
header.DocumentTypeId = definition.Type.Id;
header.Kind = definition.Kind;
header.Status = DocumentStatus.Draft;
header.DocumentDate = Today();
header.Year = header.DocumentDate.Year;
header.InventoryReasonId = definition.Type.InventoryReasonId;
return new DocumentRecord { Family = definition.Family, Header = header };
}
/// <summary>Reads a document.</summary>
/// <param name="actor">Who reads.</param>
/// <param name="companyCode">The company.</param>
/// <param name="family">The family.</param>
/// <param name="id">The document.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The document, if any.</returns>
public async Task<DocumentRecord?> GetAsync(Actor actor, string companyCode, DocumentFamily family, long id, CancellationToken cancellationToken = default)
{
var company = Company(actor, companyCode);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
var record = await LoadAsync(uow, family, id, cancellationToken).ConfigureAwait(false);
if (record is not null)
{
await _permissions.DemandAsync(actor, DocumentBehaviors.Of(record.Header.Kind).ReadPermission, cancellationToken).ConfigureAwait(false);
}
return record;
}
/// <summary>
/// Saves a draft (or the lines of a confirmed order still open): the engine keeps the number, state and other fields
/// it owns, numbers the lines and recomputes the fulfilment of a confirmed order.
/// </summary>
/// <param name="actor">Who saves.</param>
/// <param name="companyCode">The company.</param>
/// <param name="record">The document.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The document as saved.</returns>
/// <exception cref="ValidationFailedException">The document breaks a rule.</exception>
/// <exception cref="InvalidDocumentActionException">The state does not admit changes.</exception>
public async Task<DocumentRecord> SaveAsync(Actor actor, string companyCode, DocumentRecord record, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(record);
var company = Company(actor, companyCode);
var store = DocumentStores.Of(record.Family);
var pack = await _packs.PackOfAsync(company, cancellationToken).ConfigureAwait(false);
long id;
await using (var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false))
{
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
var header = record.Header;
var before = header.Id == 0 ? null : await LoadAsync(uow, record.Family, header.Id, cancellationToken).ConfigureAwait(false)
?? throw new ValidationFailedException([":" + DocumentErrors.NotFound]);
var definition = await DocumentDefinitionService.GetAsync(uow, before?.Header.DocumentTypeId ?? header.DocumentTypeId, cancellationToken).ConfigureAwait(false);
await _permissions.DemandAsync(actor, definition.Behavior.WritePermission, cancellationToken).ConfigureAwait(false);
if (before is null)
{
header.Kind = definition.Kind;
header.Status = DocumentStatus.Draft;
Release(header);
}
else
{
DocumentStateMachine.Apply(definition.Lifecycle, before.Header.Status, DocumentAction.Edit);
Keep(header, before.Header);
}
var errors = Check(definition, record, before);
await CheckSupplierDocumentAsync(uow, record, confirming: false, errors, cancellationToken).ConfigureAwait(false);
if (errors.Count > 0)
{
throw new ValidationFailedException(errors);
}
if (before is not null && definition.Kind == DocumentKind.Quotation && DocumentStateMachine.IsInForce(header.Status))
{
// A confirmed quotation that changes is a new revision of the same offer.
header.Revision = before.Header.Revision + 1;
}
var figures = await DocumentCalculation.ApplyAsync(uow, pack.TaxEngine, definition.Behavior, record, cancellationToken).ConfigureAwait(false);
id = await WriteAsync(uow, store, record, before, actor.UserName, cancellationToken).ConfigureAwait(false);
await DocumentCalculation.WriteAsync(uow, record.Family, id, figures, cancellationToken).ConfigureAwait(false);
if (before is not null && DocumentStateMachine.IsInForce(header.Status))
{
await RefreshFulfillmentAsync(uow, record.Family, id, actor.UserName, cancellationToken).ConfigureAwait(false);
await InventoryPoster.SyncAsync(uow, record.Family, id, cancellationToken).ConfigureAwait(false);
await _ledger.SyncAsync(uow, record.Family, id, cancellationToken).ConfigureAwait(false);
}
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
}
return await GetAsync(actor, company, record.Family, id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(DocumentErrors.NotFound);
}
/// <summary>
/// Confirms a document, or issues an invoice: checks it, numbers it, records the fulfilment of the documents its
/// lines come from.
/// </summary>
/// <param name="actor">Who confirms.</param>
/// <param name="companyCode">The company.</param>
/// <param name="family">The family.</param>
/// <param name="id">The document.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The document as confirmed.</returns>
public async Task<DocumentRecord> ConfirmAsync(Actor actor, string companyCode, DocumentFamily family, long id, CancellationToken cancellationToken = default)
{
var company = Company(actor, companyCode);
var store = DocumentStores.Of(family);
await using (var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false))
{
// The open period is read outside the transaction (the calendar has its own cache and connection).
var draft = await LoadAsync(uow, family, id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(DocumentErrors.NotFound);
var definition = await DocumentDefinitionService.GetAsync(uow, draft.Header.DocumentTypeId, cancellationToken).ConfigureAwait(false);
await _permissions.DemandAsync(actor, definition.Behavior.ConfirmPermission, cancellationToken).ConfigureAwait(false);
DocumentStateMachine.Apply(definition.Lifecycle, draft.Header.Status, definition.ConfirmAction);
if (definition.Behavior.Has(DocumentEffects.Ledger))
{
await _fiscal.DemandOpenAsync(company, draft.Header.DocumentDate, PeriodUse.Vat, cancellationToken).ConfigureAwait(false);
}
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
var record = await LoadAsync(uow, family, id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(DocumentErrors.NotFound);
var next = DocumentStateMachine.Apply(definition.Lifecycle, record.Header.Status, definition.ConfirmAction);
var errors = Check(definition, record, record);
if (record.Lines.Count == 0)
{
errors.Add("Lines:" + DocumentErrors.LinesRequired);
}
await CheckSupplierDocumentAsync(uow, record, confirming: true, errors, cancellationToken).ConfigureAwait(false);
if (definition.Behavior.Has(DocumentEffects.Ledger))
{
// A document that goes to the VAT registers needs the VAT of every line with an amount.
for (var i = 0; i < record.Lines.Count; i++)
{
if (record.Lines[i] is { Kind: not DocumentLineKind.Description, TaxCodeId: null })
{
errors.Add("Lines." + i.ToString(System.Globalization.CultureInfo.InvariantCulture) + "." + nameof(DocumentLine.TaxCodeId) + ":" + DocumentErrors.LineTaxRequired);
}
}
}
if (errors.Count > 0 || record.Header.DocumentDate != draft.Header.DocumentDate)
{
throw errors.Count > 0 ? new ValidationFailedException(errors) : new Core.Common.ConcurrencyException();
}
var header = record.Header;
var before = header.Clone();
if (definition.Type.NumeratorId is { } numeratorId)
{
var number = await DocumentNumberingService.NextAsync(uow, numeratorId, header.DocumentDate, cancellationToken).ConfigureAwait(false);
header.NumeratorId = number.Numerator.Id;
header.Section = number.Numerator.Section;
header.Number = number.Number;
header.DocumentNumber = number.Text;
}
header.Year = header.DocumentDate.Year;
if (IsRegistered(header.Kind))
{
// A supplier invoice takes its protocol from the numbering of the purchase register (§11.5).
header.VatProtocol = header.Number;
header.VatDate ??= header.DocumentDate;
}
header.Status = next;
header.ConfirmedAt = _clock.GetUtcNow().UtcDateTime;
header.ConfirmedBy = actor.UserName;
await store.UpdateAsync(uow, header, cancellationToken).ConfigureAwait(false);
await store.RecordAsync(_audit, uow, AuditAction.Update, id, before, header, actor.UserName, cancellationToken).ConfigureAwait(false);
await LinkAsync(uow, definition, record, actor.UserName, cancellationToken).ConfigureAwait(false);
await InventoryPoster.SyncAsync(uow, family, id, cancellationToken).ConfigureAwait(false);
await _ledger.SyncAsync(uow, family, id, cancellationToken).ConfigureAwait(false);
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
LogConfirmed(_logger, header.Kind, header.DocumentNumber ?? id.ToString(System.Globalization.CultureInfo.InvariantCulture), header.Status, company, actor.UserName);
}
return await GetAsync(actor, company, family, id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(DocumentErrors.NotFound);
}
/// <summary>
/// Cancels a document: the number stays, the fulfilment it recorded is given back. An invoice needs a reason and is
/// cancelled only before its file reaches the exchange system (or after a rejection).
/// </summary>
/// <param name="actor">Who cancels.</param>
/// <param name="companyCode">The company.</param>
/// <param name="family">The family.</param>
/// <param name="id">The document.</param>
/// <param name="reason">Why.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The document as cancelled.</returns>
public Task<DocumentRecord> CancelAsync(Actor actor, string companyCode, DocumentFamily family, long id, string? reason, CancellationToken cancellationToken = default) =>
ChangeStateAsync(actor, companyCode, family, id, DocumentAction.Cancel, async (uow, definition, record, ct) =>
{
var text = reason?.Trim();
if (definition.Lifecycle == DocumentLifecycle.Invoice && string.IsNullOrEmpty(text))
{
throw new ValidationFailedException([nameof(DocumentHeader.CancelReason) + ":" + DocumentErrors.CancelReasonRequired]);
}
if ((await LinksFromAsync(uow, family, id, ct).ConfigureAwait(false)).Count > 0)
{
throw new ValidationFailedException([":" + DocumentErrors.CancelHasFollowers]);
}
record.Header.CancelReason = string.IsNullOrEmpty(text) ? null : text[..Math.Min(text.Length, 200)];
record.Header.CancelledAt = _clock.GetUtcNow().UtcDateTime;
},
(uow, record, user, ct) => UnlinkAsync(uow, family, id, user, ct),
cancellationToken);
/// <summary>Closes what is left to fulfil of an order, quotation, delivery note or pro forma.</summary>
/// <param name="actor">Who closes.</param>
/// <param name="companyCode">The company.</param>
/// <param name="family">The family.</param>
/// <param name="id">The document.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The document as closed.</returns>
public Task<DocumentRecord> CloseAsync(Actor actor, string companyCode, DocumentFamily family, long id, CancellationToken cancellationToken = default) =>
ChangeStateAsync(actor, companyCode, family, id, DocumentAction.Close, null, null, cancellationToken);
/// <summary>Reopens a closed document: its state comes back from the fulfilment of its lines.</summary>
/// <param name="actor">Who reopens.</param>
/// <param name="companyCode">The company.</param>
/// <param name="family">The family.</param>
/// <param name="id">The document.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The document as reopened.</returns>
public Task<DocumentRecord> ReopenAsync(Actor actor, string companyCode, DocumentFamily family, long id, CancellationToken cancellationToken = default) =>
ChangeStateAsync(actor, companyCode, family, id, DocumentAction.Reopen, null,
(uow, record, user, ct) => RefreshFulfillmentAsync(uow, family, id, user, ct), cancellationToken);
/// <summary>
/// Records a step of the electronic invoice (file generated, sent, delivered, rejected, not delivered); the module
/// of the electronic invoice (M8) calls it.
/// </summary>
/// <param name="actor">Who records it.</param>
/// <param name="companyCode">The company.</param>
/// <param name="family">The family.</param>
/// <param name="id">The document.</param>
/// <param name="action">The step.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The document.</returns>
public Task<DocumentRecord> RecordExchangeAsync(Actor actor, string companyCode, DocumentFamily family, long id, DocumentAction action, CancellationToken cancellationToken = default)
{
if (action is not (DocumentAction.GenerateXml or DocumentAction.Send or DocumentAction.MarkDelivered or DocumentAction.MarkRejected or DocumentAction.MarkNotDelivered))
{
throw new ArgumentOutOfRangeException(nameof(action), action, "Not a step of the electronic invoice.");
}
return ChangeStateAsync(actor, companyCode, family, id, action, (uow, definition, record, ct) =>
{
if (action == DocumentAction.GenerateXml)
{
record.Header.XmlGenerated = true;
}
return Task.CompletedTask;
}, null, cancellationToken);
}
/// <summary>Records that the document was printed (its PDF kept among the attachments); the state does not change.</summary>
/// <param name="actor">Who prints: needs to read the document.</param>
/// <param name="companyCode">The company.</param>
/// <param name="family">The family.</param>
/// <param name="id">The document.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
public Task MarkPrintedAsync(Actor actor, string companyCode, DocumentFamily family, long id, CancellationToken cancellationToken = default) =>
MarkAsync(actor, companyCode, family, id, h => h.Printed = true, cancellationToken);
/// <summary>Records that the document was sent by e-mail; the state does not change.</summary>
/// <param name="actor">Who sends: needs to read the document.</param>
/// <param name="companyCode">The company.</param>
/// <param name="family">The family.</param>
/// <param name="id">The document.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
public Task MarkSentAsync(Actor actor, string companyCode, DocumentFamily family, long id, CancellationToken cancellationToken = default) =>
MarkAsync(actor, companyCode, family, id, h => h.Sent = true, cancellationToken);
/// <summary>Deletes a draft.</summary>
/// <param name="actor">Who deletes.</param>
/// <param name="companyCode">The company.</param>
/// <param name="family">The family.</param>
/// <param name="id">The document.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
public async Task DeleteAsync(Actor actor, string companyCode, DocumentFamily family, long id, CancellationToken cancellationToken = default)
{
var company = Company(actor, companyCode);
var store = DocumentStores.Of(family);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
var record = await LoadAsync(uow, family, id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(DocumentErrors.NotFound);
var definition = DocumentBehaviors.Of(record.Header.Kind);
await _permissions.DemandAsync(actor, definition.DeletePermission, cancellationToken).ConfigureAwait(false);
DocumentStateMachine.Apply(definition.Lifecycle, record.Header.Status, DocumentAction.Delete);
await store.DeleteAsync(uow, id, cancellationToken).ConfigureAwait(false);
await store.RecordAsync(_audit, uow, AuditAction.Delete, id, record.Header, null, actor.UserName, cancellationToken).ConfigureAwait(false);
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
LogDeleted(_logger, record.Header.Kind, id, company, actor.UserName);
}
/// <summary>The actions the state of a document admits for an actor.</summary>
/// <param name="actor">Who asks.</param>
/// <param name="record">The document.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The actions.</returns>
public async Task<IReadOnlyList<DocumentAction>> ActionsAsync(Actor actor, DocumentRecord record, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(record);
var behavior = DocumentBehaviors.Of(record.Header.Kind);
var result = new List<DocumentAction>();
foreach (var action in DocumentStateMachine.Actions(behavior.Lifecycle, record.Header.Status))
{
var permission = action switch
{
DocumentAction.Edit or DocumentAction.Copy => behavior.WritePermission,
DocumentAction.Delete => behavior.DeletePermission,
_ => behavior.ConfirmPermission,
};
if ((await _permissions.CheckAsync(actor, permission, cancellationToken).ConfigureAwait(false)).Allowed)
{
result.Add(action);
}
}
return result;
}
internal static async Task<DocumentRecord?> LoadAsync(IUnitOfWork uow, DocumentFamily family, long id, CancellationToken cancellationToken)
{
var store = DocumentStores.Of(family);
if (await store.GetAsync(uow, id, cancellationToken).ConfigureAwait(false) is not { } header)
{
return null;
}
return new DocumentRecord
{
Family = family,
Header = header,
Lines = await store.LinesAsync(uow, id, cancellationToken).ConfigureAwait(false),
Figures = await DocumentCalculation.ReadAsync(uow, family, id, cancellationToken).ConfigureAwait(false),
};
}
/// <summary>Checks a document against its definition; <paramref name="before"/> is the stored one.</summary>
internal static List<string> Check(DocumentDefinition definition, DocumentRecord record, DocumentRecord? before)
{
var errors = new List<string>();
var header = record.Header;
if (definition.Family != record.Family)
{
errors.Add(nameof(DocumentHeader.DocumentTypeId) + ":" + DocumentErrors.TypeFamily);
}
if (before is not null && header.DocumentTypeId != before.Header.DocumentTypeId)
{
errors.Add(nameof(DocumentHeader.DocumentTypeId) + ":" + DocumentErrors.TypeLocked);
}
if (definition.Type.Disabled && before is null)
{
errors.Add(nameof(DocumentHeader.DocumentTypeId) + ":" + DocumentDefinitionService.TypeDisabled);
}
if (definition.Behavior.NeedsParty && header.PartyId is null)
{
errors.Add(nameof(DocumentHeader.PartyId) + ":" + DocumentErrors.PartyRequired);
}
if (header.DocumentDate == default)
{
errors.Add(nameof(DocumentHeader.DocumentDate) + ":" + DocumentErrors.DateRequired);
}
else if (before?.Header.Number is not null && header.DocumentDate != before.Header.DocumentDate)
{
errors.Add(nameof(DocumentHeader.DocumentDate) + ":" + DocumentErrors.DateNumbered);
}
var stored = before?.Lines.ToDictionary(l => l.Id) ?? [];
for (var i = 0; i < record.Lines.Count; i++)
{
var line = record.Lines[i];
var field = "Lines." + i.ToString(System.Globalization.CultureInfo.InvariantCulture) + ".";
if (!definition.Behavior.Lines.Contains(line.Kind))
{
errors.Add(field + nameof(DocumentLine.Kind) + ":" + DocumentErrors.LineKindNotAllowed);
}
if (string.IsNullOrWhiteSpace(line.Description))
{
errors.Add(field + nameof(DocumentLine.Description) + ":" + DocumentErrors.LineDescriptionRequired);
}
if (!string.IsNullOrWhiteSpace(line.DiscountFormula) && !DiscountFormula.TryParse(line.DiscountFormula, out _))
{
errors.Add(field + nameof(DocumentLine.DiscountFormula) + ":" + DocumentErrors.LineDiscountInvalid);
}
if (line.Kind == DocumentLineKind.Item && line.ItemId is null)
{
errors.Add(field + nameof(DocumentLine.ItemId) + ":" + DocumentErrors.LineItemRequired);
}
if (line.Id != 0 && stored.TryGetValue(line.Id, out var old) && old.FulfilledQuantity > 0 && line.Quantity < old.FulfilledQuantity)
{
errors.Add(field + nameof(DocumentLine.Quantity) + ":" + DocumentErrors.LineBelowFulfilled);
}
}
var kept = record.Lines.Where(l => l.Id != 0).Select(l => l.Id).ToHashSet();
if (before is not null && before.Lines.Any(l => !kept.Contains(l.Id) && l.FulfilledQuantity > 0))
{
errors.Add("Lines:" + DocumentErrors.LineFulfilledRemoved);
}
return errors;
}
/// <summary>Writes the header and replaces the lines of a draft or open document.</summary>
internal async Task<long> WriteAsync(IUnitOfWork uow, IDocumentStore store, DocumentRecord record, DocumentRecord? before, string userName, CancellationToken cancellationToken)
{
var header = record.Header;
if (before is null)
{
header.Year = header.DocumentDate.Year;
await store.InsertAsync(uow, header, cancellationToken).ConfigureAwait(false);
await store.RecordAsync(_audit, uow, AuditAction.Insert, header.Id, null, header, userName, cancellationToken).ConfigureAwait(false);
}
else
{
if (header.Number is null)
{
header.Year = header.DocumentDate.Year;
}
header.RowVersion = before.Header.RowVersion;
await store.UpdateAsync(uow, header, cancellationToken).ConfigureAwait(false);
await store.RecordAsync(_audit, uow, AuditAction.Update, header.Id, before.Header, header, userName, cancellationToken).ConfigureAwait(false);
}
var id = header.Id;
var previous = before?.Lines.ToDictionary(l => l.Id) ?? [];
var kept = record.Lines.Where(l => l.Id != 0 && previous.ContainsKey(l.Id)).Select(l => l.Id).ToHashSet();
foreach (var old in previous.Values.Where(l => !kept.Contains(l.Id)))
{
await store.DeleteLineAsync(uow, old.Id, cancellationToken).ConfigureAwait(false);
}
for (var i = 0; i < record.Lines.Count; i++)
{
var line = record.Lines[i];
line.DocumentId = id;
line.LineNumber = i + 1;
line.SortOrder = i + 1;
if (line.Id != 0 && previous.TryGetValue(line.Id, out var old))
{
// The fulfilment is the engine's: what the links say, not what the screen sends.
line.FulfilledQuantity = old.FulfilledQuantity;
line.SourceFamily = old.SourceFamily;
line.SourceLineId = old.SourceLineId;
line.RowVersion = old.RowVersion;
await store.UpdateLineAsync(uow, line, cancellationToken).ConfigureAwait(false);
}
else
{
line.Id = 0;
line.FulfilledQuantity = 0;
if (line.SourceLineId is null || line.SourceFamily is null)
{
line.SourceLineId = null;
line.SourceFamily = null;
}
await store.InsertLineAsync(uow, line, cancellationToken).ConfigureAwait(false);
}
}
return id;
}
private async Task<DocumentRecord> ChangeStateAsync(
Actor actor,
string companyCode,
DocumentFamily family,
long id,
DocumentAction action,
Func<IUnitOfWork, DocumentDefinition, DocumentRecord, CancellationToken, Task>? before,
Func<IUnitOfWork, DocumentRecord, string, CancellationToken, Task>? after,
CancellationToken cancellationToken)
{
var company = Company(actor, companyCode);
var store = DocumentStores.Of(family);
await using (var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false))
{
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
var record = await LoadAsync(uow, family, id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(DocumentErrors.NotFound);
var definition = await DocumentDefinitionService.GetAsync(uow, record.Header.DocumentTypeId, cancellationToken).ConfigureAwait(false);
await _permissions.DemandAsync(actor, definition.Behavior.ConfirmPermission, cancellationToken).ConfigureAwait(false);
var next = DocumentStateMachine.Apply(definition.Lifecycle, record.Header.Status, action);
var old = record.Header.Clone();
if (before is not null)
{
await before(uow, definition, record, cancellationToken).ConfigureAwait(false);
}
record.Header.Status = next;
await store.UpdateAsync(uow, record.Header, cancellationToken).ConfigureAwait(false);
await store.RecordAsync(_audit, uow, AuditAction.Update, id, old, record.Header, actor.UserName, cancellationToken).ConfigureAwait(false);
if (after is not null)
{
await after(uow, record, actor.UserName, cancellationToken).ConfigureAwait(false);
}
// A cancelled delivery note gives its stock back; a closed or reopened order its open quantities.
await InventoryPoster.SyncAsync(uow, family, id, cancellationToken).ConfigureAwait(false);
await _ledger.SyncAsync(uow, family, id, cancellationToken).ConfigureAwait(false);
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
LogChanged(_logger, record.Header.Kind, record.Header.DocumentNumber ?? id.ToString(System.Globalization.CultureInfo.InvariantCulture), action, next, company, actor.UserName);
}
return await GetAsync(actor, company, family, id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(DocumentErrors.NotFound);
}
// Sets an output flag (printed, sent) with its trace in the history, whatever the state.
private async Task MarkAsync(Actor actor, string companyCode, DocumentFamily family, long id, Action<DocumentHeader> change, CancellationToken cancellationToken)
{
var company = Company(actor, companyCode);
var store = DocumentStores.Of(family);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
var header = await store.GetAsync(uow, id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(DocumentErrors.NotFound);
await _permissions.DemandAsync(actor, DocumentBehaviors.Of(header.Kind).ReadPermission, cancellationToken).ConfigureAwait(false);
var old = header.Clone();
change(header);
if (old.Printed != header.Printed || old.Sent != header.Sent)
{
await store.UpdateAsync(uow, header, cancellationToken).ConfigureAwait(false);
await store.RecordAsync(_audit, uow, AuditAction.Update, id, old, header, actor.UserName, cancellationToken).ConfigureAwait(false);
}
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
}
// Records the links of a confirmed document towards the lines it fulfils, then the fulfilment of those documents.
private async Task LinkAsync(IUnitOfWork uow, DocumentDefinition definition, DocumentRecord record, string userName, CancellationToken cancellationToken)
{
var links = uow.Repository<DocumentLink, long>();
var touched = new HashSet<(DocumentFamily, long)>();
foreach (var line in record.Lines.Where(l => l.SourceLineId is not null && l.SourceFamily is not null))
{
var sourceFamily = line.SourceFamily!.Value;
var source = await DocumentStores.Of(sourceFamily).GetLineAsync(uow, line.SourceLineId!.Value, cancellationToken).ConfigureAwait(false);
var sourceHeader = source is null ? null : await DocumentStores.Of(sourceFamily).GetAsync(uow, source.DocumentId, cancellationToken).ConfigureAwait(false);
if (source is null || sourceHeader is null || !definition.Behavior.Fulfils(sourceHeader.Kind) || !DocumentStateMachine.IsInForce(sourceHeader.Status))
{
throw new ValidationFailedException(["Lines." + (line.LineNumber - 1).ToString(System.Globalization.CultureInfo.InvariantCulture) + ".SourceLineId:" + DocumentErrors.LineSourceInvalid]);
}
await links.InsertAsync(
new DocumentLink
{
TargetFamily = record.Family,
TargetDocumentId = record.Header.Id,
TargetLineId = line.Id,
SourceFamily = sourceFamily,
SourceDocumentId = source.DocumentId,
SourceLineId = source.Id,
Quantity = line.Quantity,
},
cancellationToken).ConfigureAwait(false);
touched.Add((sourceFamily, source.DocumentId));
}
foreach (var (family, documentId) in touched)
{
await RefreshFulfillmentAsync(uow, family, documentId, userName, cancellationToken).ConfigureAwait(false);
}
}
// Removes the links of a cancelled document and gives the quantities back to the documents it fulfilled.
private async Task UnlinkAsync(IUnitOfWork uow, DocumentFamily family, long id, string userName, CancellationToken cancellationToken)
{
var links = uow.Repository<DocumentLink, long>();
var mine = (await links.ListAsync(Query.For<DocumentLink>().Where(l => l.TargetFamily == family && l.TargetDocumentId == id), cancellationToken).ConfigureAwait(false)).Items;
foreach (var link in mine)
{
await links.DeleteAsync(link.Id, cancellationToken).ConfigureAwait(false);
}
foreach (var source in mine.Select(l => (l.SourceFamily, l.SourceDocumentId)).Distinct())
{
await RefreshFulfillmentAsync(uow, source.SourceFamily, source.SourceDocumentId, userName, cancellationToken).ConfigureAwait(false);
}
}
private static async Task<IReadOnlyList<DocumentLink>> LinksFromAsync(IUnitOfWork uow, DocumentFamily family, long id, CancellationToken cancellationToken) =>
(await uow.Repository<DocumentLink, long>().ListAsync(Query.For<DocumentLink>().Where(l => l.SourceFamily == family && l.SourceDocumentId == id), cancellationToken)
.ConfigureAwait(false)).Items;
// The quantities fulfilled of each line from the links, then the state of the document from its lines.
private async Task RefreshFulfillmentAsync(IUnitOfWork uow, DocumentFamily family, long id, string userName, CancellationToken cancellationToken)
{
var store = DocumentStores.Of(family);
var record = await LoadAsync(uow, family, id, cancellationToken).ConfigureAwait(false);
if (record is null)
{
return;
}
var links = await LinksFromAsync(uow, family, id, cancellationToken).ConfigureAwait(false);
foreach (var line in FulfillmentCalculator.Apply(record.Lines, links))
{
await store.UpdateLineAsync(uow, line, cancellationToken).ConfigureAwait(false);
}
var header = record.Header;
var lifecycle = DocumentBehaviors.Of(header.Kind).Lifecycle;
var status = DocumentStateMachine.AfterFulfillment(lifecycle, header.Status, FulfillmentCalculator.StateOf(record.Lines));
if (status != header.Status)
{
var before = header.Clone();
header.Status = status;
await store.UpdateAsync(uow, header, cancellationToken).ConfigureAwait(false);
await store.RecordAsync(_audit, uow, AuditAction.Update, id, before, header, userName, cancellationToken).ConfigureAwait(false);
}
}
// The fields the engine owns keep their stored value whatever the screen sends.
private static void Keep(DocumentHeader header, DocumentHeader stored)
{
header.Kind = stored.Kind;
header.Status = stored.Status;
header.NumeratorId = stored.NumeratorId;
header.Section = stored.Section;
header.Number = stored.Number;
header.DocumentNumber = stored.DocumentNumber;
header.Year = stored.Year;
header.ConfirmedAt = stored.ConfirmedAt;
header.ConfirmedBy = stored.ConfirmedBy;
header.CancelledAt = stored.CancelledAt;
header.CancelReason = stored.CancelReason;
header.XmlGenerated = stored.XmlGenerated;
header.Posted = stored.Posted;
header.GlEntryId = stored.GlEntryId;
header.InstallmentsGenerated = stored.InstallmentsGenerated;
header.Printed = stored.Printed;
header.Sent = stored.Sent;
header.Revision = stored.Revision;
header.IsDemo = stored.IsDemo;
}
// A new draft has no number and no history of states.
private static void Release(DocumentHeader header)
{
header.Id = 0;
header.NumeratorId = null;
header.Number = null;
header.DocumentNumber = null;
header.ConfirmedAt = null;
header.ConfirmedBy = null;
header.CancelledAt = null;
header.CancelReason = null;
header.XmlGenerated = false;
header.Posted = false;
header.GlEntryId = null;
header.InstallmentsGenerated = false;
header.Printed = false;
header.Sent = false;
header.Revision = 0;
}
// Supplier invoices and credit notes go to the purchase register with a protocol and a VAT date.
private static bool IsRegistered(DocumentKind kind) => kind is DocumentKind.PurchaseInvoice or DocumentKind.PurchaseCreditNote;
// The rules of a supplier document (§11.5): its own number and date, the VAT date not before it, no duplicate of
// the same supplier, kind, number and year among the documents in force or in draft.
private static async Task CheckSupplierDocumentAsync(IUnitOfWork uow, DocumentRecord record, bool confirming, List<string> errors, CancellationToken cancellationToken)
{
var header = record.Header;
if (!IsRegistered(header.Kind))
{
return;
}
var number = header.ExternalReference?.Trim();
if (confirming && string.IsNullOrEmpty(number))
{
errors.Add(nameof(DocumentHeader.ExternalReference) + ":" + DocumentErrors.SupplierNumberRequired);
}
if (confirming && header.ExternalDate is null)
{
errors.Add(nameof(DocumentHeader.ExternalDate) + ":" + DocumentErrors.SupplierNumberRequired);
}
if (header.VatDate is { } vatDate && header.ExternalDate is { } supplierDate && vatDate < supplierDate)
{
errors.Add(nameof(DocumentHeader.VatDate) + ":" + DocumentErrors.VatDateBefore);
}
if (string.IsNullOrEmpty(number) || header.PartyId is not { } party)
{
return;
}
var year = (header.ExternalDate ?? header.DocumentDate).Year;
var kind = header.Kind;
var id = header.Id;
var others = (await uow.Repository<PurchaseDocument, long>().ListAsync(
Query.For<PurchaseDocument>().Where(d => d.PartyId == party && d.Kind == kind && d.ExternalReference == number && d.Id != id && d.Status != DocumentStatus.Cancelled),
cancellationToken).ConfigureAwait(false)).Items;
if (others.Any(d => (d.ExternalDate ?? d.DocumentDate).Year == year))
{
errors.Add(nameof(DocumentHeader.ExternalReference) + ":" + DocumentErrors.SupplierDuplicate);
}
}
private static string Company(Actor actor, string companyCode)
{
ArgumentNullException.ThrowIfNull(actor);
var company = CompanyCodes.Normalize(companyCode);
if (!actor.IsInstanceAccount && !string.Equals(actor.CompanyCode, company, StringComparison.Ordinal))
{
throw new AccessDeniedException(SecurityErrors.PermissionDenied, "A company user works only in its own company.");
}
return company;
}
private DateOnly Today() => DateOnly.FromDateTime(_clock.GetLocalNow().DateTime);
[LoggerMessage(EventId = 4101, Level = LogLevel.Information, Message = "{Kind} {Number} confirmed ({Status}) in {Company} by {User}")]
private static partial void LogConfirmed(ILogger logger, DocumentKind kind, string number, DocumentStatus status, string company, string user);
[LoggerMessage(EventId = 4102, Level = LogLevel.Information, Message = "{Kind} {Number}: {Action}, now {Status}, in {Company} by {User}")]
private static partial void LogChanged(ILogger logger, DocumentKind kind, string number, DocumentAction action, DocumentStatus status, string company, string user);
[LoggerMessage(EventId = 4103, Level = LogLevel.Information, Message = "Draft {Kind} {Id} deleted in {Company} by {User}")]
private static partial void LogDeleted(ILogger logger, DocumentKind kind, long id, string company, string user);
}
@@ -0,0 +1,178 @@
using System.Text.RegularExpressions;
using Khaemhat.Application.Files;
using Khaemhat.Application.Localization;
using Khaemhat.Application.Security;
using Khaemhat.Core.Documents;
using Khaemhat.Core.Parties;
using Khaemhat.Data;
using Khaemhat.Infrastructure.Mail;
namespace Khaemhat.Application.Documents;
/// <summary>
/// Fills a mail template (SPEC §12.6): <c>{{Name}}</c> becomes the value of the field, unknown fields stay as they are
/// so that a typing error shows in the message instead of disappearing.
/// </summary>
public static partial class MailTemplateRenderer
{
/// <summary>Fills a template.</summary>
/// <param name="template">The template.</param>
/// <param name="fields">The values by name (case does not matter).</param>
/// <returns>The text.</returns>
public static string Render(string template, IReadOnlyDictionary<string, string?> fields)
{
ArgumentNullException.ThrowIfNull(template);
ArgumentNullException.ThrowIfNull(fields);
var lookup = new Dictionary<string, string?>(fields, StringComparer.OrdinalIgnoreCase);
return Field().Replace(template, m => lookup.TryGetValue(m.Groups[1].Value, out var value) ? value ?? string.Empty : m.Value);
}
[GeneratedRegex(@"\{\{\s*([A-Za-z][A-Za-z0-9]*)\s*\}\}", RegexOptions.CultureInvariant, 1000)]
private static partial Regex Field();
}
/// <summary>A message about a document, as the user is about to send it.</summary>
/// <param name="To">The recipients, separated by commas or semicolons.</param>
/// <param name="Subject">The subject.</param>
/// <param name="Body">The text.</param>
public sealed record DocumentMailDraft(string To, string Subject, string Body);
/// <summary>The errors of <see cref="DocumentMailService"/> (text keys).</summary>
public static class DocumentMailErrors
{
/// <summary>No SMTP server is configured.</summary>
public const string NotConfigured = "document.mail.not-configured";
/// <summary>No recipient, or one that is not an e-mail address.</summary>
public const string RecipientInvalid = "document.mail.recipient-invalid";
/// <summary>The subject is empty.</summary>
public const string SubjectRequired = "document.mail.subject-required";
/// <summary>The queue is full.</summary>
public const string QueueFull = "document.mail.queue-full";
}
/// <summary>
/// Sends a document by e-mail (SPEC §9.4, §12.6, issue #52): proposes recipient, subject and text from the templates
/// (<c>Print.Mail.*</c>) and the e-mail of the party; on sending keeps the PDF as a new version among the attachments,
/// attaches it, queues the message and marks the document as sent. The outcome is in the log, section E-mail/PEC.
/// </summary>
/// <param name="prints">The printed form of documents.</param>
/// <param name="engine">The document engine.</param>
/// <param name="generation">The generated files (the PDF).</param>
/// <param name="attachments">The attachments.</param>
/// <param name="queue">The mail queue.</param>
/// <param name="factory">The units of work.</param>
/// <param name="texts">The texts.</param>
public sealed partial class DocumentMailService(
DocumentPrintService prints, DocumentEngine engine, FileGenerationService generation, AttachmentService attachments, IMailQueue queue, IUnitOfWorkFactory factory,
ITexts texts)
{
/// <summary>Whether mail can be sent from this instance.</summary>
public bool IsConfigured => queue.IsConfigured;
/// <summary>The message proposed for a document.</summary>
/// <param name="actor">Who sends.</param>
/// <param name="companyCode">The company.</param>
/// <param name="family">The family.</param>
/// <param name="id">The document.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The draft.</returns>
public async Task<DocumentMailDraft> DraftAsync(Actor actor, string companyCode, DocumentFamily family, long id, CancellationToken cancellationToken = default)
{
var model = await prints.BuildAsync(actor, companyCode, family, id, null, cancellationToken).ConfigureAwait(false);
var record = await engine.GetAsync(actor, companyCode, family, id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(DocumentErrors.NotFound);
string? email = null;
if (record.Header.PartyId is { } partyId)
{
await using var uow = await factory.CreateAsync(DatabaseScope.Company(CompanyCodes.Normalize(companyCode)), cancellationToken).ConfigureAwait(false);
email = (await uow.Repository<Party, long>().GetAsync(partyId, cancellationToken).ConfigureAwait(false))?.Email;
}
var fields = new Dictionary<string, string?>
{
["Documento"] = model.Title,
["Numero"] = model.Number,
["Data"] = model.Date,
["Cliente"] = model.Party.Name,
["Azienda"] = model.Company.Name,
["Totale"] = model.Totals.LastOrDefault(t => t.Strong)?.Value,
};
return new DocumentMailDraft(
email ?? string.Empty,
MailTemplateRenderer.Render(texts["Print.Mail.Subject"], fields),
MailTemplateRenderer.Render(texts["Print.Mail.Body"], fields));
}
/// <summary>Sends a document: the PDF becomes a new attachment version and leaves with the message.</summary>
/// <param name="actor">Who sends.</param>
/// <param name="companyCode">The company.</param>
/// <param name="family">The family.</param>
/// <param name="id">The document.</param>
/// <param name="draft">The message.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The PDF attached.</returns>
/// <exception cref="ValidationFailedException">The message is not complete, or mail is not configured.</exception>
public async Task<AttachmentView> SendAsync(
Actor actor, string companyCode, DocumentFamily family, long id, DocumentMailDraft draft, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(draft);
var recipients = Recipients(draft.To);
var errors = new List<string>();
if (!queue.IsConfigured)
{
errors.Add(":" + DocumentMailErrors.NotConfigured);
}
if (recipients.Count == 0 || !recipients.All(r => Address().IsMatch(r)))
{
errors.Add(nameof(DocumentMailDraft.To) + ":" + DocumentMailErrors.RecipientInvalid);
}
if (string.IsNullOrWhiteSpace(draft.Subject))
{
errors.Add(nameof(DocumentMailDraft.Subject) + ":" + DocumentMailErrors.SubjectRequired);
}
if (errors.Count > 0)
{
throw new ValidationFailedException(errors);
}
var model = await prints.BuildAsync(actor, companyCode, family, id, null, cancellationToken).ConfigureAwait(false);
var pdf = await generation.GenerateAsync(actor, companyCode, DocumentPrintService.EntityOf(family), id, DocumentPdfGenerator.GeneratorCode, cancellationToken)
.ConfigureAwait(false);
byte[] bytes;
await using (var content = await attachments.OpenAsync(actor, companyCode, pdf.Id, cancellationToken).ConfigureAwait(false))
{
using var buffer = new MemoryStream();
await content.Content.CopyToAsync(buffer, cancellationToken).ConfigureAwait(false);
bytes = buffer.ToArray();
}
var mail = new OutgoingMail(recipients, draft.Subject.Trim(), draft.Body)
{
Attachments = [new MailAttachment(pdf.FileName, pdf.Mime, bytes)],
Reference = model.Title + " " + model.Number,
};
if (!queue.Enqueue(mail))
{
throw new ValidationFailedException([":" + DocumentMailErrors.QueueFull]);
}
await engine.MarkSentAsync(actor, companyCode, family, id, cancellationToken).ConfigureAwait(false);
return pdf;
}
/// <summary>The addresses of a recipient field (commas, semicolons or spaces between them).</summary>
/// <param name="text">The field.</param>
/// <returns>The addresses.</returns>
public static IReadOnlyList<string> Recipients(string? text) =>
string.IsNullOrWhiteSpace(text) ? [] : text.Split([',', ';', ' ', '\n'], StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
[GeneratedRegex(@"^[^@\s<>]+@[^@\s<>]+\.[^@\s<>]+$", RegexOptions.CultureInvariant, 1000)]
private static partial Regex Address();
}
@@ -0,0 +1,172 @@
using System.Globalization;
using Khaemhat.Application.Security;
using Khaemhat.Application.Tables;
using Khaemhat.Core.Tables;
using Khaemhat.Data;
using Khaemhat.Data.Querying;
namespace Khaemhat.Application.Documents;
/// <summary>A number given to a document.</summary>
/// <param name="Numerator">The numerator row (code and year) that gave it, already updated.</param>
/// <param name="Number">The progressive number.</param>
/// <param name="Text">The number as printed.</param>
public sealed record AssignedNumber(DocumentNumerator Numerator, long Number, string Text);
/// <summary>
/// Numbers documents (SPEC §11.3, ADR 0032): inside the transaction that confirms the document, under the lock of the
/// numerator and year, so that two confirmations never get the same number and a rollback gives the number back.
/// </summary>
public static class DocumentNumberingService
{
/// <summary>Error: on a numerator without gaps the date precedes the last document numbered.</summary>
public const string DateBeforeLast = "document.number.date-before-last";
/// <summary>Error: the numerator of the document type does not exist.</summary>
public const string NumeratorMissing = "document.number.numerator-missing";
/// <summary>Error: the numerator is disabled.</summary>
public const string NumeratorDisabled = "document.number.numerator-disabled";
/// <summary>Error: the formatted number is longer than the column.</summary>
public const string NumberTooLong = "document.number.too-long";
/// <summary>The longest number as printed.</summary>
public const int MaxLength = 30;
/// <summary>The lock that serializes the numbering of a numerator in a year.</summary>
/// <param name="code">The numerator code.</param>
/// <param name="year">The year.</param>
/// <returns>The lock key.</returns>
public static string LockKey(string code, int year) => "numerator:" + code + ":" + year.ToString(CultureInfo.InvariantCulture);
/// <summary>
/// Gives the next number of a numerator for a date. The numerator row of the document type names the code; the
/// number comes from the row of the same code for the year of the date, created from the latest one when missing.
/// </summary>
/// <param name="uow">A company unit of work inside a transaction.</param>
/// <param name="numeratorId">The numerator of the document type.</param>
/// <param name="date">The date of the document.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The number.</returns>
/// <exception cref="ValidationFailedException">The numerator is missing or disabled, or the date is out of sequence.</exception>
public static async Task<AssignedNumber> NextAsync(IUnitOfWork uow, long numeratorId, DateOnly date, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(uow);
var numerators = uow.Repository<DocumentNumerator, long>();
var template = await numerators.GetAsync(numeratorId, cancellationToken).ConfigureAwait(false)
?? throw new ValidationFailedException([NumeratorMissing]);
await uow.AcquireLockAsync(LockKey(template.Code, date.Year), cancellationToken).ConfigureAwait(false);
// Read again under the lock: another transaction may have numbered (or created the year) meanwhile.
var numerator = await ForYearAsync(uow, template, date.Year, cancellationToken).ConfigureAwait(false);
if (numerator.Disabled)
{
throw new ValidationFailedException([NumeratorDisabled]);
}
if (!numerator.GapsAllowed && numerator.LastDate is { } last && date < last)
{
throw new ValidationFailedException([DateBeforeLast]);
}
var number = numerator.LastNumber + 1;
var text = DocumentNumberFormat.Apply(numerator.Format, number, numerator.Year, numerator.Prefix, numerator.Section);
if (text.Length > MaxLength)
{
throw new ValidationFailedException([NumberTooLong]);
}
numerator.LastNumber = number;
if (numerator.LastDate is null || date > numerator.LastDate)
{
numerator.LastDate = date;
}
await numerators.UpdateAsync(numerator, cancellationToken).ConfigureAwait(false);
return new AssignedNumber(numerator, number, text);
}
/// <summary>What the next number would be, without giving it (the preview of a draft).</summary>
/// <param name="uow">A company unit of work.</param>
/// <param name="numeratorId">The numerator of the document type.</param>
/// <param name="date">The date.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The number as printed, or <see langword="null"/> when the numerator is missing.</returns>
public static async Task<string?> PreviewAsync(IUnitOfWork uow, long numeratorId, DateOnly date, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(uow);
var numerators = uow.Repository<DocumentNumerator, long>();
if (await numerators.GetAsync(numeratorId, cancellationToken).ConfigureAwait(false) is not { } template)
{
return null;
}
var row = template.Year == date.Year
? template
: await numerators.FindAsync(Query.For<DocumentNumerator>().Where(n => n.Code == template.Code && n.Year == date.Year), cancellationToken).ConfigureAwait(false);
var source = row ?? template;
return DocumentNumberFormat.Apply(source.Format, (row?.LastNumber ?? 0) + 1, date.Year, source.Prefix, source.Section);
}
/// <summary>
/// The numbers missing between 1 and the last number given, over every family of documents: on a numerator without
/// gaps the list must be empty.
/// </summary>
/// <param name="uow">A company unit of work.</param>
/// <param name="numeratorId">The numerator row (code and year).</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The missing numbers, in order.</returns>
public static async Task<IReadOnlyList<long>> FindGapsAsync(IUnitOfWork uow, long numeratorId, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(uow);
var numerator = await uow.Repository<DocumentNumerator, long>().GetAsync(numeratorId, cancellationToken).ConfigureAwait(false)
?? throw new ValidationFailedException([NumeratorMissing]);
var used = new HashSet<long>();
foreach (var store in DocumentStores.All)
{
var sql = SqlFragment.Literal("SELECT number FROM " + store.HeaderTable + " WHERE ") + SqlFragment.Of($"numerator_id = {numeratorId} AND number IS NOT NULL");
used.UnionWith(await uow.QueryAsync<long>(sql, cancellationToken).ConfigureAwait(false));
}
var missing = new List<long>();
for (var n = 1L; n <= numerator.LastNumber; n++)
{
if (!used.Contains(n))
{
missing.Add(n);
}
}
return missing;
}
private static async Task<DocumentNumerator> ForYearAsync(IUnitOfWork uow, DocumentNumerator template, int year, CancellationToken cancellationToken)
{
var numerators = uow.Repository<DocumentNumerator, long>();
var code = template.Code;
if (await numerators.FindAsync(Query.For<DocumentNumerator>().Where(n => n.Code == code && n.Year == year), cancellationToken).ConfigureAwait(false) is { } row)
{
return row;
}
// A new year: the same rules as the latest year of the code, starting from one.
var found = (await numerators.ListAsync(Query.For<DocumentNumerator>().Where(n => n.Code == code).OrderByDescending(n => n.Year).Take(1), cancellationToken)
.ConfigureAwait(false)).Items;
var latest = found.Count > 0 ? found[0] : template;
var created = new DocumentNumerator
{
Code = latest.Code,
Description = latest.Description,
Kind = latest.Kind,
Section = latest.Section,
Year = year,
Prefix = latest.Prefix,
Format = latest.Format,
GapsAllowed = latest.GapsAllowed,
Disabled = latest.Disabled,
};
await numerators.InsertAsync(created, cancellationToken).ConfigureAwait(false);
return created;
}
}
@@ -0,0 +1,440 @@
using Khaemhat.Application.Files;
using Khaemhat.Application.Security;
using Khaemhat.Infrastructure.Files;
namespace Khaemhat.Application.Documents;
/// <summary>
/// The PDF of a document (SPEC §9.4, issue #52): A4, letterhead with logo and company data, address box, conditions,
/// lines over as many pages as needed (the headings repeat), VAT summary, totals, installments, transport and signature
/// boxes, notes and footer. Saved as a generated attachment of the document, so every print is a new version and
/// <i>Rigenera</i> writes the current state after a change.
/// </summary>
/// <param name="prints">The printed form of documents.</param>
/// <param name="attachments">The attachments (the logo of the company).</param>
public sealed class DocumentPdfGenerator(DocumentPrintService prints, AttachmentService attachments) : IFileGenerator
{
/// <summary>The code of the generator.</summary>
public const string GeneratorCode = "documents.pdf";
private const double Margin = 42;
private const double Bottom = 60;
private static readonly PdfColor Accent = PdfColor.FromHex("#1F5F8B");
private static readonly PdfColor Muted = PdfColor.Gray(105);
private static readonly PdfColor Rule = PdfColor.Gray(205);
private static readonly PdfColor Band = PdfColor.Gray(238);
private static readonly PdfColor Warning = PdfColor.FromHex("#B54708");
/// <inheritdoc />
public string Code => GeneratorCode;
/// <inheritdoc />
public string TitleKey => "files.generators.document_pdf";
/// <inheritdoc />
public string MediaType => PdfWriter.MediaType;
/// <inheritdoc />
public string Extension => ".pdf";
/// <inheritdoc />
public bool Supports(string entity) => DocumentPrintService.FamilyOf(entity) is not null;
/// <inheritdoc />
public string FileName(FileGenerationContext context)
{
ArgumentNullException.ThrowIfNull(context);
return Stem(context) + Extension;
}
/// <inheritdoc />
public async Task GenerateAsync(FileGenerationContext context, Stream output, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(context);
var model = await ModelAsync(context, cancellationToken).ConfigureAwait(false);
await WriteAsync(model, context, output, cancellationToken).ConfigureAwait(false);
}
// The file name follows the document (number and kind); without the logo, which the name does not need.
private string Stem(FileGenerationContext context)
{
try
{
return prints.BuildAsync(context.Actor, context.CompanyCode, FamilyOf(context), context.EntityId).GetAwaiter().GetResult().FileStem;
}
catch (KeyNotFoundException)
{
return "documento-" + context.EntityId.ToString(System.Globalization.CultureInfo.InvariantCulture);
}
}
private static Core.Documents.DocumentFamily FamilyOf(FileGenerationContext context) =>
DocumentPrintService.FamilyOf(context.Entity) ?? throw new ValidationFailedException([FileGenerationService.UnknownGeneratorError]);
private Task<DocumentPrintModel> ModelAsync(FileGenerationContext context, CancellationToken cancellationToken) =>
prints.BuildAsync(context.Actor, context.CompanyCode, FamilyOf(context), context.EntityId, (id, ct) => LogoAsync(context, id, ct), cancellationToken);
// The logo, when it is a JPEG the actor may read; the PDF writer embeds JPEG only.
private async Task<byte[]?> LogoAsync(FileGenerationContext context, long id, CancellationToken cancellationToken)
{
try
{
await using var content = await attachments.OpenAsync(context.Actor, context.CompanyCode, id, cancellationToken).ConfigureAwait(false);
if (content.Attachment.Mime != "image/jpeg")
{
return null;
}
using var buffer = new MemoryStream();
await content.Content.CopyToAsync(buffer, cancellationToken).ConfigureAwait(false);
return buffer.ToArray();
}
catch (Exception ex) when (ex is KeyNotFoundException or AccessDeniedException)
{
return null;
}
}
private static async Task WriteAsync(DocumentPrintModel model, FileGenerationContext context, Stream output, CancellationToken cancellationToken)
{
var info = new PdfDocumentInfo
{
Title = model.Title + " " + model.Number,
Author = model.Company.Name,
Subject = model.Title + " " + model.Number + " · " + model.Party.Name,
CreationDate = new DateTimeOffset(DateTime.SpecifyKind(context.Now, DateTimeKind.Utc)),
};
await using var pdf = new PdfWriter(output, info, leaveOpen: true);
var sheet = new Sheet(pdf, model, cancellationToken);
await sheet.FirstPageAsync().ConfigureAwait(false);
await sheet.LinesAsync().ConfigureAwait(false);
await sheet.FooterBlocksAsync().ConfigureAwait(false);
sheet.Finish();
await pdf.CloseAsync(cancellationToken).ConfigureAwait(false);
}
// The pen on the pages: where it is, and how to go on to the next page.
private sealed class Sheet(PdfWriter pdf, DocumentPrintModel model, CancellationToken cancellationToken)
{
// Code, description, unit, quantity, price, discounts, VAT, amount: the left edge of each column and the right end.
private double[] _edges = [];
private PdfPage _page = null!;
private int _pages;
private double _y;
private double Right => _page.Width - Margin;
public async Task FirstPageAsync()
{
await NewPageAsync(first: true).ConfigureAwait(false);
}
public async Task LinesAsync()
{
Headings();
foreach (var line in model.Lines)
{
var width = _edges[2] - _edges[1] - 8;
var wrapped = PdfTextLayout.Wrap(line.Description, line.IsDescription ? PdfFont.HelveticaOblique : PdfFont.Helvetica, 8.5, line.IsDescription ? Right - _edges[1] - 8 : width);
var height = Math.Max(1, wrapped.Count) * 11 + 5;
if (_y - height < Bottom + 20)
{
await NewPageAsync(first: false).ConfigureAwait(false);
Headings();
}
var y = _y;
if (!line.IsDescription)
{
_page.DrawText(line.Code, _edges[0] + 3, y, PdfFont.Courier, 8);
_page.DrawText(line.Unit, _edges[2] + 3, y, PdfFont.Helvetica, 8.5);
_page.DrawTextRight(line.Quantity, _edges[4] - 3, y, PdfFont.Helvetica, 8.5);
_page.DrawTextRight(line.Price, _edges[5] - 3, y, PdfFont.Helvetica, 8.5);
_page.DrawTextRight(line.Discount, _edges[6] - 3, y, PdfFont.Helvetica, 8.5);
_page.DrawTextRight(line.Tax, _edges[7] - 3, y, PdfFont.Helvetica, 8.5);
_page.DrawTextRight(line.Amount, _edges[8] - 3, y, PdfFont.Helvetica, 8.5);
}
foreach (var text in wrapped)
{
_page.DrawText(text, _edges[1] + 3, y, line.IsDescription ? PdfFont.HelveticaOblique : PdfFont.Helvetica, 8.5, line.IsDescription ? Muted : null);
y -= 11;
}
_y -= height;
_page.DrawLine(Margin, _y + 8, Right, _y + 8, 0.25, Rule);
}
_y -= 6;
}
public async Task FooterBlocksAsync()
{
foreach (var note in model.Notes)
{
var wrapped = PdfTextLayout.Wrap(note, PdfFont.Helvetica, 8.5, Right - Margin);
await RoomAsync(wrapped.Count * 11 + 4).ConfigureAwait(false);
foreach (var text in wrapped)
{
_page.DrawText(text, Margin, _y, PdfFont.Helvetica, 8.5);
_y -= 11;
}
_y -= 4;
}
// VAT summary on the left, totals on the right, side by side.
var middle = Margin + (Right - Margin) * 0.58;
var summaryHeight = model.Summary is { } s ? 20 + s.Rows.Count * 13 : 0;
var totalsHeight = model.Totals.Count * 14 + 8;
await RoomAsync(Math.Max(summaryHeight, totalsHeight) + 10).ConfigureAwait(false);
var top = _y - 4;
var afterSummary = model.Summary is { } summary ? Table(summary, Margin, middle - 14, top) : top;
var y = top;
_page.DrawRectangle(middle, y - totalsHeight + 10, Right - middle, totalsHeight, fill: Band, stroke: Band);
foreach (var row in model.Totals)
{
var font = row.Strong ? PdfFont.HelveticaBold : PdfFont.Helvetica;
var size = row.Strong ? 11 : 8.5;
if (row.Strong)
{
y -= 3;
}
_page.DrawText(row.Label, middle + 8, y, font, size, row.Strong ? Accent : null);
_page.DrawTextRight(row.Value, Right - 8, y, font, size, row.Strong ? Accent : null);
y -= 14;
}
_y = Math.Min(afterSummary, y) - 12;
if (model.Installments is { } installments)
{
await RoomAsync(22 + installments.Rows.Count * 13).ConfigureAwait(false);
_y = Table(installments, Margin, middle - 14, _y) - 12;
}
if (model.Transport.Count > 0)
{
await RoomAsync(110).ConfigureAwait(false);
_y = Fields(model.Transport, 4) - 10;
var width = (Right - Margin - 24) / Math.Max(1, model.Signatures.Count);
for (var i = 0; i < model.Signatures.Count; i++)
{
var x = Margin + i * (width + 12);
_page.DrawText(model.Signatures[i], x, _y, PdfFont.Helvetica, 7.5, Muted);
_page.DrawLine(x, _y - 28, x + width, _y - 28, 0.5, Rule);
}
_y -= 40;
}
}
public void Finish() => Foot();
private async Task RoomAsync(double height)
{
if (_y - height < Bottom)
{
await NewPageAsync(first: false).ConfigureAwait(false);
}
}
private async Task NewPageAsync(bool first)
{
if (_page is not null)
{
Foot();
}
_page = await pdf.AddPageAsync(cancellationToken: cancellationToken).ConfigureAwait(false);
_pages++;
var right = _page.Width - Margin;
double[] widths = [62, 0, 30, 50, 62, 44, 30, 66];
var description = right - Margin - widths.Sum();
_edges = new double[9];
_edges[0] = Margin;
for (var i = 0; i < widths.Length; i++)
{
_edges[i + 1] = _edges[i] + (i == 1 ? description : widths[i]);
}
_y = _page.Height - Margin;
if (!first)
{
_page.DrawText(model.Company.Name, Margin, _y - 8, PdfFont.HelveticaBold, 9);
_page.DrawTextRight(model.Title + " " + model.Number + " · " + model.Date, right, _y - 8, PdfFont.Helvetica, 9, Muted);
_y -= 18;
_page.DrawLine(Margin, _y, right, _y, 0.75, Accent);
_y -= 16;
return;
}
Letterhead(right);
}
private void Letterhead(double right)
{
var top = _y;
var x = Margin;
if (model.Logo is { } logo)
{
try
{
var info = JpegInfo.Read(logo);
var image = pdf.AddJpeg(logo);
const double height = 44;
var width = Math.Min(130, height * info.Width / Math.Max(1, info.Height));
_page.DrawImage(image, Margin, top - height, width, height);
x = Margin + width + 12;
}
catch (InvalidDataException)
{
// Not a JPEG the writer can embed: the name alone.
}
}
var y = top - 12;
_page.DrawText(model.Company.Name, x, y, PdfFont.HelveticaBold, 13, Accent);
y -= 13;
foreach (var line in model.Company.Lines)
{
_page.DrawText(PdfTextLayout.Fit(line, PdfFont.Helvetica, 7.5, right - x - 190), x, y, PdfFont.Helvetica, 7.5, Muted);
y -= 9.5;
}
// Kind, number and date on the right; a mark for drafts, cancelled and demo documents.
_page.DrawTextRight(model.Title.ToUpperInvariant(), right, top - 10, PdfFont.HelveticaBold, 9, Accent);
_page.DrawTextRight(model.Number, right, top - 28, PdfFont.HelveticaBold, 16);
_page.DrawTextRight(model.Date, right, top - 42, PdfFont.Helvetica, 9, Muted);
if (model.Watermark is { } mark)
{
_page.DrawTextRight(mark.ToUpperInvariant(), right, top - 56, PdfFont.HelveticaBold, 9, Warning);
}
_y = Math.Min(y, top - 62) - 8;
_page.DrawLine(Margin, _y, right, _y, 1, Accent);
_y -= 14;
// The address box on the right half, the conditions on the left.
var boxLeft = Margin + (right - Margin) * 0.52;
var boxTop = _y + 6;
var lines = 2 + model.Party.Lines.Count;
var boxHeight = lines * 11 + 14;
_page.DrawRectangle(boxLeft, boxTop - boxHeight, right - boxLeft, boxHeight, stroke: Rule);
var by = boxTop - 13;
_page.DrawText(model.PartyLabel, boxLeft + 8, by, PdfFont.Helvetica, 7.5, Muted);
if (model.Party.Code is { } code)
{
_page.DrawTextRight(code, right - 8, by, PdfFont.Courier, 7.5, Muted);
}
by -= 13;
_page.DrawText(PdfTextLayout.Fit(model.Party.Name, PdfFont.HelveticaBold, 10, right - boxLeft - 16), boxLeft + 8, by, PdfFont.HelveticaBold, 10);
foreach (var line in model.Party.Lines)
{
by -= 11;
_page.DrawText(PdfTextLayout.Fit(line, PdfFont.Helvetica, 8.5, right - boxLeft - 16), boxLeft + 8, by, PdfFont.Helvetica, 8.5);
}
var fy = _y - 6;
foreach (var field in model.Fields)
{
_page.DrawText(field.Label, Margin, fy, PdfFont.Helvetica, 7.5, Muted);
_page.DrawText(PdfTextLayout.Fit(field.Value, PdfFont.Helvetica, 8.5, boxLeft - Margin - 100), Margin + 92, fy, PdfFont.Helvetica, 8.5);
fy -= 12;
}
_y = Math.Min(boxTop - boxHeight, fy) - 14;
}
private void Headings()
{
_page.DrawRectangle(Margin, _y - 5, Right - Margin, 16, fill: Band, stroke: Band);
for (var i = 0; i < model.LineHeaders.Count; i++)
{
if (i is 0 or 1 or 2)
{
_page.DrawText(model.LineHeaders[i], _edges[i] + 3, _y, PdfFont.HelveticaBold, 7.5);
}
else
{
_page.DrawTextRight(model.LineHeaders[i], _edges[i + 1] - 3, _y, PdfFont.HelveticaBold, 7.5);
}
}
_y -= 17;
}
// A small table; returns the y under it.
private double Table(PrintTable table, double left, double right, double y)
{
_page.DrawText(table.Title, left, y, PdfFont.HelveticaBold, 8.5, Accent);
y -= 13;
var width = (right - left) / table.Headers.Count;
for (var i = 0; i < table.Headers.Count; i++)
{
Cell(table.Headers[i], left + i * width, width, y, table.Numeric[i], PdfFont.HelveticaBold, 7.5);
}
_page.DrawLine(left, y - 4, right, y - 4, 0.5, Rule);
y -= 13;
foreach (var row in table.Rows)
{
for (var i = 0; i < row.Count; i++)
{
Cell(row[i], left + i * width, width, y, table.Numeric[i], PdfFont.Helvetica, 8);
}
y -= 13;
}
return y;
}
private void Cell(string text, double x, double width, double y, bool numeric, PdfFont font, double size)
{
var fitted = PdfTextLayout.Fit(text, font, size, width - 6);
if (numeric)
{
_page.DrawTextRight(fitted, x + width - 3, y, font, size);
}
else
{
_page.DrawText(fitted, x + 3, y, font, size);
}
}
// Label and value pairs in columns; returns the y under them.
private double Fields(IReadOnlyList<PrintField> fields, int columns)
{
var width = (Right - Margin) / columns;
var y = _y;
for (var i = 0; i < fields.Count; i++)
{
var x = Margin + (i % columns) * width;
_page.DrawText(fields[i].Label, x, y, PdfFont.Helvetica, 7.5, Muted);
_page.DrawText(PdfTextLayout.Fit(fields[i].Value, PdfFont.Helvetica, 8.5, width - 8), x, y - 11, PdfFont.Helvetica, 8.5);
if (i % columns == columns - 1 || i == fields.Count - 1)
{
y -= 26;
}
}
return y;
}
private void Foot()
{
var right = _page.Width - Margin;
_page.DrawLine(Margin, 46, right, 46, 0.5, Rule);
if (model.Footer is { } footer)
{
_page.DrawText(PdfTextLayout.Fit(footer, PdfFont.Helvetica, 7, right - Margin - 80), Margin, 34, PdfFont.Helvetica, 7, Muted);
}
_page.DrawTextRight(_pages.ToString(System.Globalization.CultureInfo.InvariantCulture), right, 34, PdfFont.Helvetica, 7, Muted);
}
}
}
@@ -0,0 +1,514 @@
using System.Globalization;
using Khaemhat.Application.Localization;
using Khaemhat.Application.Security;
using Khaemhat.Core.Documents;
using Khaemhat.Core.Items;
using Khaemhat.Core.Parties;
using Khaemhat.Core.Tables;
using Khaemhat.Data;
using Khaemhat.Data.Companies;
using Khaemhat.Data.Querying;
namespace Khaemhat.Application.Documents;
/// <summary>A block of name and lines: the company in the letterhead, the party in the address box.</summary>
/// <param name="Name">The name.</param>
/// <param name="Code">The code of the party, when there is one.</param>
/// <param name="Lines">Address, tax numbers, contacts.</param>
public sealed record PrintParty(string Name, string? Code, IReadOnlyList<string> Lines);
/// <summary>A label and its value.</summary>
/// <param name="Label">The label.</param>
/// <param name="Value">The value, formatted.</param>
public sealed record PrintField(string Label, string Value);
/// <summary>A row of the totals.</summary>
/// <param name="Label">The label.</param>
/// <param name="Value">The amount, formatted.</param>
/// <param name="Strong">Whether it is the amount to pay.</param>
public sealed record PrintRow(string Label, string Value, bool Strong);
/// <summary>A line of the document as printed; every value formatted, empty for a descriptive line.</summary>
/// <param name="Code">The item code.</param>
/// <param name="Description">The description.</param>
/// <param name="Unit">The unit of measure.</param>
/// <param name="Quantity">The quantity.</param>
/// <param name="Price">The unit price.</param>
/// <param name="Discount">The discounts, such as 10+5.</param>
/// <param name="Tax">The VAT code.</param>
/// <param name="Amount">The amount.</param>
/// <param name="IsDescription">Whether the line is only text.</param>
public sealed record PrintLine(
string? Code, string Description, string? Unit, string? Quantity, string? Price, string? Discount, string? Tax, string? Amount, bool IsDescription);
/// <summary>A small table (VAT summary, installments) with its headings and rows.</summary>
/// <param name="Title">The title.</param>
/// <param name="Headers">The headings.</param>
/// <param name="Numeric">Which columns hold numbers (aligned right).</param>
/// <param name="Rows">The rows, formatted.</param>
public sealed record PrintTable(string Title, IReadOnlyList<string> Headers, IReadOnlyList<bool> Numeric, IReadOnlyList<IReadOnlyList<string>> Rows);
/// <summary>
/// A document ready to print (SPEC §9.4, issue #52): every text already formatted and translated, so that the HTML
/// preview and the PDF show exactly the same thing.
/// </summary>
public sealed record DocumentPrintModel
{
/// <summary>The kind, such as Fattura immediata.</summary>
public required string Title { get; init; }
/// <summary>The number, or the draft label.</summary>
public required string Number { get; init; }
/// <summary>The date.</summary>
public required string Date { get; init; }
/// <summary>A mark across the sheet: draft, cancelled, demo; none for a valid document.</summary>
public string? Watermark { get; init; }
/// <summary>The company in the letterhead.</summary>
public required PrintParty Company { get; init; }
/// <summary>The logo of the company, a JPEG, when it has one.</summary>
public byte[]? Logo { get; init; }
/// <summary>The attachment of the logo, for the HTML preview.</summary>
public long? LogoAttachmentId { get; init; }
/// <summary>The heading of the address box (Spett.le, Fornitore).</summary>
public required string PartyLabel { get; init; }
/// <summary>The customer or supplier.</summary>
public required PrintParty Party { get; init; }
/// <summary>Payment, reference, validity, delivery, agent, CIG and CUP.</summary>
public required IReadOnlyList<PrintField> Fields { get; init; }
/// <summary>The headings of the lines.</summary>
public required IReadOnlyList<string> LineHeaders { get; init; }
/// <summary>The lines.</summary>
public required IReadOnlyList<PrintLine> Lines { get; init; }
/// <summary>The VAT summary; empty for documents without VAT.</summary>
public PrintTable? Summary { get; init; }
/// <summary>The installments; empty when the document has none.</summary>
public PrintTable? Installments { get; init; }
/// <summary>The totals, the amount to pay last.</summary>
public required IReadOnlyList<PrintRow> Totals { get; init; }
/// <summary>The transport data of a delivery note or accompanying invoice; empty otherwise.</summary>
public required IReadOnlyList<PrintField> Transport { get; init; }
/// <summary>The signature boxes of a delivery note.</summary>
public required IReadOnlyList<string> Signatures { get; init; }
/// <summary>Notes printed under the lines (document notes, legal notes such as split payment).</summary>
public required IReadOnlyList<string> Notes { get; init; }
/// <summary>The footer of the company.</summary>
public string? Footer { get; init; }
/// <summary>The name of the file without extension, such as fattura-immediata-6-2026.</summary>
public required string FileStem { get; init; }
}
/// <summary>
/// Builds the printed form of a document (SPEC §9.4, §11.3, issue #52; mockup 025): letterhead with logo and data of
/// the company, address box, conditions, lines, VAT summary, installments, totals, transport and notes. The texts come
/// from the resources (<c>Print.*</c>); the same model feeds the HTML preview and the PDF generator.
/// </summary>
/// <param name="engine">The document engine (reads the document with its permission).</param>
/// <param name="factory">The units of work.</param>
/// <param name="companies">The company registry (name of a company without profile).</param>
/// <param name="texts">The texts.</param>
public sealed class DocumentPrintService(DocumentEngine engine, IUnitOfWorkFactory factory, ICompanyRegistry companies, ITexts texts)
{
private static readonly Dictionary<DocumentFamily, string> Entities = new Dictionary<DocumentFamily, string>
{
[DocumentFamily.SaleQuotation] = "sales.salequotation",
[DocumentFamily.SaleOrder] = "sales.saleorder",
[DocumentFamily.SaleDocument] = "sales.saledocument",
[DocumentFamily.PurchaseOrder] = "purchases.purchaseorder",
[DocumentFamily.PurchaseDocument] = "purchases.purchasedocument",
[DocumentFamily.InventoryDocument] = "inventory.inventorydocument",
};
/// <summary>The entity of the attachments of a family, such as <c>sales.saledocument</c>.</summary>
/// <param name="family">The family.</param>
/// <returns>The entity.</returns>
public static string EntityOf(DocumentFamily family) => Entities[family];
/// <summary>The family of an attachment entity.</summary>
/// <param name="entity">The entity.</param>
/// <returns>The family, or none for another entity.</returns>
public static DocumentFamily? FamilyOf(string? entity) =>
Entities.Where(e => string.Equals(e.Value, entity, StringComparison.Ordinal)).Select(e => (DocumentFamily?)e.Key).FirstOrDefault();
/// <summary>The printed form of a document.</summary>
/// <param name="actor">Who prints: needs to read the document.</param>
/// <param name="companyCode">The company.</param>
/// <param name="family">The family.</param>
/// <param name="id">The document.</param>
/// <param name="logo">The logo, read by the caller with its own permission (a JPEG for the PDF).</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The model.</returns>
/// <exception cref="KeyNotFoundException">No such document.</exception>
public async Task<DocumentPrintModel> BuildAsync(
Actor actor, string companyCode, DocumentFamily family, long id, Func<long, CancellationToken, Task<byte[]?>>? logo = null, CancellationToken cancellationToken = default)
{
var record = await engine.GetAsync(actor, companyCode, family, id, cancellationToken).ConfigureAwait(false)
?? throw new KeyNotFoundException(DocumentErrors.NotFound);
var company = CompanyCodes.Normalize(companyCode);
await using var uow = await factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
var h = record.Header;
var definition = await DocumentDefinitionService.GetAsync(uow, h.DocumentTypeId, cancellationToken).ConfigureAwait(false);
var profile = await uow.Repository<CompanyProfile, long>().FindAsync(Query.For<CompanyProfile>(), cancellationToken).ConfigureAwait(false);
var registered = profile is null ? await companies.FindAsync(company, cancellationToken).ConfigureAwait(false) : null;
var party = h.PartyId is { } partyId ? await uow.Repository<Party, long>().GetAsync(partyId, cancellationToken).ConfigureAwait(false) : null;
var lookups = new Lookups(uow, cancellationToken);
var behavior = definition.Behavior;
var lines = new List<PrintLine>();
foreach (var line in record.Lines)
{
if (line.Kind == DocumentLineKind.Description)
{
lines.Add(new PrintLine(null, line.Description, null, null, null, null, null, null, true));
continue;
}
var code = line.ItemId is { } itemId ? (await lookups.GetAsync<Item>(itemId).ConfigureAwait(false))?.Code : null;
lines.Add(new PrintLine(
code,
line.Description,
await lookups.CodeAsync<UnitOfMeasure>(line.UnitOfMeasureId).ConfigureAwait(false),
texts.Number(line.Quantity, 2),
texts.Money(line.Price),
string.IsNullOrWhiteSpace(line.DiscountFormula) ? null : line.DiscountFormula,
await lookups.CodeAsync<TaxCode>(line.TaxCodeId).ConfigureAwait(false),
texts.Money(line.TaxableAmount),
false));
}
var fields = new List<PrintField>();
void Field(string key, string? value)
{
if (!string.IsNullOrWhiteSpace(value))
{
fields.Add(new PrintField(texts["Print.Fields." + key], value));
}
}
Field("Payment", await lookups.DescriptionAsync<PaymentTerm>(h.PaymentTermId).ConfigureAwait(false));
if (h.BankAccountId is { } bankId && await lookups.GetAsync<BankAccount>(bankId).ConfigureAwait(false) is { } bank)
{
Field("Bank", string.Join(" · ", new[] { bank.BankName ?? bank.Description, bank.Iban }.Where(s => !string.IsNullOrWhiteSpace(s))));
}
Field("Reference", h.ExternalReference is { } reference
? reference + (h.ExternalDate is { } externalDate ? " " + texts.Format("Print.Of", texts.Date(externalDate)) : null)
: null);
Field("ValidUntil", h.ValidUntil is { } validUntil ? texts.Date(validUntil) : null);
Field("Delivery", h.DeliveryDate is { } delivery ? texts.Date(delivery) : null);
Field("Salesperson", await lookups.DescriptionAsync<Salesperson>(h.SalespersonId).ConfigureAwait(false));
Field("Revision", h.Revision > 0 ? h.Revision.ToString(texts.Culture) : null);
Field("Cig", h.Cig);
Field("Cup", h.Cup);
Field("Related", h.RelatedNumber is { } related
? related + (h.RelatedDate is { } relatedDate ? " " + texts.Format("Print.Of", texts.Date(relatedDate)) : null)
: null);
var transport = new List<PrintField>();
var signatures = new List<string>();
if (behavior.Has(DocumentEffects.Inventory) && definition.Kind is DocumentKind.DeliveryNote or DocumentKind.AccompanyingInvoice or DocumentKind.PurchaseDeliveryNote)
{
void Transport(string key, string? value)
{
if (!string.IsNullOrWhiteSpace(value))
{
transport.Add(new PrintField(texts["Print.Transport." + key], value));
}
}
Transport("Reason", await lookups.DescriptionAsync<TransportReason>(h.TransportReasonId).ConfigureAwait(false));
Transport("By", h.TransportBy is { } by ? texts["Sales.TransportBy." + by] : null);
Transport("Carrier", await lookups.DescriptionAsync<Carrier>(h.CarrierId).ConfigureAwait(false));
Transport("Port", await lookups.DescriptionAsync<ShippingTerm>(h.ShippingTermId).ConfigureAwait(false));
Transport("Appearance", await lookups.DescriptionAsync<GoodsAppearance>(h.GoodsAppearanceId).ConfigureAwait(false));
Transport("Packages", h.Packages?.ToString(texts.Culture));
Transport("GrossWeight", h.GrossWeight is { } gross ? texts.Number(gross, 3) : null);
Transport("NetWeight", h.NetWeight is { } net ? texts.Number(net, 3) : null);
Transport("Start", h.TransportStart is { } start ? start.ToString("g", texts.Culture) : null);
signatures.AddRange([texts["Print.Transport.SignatureDriver"], texts["Print.Transport.SignatureCarrier"], texts["Print.Transport.SignatureRecipient"]]);
}
PrintTable? summary = null;
if (record.Figures.Summary.Count > 0)
{
var rows = new List<IReadOnlyList<string>>();
foreach (var row in record.Figures.Summary)
{
var tax = row.TaxCodeId is { } taxId ? await lookups.GetAsync<TaxCode>(taxId).ConfigureAwait(false) : null;
rows.Add([
tax is null ? row.Nature ?? string.Empty : tax.Code + " · " + tax.Description,
row.Rate.ToString("0.##", texts.Culture) + "%",
texts.Money(row.Taxable),
texts.Money(row.Tax),
]);
}
summary = new PrintTable(
texts["Print.Summary.Title"],
[texts["Print.Summary.Code"], texts["Print.Summary.Rate"], texts["Print.Summary.Taxable"], texts["Print.Summary.Tax"]],
[false, true, true, true],
rows);
}
PrintTable? installments = null;
if (record.Figures.Installments.Count > 0)
{
var rows = new List<IReadOnlyList<string>>();
foreach (var due in record.Figures.Installments)
{
rows.Add([
due.Number.ToString(texts.Culture),
texts.Date(due.DueDate),
await lookups.DescriptionAsync<PaymentMethod>(due.PaymentMethodId).ConfigureAwait(false) ?? string.Empty,
texts.Money(due.Amount),
]);
}
installments = new PrintTable(
texts["Print.Installments.Title"],
[texts["Print.Installments.Number"], texts["Print.Installments.Due"], texts["Print.Installments.Method"], texts["Print.Installments.Amount"]],
[true, false, false, true],
rows);
}
var notes = new List<string>();
if (!string.IsNullOrWhiteSpace(h.Notes))
{
notes.Add(h.Notes.Trim());
}
if (h.SplitPayment)
{
notes.Add(texts["Print.Notes.SplitPayment"]);
}
if (definition.Kind == DocumentKind.ProForma)
{
notes.Add(texts["Print.Notes.ProForma"]);
}
if (definition.Kind is DocumentKind.DeferredInvoice)
{
notes.Add(texts["Print.Notes.Deferred"]);
}
var title = definition.Type.Description;
var number = h.DocumentNumber ?? texts["Print.Draft"];
var stem = Slug(title + (h.DocumentNumber is { } n ? " " + n : " " + texts["Print.Draft"]));
return new DocumentPrintModel
{
Title = title,
Number = number,
Date = texts.Date(h.DocumentDate),
Watermark = h.Status switch
{
DocumentStatus.Draft => texts["Print.Watermarks.Draft"],
DocumentStatus.Cancelled => texts["Print.Watermarks.Cancelled"],
_ => h.IsDemo ? texts["Print.Watermarks.Demo"] : null,
},
Company = CompanyBlock(profile, registered?.Name ?? company),
Logo = profile?.LogoAttachmentId is { } logoId && logo is not null ? await logo(logoId, cancellationToken).ConfigureAwait(false) : null,
LogoAttachmentId = profile?.LogoAttachmentId,
PartyLabel = texts[behavior.Direction == DocumentDirection.Purchase ? "Print.Supplier" : "Print.Customer"],
Party = PartyBlock(party),
Fields = fields,
LineHeaders =
[
texts["Print.Lines.Code"], texts["Print.Lines.Description"], texts["Print.Lines.Unit"], texts["Print.Lines.Quantity"],
texts["Print.Lines.Price"], texts["Print.Lines.Discount"], texts["Print.Lines.Tax"], texts["Print.Lines.Amount"],
],
Lines = lines,
Summary = summary,
Installments = installments,
Totals = TotalsOf(record, definition),
Transport = transport,
Signatures = signatures,
Notes = notes,
Footer = profile?.FooterNotes,
FileStem = stem,
};
}
// A name for files: lower case letters and digits joined by dashes, such as fattura-immediata-6-2026.
private static string Slug(string text)
{
var builder = new System.Text.StringBuilder();
foreach (var c in text.Normalize(System.Text.NormalizationForm.FormD))
{
if (char.IsLetterOrDigit(c) && c < 128)
{
builder.Append(char.ToLowerInvariant(c));
}
else if (CharUnicodeInfo.GetUnicodeCategory(c) != UnicodeCategory.NonSpacingMark && builder.Length > 0 && builder[^1] != '-')
{
builder.Append('-');
}
}
return builder.ToString().Trim('-');
}
private PrintParty CompanyBlock(CompanyProfile? profile, string fallbackName)
{
if (profile is null)
{
return new PrintParty(fallbackName, null, []);
}
var lines = new List<string>();
Add(lines, Address(profile.Address, profile.StreetNumber, profile.PostalCode, profile.City, profile.ProvinceCode, profile.AddressCountry));
Add(lines, Join(
profile.VatNumber is { Length: > 0 } vat ? texts.Format("Print.VatNumber", vat) : null,
profile.TaxCode is { Length: > 0 } taxCode && taxCode != profile.VatNumber ? texts.Format("Print.TaxCode", taxCode) : null));
Add(lines, Join(
profile.ReaNumber is { Length: > 0 } rea ? texts.Format("Print.Rea", profile.ReaOffice ?? string.Empty, rea) : null,
profile.ShareCapital is { } capital ? texts.Format("Print.ShareCapital", texts.Money(capital)) : null));
Add(lines, Join(
profile.Phone is { Length: > 0 } phone ? texts.Format("Print.Phone", phone) : null,
profile.Email,
profile.Pec is { Length: > 0 } pec ? texts.Format("Print.Pec", pec) : null,
profile.Website));
return new PrintParty(profile.LegalName, null, lines);
}
private PrintParty PartyBlock(Party? party)
{
if (party is null)
{
return new PrintParty(texts["Print.NoParty"], null, []);
}
var lines = new List<string>();
Add(lines, Join(party.Address, party.StreetNumber));
Add(lines, Join(party.PostalCode, party.City, party.Province is { Length: > 0 } province ? "(" + province + ")" : null)
+ (party.CountryCode is { Length: > 0 } country && country != "IT" ? " · " + country : null));
Add(lines, Join(
party.VatNumber is { Length: > 0 } vat ? texts.Format("Print.VatNumber", vat) : null,
party.TaxCode is { Length: > 0 } taxCode && taxCode != party.VatNumber ? texts.Format("Print.TaxCode", taxCode) : null));
Add(lines, party.Pec is { Length: > 0 } pec ? texts.Format("Print.Pec", pec) : null);
return new PrintParty(party.Name, party.Code, lines);
}
private List<PrintRow> TotalsOf(DocumentRecord record, DocumentDefinition definition)
{
var h = record.Header;
var rows = new List<PrintRow>();
void Row(string key, decimal value, bool strong = false, string? suffix = null) =>
rows.Add(new PrintRow(texts["Print.Totals." + key] + suffix, texts.Money(value), strong));
var goods = record.Lines.Where(l => l.Kind is DocumentLineKind.Item or DocumentLineKind.Free or DocumentLineKind.Discount).Sum(l => l.TaxableAmount);
Row("Goods", goods);
if (h.FooterDiscountAmount != 0m)
{
Row("FooterDiscount", -h.FooterDiscountAmount, suffix: h.FooterDiscount is { } f ? " " + f + "%" : null);
}
if (h.ExpensesAmount != 0m)
{
Row("Expenses", h.ExpensesAmount);
}
if (h.SocialSecurityAmount != 0m)
{
Row("SocialSecurity", h.SocialSecurityAmount);
}
var ledger = definition.Behavior.Has(DocumentEffects.Ledger) || h.TaxAmount != 0m;
if (ledger)
{
Row("Taxable", h.TaxableAmount);
Row("Tax", h.TaxAmount);
}
if (h.StampDuty != 0m)
{
Row("StampDuty", h.StampDuty);
}
var showsNet = h.NetAmount != h.TotalAmount && h.NetAmount != 0m;
Row("Total", h.TotalAmount, strong: !showsNet);
if (h.WithholdingAmount != 0m)
{
Row("Withholding", -h.WithholdingAmount);
}
if (h.EnasarcoAmount != 0m)
{
Row("Enasarco", -h.EnasarcoAmount);
}
if (h.SplitPayment && h.TaxAmount != 0m)
{
Row("SplitPayment", -h.TaxAmount);
}
if (showsNet)
{
Row("Net", h.NetAmount, strong: true);
}
return rows;
}
private static string? Address(string? street, string? number, string? postalCode, string? city, string? province, string? country) =>
Join(Join(street, number), Join(postalCode, city, province is { Length: > 0 } p ? "(" + p + ")" : null), country is { Length: > 0 } c && c != "IT" ? c : null) is { } text
? text.Replace(" · ", " - ", StringComparison.Ordinal)
: null;
private static string? Join(params string?[] parts)
{
var present = parts.Where(p => !string.IsNullOrWhiteSpace(p)).ToList();
return present.Count == 0 ? null : string.Join(" · ", present);
}
private static void Add(List<string> lines, string? line)
{
if (!string.IsNullOrWhiteSpace(line))
{
lines.Add(line);
}
}
// The coded rows the printout names, read once each.
private sealed class Lookups(IUnitOfWork uow, CancellationToken cancellationToken)
{
private readonly Dictionary<(Type, long), object?> _cache = [];
public async Task<T?> GetAsync<T>(long id)
where T : Core.Entities.Entity<long>, new()
{
if (!_cache.TryGetValue((typeof(T), id), out var found))
{
found = await uow.Repository<T, long>().GetAsync(id, cancellationToken).ConfigureAwait(false);
_cache[(typeof(T), id)] = found;
}
return (T?)found;
}
public async Task<string?> CodeAsync<T>(long? id)
where T : CodedEntity, new() =>
id is { } value ? (await GetAsync<T>(value).ConfigureAwait(false))?.Code : null;
public async Task<string?> DescriptionAsync<T>(long? id)
where T : CodedEntity, new() =>
id is { } value ? (await GetAsync<T>(value).ConfigureAwait(false))?.Description : null;
}
}
@@ -0,0 +1,149 @@
using Khaemhat.Application.Security;
using Khaemhat.Core.Documents;
namespace Khaemhat.Application.Documents;
/// <summary>A document of one family, with its lines.</summary>
/// <typeparam name="THeader">The header.</typeparam>
/// <typeparam name="TLine">The line.</typeparam>
public sealed class DocumentRecord<THeader, TLine>
where THeader : DocumentHeader, new()
where TLine : DocumentLine, new()
{
/// <summary>The header.</summary>
public THeader Header { get; set; } = new();
/// <summary>The lines, in order.</summary>
public List<TLine> Lines { get; set; } = [];
}
/// <summary>
/// The document engine for one family (SPEC §11.3): create, read, save, confirm or issue, cancel, close, reopen,
/// delete and copy, with the types of that family. The screens of quotations, orders, invoices use one each.
/// </summary>
/// <typeparam name="THeader">The header.</typeparam>
/// <typeparam name="TLine">The line.</typeparam>
public sealed class DocumentService<THeader, TLine>
where THeader : DocumentHeader, new()
where TLine : DocumentLine, new()
{
private readonly DocumentEngine _engine;
private readonly DocumentCopyService _copies;
/// <summary>Creates the service.</summary>
/// <param name="engine">The engine.</param>
/// <param name="copies">The copies.</param>
public DocumentService(DocumentEngine engine, DocumentCopyService copies)
{
ArgumentNullException.ThrowIfNull(engine);
ArgumentNullException.ThrowIfNull(copies);
_engine = engine;
_copies = copies;
}
/// <summary>The family.</summary>
public DocumentFamily Family => FamilyOfHeader;
private static readonly DocumentFamily FamilyOfHeader = DocumentStores.FamilyOf<THeader>();
/// <summary>A new draft of a type of this family, not saved.</summary>
/// <param name="actor">Who creates.</param>
/// <param name="companyCode">The company.</param>
/// <param name="typeCode">The document type.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The draft.</returns>
public async Task<DocumentRecord<THeader, TLine>> NewAsync(Actor actor, string companyCode, string typeCode, CancellationToken cancellationToken = default)
{
var record = await _engine.NewAsync(actor, companyCode, typeCode, cancellationToken).ConfigureAwait(false);
if (record.Family != Family)
{
throw new ValidationFailedException([nameof(DocumentHeader.DocumentTypeId) + ":" + DocumentErrors.TypeFamily]);
}
return Typed(record);
}
/// <summary>Reads a document.</summary>
/// <param name="actor">Who reads.</param>
/// <param name="companyCode">The company.</param>
/// <param name="id">The document.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The document, if any.</returns>
public async Task<DocumentRecord<THeader, TLine>?> GetAsync(Actor actor, string companyCode, long id, CancellationToken cancellationToken = default) =>
await _engine.GetAsync(actor, companyCode, Family, id, cancellationToken).ConfigureAwait(false) is { } record ? Typed(record) : null;
/// <summary>Saves a draft, or an order still open.</summary>
/// <param name="actor">Who saves.</param>
/// <param name="companyCode">The company.</param>
/// <param name="record">The document.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The document as saved.</returns>
public async Task<DocumentRecord<THeader, TLine>> SaveAsync(Actor actor, string companyCode, DocumentRecord<THeader, TLine> record, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(record);
var saved = await _engine.SaveAsync(actor, companyCode, new DocumentRecord { Family = Family, Header = record.Header, Lines = [.. record.Lines] }, cancellationToken)
.ConfigureAwait(false);
return Typed(saved);
}
/// <summary>Confirms a document, or issues an invoice.</summary>
/// <param name="actor">Who confirms.</param>
/// <param name="companyCode">The company.</param>
/// <param name="id">The document.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The document.</returns>
public async Task<DocumentRecord<THeader, TLine>> ConfirmAsync(Actor actor, string companyCode, long id, CancellationToken cancellationToken = default) =>
Typed(await _engine.ConfirmAsync(actor, companyCode, Family, id, cancellationToken).ConfigureAwait(false));
/// <summary>Cancels a document.</summary>
/// <param name="actor">Who cancels.</param>
/// <param name="companyCode">The company.</param>
/// <param name="id">The document.</param>
/// <param name="reason">Why (required for invoices).</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The document.</returns>
public async Task<DocumentRecord<THeader, TLine>> CancelAsync(Actor actor, string companyCode, long id, string? reason, CancellationToken cancellationToken = default) =>
Typed(await _engine.CancelAsync(actor, companyCode, Family, id, reason, cancellationToken).ConfigureAwait(false));
/// <summary>Closes what is left to fulfil.</summary>
/// <param name="actor">Who closes.</param>
/// <param name="companyCode">The company.</param>
/// <param name="id">The document.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The document.</returns>
public async Task<DocumentRecord<THeader, TLine>> CloseAsync(Actor actor, string companyCode, long id, CancellationToken cancellationToken = default) =>
Typed(await _engine.CloseAsync(actor, companyCode, Family, id, cancellationToken).ConfigureAwait(false));
/// <summary>Reopens a closed document.</summary>
/// <param name="actor">Who reopens.</param>
/// <param name="companyCode">The company.</param>
/// <param name="id">The document.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The document.</returns>
public async Task<DocumentRecord<THeader, TLine>> ReopenAsync(Actor actor, string companyCode, long id, CancellationToken cancellationToken = default) =>
Typed(await _engine.ReopenAsync(actor, companyCode, Family, id, cancellationToken).ConfigureAwait(false));
/// <summary>Deletes a draft.</summary>
/// <param name="actor">Who deletes.</param>
/// <param name="companyCode">The company.</param>
/// <param name="id">The document.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
public Task DeleteAsync(Actor actor, string companyCode, long id, CancellationToken cancellationToken = default) =>
_engine.DeleteAsync(actor, companyCode, Family, id, cancellationToken);
/// <summary>Copies a document of this family into a new draft of any type of the same direction.</summary>
/// <param name="actor">Who copies.</param>
/// <param name="companyCode">The company.</param>
/// <param name="id">The source.</param>
/// <param name="targetTypeCode">The type of the new document.</param>
/// <param name="lineIds">The lines to copy; all when empty.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The new draft, in its own family.</returns>
public Task<DocumentRecord> CopyAsync(
Actor actor, string companyCode, long id, string targetTypeCode, IReadOnlyCollection<long>? lineIds = null, CancellationToken cancellationToken = default) =>
_copies.CopyAsync(actor, companyCode, Family, id, targetTypeCode, lineIds, cancellationToken);
private static DocumentRecord<THeader, TLine> Typed(DocumentRecord record) =>
new() { Header = (THeader)record.Header, Lines = [.. record.Lines.Cast<TLine>()] };
}
@@ -0,0 +1,291 @@
using Khaemhat.Application.Audit;
using Khaemhat.Application.Querying;
using Khaemhat.Core.Documents;
using Khaemhat.Data;
using Khaemhat.Data.Querying;
namespace Khaemhat.Application.Documents;
/// <summary>
/// Reads and writes the headers and lines of one family through the base classes, so that the engine can follow
/// fulfilment links and copies from one family to another (ADR 0032).
/// </summary>
internal interface IDocumentStore
{
/// <summary>The family.</summary>
DocumentFamily Family { get; }
/// <summary>The header table.</summary>
string HeaderTable { get; }
/// <summary>A new header of the family.</summary>
/// <returns>The header.</returns>
DocumentHeader NewHeader();
/// <summary>A new line of the family.</summary>
/// <returns>The line.</returns>
DocumentLine NewLine();
/// <summary>Reads a header.</summary>
/// <param name="uow">The unit of work.</param>
/// <param name="id">The document.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The header, if any.</returns>
Task<DocumentHeader?> GetAsync(IUnitOfWork uow, long id, CancellationToken cancellationToken);
/// <summary>Reads the lines of a document in their order.</summary>
/// <param name="uow">The unit of work.</param>
/// <param name="documentId">The document.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The lines.</returns>
Task<List<DocumentLine>> LinesAsync(IUnitOfWork uow, long documentId, CancellationToken cancellationToken);
/// <summary>Reads the headers of the documents in force (neither drafts nor cancelled).</summary>
/// <param name="uow">The unit of work.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The headers.</returns>
Task<IReadOnlyList<DocumentHeader>> InForceAsync(IUnitOfWork uow, CancellationToken cancellationToken);
/// <summary>Reads a line.</summary>
/// <param name="uow">The unit of work.</param>
/// <param name="id">The line.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The line, if any.</returns>
Task<DocumentLine?> GetLineAsync(IUnitOfWork uow, long id, CancellationToken cancellationToken);
/// <summary>Inserts a header.</summary>
/// <param name="uow">The unit of work.</param>
/// <param name="header">The header.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
Task InsertAsync(IUnitOfWork uow, DocumentHeader header, CancellationToken cancellationToken);
/// <summary>Updates a header.</summary>
/// <param name="uow">The unit of work.</param>
/// <param name="header">The header.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
Task UpdateAsync(IUnitOfWork uow, DocumentHeader header, CancellationToken cancellationToken);
/// <summary>Deletes a header and, by cascade, its lines.</summary>
/// <param name="uow">The unit of work.</param>
/// <param name="id">The document.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
Task DeleteAsync(IUnitOfWork uow, long id, CancellationToken cancellationToken);
/// <summary>Inserts a line.</summary>
/// <param name="uow">The unit of work.</param>
/// <param name="line">The line.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
Task InsertLineAsync(IUnitOfWork uow, DocumentLine line, CancellationToken cancellationToken);
/// <summary>Updates a line.</summary>
/// <param name="uow">The unit of work.</param>
/// <param name="line">The line.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
Task UpdateLineAsync(IUnitOfWork uow, DocumentLine line, CancellationToken cancellationToken);
/// <summary>Deletes a line.</summary>
/// <param name="uow">The unit of work.</param>
/// <param name="id">The line.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
Task DeleteLineAsync(IUnitOfWork uow, long id, CancellationToken cancellationToken);
/// <summary>Writes a change of a header in the history, under the name of its class.</summary>
/// <param name="audit">The history.</param>
/// <param name="uow">The unit of work.</param>
/// <param name="action">What happened.</param>
/// <param name="id">The document.</param>
/// <param name="before">The header before.</param>
/// <param name="after">The header after.</param>
/// <param name="userName">Who did it.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
Task RecordAsync(
AuditTrail audit, IUnitOfWork uow, AuditAction action, long id, DocumentHeader? before, DocumentHeader? after, string? userName,
CancellationToken cancellationToken);
/// <summary>A page of headers: the list request, plus the conditions the caller adds (kinds, search on parties).</summary>
Task<ListPage<DocumentHeader>> ListAsync(IUnitOfWork uow, ListQuery list, IReadOnlyList<SqlFragment> conditions, CancellationToken cancellationToken);
/// <summary>Headers by id.</summary>
Task<IReadOnlyList<DocumentHeader>> ManyAsync(IUnitOfWork uow, IReadOnlyCollection<long> ids, CancellationToken cancellationToken);
/// <summary>Lines by id.</summary>
Task<IReadOnlyList<DocumentLine>> LinesByIdAsync(IUnitOfWork uow, IReadOnlyCollection<long> ids, CancellationToken cancellationToken);
}
/// <summary>The store of one family.</summary>
/// <typeparam name="THeader">The header.</typeparam>
/// <typeparam name="TLine">The line.</typeparam>
internal sealed class DocumentStore<THeader, TLine>(DocumentFamily family, string headerTable) : IDocumentStore
where THeader : DocumentHeader, new()
where TLine : DocumentLine, new()
{
/// <inheritdoc />
public DocumentFamily Family => family;
/// <inheritdoc />
public string HeaderTable => headerTable;
/// <inheritdoc />
public DocumentHeader NewHeader() => new THeader();
/// <inheritdoc />
public DocumentLine NewLine() => new TLine();
/// <inheritdoc />
public async Task<DocumentHeader?> GetAsync(IUnitOfWork uow, long id, CancellationToken cancellationToken) =>
await uow.Repository<THeader, long>().GetAsync(id, cancellationToken).ConfigureAwait(false);
/// <inheritdoc />
public async Task<IReadOnlyList<DocumentHeader>> InForceAsync(IUnitOfWork uow, CancellationToken cancellationToken) =>
[.. (await uow.Repository<THeader, long>().ListAsync(
Query.For<THeader>().Where(h => h.Status != DocumentStatus.Draft && h.Status != DocumentStatus.Cancelled), cancellationToken).ConfigureAwait(false)).Items];
/// <inheritdoc />
public async Task<List<DocumentLine>> LinesAsync(IUnitOfWork uow, long documentId, CancellationToken cancellationToken)
{
// A SQL condition: the expression of a generic parameter may reach the base property through a conversion.
var rows = await uow.Repository<TLine, long>().ListAsync(Query.For<TLine>().Where(SqlFragment.Of($"document_id = {documentId}")), cancellationToken)
.ConfigureAwait(false);
return [.. rows.Items.OrderBy(l => l.SortOrder).ThenBy(l => l.LineNumber).ThenBy(l => l.Id).Cast<DocumentLine>()];
}
/// <inheritdoc />
public async Task<DocumentLine?> GetLineAsync(IUnitOfWork uow, long id, CancellationToken cancellationToken) =>
await uow.Repository<TLine, long>().GetAsync(id, cancellationToken).ConfigureAwait(false);
/// <inheritdoc />
public async Task InsertAsync(IUnitOfWork uow, DocumentHeader header, CancellationToken cancellationToken) =>
header.Id = await uow.Repository<THeader, long>().InsertAsync((THeader)header, cancellationToken).ConfigureAwait(false);
/// <inheritdoc />
public Task UpdateAsync(IUnitOfWork uow, DocumentHeader header, CancellationToken cancellationToken) =>
uow.Repository<THeader, long>().UpdateAsync((THeader)header, cancellationToken);
/// <inheritdoc />
public Task DeleteAsync(IUnitOfWork uow, long id, CancellationToken cancellationToken) =>
uow.Repository<THeader, long>().DeleteAsync(id, cancellationToken);
/// <inheritdoc />
public async Task InsertLineAsync(IUnitOfWork uow, DocumentLine line, CancellationToken cancellationToken) =>
line.Id = await uow.Repository<TLine, long>().InsertAsync((TLine)line, cancellationToken).ConfigureAwait(false);
/// <inheritdoc />
public Task UpdateLineAsync(IUnitOfWork uow, DocumentLine line, CancellationToken cancellationToken) =>
uow.Repository<TLine, long>().UpdateAsync((TLine)line, cancellationToken);
/// <inheritdoc />
public Task DeleteLineAsync(IUnitOfWork uow, long id, CancellationToken cancellationToken) =>
uow.Repository<TLine, long>().DeleteAsync(id, cancellationToken);
/// <inheritdoc />
public Task RecordAsync(
AuditTrail audit, IUnitOfWork uow, AuditAction action, long id, DocumentHeader? before, DocumentHeader? after, string? userName,
CancellationToken cancellationToken) =>
audit.RecordAsync(uow, action, id, (THeader?)before, (THeader?)after, userName, cancellationToken);
/// <inheritdoc />
public async Task<ListPage<DocumentHeader>> ListAsync(IUnitOfWork uow, ListQuery list, IReadOnlyList<SqlFragment> conditions, CancellationToken cancellationToken)
{
var query = Query.For<THeader>();
foreach (var condition in conditions)
{
query = query.Where(condition);
}
var fields = DocumentListFields<THeader>.Fields;
var page = await uow.Repository<THeader, long>().ListAsync(fields.Apply(query, list), cancellationToken).ConfigureAwait(false);
return new ListPage<DocumentHeader>([.. page.Items], page.TotalCount, new Dictionary<string, decimal>());
}
/// <inheritdoc />
public async Task<IReadOnlyList<DocumentHeader>> ManyAsync(IUnitOfWork uow, IReadOnlyCollection<long> ids, CancellationToken cancellationToken)
{
if (ids.Count == 0)
{
return [];
}
var list = ids.ToList();
var rows = await uow.Repository<THeader, long>().ListAsync(Query.For<THeader>().Where(h => list.Contains(h.Id)), cancellationToken).ConfigureAwait(false);
return [.. rows.Items];
}
/// <inheritdoc />
public async Task<IReadOnlyList<DocumentLine>> LinesByIdAsync(IUnitOfWork uow, IReadOnlyCollection<long> ids, CancellationToken cancellationToken)
{
if (ids.Count == 0)
{
return [];
}
var list = ids.ToList();
var rows = await uow.Repository<TLine, long>().ListAsync(Query.For<TLine>().Where(l => list.Contains(l.Id)), cancellationToken).ConfigureAwait(false);
return [.. rows.Items];
}
}
/// <summary>The fields of the document radars (ADR 0032): the same for every family.</summary>
/// <typeparam name="THeader">The header.</typeparam>
internal static class DocumentListFields<THeader>
where THeader : DocumentHeader
{
/// <summary>The fields.</summary>
public static ListFields<THeader> Fields { get; } = new ListFields<THeader>()
.Add("number", h => h.Number)
.Add("documentNumber", h => h.DocumentNumber, searchable: true)
.Add("date", h => h.DocumentDate)
.Add("year", h => h.Year)
.Add("kind", h => h.Kind)
.Add("type", h => h.DocumentTypeId)
.Add("status", h => h.Status)
.Add("party", h => h.PartyId)
.Add("reference", h => h.ExternalReference, searchable: true)
.Add("salesperson", h => h.SalespersonId)
.Add("taxable", h => h.TaxableAmount, total: true)
.Add("tax", h => h.TaxAmount, total: true)
.Add("total", h => h.TotalAmount, total: true)
.Add("net", h => h.NetAmount, total: true)
.Add("delivery", h => h.DeliveryDate)
.Add("validUntil", h => h.ValidUntil)
.Add("demo", h => h.IsDemo)
.OrderByDefault(new ListSort("date", Descending: true), new ListSort("number", Descending: true));
}
/// <summary>The stores of the six families.</summary>
internal static class DocumentStores
{
private static readonly Dictionary<DocumentFamily, IDocumentStore> ByFamily = new IDocumentStore[]
{
new DocumentStore<SaleQuotation, SaleQuotationLine>(DocumentFamily.SaleQuotation, "sale_quotations"),
new DocumentStore<SaleOrder, SaleOrderLine>(DocumentFamily.SaleOrder, "sale_orders"),
new DocumentStore<SaleDocument, SaleDocumentLine>(DocumentFamily.SaleDocument, "sale_documents"),
new DocumentStore<PurchaseOrder, PurchaseOrderLine>(DocumentFamily.PurchaseOrder, "purchase_orders"),
new DocumentStore<PurchaseDocument, PurchaseDocumentLine>(DocumentFamily.PurchaseDocument, "purchase_documents"),
new DocumentStore<InventoryDocument, InventoryDocumentLine>(DocumentFamily.InventoryDocument, "inventory_documents"),
}.ToDictionary(s => s.Family);
/// <summary>Every store.</summary>
public static IEnumerable<IDocumentStore> All => ByFamily.Values;
/// <summary>The store of a family.</summary>
/// <param name="family">The family.</param>
/// <returns>The store.</returns>
public static IDocumentStore Of(DocumentFamily family) => ByFamily[family];
/// <summary>The family of a header class.</summary>
/// <typeparam name="THeader">The header.</typeparam>
/// <returns>The family.</returns>
public static DocumentFamily FamilyOf<THeader>()
where THeader : DocumentHeader, new()
{
var type = typeof(THeader);
return All.Single(s => s.NewHeader().GetType() == type).Family;
}
}
@@ -0,0 +1,257 @@
using Khaemhat.Application.Tables;
using Khaemhat.Core.Documents;
using Khaemhat.Core.Tax;
using Khaemhat.Fiscal.Abstractions;
namespace Khaemhat.Application.Documents;
/// <summary>The VAT of a line, from its tax code.</summary>
/// <param name="TaxCodeId">The tax code.</param>
/// <param name="Rate">The rate in percent.</param>
/// <param name="Nature">The nature of operations without VAT.</param>
/// <param name="Exigibility">When the VAT becomes due.</param>
/// <param name="NonDeductiblePercent">The non-deductible share (purchases).</param>
/// <param name="LegalReference">The law printed for operations without VAT.</param>
public sealed record TotalsTax(
long? TaxCodeId,
decimal Rate,
string? Nature = null,
TaxExigibility Exigibility = TaxExigibility.Immediate,
decimal NonDeductiblePercent = 0m,
string? LegalReference = null);
/// <summary>A line as the calculator sees it.</summary>
/// <param name="Kind">The kind of line.</param>
/// <param name="Quantity">The quantity (expenses and discounts without quantity count as one).</param>
/// <param name="Price">The unit price, with VAT when the document's prices include it.</param>
/// <param name="DiscountFormula">The discounts, such as <c>10+5</c>.</param>
/// <param name="Tax">The VAT; lines without it are left out of the summary.</param>
/// <param name="WithholdingExcluded">The line is out of the withholding and of the social security contribution.</param>
public sealed record TotalsLine(
DocumentLineKind Kind,
decimal Quantity,
decimal Price,
string? DiscountFormula,
TotalsTax? Tax,
bool WithholdingExcluded = false);
/// <summary>The settings of the document that change its totals.</summary>
public sealed record TotalsOptions
{
/// <summary>The prices include VAT: the taxable amount is computed back from each VAT group.</summary>
public bool PricesIncludeTax { get; init; }
/// <summary>The discount on the goods (not on expenses), such as <c>5</c> or <c>10+5</c>.</summary>
public string? FooterDiscount { get; init; }
/// <summary>The exigibility of the whole document (cash basis, deferred), when not the one of the tax codes.</summary>
public TaxExigibility? Exigibility { get; init; }
/// <summary>Split payment: the VAT is paid by the customer to the State.</summary>
public bool SplitPayment { get; init; }
/// <summary>The document can carry the stamp duty (invoices and notes).</summary>
public bool StampDutyApplies { get; init; }
/// <summary>The stamp duty is added to the total.</summary>
public bool StampDutyCharged { get; init; }
/// <summary>The withholding rate, percent.</summary>
public decimal? WithholdingRate { get; init; }
/// <summary>The share of the amount the withholding applies to, percent.</summary>
public decimal WithholdingBasePercent { get; init; } = 100m;
/// <summary>The social security contribution rate, percent.</summary>
public decimal? SocialSecurityRate { get; init; }
/// <summary>The VAT of the contribution; the one of the first taxed line when empty.</summary>
public TotalsTax? SocialSecurityTax { get; init; }
/// <summary>The contribution is part of the withholding base.</summary>
public bool SocialSecurityWithheld { get; init; }
/// <summary>The ENASARCO rate withheld, percent.</summary>
public decimal? EnasarcoRate { get; init; }
}
/// <summary>A line of the computed tax summary.</summary>
/// <param name="Tax">The VAT of the group, with the exigibility of the document.</param>
/// <param name="Taxable">The taxable amount.</param>
/// <param name="TaxAmount">The VAT.</param>
/// <param name="NonDeductibleTax">The non-deductible part of the VAT.</param>
public sealed record TotalsSummaryLine(TotalsTax Tax, decimal Taxable, decimal TaxAmount, decimal NonDeductibleTax);
/// <summary>The totals of a document.</summary>
/// <param name="LineAmounts">The amount of each line (quantity × price less its discounts), in the order given.</param>
/// <param name="Summary">The tax summary, by rate (highest first).</param>
/// <param name="Expenses">The total of the expense lines.</param>
/// <param name="FooterDiscountAmount">What the footer discount took off.</param>
/// <param name="SocialSecurity">The social security contribution.</param>
/// <param name="Taxable">The taxable amount.</param>
/// <param name="Tax">The VAT.</param>
/// <param name="StampDuty">The stamp duty due (charged or not).</param>
/// <param name="Total">The total of the document.</param>
/// <param name="Withholding">The withholding tax.</param>
/// <param name="Enasarco">The ENASARCO contribution withheld.</param>
/// <param name="SplitPaymentTax">The VAT the customer pays to the State.</param>
/// <param name="Net">The amount to pay.</param>
public sealed record DocumentTotals(
IReadOnlyList<decimal> LineAmounts,
IReadOnlyList<TotalsSummaryLine> Summary,
decimal Expenses,
decimal FooterDiscountAmount,
decimal SocialSecurity,
decimal Taxable,
decimal Tax,
decimal StampDuty,
decimal Total,
decimal Withholding,
decimal Enasarco,
decimal SplitPaymentTax,
decimal Net);
/// <summary>
/// The totals of a document (SPEC §11.3, issue #48): line amount = quantity × price × (1 − d1)(1 − d2)… rounded to the
/// cent; footer discount on the goods; tax summary per VAT code with the tax computed on the total of each group
/// (FatturaPA <c>DatiRiepilogo</c>); social security contribution with its own VAT; stamp duty; withholding, ENASARCO
/// and split payment taken off the amount to pay.
/// </summary>
public static class DocumentTotalsCalculator
{
/// <summary>Computes the totals.</summary>
/// <param name="lines">The lines.</param>
/// <param name="options">The settings of the document.</param>
/// <param name="engine">The country's rounding and stamp duty rules.</param>
/// <returns>The totals.</returns>
public static DocumentTotals Compute(IReadOnlyList<TotalsLine> lines, TotalsOptions options, ITaxEngine engine)
{
ArgumentNullException.ThrowIfNull(lines);
ArgumentNullException.ThrowIfNull(options);
ArgumentNullException.ThrowIfNull(engine);
var footer = Factor(options.FooterDiscount);
var amounts = new decimal[lines.Count];
var groups = new List<Group>();
decimal beforeFooter = 0m, afterFooter = 0m, expenses = 0m, withholdingBase = 0m;
TotalsTax? firstTax = null;
for (var i = 0; i < lines.Count; i++)
{
var line = lines[i];
if (line.Kind == DocumentLineKind.Description)
{
continue;
}
var quantity = line.Kind is DocumentLineKind.Expense or DocumentLineKind.Discount && line.Quantity == 0m ? 1m : line.Quantity;
var raw = quantity * line.Price * Factor(line.DiscountFormula);
if (line.Kind == DocumentLineKind.Discount)
{
raw = -Math.Abs(raw);
}
amounts[i] = engine.Round(raw);
var net = amounts[i];
if (line.Kind == DocumentLineKind.Expense)
{
expenses += net;
}
else if (footer != 1m)
{
net = engine.Round(raw * footer);
beforeFooter += amounts[i];
afterFooter += net;
}
if (!line.WithholdingExcluded)
{
withholdingBase += net;
}
if (line.Tax is { } tax)
{
firstTax ??= tax.Rate > 0m ? tax : null;
var group = GroupOf(groups, tax);
if (options.PricesIncludeTax)
{
group.Gross += net;
}
else
{
group.Net += net;
}
}
}
var socialSecurity = 0m;
if (options.SocialSecurityRate is > 0m and var rate)
{
socialSecurity = engine.Round(withholdingBase * rate / 100m);
if ((options.SocialSecurityTax ?? firstTax ?? groups.FirstOrDefault()?.Tax) is { } tax)
{
GroupOf(groups, tax).Net += socialSecurity;
}
}
var summary = groups
.Select(g => Summarize(g, options, engine))
.OrderByDescending(s => s.Tax.Rate)
.ThenBy(s => s.Tax.Nature, StringComparer.Ordinal)
.ToList();
var taxable = summary.Sum(s => s.Taxable);
var taxAmount = summary.Sum(s => s.TaxAmount);
var stamp = 0m;
if (options.StampDutyApplies)
{
stamp = engine.AssessStampDuty(summary.Select(s => new TaxSummaryLine(s.Tax.Rate, s.Tax.Nature, s.Tax.Exigibility,
s.Tax.NonDeductiblePercent, s.Taxable, s.TaxAmount, s.NonDeductibleTax))).Amount;
}
var total = taxable + taxAmount + (options.StampDutyCharged ? stamp : 0m);
var withholding = options.WithholdingRate is > 0m and var withholdingRate
? engine.Round((withholdingBase + (options.SocialSecurityWithheld ? socialSecurity : 0m)) * options.WithholdingBasePercent / 100m * withholdingRate / 100m)
: 0m;
var enasarco = options.EnasarcoRate is > 0m and var enasarcoRate ? engine.Round(withholdingBase * enasarcoRate / 100m) : 0m;
var split = summary.Where(s => s.Tax.Exigibility == TaxExigibility.SplitPayment).Sum(s => s.TaxAmount);
return new DocumentTotals(amounts, summary, expenses, beforeFooter - afterFooter, socialSecurity, taxable, taxAmount, stamp, total,
withholding, enasarco, split, total - withholding - enasarco - split);
}
/// <summary>The factor of a discount formula: 10+5 is 0.855; an empty or invalid formula is 1.</summary>
/// <param name="formula">The formula.</param>
/// <returns>The factor.</returns>
public static decimal Factor(string? formula) =>
DiscountFormula.TryParse(formula, out var steps) ? steps.Aggregate(1m, (left, step) => left * (1m - (step / 100m))) : 1m;
private static Group GroupOf(List<Group> groups, TotalsTax tax)
{
var group = groups.Find(g => g.Tax.TaxCodeId == tax.TaxCodeId && g.Tax.Rate == tax.Rate && g.Tax.Nature == tax.Nature);
if (group is null)
{
group = new Group(tax);
groups.Add(group);
}
return group;
}
private static TotalsSummaryLine Summarize(Group group, TotalsOptions options, ITaxEngine engine)
{
var tax = group.Tax;
var exigibility = tax.Rate == 0m ? tax.Exigibility
: options.SplitPayment ? TaxExigibility.SplitPayment
: options.Exigibility ?? tax.Exigibility;
var grossTaxable = group.Gross == 0m ? 0m : engine.Round(group.Gross * 100m / (100m + tax.Rate));
var taxable = grossTaxable + group.Net;
var amount = group.Gross - grossTaxable + engine.ComputeTax(group.Net, tax.Rate);
return new TotalsSummaryLine(tax with { Exigibility = exigibility }, taxable, amount, engine.Round(amount * tax.NonDeductiblePercent / 100m));
}
private sealed class Group(TotalsTax tax)
{
public TotalsTax Tax { get; } = tax;
public decimal Net { get; set; }
public decimal Gross { get; set; }
}
}
@@ -0,0 +1,110 @@
namespace Khaemhat.Application.Documents;
/// <summary>An installment of payment terms.</summary>
/// <param name="Days">Days from the document date.</param>
/// <param name="EndOfMonth">Move to the end of that month.</param>
/// <param name="FixedDay">A fixed day: of the next month after the end-of-month move, else the next such day.</param>
/// <param name="Percent">The share of the amount, percent.</param>
public sealed record InstallmentRule(int Days, bool EndOfMonth, int? FixedDay, decimal Percent);
/// <summary>Months without due dates (mesi esclusi): a due date in them moves to a day of the next month.</summary>
/// <param name="First">The first month (1-12).</param>
/// <param name="Second">The second month.</param>
/// <param name="Day">The day of the next month.</param>
public sealed record ExcludedMonths(int? First, int? Second, int Day = 10)
{
/// <summary>Whether a month is excluded.</summary>
/// <param name="month">The month.</param>
/// <returns>Whether it is.</returns>
public bool Contains(int month) => First == month || Second == month;
}
/// <summary>A computed installment.</summary>
/// <param name="Number">The order, from 1.</param>
/// <param name="DueDate">The due date.</param>
/// <param name="Amount">The amount.</param>
public sealed record InstallmentDue(int Number, DateOnly DueDate, decimal Amount);
/// <summary>
/// The installments of a document from its payment terms (SPEC §11.3, issue #48): days, end of month, fixed day,
/// excluded months, percentages, all the VAT on the first installment; the rounding goes on the last one.
/// </summary>
public static class InstallmentGenerator
{
/// <summary>Computes the installments.</summary>
/// <param name="date">The document date.</param>
/// <param name="amount">The amount to pay.</param>
/// <param name="tax">The VAT included in <paramref name="amount"/> (for <paramref name="vatOnFirst"/>).</param>
/// <param name="rules">The installments of the terms; none means one installment on the document date.</param>
/// <param name="vatOnFirst">All the VAT is paid with the first installment.</param>
/// <param name="excluded">The months without due dates.</param>
/// <param name="round">Rounding to the cent.</param>
/// <returns>The installments, empty for a zero amount.</returns>
public static IReadOnlyList<InstallmentDue> Generate(
DateOnly date, decimal amount, decimal tax, IReadOnlyList<InstallmentRule> rules, bool vatOnFirst, ExcludedMonths? excluded, Func<decimal, decimal> round)
{
ArgumentNullException.ThrowIfNull(rules);
ArgumentNullException.ThrowIfNull(round);
if (amount == 0m)
{
return [];
}
if (rules.Count == 0)
{
return [new InstallmentDue(1, Move(date, excluded), amount)];
}
var share = vatOnFirst && rules.Count > 1 ? tax : 0m;
var spread = amount - share;
var percents = rules.Sum(r => r.Percent);
var result = new List<InstallmentDue>(rules.Count);
var assigned = 0m;
for (var i = 0; i < rules.Count; i++)
{
var rule = rules[i];
var part = i == rules.Count - 1
? spread - assigned
: round(spread * (percents == 0m ? 1m / rules.Count : rule.Percent / percents));
assigned += part;
result.Add(new InstallmentDue(i + 1, DueDate(date, rule, excluded), part + (i == 0 ? share : 0m)));
}
return result;
}
/// <summary>The due date of an installment.</summary>
/// <param name="date">The document date.</param>
/// <param name="rule">The installment.</param>
/// <param name="excluded">The months without due dates.</param>
/// <returns>The due date.</returns>
public static DateOnly DueDate(DateOnly date, InstallmentRule rule, ExcludedMonths? excluded)
{
ArgumentNullException.ThrowIfNull(rule);
var due = date.AddDays(rule.Days);
if (rule.EndOfMonth)
{
due = new DateOnly(due.Year, due.Month, DateTime.DaysInMonth(due.Year, due.Month));
}
if (rule.FixedDay is { } day and >= 1 and <= 31)
{
due = rule.EndOfMonth || due.Day > day ? Day(due.AddMonths(1), day) : Day(due, day);
}
return Move(due, excluded);
}
private static DateOnly Move(DateOnly due, ExcludedMonths? excluded)
{
for (var guard = 0; excluded is not null && excluded.Contains(due.Month) && guard < 12; guard++)
{
due = Day(due.AddMonths(1), excluded.Day);
}
return due;
}
private static DateOnly Day(DateOnly month, int day) =>
new(month.Year, month.Month, Math.Min(day, DateTime.DaysInMonth(month.Year, month.Month)));
}
@@ -2,10 +2,7 @@ using Khaemhat.Application.Modules;
using Khaemhat.Application.Security;
using Khaemhat.Application.Tables;
using Khaemhat.Core.Accounting;
using Khaemhat.Core.Items;
using Khaemhat.Core.Tables;
using Khaemhat.Data;
using Khaemhat.Data.Querying;
namespace Khaemhat.Application.ImportExport;
@@ -21,9 +18,11 @@ namespace Khaemhat.Application.ImportExport;
/// <param name="SubLedger">With a sub-ledger of customers or suppliers.</param>
/// <param name="ClosesAutomatically">Closed by the year end.</param>
/// <param name="Disabled">Not used any more.</param>
/// <param name="StatementLine">The line of the legal statements (voce CEE).</param>
/// <param name="Reclassification">The line of the reclassified statements.</param>
public sealed record ImportedAccount(
string Code, string Description, int Level, string? ParentCode, AccountNature Nature, AccountType Type, bool Postable, bool VatRelevant, bool SubLedger,
bool ClosesAutomatically, bool Disabled);
bool ClosesAutomatically, bool Disabled, string? StatementLine = null, string? Reclassification = null);
/// <summary>
/// The checks of a chart of accounts from a file (SPEC §12.12, ADR 0031): codes of one to three parts separated by
@@ -149,7 +148,7 @@ public static class ChartOfAccountsImportValidator
if (messages.All(m => m.IsWarning) && nature is { } valid)
{
accounts.Add(new(code, row["descrizione"] ?? string.Empty, level, parent, valid, type, postable, flags.Contains('I'), flags.Contains('P'), flags.Contains('C'),
flags.Contains('X')));
flags.Contains('X'), row["voce_cee"], row["riclassifica"]));
}
results.Add(new(row.Line, code, messages.Any(m => !m.IsWarning) ? ImportAction.Skip : ImportAction.Create, messages));
@@ -186,15 +185,26 @@ public static class ChartOfAccountsImportValidator
}
/// <summary>
/// The chart of accounts (<c>piano-dei-conti</c>): CSV, XLSX or <c>khaemhat-coa.json</c>. Until the ledger exists (M7)
/// the file is only checked; M7 writes the accounts this check accepts.
/// The chart of accounts (<c>piano-dei-conti</c>): CSV, XLSX or <c>khaemhat-coa.json</c>. The accounts the check
/// accepts are added; those that exist are updated when the options say so (M7, issue #62).
/// </summary>
/// <param name="permissions">Checks the permission.</param>
public sealed class ChartOfAccountsImportTarget(PermissionService permissions) : IImportTarget
public sealed class ChartOfAccountsImportTarget : IImportTarget
{
/// <summary>The permission to change the chart of accounts.</summary>
public const string WritePermission = "ledger.account.write";
private readonly PermissionService _permissions;
private readonly IUnitOfWorkFactory? _factory;
/// <summary>Creates the target.</summary>
/// <param name="permissions">Checks the permission.</param>
/// <param name="factory">The units of work, to write the accounts.</param>
public ChartOfAccountsImportTarget(PermissionService permissions, IUnitOfWorkFactory? factory = null)
{
_permissions = permissions;
_factory = factory;
}
/// <inheritdoc />
public string Key => "piano-dei-conti";
@@ -208,10 +218,10 @@ public sealed class ChartOfAccountsImportTarget(PermissionService permissions) :
public string ExportPermission => "ledger.account.read";
/// <inheritdoc />
public bool CanApply => false;
public bool CanApply => _factory is not null;
/// <inheritdoc />
public bool CanExport => false;
public bool CanExport => _factory is not null;
/// <inheritdoc />
public IReadOnlyList<ImportField> Fields => ChartOfAccountsImportValidator.Fields;
@@ -220,113 +230,46 @@ public sealed class ChartOfAccountsImportTarget(PermissionService permissions) :
public async Task<IReadOnlyList<ImportRowResult>> CheckAsync(ImportContext context, IReadOnlyList<ImportRow> rows, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(context);
await CompanyGuard.DemandAsync(permissions, context.Actor, context.CompanyCode, Permission, cancellationToken).ConfigureAwait(false);
await CompanyGuard.DemandAsync(_permissions, context.Actor, context.CompanyCode, Permission, cancellationToken).ConfigureAwait(false);
return ChartOfAccountsImportValidator.Check(rows).Results;
}
/// <inheritdoc />
public Task<IReadOnlyList<ImportRowResult>> ApplyAsync(ImportContext context, IReadOnlyList<ImportRow> rows, CancellationToken cancellationToken) =>
throw new InvalidOperationException(ImportErrors.CheckOnly);
/// <inheritdoc />
public Task<IReadOnlyList<IReadOnlyList<object?>>> ExportAsync(ImportContext context, CancellationToken cancellationToken) =>
Task.FromResult<IReadOnlyList<IReadOnlyList<object?>>>([]);
}
/// <summary>
/// The opening stock (<c>giacenze-iniziali</c>): item, warehouse, quantity and unit cost. Until the stock entries exist
/// (M6) the file is only checked; M6 writes the opening entry from the rows this check accepts.
/// </summary>
/// <param name="factory">Opens the company databases.</param>
/// <param name="permissions">Checks the permission.</param>
public sealed class OpeningStockImportTarget(IUnitOfWorkFactory factory, PermissionService permissions) : IImportTarget
{
private static readonly ImportField[] StockFields =
[
new("articolo", ImportFieldKind.Code, Required: true, Aliases: ["codice_articolo", "codice", "cod_articolo", "sku"]),
new("deposito", ImportFieldKind.Code, Aliases: ["magazzino", "codice_magazzino"]),
new("quantita", ImportFieldKind.Number, Required: true, Aliases: ["qta", "qty", "giacenza", "esistenza"]),
new("costo_unitario", ImportFieldKind.Number, Aliases: ["costo", "valore_unitario", "prezzo_acquisto"]),
];
/// <inheritdoc />
public string Key => "giacenze-iniziali";
/// <inheritdoc />
public string ModuleCode => ModuleCodes.Core;
/// <inheritdoc />
public string Permission => "inventory.entry.write";
/// <inheritdoc />
public string ExportPermission => "inventory.stock.read";
/// <inheritdoc />
public bool CanApply => false;
/// <inheritdoc />
public bool CanExport => false;
/// <inheritdoc />
public IReadOnlyList<ImportField> Fields => StockFields;
/// <inheritdoc />
public async Task<IReadOnlyList<ImportRowResult>> CheckAsync(ImportContext context, IReadOnlyList<ImportRow> rows, CancellationToken cancellationToken)
public async Task<IReadOnlyList<ImportRowResult>> ApplyAsync(ImportContext context, IReadOnlyList<ImportRow> rows, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(context);
ArgumentNullException.ThrowIfNull(rows);
var company = await CompanyGuard.DemandAsync(permissions, context.Actor, context.CompanyCode, Permission, cancellationToken).ConfigureAwait(false);
await using var uow = await factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
var items = (await uow.Repository<Item, long>().ListAsync(Query.For<Item>(), cancellationToken).ConfigureAwait(false)).Items;
var codes = new CodeIndex(items.Select(i => (i.Code, i.Id)));
var byId = items.ToDictionary(i => i.Id);
var warehouses = await CodeIndex.LoadAsync<Warehouse>(uow, cancellationToken).ConfigureAwait(false);
var seen = new HashSet<(long, long)>();
var results = new List<ImportRowResult>(rows.Count);
foreach (var row in rows)
var factory = _factory ?? throw new InvalidOperationException(ImportErrors.CheckOnly);
var company = await CompanyGuard.DemandAsync(_permissions, context.Actor, context.CompanyCode, Permission, cancellationToken).ConfigureAwait(false);
var (results, accounts) = ChartOfAccountsImportValidator.Check(rows);
var update = context.Options.Existing == ExistingCodeAction.Update;
Dictionary<string, bool> written;
await using (var uow = await factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false))
{
var messages = new List<ImportMessage>();
var cells = new CellReader(row, messages);
messages.AddRange(StockFields.Where(f => f.Required && !cells.Has(f.Key)).Select(f => new ImportMessage(f.Key, ImportErrors.Required)));
var item = cells.Code("articolo", codes) is { } id ? byId[id] : null;
var warehouse = cells.Code("deposito", warehouses) ?? (cells.Has("deposito") ? null : item?.WarehouseId);
if (item is not null && (item.Kind != ItemKind.Goods || !item.Stocked))
{
messages.Add(new("articolo", ImportErrors.NotStocked, Value: item.Code));
}
if (item is not null && warehouse is null && !cells.Has("deposito"))
{
messages.Add(new("deposito", ImportErrors.Required));
}
if (cells.Number("quantita") is <= 0)
{
messages.Add(new("quantita", ImportErrors.Positive));
}
if (cells.Number("costo_unitario") is < 0)
{
messages.Add(new("costo_unitario", Items.ItemService.NotNegative));
}
var label = row["articolo"] ?? string.Empty;
if (item is not null && warehouse is { } w && !seen.Add((item.Id, w)))
{
messages.Add(new("articolo", ImportErrors.CodeRepeated, Value: label));
}
results.Add(new(row.Line, label, messages.Any(m => !m.IsWarning) ? ImportAction.Skip : ImportAction.Create, messages));
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
written = await Ledger.LedgerService.ImportAsync(uow, accounts, update, cancellationToken).ConfigureAwait(false);
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
}
return results;
return [.. results.Select(r => r.Action == ImportAction.Skip
? r
: r with { Action = written.TryGetValue(r.Key, out var created) ? (created ? ImportAction.Create : ImportAction.Update) : ImportAction.Skip })];
}
/// <inheritdoc />
public Task<IReadOnlyList<ImportRowResult>> ApplyAsync(ImportContext context, IReadOnlyList<ImportRow> rows, CancellationToken cancellationToken) =>
throw new InvalidOperationException(ImportErrors.CheckOnly);
/// <inheritdoc />
public Task<IReadOnlyList<IReadOnlyList<object?>>> ExportAsync(ImportContext context, CancellationToken cancellationToken) =>
Task.FromResult<IReadOnlyList<IReadOnlyList<object?>>>([]);
public async Task<IReadOnlyList<IReadOnlyList<object?>>> ExportAsync(ImportContext context, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(context);
var factory = _factory ?? throw new InvalidOperationException(ImportErrors.CheckOnly);
var company = await CompanyGuard.DemandAsync(_permissions, context.Actor, context.CompanyCode, ExportPermission, cancellationToken).ConfigureAwait(false);
await using var uow = await factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
var accounts = (await uow.Repository<GlAccount, long>().ListAsync(Data.Querying.Query.For<GlAccount>(), cancellationToken).ConfigureAwait(false)).Items
.OrderBy(a => a.Code, StringComparer.Ordinal);
return [.. accounts.Select(a => (IReadOnlyList<object?>)
[
a.Code, a.Description, a.Level, ChartOfAccountsImportValidator.ParentOf(a.Code), ChartOfAccountsImportValidator.NatureWords[(int)a.Nature],
ChartOfAccountsImportValidator.TypeWords[(int)a.Type], a.StatementLine, a.Reclassification,
(a.Postable ? "M" : string.Empty) + (a.VatRelevant ? "I" : string.Empty) + (a.SubLedger ? "P" : string.Empty)
+ (a.ClosesAutomatically ? "C" : string.Empty) + (a.Disabled ? "X" : string.Empty),
])];
}
}
@@ -0,0 +1,191 @@
using Khaemhat.Application.Documents;
using Khaemhat.Application.Modules;
using Khaemhat.Application.Security;
using Khaemhat.Application.Tables;
using Khaemhat.Core.Documents;
using Khaemhat.Core.Items;
using Khaemhat.Core.Tables;
using Khaemhat.Data;
using Khaemhat.Data.Querying;
namespace Khaemhat.Application.ImportExport;
/// <summary>
/// The opening stock (<c>giacenze-iniziali</c>, SPEC §12.12): item, warehouse, quantity and unit cost. The rows accepted
/// become one warehouse movement per warehouse with the reason <c>APE</c> (opening stock), confirmed at the day of the
/// import: the stock and the average cost start from there.
/// </summary>
/// <param name="factory">Opens the company databases.</param>
/// <param name="permissions">Checks the permission.</param>
/// <param name="engine">Writes the movements.</param>
/// <param name="clock">The day of the movements.</param>
public sealed class OpeningStockImportTarget(IUnitOfWorkFactory factory, PermissionService permissions, DocumentEngine engine, TimeProvider clock) : IImportTarget
{
/// <summary>The reason of the opening stock.</summary>
public const string OpeningReason = "APE";
/// <summary>Error: the reason APE is missing.</summary>
public const string ReasonMissing = "import.stock.reason-missing";
private static readonly ImportField[] StockFields =
[
new("articolo", ImportFieldKind.Code, Required: true, Aliases: ["codice_articolo", "codice", "cod_articolo", "sku"]),
new("deposito", ImportFieldKind.Code, Aliases: ["magazzino", "codice_magazzino"]),
new("quantita", ImportFieldKind.Number, Required: true, Aliases: ["qta", "qty", "giacenza", "esistenza"]),
new("costo_unitario", ImportFieldKind.Number, Aliases: ["costo", "valore_unitario", "prezzo_acquisto"]),
];
/// <inheritdoc />
public string Key => "giacenze-iniziali";
/// <inheritdoc />
public string ModuleCode => ModuleCodes.Core;
/// <inheritdoc />
public string Permission => "inventory.entry.write";
/// <inheritdoc />
public string ExportPermission => "inventory.stock.read";
/// <inheritdoc />
public bool CanApply => true;
/// <inheritdoc />
public bool CanExport => false;
/// <inheritdoc />
public IReadOnlyList<ImportField> Fields => StockFields;
/// <inheritdoc />
public async Task<IReadOnlyList<ImportRowResult>> CheckAsync(ImportContext context, IReadOnlyList<ImportRow> rows, CancellationToken cancellationToken) =>
[.. (await ReadAsync(context, rows, cancellationToken).ConfigureAwait(false)).Select(r => r.Result)];
/// <inheritdoc />
public async Task<IReadOnlyList<ImportRowResult>> ApplyAsync(ImportContext context, IReadOnlyList<ImportRow> rows, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(context);
var read = await ReadAsync(context, rows, cancellationToken).ConfigureAwait(false);
var company = await CompanyGuard.DemandAsync(permissions, context.Actor, context.CompanyCode, Permission, cancellationToken).ConfigureAwait(false);
long? reason;
await using (var uow = await factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false))
{
reason = (await uow.Repository<InventoryReason, long>().FindAsync(Query.For<InventoryReason>().Where(r => r.Code == OpeningReason), cancellationToken)
.ConfigureAwait(false))?.Id;
}
var results = read.Select(r => r.Result).ToArray();
var good = read.Select((r, i) => (Row: r, Index: i)).Where(x => x.Row.Result.Action == ImportAction.Create && x.Row.Stock is not null).ToList();
if (reason is null)
{
foreach (var (_, index) in good)
{
results[index] = results[index] with { Action = ImportAction.Skip, Messages = [.. results[index].Messages, new ImportMessage("articolo", ReasonMissing)] };
}
return results;
}
var today = DateOnly.FromDateTime(clock.GetLocalNow().DateTime);
foreach (var group in good.GroupBy(x => x.Row.Stock!.Value.WarehouseId))
{
var movement = await engine.NewAsync(context.Actor, company, "MM", cancellationToken).ConfigureAwait(false);
movement.Header.DocumentDate = today;
movement.Header.WarehouseId = group.Key;
movement.Header.InventoryReasonId = reason;
foreach (var (row, _) in group)
{
var stock = row.Stock!.Value;
movement.Lines.Add(new InventoryDocumentLine
{
Kind = DocumentLineKind.Item,
ItemId = stock.Item.Id,
Description = stock.Item.Description,
UnitOfMeasureId = stock.Item.UnitOfMeasureId,
Quantity = stock.Quantity,
Price = stock.Cost,
WarehouseId = group.Key,
});
}
try
{
var saved = await engine.SaveAsync(context.Actor, company, movement, cancellationToken).ConfigureAwait(false);
await engine.ConfirmAsync(context.Actor, company, saved.Family, saved.Header.Id, cancellationToken).ConfigureAwait(false);
}
catch (ValidationFailedException ex)
{
var message = new ImportMessage("articolo", ex.Errors.Count > 0 ? ex.Errors[0].Split(':', 2)[^1] : ImportErrors.Required);
foreach (var (_, index) in group)
{
results[index] = results[index] with { Action = ImportAction.Skip, Messages = [.. results[index].Messages, message] };
}
}
}
return results;
}
/// <inheritdoc />
public Task<IReadOnlyList<IReadOnlyList<object?>>> ExportAsync(ImportContext context, CancellationToken cancellationToken) =>
Task.FromResult<IReadOnlyList<IReadOnlyList<object?>>>([]);
private async Task<List<(ImportRowResult Result, (Item Item, long WarehouseId, decimal Quantity, decimal Cost)? Stock)>> ReadAsync(
ImportContext context, IReadOnlyList<ImportRow> rows, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(context);
ArgumentNullException.ThrowIfNull(rows);
var company = await CompanyGuard.DemandAsync(permissions, context.Actor, context.CompanyCode, Permission, cancellationToken).ConfigureAwait(false);
await using var uow = await factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
var items = (await uow.Repository<Item, long>().ListAsync(Query.For<Item>(), cancellationToken).ConfigureAwait(false)).Items;
var codes = new CodeIndex(items.Select(i => (i.Code, i.Id)));
var byId = items.ToDictionary(i => i.Id);
var warehouses = await CodeIndex.LoadAsync<Warehouse>(uow, cancellationToken).ConfigureAwait(false);
var fallback = (await uow.Repository<Warehouse, long>().ListAsync(Query.For<Warehouse>().Where(w => !w.Disabled), cancellationToken).ConfigureAwait(false)).Items
.OrderByDescending(w => w.IsDefault).ThenBy(w => w.Code, StringComparer.Ordinal).FirstOrDefault()?.Id;
var seen = new HashSet<(long, long)>();
var results = new List<(ImportRowResult, (Item, long, decimal, decimal)?)>(rows.Count);
foreach (var row in rows)
{
var messages = new List<ImportMessage>();
var cells = new CellReader(row, messages);
messages.AddRange(StockFields.Where(f => f.Required && !cells.Has(f.Key)).Select(f => new ImportMessage(f.Key, ImportErrors.Required)));
var item = cells.Code("articolo", codes) is { } id ? byId[id] : null;
var warehouse = cells.Code("deposito", warehouses) ?? (cells.Has("deposito") ? null : item?.WarehouseId ?? fallback);
if (item is not null && (item.Kind != ItemKind.Goods || !item.Stocked))
{
messages.Add(new("articolo", ImportErrors.NotStocked, Value: item.Code));
}
if (item is not null && warehouse is null && !cells.Has("deposito"))
{
messages.Add(new("deposito", ImportErrors.Required));
}
var quantity = cells.Number("quantita");
if (quantity is <= 0)
{
messages.Add(new("quantita", ImportErrors.Positive));
}
var cost = cells.Number("costo_unitario");
if (cost is < 0)
{
messages.Add(new("costo_unitario", Items.ItemService.NotNegative));
}
var label = row["articolo"] ?? string.Empty;
if (item is not null && warehouse is { } w && !seen.Add((item.Id, w)))
{
messages.Add(new("articolo", ImportErrors.CodeRepeated, Value: label));
}
var failed = messages.Any(m => !m.IsWarning);
(Item, long, decimal, decimal)? stock = !failed && item is not null && warehouse is { } where && quantity is { } q
? (item, where, q, cost ?? item.AverageCost ?? item.StandardCost ?? item.LastCost ?? 0m)
: null;
results.Add((new ImportRowResult(row.Line, label, failed ? ImportAction.Skip : ImportAction.Create, messages), stock));
}
return results;
}
}
@@ -0,0 +1,553 @@
using Khaemhat.Application.Security;
using Khaemhat.Core.Documents;
using Khaemhat.Core.Inventory;
using Khaemhat.Core.Items;
using Khaemhat.Core.Tables;
using Khaemhat.Data;
using Khaemhat.Data.Querying;
namespace Khaemhat.Application.Inventory;
/// <summary>
/// Posts the documents to the warehouse (SPEC §11.6, ADR 0035) inside the transaction of the document engine: a
/// confirmed document that moves the stock writes one movement per stocked line; a cancelled one loses it. After every
/// change the history of the items touched runs again through the weighted average and gives the balances of each
/// warehouse, the committed and ordered quantities of the open orders and the costs on the item card.
/// </summary>
public static class InventoryPoster
{
/// <summary>A transfer needs a destination different from the origin.</summary>
public const string TransferDestination = "document.transfer.destination";
/// <summary>Writes again the movements of a document from its current state and refreshes its items.</summary>
/// <param name="uow">The unit of work of the company, in a transaction.</param>
/// <param name="family">The family of the document.</param>
/// <param name="documentId">The document.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
public static async Task SyncAsync(IUnitOfWork uow, DocumentFamily family, long documentId, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(uow);
var items = new HashSet<long>();
await RemoveAsync(uow, family, documentId, items, cancellationToken).ConfigureAwait(false);
var header = await HeaderAsync(uow, family, documentId, cancellationToken).ConfigureAwait(false);
if (header is null)
{
await RecomputeAsync(uow, items, cancellationToken).ConfigureAwait(false);
return;
}
var lines = await LinesAsync(uow, family, documentId, cancellationToken).ConfigureAwait(false);
foreach (var line in lines.Where(l => l.ItemId is not null))
{
// Orders hold committed and ordered quantities; every state change of theirs moves the balances.
items.Add(line.ItemId!.Value);
}
if (DocumentStateMachine.IsInForce(header.Status) && StockEffectMatrix.MovesStock(header.Kind))
{
await PostAsync(uow, family, header, lines, items, cancellationToken).ConfigureAwait(false);
}
await RecomputeAsync(uow, items, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Rebuilds the warehouse from the documents (SPEC §11.6, <i>ricostruzione</i>): removes every movement, posts
/// again every document in force that moves the stock, oldest first and the delivery notes before the invoices of
/// the same day, then runs the history of every item.
/// </summary>
/// <param name="uow">The unit of work of the company, in a transaction.</param>
/// <param name="progress">Receives the documents posted and the total, then the items and their total.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The documents posted and the items computed.</returns>
public static async Task<(int Documents, int Items)> RebuildAsync(IUnitOfWork uow, IProgress<RebuildProgress>? progress = null, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(uow);
await uow.ExecuteAsync(SqlFragment.Of($"DELETE FROM inventory_entry_lines"), cancellationToken).ConfigureAwait(false);
await uow.ExecuteAsync(SqlFragment.Of($"DELETE FROM inventory_entries"), cancellationToken).ConfigureAwait(false);
var documents = new List<(DocumentFamily Family, DocumentHeader Header)>();
foreach (var family in new[] { DocumentFamily.SaleDocument, DocumentFamily.PurchaseDocument, DocumentFamily.InventoryDocument })
{
foreach (var header in await Documents.DocumentStores.Of(family).InForceAsync(uow, cancellationToken).ConfigureAwait(false))
{
if (StockEffectMatrix.MovesStock(header.Kind))
{
documents.Add((family, header));
}
}
}
// Delivery notes and receipts first: their invoices then find the goods already moved.
var ordered = documents
.OrderBy(d => d.Header.DocumentDate)
.ThenBy(d => d.Header.Kind is DocumentKind.DeliveryNote or DocumentKind.PurchaseDeliveryNote or DocumentKind.InventoryEntry ? 0 : 1)
.ThenBy(d => d.Header.ConfirmedAt)
.ThenBy(d => d.Header.Id)
.ToList();
var items = new HashSet<long>();
for (var i = 0; i < ordered.Count; i++)
{
var (family, header) = ordered[i];
var lines = await LinesAsync(uow, family, header.Id, cancellationToken).ConfigureAwait(false);
await PostAsync(uow, family, header, lines, items, cancellationToken).ConfigureAwait(false);
progress?.Report(new RebuildProgress(RebuildPhase.Documents, i + 1, ordered.Count));
}
// Every stocked item, also those with only orders or with no movement left.
var all = (await uow.Repository<Item, long>().ListAsync(Query.For<Item>().Where(i => i.Stocked), cancellationToken).ConfigureAwait(false)).Items.Select(i => i.Id);
var balanced = (await uow.Repository<ItemBalance, long>().ListAsync(Query.For<ItemBalance>(), cancellationToken).ConfigureAwait(false)).Items.Select(b => b.ItemId);
var ids = items.Concat(all).Concat(balanced).Distinct().ToList();
for (var i = 0; i < ids.Count; i += 50)
{
await RecomputeAsync(uow, ids.Skip(i).Take(50), cancellationToken).ConfigureAwait(false);
progress?.Report(new RebuildProgress(RebuildPhase.Items, Math.Min(i + 50, ids.Count), ids.Count));
}
return (ordered.Count, ids.Count);
}
/// <summary>
/// Runs again the history of items: the cost of every movement, the balances of each warehouse, the committed and
/// ordered quantities, the average and last cost on the item card.
/// </summary>
/// <param name="uow">The unit of work of the company, in a transaction.</param>
/// <param name="itemIds">The items.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
public static async Task RecomputeAsync(IUnitOfWork uow, IEnumerable<long> itemIds, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(uow);
ArgumentNullException.ThrowIfNull(itemIds);
var ids = itemIds.Distinct().ToList();
if (ids.Count == 0)
{
return;
}
var committed = await OpenQuantitiesAsync<SaleOrder, SaleOrderLine>(uow, ids, cancellationToken).ConfigureAwait(false);
var ordered = await OpenQuantitiesAsync<PurchaseOrder, PurchaseOrderLine>(uow, ids, cancellationToken).ConfigureAwait(false);
var defaultWarehouse = await DefaultWarehouseAsync(uow, cancellationToken).ConfigureAwait(false);
foreach (var itemId in ids)
{
await RecomputeItemAsync(uow, itemId, committed, ordered, defaultWarehouse, cancellationToken).ConfigureAwait(false);
}
}
/// <summary>The default warehouse of the company: the one marked as such, or the first.</summary>
/// <param name="uow">The unit of work.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The warehouse, if any.</returns>
public static async Task<long?> DefaultWarehouseAsync(IUnitOfWork uow, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(uow);
var warehouses = uow.Repository<Warehouse, long>();
var marked = await warehouses.FindAsync(Query.For<Warehouse>().Where(w => w.IsDefault && !w.Disabled), cancellationToken).ConfigureAwait(false);
return marked?.Id ?? (await warehouses.FindAsync(Query.For<Warehouse>().Where(w => !w.Disabled).OrderBy(w => w.Code), cancellationToken).ConfigureAwait(false))?.Id;
}
/// <summary>The quantity of a line in the base unit of its item.</summary>
/// <param name="quantity">The quantity on the line.</param>
/// <param name="lineUnit">The unit of the line.</param>
/// <param name="item">The item.</param>
/// <param name="units">The alternative units of the item.</param>
/// <returns>The quantity in the base unit.</returns>
public static decimal ToBase(decimal quantity, long? lineUnit, Item item, IEnumerable<ItemUnit> units)
{
ArgumentNullException.ThrowIfNull(item);
ArgumentNullException.ThrowIfNull(units);
if (lineUnit is null || lineUnit == item.UnitOfMeasureId)
{
return quantity;
}
var unit = units.FirstOrDefault(u => u.ItemId == item.Id && u.UnitOfMeasureId == lineUnit);
return unit is null || unit.Factor <= 0m ? quantity : quantity * unit.Factor;
}
private static async Task RemoveAsync(IUnitOfWork uow, DocumentFamily family, long documentId, HashSet<long> items, CancellationToken cancellationToken)
{
var entries = uow.Repository<InventoryEntry, long>();
var lines = uow.Repository<InventoryEntryLine, long>();
foreach (var entry in (await entries.ListAsync(Query.For<InventoryEntry>().Where(e => e.SourceFamily == family && e.SourceDocumentId == documentId), cancellationToken)
.ConfigureAwait(false)).Items)
{
foreach (var line in (await lines.ListAsync(Query.For<InventoryEntryLine>().Where(l => l.EntryId == entry.Id), cancellationToken).ConfigureAwait(false)).Items)
{
items.Add(line.ItemId);
await lines.DeleteAsync(line.Id, cancellationToken).ConfigureAwait(false);
}
await entries.DeleteAsync(entry.Id, cancellationToken).ConfigureAwait(false);
}
}
private static async Task PostAsync(
IUnitOfWork uow, DocumentFamily family, DocumentHeader header, IReadOnlyList<DocumentLine> lines, HashSet<long> items, CancellationToken cancellationToken)
{
if (header.InventoryReasonId is not { } reasonId
|| await uow.Repository<InventoryReason, long>().GetAsync(reasonId, cancellationToken).ConfigureAwait(false) is not { } reason)
{
return;
}
// A line that comes from a document that already moved its goods the same way (the invoice of a delivery note)
// does not move them again; a credit note of an invoice moves them back.
var sign = reason.IsTransfer ? 0 : reason.Effect switch { StockEffect.Load => 1, StockEffect.Unload => -1, _ => 0 };
var stockLines = await StockLinesAsync(uow, header, lines, sign, cancellationToken).ConfigureAwait(false);
IReadOnlyList<StockMovement> movements;
try
{
movements = StockEffectMatrix.Movements(header.Kind, StockReason.Of(reason), header.ToWarehouseId, stockLines);
}
catch (InvalidOperationException)
{
throw new ValidationFailedException([nameof(DocumentHeader.ToWarehouseId) + ":" + TransferDestination]);
}
if (movements.Count == 0)
{
return;
}
var entry = new InventoryEntry
{
EntryDate = header.DocumentDate,
SourceFamily = family,
SourceDocumentId = header.Id,
SourceKind = header.Kind,
SourceNumber = header.DocumentNumber,
InventoryReasonId = reason.Id,
PartyId = header.PartyId,
IsDemo = header.IsDemo,
};
await uow.Repository<InventoryEntry, long>().InsertAsync(entry, cancellationToken).ConfigureAwait(false);
var repository = uow.Repository<InventoryEntryLine, long>();
var order = 0;
foreach (var m in movements)
{
items.Add(m.ItemId);
await repository.InsertAsync(
new InventoryEntryLine
{
EntryId = entry.Id,
EntryDate = entry.EntryDate,
ItemId = m.ItemId,
WarehouseId = m.WarehouseId,
Quantity = m.Quantity,
Valued = m.Valued,
UnitCost = m.UnitCost,
Value = StockCostCalculator.Value(m.Quantity, m.UnitCost),
SourceLineId = m.SourceLineId,
SortOrder = ++order,
},
cancellationToken).ConfigureAwait(false);
}
}
// The stocked lines of a document in the base unit, with their warehouse and cost; the lines that come from a
// document that already moved the stock (the invoice of a delivery note) are left out.
private static async Task<List<StockLineInput>> StockLinesAsync(
IUnitOfWork uow, DocumentHeader header, IReadOnlyList<DocumentLine> lines, int sign, CancellationToken cancellationToken)
{
var result = new List<StockLineInput>();
var itemIds = lines.Where(l => l.Kind == DocumentLineKind.Item && l.ItemId is not null).Select(l => l.ItemId).Distinct().ToList();
if (itemIds.Count == 0)
{
return result;
}
var catalog = (await uow.Repository<Item, long>().ListAsync(Query.For<Item>().Where(i => itemIds.Contains(i.Id)), cancellationToken).ConfigureAwait(false)).Items
.ToDictionary(i => i.Id);
var ids = catalog.Keys.ToList();
var units = (await uow.Repository<ItemUnit, long>().ListAsync(Query.For<ItemUnit>().Where(u => ids.Contains(u.ItemId)), cancellationToken).ConfigureAwait(false)).Items;
var fallback = await DefaultWarehouseAsync(uow, cancellationToken).ConfigureAwait(false);
var moved = new Dictionary<(DocumentFamily, long), Dictionary<long, int>>();
foreach (var line in lines.Where(l => l.Kind == DocumentLineKind.Item && l.ItemId is not null && l.Quantity != 0m))
{
if (!catalog.TryGetValue(line.ItemId!.Value, out var item) || !item.Stocked || item.Kind != ItemKind.Goods)
{
continue;
}
if (sign != 0 && line.SourceFamily is { } sourceFamily && line.SourceLineId is { } sourceLineId
&& await MovedSignAsync(uow, sourceFamily, sourceLineId, moved, cancellationToken).ConfigureAwait(false) == sign)
{
continue;
}
var warehouse = line.WarehouseId ?? header.WarehouseId ?? item.WarehouseId ?? fallback;
if (warehouse is null)
{
continue;
}
var quantity = ToBase(Math.Abs(line.Quantity), line.UnitOfMeasureId, item, units);
result.Add(new StockLineInput(line.Id, item.Id, quantity, warehouse.Value, UnitCost(header, line, quantity)));
}
return result;
}
// The cost per base unit in euro of a line: its taxable amount over the quantity, at the exchange rate of the document.
private static decimal? UnitCost(DocumentHeader header, DocumentLine line, decimal baseQuantity)
{
if (baseQuantity == 0m || line.TaxableAmount == 0m)
{
return null;
}
var amount = Math.Abs(line.TaxableAmount);
if (!string.Equals(header.CurrencyCode, "EUR", StringComparison.Ordinal) && header.ExchangeRate > 0m)
{
amount /= header.ExchangeRate;
}
return Math.Round(amount / baseQuantity, StockCostCalculator.CostDecimals, MidpointRounding.AwayFromZero);
}
// How a line of another document moved the stock: 1 loaded, -1 unloaded, 0 not at all.
private static async Task<int> MovedSignAsync(
IUnitOfWork uow, DocumentFamily sourceFamily, long sourceLineId, Dictionary<(DocumentFamily, long), Dictionary<long, int>> moved, CancellationToken cancellationToken)
{
var source = await StoreLineAsync(uow, sourceFamily, sourceLineId, cancellationToken).ConfigureAwait(false);
if (source is null)
{
return 0;
}
var key = (sourceFamily, source.DocumentId);
if (!moved.TryGetValue(key, out var lines))
{
lines = [];
var entries = (await uow.Repository<InventoryEntry, long>()
.ListAsync(Query.For<InventoryEntry>().Where(e => e.SourceFamily == sourceFamily && e.SourceDocumentId == source.DocumentId), cancellationToken).ConfigureAwait(false)).Items;
foreach (var entry in entries)
{
foreach (var line in (await uow.Repository<InventoryEntryLine, long>()
.ListAsync(Query.For<InventoryEntryLine>().Where(l => l.EntryId == entry.Id), cancellationToken).ConfigureAwait(false)).Items)
{
if (line.SourceLineId is { } id)
{
lines[id] = Math.Sign(line.Quantity);
}
}
}
moved[key] = lines;
}
return lines.GetValueOrDefault(sourceLineId);
}
private static async Task RecomputeItemAsync(
IUnitOfWork uow, long itemId, IReadOnlyDictionary<(long, long?), decimal> committed, IReadOnlyDictionary<(long, long?), decimal> ordered, long? defaultWarehouse,
CancellationToken cancellationToken)
{
if (await uow.Repository<Item, long>().GetAsync(itemId, cancellationToken).ConfigureAwait(false) is not { } item)
{
return;
}
var repository = uow.Repository<InventoryEntryLine, long>();
var lines = (await repository.ListAsync(
Query.For<InventoryEntryLine>().Where(l => l.ItemId == itemId).OrderBy(l => l.EntryDate).OrderBy(l => l.EntryId).OrderBy(l => l.SortOrder), cancellationToken)
.ConfigureAwait(false)).Items;
var invoiced = await InvoicedCostsAsync(uow, lines, cancellationToken).ConfigureAwait(false);
var history = StockCostCalculator.Run(
lines.Select(l => new CostedMovement(
l.Id, l.EntryDate, l.WarehouseId, l.Quantity, l.Valued || invoiced.ContainsKey(l.Id), invoiced.TryGetValue(l.Id, out var cost) ? cost : l.UnitCost)),
item.StandardCost ?? 0m);
foreach (var line in lines)
{
var unitCost = history.UnitCosts[line.Id];
var value = StockCostCalculator.Value(line.Quantity, unitCost);
if (line.UnitCost != unitCost || line.Value != value)
{
line.UnitCost = unitCost;
line.Value = value;
await repository.UpdateAsync(line, cancellationToken).ConfigureAwait(false);
}
}
await uow.ExecuteAsync(SqlFragment.Of($"DELETE FROM item_balances WHERE item_id = {itemId}"), cancellationToken).ConfigureAwait(false);
var warehouses = history.Warehouses.Keys
.Concat(committed.Keys.Concat(ordered.Keys).Where(k => k.Item1 == itemId).Select(k => k.Item2 ?? item.WarehouseId ?? defaultWarehouse).OfType<long>())
.Distinct();
var balances = uow.Repository<ItemBalance, long>();
foreach (var warehouseId in warehouses)
{
var stock = history.Warehouses.GetValueOrDefault(warehouseId) ?? new WarehouseStock(0m, null, null);
await balances.InsertAsync(
new ItemBalance
{
ItemId = itemId,
WarehouseId = warehouseId,
OnHand = stock.OnHand,
Committed = Open(committed, itemId, warehouseId, item.WarehouseId ?? defaultWarehouse),
Ordered = Open(ordered, itemId, warehouseId, item.WarehouseId ?? defaultWarehouse),
AverageCost = history.AverageCost,
Value = StockCostCalculator.Value(stock.OnHand, history.AverageCost),
LastCost = history.LastCost,
LastLoadDate = stock.LastLoad,
LastUnloadDate = stock.LastUnload,
},
cancellationToken).ConfigureAwait(false);
}
// Only the costs: the card keeps its version, so whoever is editing it does not collide with a posting.
decimal? average = lines.Count == 0 ? item.AverageCost : history.AverageCost;
var last = history.LastCost ?? item.LastCost;
if (average != item.AverageCost || last != item.LastCost)
{
await uow.ExecuteAsync(SqlFragment.Of($"UPDATE items SET average_cost = {average}, last_cost = {last} WHERE id = {itemId}"), cancellationToken).ConfigureAwait(false);
}
}
// The quantity still open of an item in a warehouse; the lines without a warehouse count in the usual one.
private static decimal Open(IReadOnlyDictionary<(long, long?), decimal> open, long itemId, long warehouseId, long? usual)
{
var total = open.GetValueOrDefault((itemId, warehouseId));
if (usual == warehouseId)
{
total += open.GetValueOrDefault((itemId, null));
}
return total;
}
// The cost a supplier invoice gives to the loads of the delivery notes it invoices (the difference of price, §11.5).
private static async Task<Dictionary<long, decimal>> InvoicedCostsAsync(IUnitOfWork uow, IReadOnlyList<InventoryEntryLine> lines, CancellationToken cancellationToken)
{
var result = new Dictionary<long, decimal>();
var loads = lines.Where(l => l.Quantity > 0m && l.SourceLineId is not null).ToList();
if (loads.Count == 0)
{
return result;
}
var entryIds = loads.Select(l => l.EntryId).Distinct().ToList();
var receipts = (await uow.Repository<InventoryEntry, long>()
.ListAsync(Query.For<InventoryEntry>().Where(e => entryIds.Contains(e.Id) && e.SourceKind == DocumentKind.PurchaseDeliveryNote), cancellationToken).ConfigureAwait(false))
.Items.Select(e => e.Id).ToHashSet();
var receiptLines = loads.Where(l => receipts.Contains(l.EntryId)).ToList();
if (receiptLines.Count == 0)
{
return result;
}
var sourceIds = receiptLines.Select(l => l.SourceLineId!.Value).Distinct().ToList();
var links = (await uow.Repository<DocumentLink, long>().ListAsync(
Query.For<DocumentLink>().Where(k => k.SourceFamily == DocumentFamily.PurchaseDocument && k.TargetFamily == DocumentFamily.PurchaseDocument && sourceIds.Contains(k.SourceLineId)),
cancellationToken).ConfigureAwait(false)).Items;
foreach (var load in receiptLines)
{
decimal amount = 0m, quantity = 0m;
foreach (var link in links.Where(k => k.SourceLineId == load.SourceLineId))
{
var target = await StoreLineAsync(uow, DocumentFamily.PurchaseDocument, link.TargetLineId, cancellationToken).ConfigureAwait(false);
var header = target is null ? null : await HeaderAsync(uow, DocumentFamily.PurchaseDocument, target.DocumentId, cancellationToken).ConfigureAwait(false);
if (target is null || header is null || header.Kind != DocumentKind.PurchaseInvoice || !DocumentStateMachine.IsInForce(header.Status) || target.Quantity == 0m)
{
continue;
}
var lineAmount = Math.Abs(target.TaxableAmount);
if (!string.Equals(header.CurrencyCode, "EUR", StringComparison.Ordinal) && header.ExchangeRate > 0m)
{
lineAmount /= header.ExchangeRate;
}
// The invoice line in the unit of the delivery note: its share of the load is the linked quantity.
var share = Math.Abs(link.Quantity / target.Quantity);
amount += lineAmount * share;
quantity += Math.Abs(link.Quantity);
}
var source = quantity == 0m ? null : await StoreLineAsync(uow, DocumentFamily.PurchaseDocument, load.SourceLineId!.Value, cancellationToken).ConfigureAwait(false);
if (source is null || source.Quantity == 0m)
{
continue;
}
// The load is in the base unit; the invoiced part of the delivery line is quantity / source.Quantity of it.
var baseQuantity = load.Quantity * (quantity / Math.Abs(source.Quantity));
if (baseQuantity > 0m && amount > 0m)
{
result[load.Id] = Math.Round(amount / baseQuantity, StockCostCalculator.CostDecimals, MidpointRounding.AwayFromZero);
}
}
return result;
}
// The quantities still to deliver of the open orders of a family, by item and warehouse of the line.
private static async Task<Dictionary<(long, long?), decimal>> OpenQuantitiesAsync<THeader, TLine>(IUnitOfWork uow, List<long> itemIds, CancellationToken cancellationToken)
where THeader : DocumentHeader, new()
where TLine : DocumentLine, new()
{
var result = new Dictionary<(long, long?), decimal>();
var ids = itemIds.Select(i => (long?)i).ToList();
var lines = (await uow.Repository<TLine, long>().ListAsync(
Query.For<TLine>().Where(l => ids.Contains(l.ItemId) && !l.FulfillmentClosed), cancellationToken).ConfigureAwait(false)).Items;
if (lines.Count == 0)
{
return result;
}
var documentIds = lines.Select(l => l.DocumentId).Distinct().ToList();
var open = (await uow.Repository<THeader, long>().ListAsync(
Query.For<THeader>().Where(h => documentIds.Contains(h.Id) && (h.Status == DocumentStatus.Confirmed || h.Status == DocumentStatus.PartiallyFulfilled)), cancellationToken)
.ConfigureAwait(false)).Items.ToDictionary(h => h.Id);
if (open.Count == 0)
{
return result;
}
var catalog = (await uow.Repository<Item, long>().ListAsync(Query.For<Item>().Where(i => itemIds.Contains(i.Id)), cancellationToken).ConfigureAwait(false)).Items
.ToDictionary(i => i.Id);
var units = (await uow.Repository<ItemUnit, long>().ListAsync(Query.For<ItemUnit>().Where(u => itemIds.Contains(u.ItemId)), cancellationToken).ConfigureAwait(false)).Items;
foreach (var line in lines)
{
if (!open.TryGetValue(line.DocumentId, out var header) || !catalog.TryGetValue(line.ItemId!.Value, out var item) || !item.Stocked)
{
continue;
}
var residual = line.Quantity - line.FulfilledQuantity;
if (residual <= 0m)
{
continue;
}
var key = (item.Id, line.WarehouseId ?? header.WarehouseId);
result[key] = result.GetValueOrDefault(key) + ToBase(residual, line.UnitOfMeasureId, item, units);
}
return result;
}
private static Task<DocumentHeader?> HeaderAsync(IUnitOfWork uow, DocumentFamily family, long id, CancellationToken cancellationToken) =>
Documents.DocumentStores.Of(family).GetAsync(uow, id, cancellationToken);
private static Task<List<DocumentLine>> LinesAsync(IUnitOfWork uow, DocumentFamily family, long id, CancellationToken cancellationToken) =>
Documents.DocumentStores.Of(family).LinesAsync(uow, id, cancellationToken);
private static Task<DocumentLine?> StoreLineAsync(IUnitOfWork uow, DocumentFamily family, long id, CancellationToken cancellationToken) =>
Documents.DocumentStores.Of(family).GetLineAsync(uow, id, cancellationToken);
}
/// <summary>The step of a rebuild.</summary>
public enum RebuildPhase
{
/// <summary>Posting the documents.</summary>
Documents = 0,
/// <summary>Computing the items.</summary>
Items = 1,
}
/// <summary>How far a rebuild is.</summary>
/// <param name="Phase">The step.</param>
/// <param name="Done">How many done.</param>
/// <param name="Total">How many in all.</param>
public sealed record RebuildProgress(RebuildPhase Phase, int Done, int Total);
@@ -0,0 +1,42 @@
using System.Globalization;
using Khaemhat.Application.Jobs;
using Khaemhat.Core.Instance;
using Khaemhat.Data;
using Khaemhat.Data.Companies;
namespace Khaemhat.Application.Inventory;
/// <summary>
/// Rebuilds the warehouse of every active company from its documents, once a week at night (SPEC §11.6): a safety net
/// that brings balances and costs back in line after imports or corrections made outside the screens.
/// </summary>
/// <param name="factory">The units of work.</param>
/// <param name="companies">The companies.</param>
public sealed class InventoryRebuildJob(IUnitOfWorkFactory factory, ICompanyRegistry companies) : IScheduledJob
{
/// <summary>The job type.</summary>
public const string JobType = "inventory.rebuild";
/// <inheritdoc />
public string Type => JobType;
/// <inheritdoc />
public async Task<string?> RunAsync(JobContext context, CancellationToken cancellationToken)
{
int documents = 0, items = 0, done = 0;
foreach (var company in await companies.ListAsync(cancellationToken).ConfigureAwait(false))
{
if (company.Status is CompanyStatus.Disabled)
{
continue;
}
var (d, i) = await InventoryService.RebuildCompanyAsync(factory, company.Code, null, cancellationToken).ConfigureAwait(false);
documents += d;
items += i;
done++;
}
return string.Create(CultureInfo.InvariantCulture, $"{done} aziende, {documents} documenti, {items} articoli ricalcolati.");
}
}
@@ -0,0 +1,422 @@
using Khaemhat.Application.Items;
using Khaemhat.Application.Security;
using Khaemhat.Application.Tables;
using Khaemhat.Core.Documents;
using Khaemhat.Core.Inventory;
using Khaemhat.Core.Items;
using Khaemhat.Core.Parties;
using Khaemhat.Core.Tables;
using Khaemhat.Data;
using Khaemhat.Data.Querying;
namespace Khaemhat.Application.Inventory;
/// <summary>What the stock screen asks (mockup 036).</summary>
public sealed record StockFilter
{
/// <summary>Code, description or brand.</summary>
public string? Search { get; init; }
/// <summary>One warehouse, or all together.</summary>
public long? WarehouseId { get; init; }
/// <summary>One category.</summary>
public long? CategoryId { get; init; }
/// <summary>Only the items under their minimum stock or reorder point.</summary>
public bool UnderstockOnly { get; init; }
/// <summary>Also the items with nothing on hand, committed or ordered.</summary>
public bool IncludeEmpty { get; init; }
}
/// <summary>The state of an item under its thresholds.</summary>
public enum StockLevel
{
/// <summary>Enough.</summary>
Ok = 0,
/// <summary>The available quantity reached the reorder point.</summary>
Reorder = 1,
/// <summary>The available quantity is under the minimum stock.</summary>
Understock = 2,
/// <summary>Nothing left, or less than nothing.</summary>
Out = 3,
}
/// <summary>A row of the stock screen: an item in one warehouse or in all.</summary>
/// <param name="ItemId">The item.</param>
/// <param name="Code">Its code.</param>
/// <param name="Description">Its description.</param>
/// <param name="CategoryId">Its category.</param>
/// <param name="UnitOfMeasureId">Its base unit.</param>
/// <param name="OnHand">On hand.</param>
/// <param name="Committed">Committed to customers.</param>
/// <param name="Ordered">Ordered from suppliers.</param>
/// <param name="Available">On hand less committed.</param>
/// <param name="MinimumStock">The minimum stock.</param>
/// <param name="ReorderPoint">The reorder point.</param>
/// <param name="AverageCost">The weighted average cost (none without the permission on costs).</param>
/// <param name="Value">The value at the average (none without the permission).</param>
/// <param name="LastLoad">The last load.</param>
/// <param name="LastUnload">The last unload.</param>
/// <param name="Level">The state under the thresholds.</param>
public sealed record StockRow(
long ItemId, string Code, string Description, long? CategoryId, long? UnitOfMeasureId, decimal OnHand, decimal Committed, decimal Ordered, decimal Available,
decimal? MinimumStock, decimal? ReorderPoint, decimal? AverageCost, decimal? Value, DateOnly? LastLoad, DateOnly? LastUnload, StockLevel Level);
/// <summary>A movement of an item, with the balance after it.</summary>
/// <param name="Id">The movement.</param>
/// <param name="Date">The date.</param>
/// <param name="Family">The family of the document.</param>
/// <param name="DocumentId">The document.</param>
/// <param name="Kind">Its kind.</param>
/// <param name="Number">Its number.</param>
/// <param name="ReasonCode">The warehouse reason.</param>
/// <param name="PartyName">The customer or supplier.</param>
/// <param name="WarehouseId">The warehouse.</param>
/// <param name="Quantity">Positive loads, negative unloads.</param>
/// <param name="UnitCost">The cost (none without the permission).</param>
/// <param name="Value">The value (none without the permission).</param>
/// <param name="Balance">The balance after the movement, in the warehouses shown.</param>
public sealed record MovementRow(
long Id, DateOnly Date, DocumentFamily? Family, long? DocumentId, DocumentKind? Kind, string? Number, string? ReasonCode, string? PartyName, long WarehouseId,
decimal Quantity, decimal? UnitCost, decimal? Value, decimal Balance);
/// <summary>The value of an item at a date (closing stock, libro inventari).</summary>
/// <param name="ItemId">The item.</param>
/// <param name="Code">Its code.</param>
/// <param name="Description">Its description.</param>
/// <param name="Quantity">On hand at the date.</param>
/// <param name="UnitCost">The cost of the method.</param>
/// <param name="Value">Quantity times cost.</param>
/// <param name="AbcClass">A (the first 80% of the value), B (up to 95%) or C.</param>
public sealed record ValuationRow(long ItemId, string Code, string Description, decimal Quantity, decimal UnitCost, decimal Value, char AbcClass);
/// <summary>
/// The warehouse as people read it (SPEC §11.6, mockups 036-037): stock and availability, the movements of an item,
/// the value at a date. The balances are kept by <see cref="InventoryPoster"/>; this service only reads them.
/// </summary>
/// <remarks>Permission <c>inventory.stock.read</c>, movements <c>inventory.entry.read</c>; costs only with <c>items.cost.read</c>.</remarks>
public sealed class InventoryService
{
/// <summary>Permission to read the stock.</summary>
public const string StockPermission = "inventory.stock.read";
/// <summary>Permission to read the movements.</summary>
public const string EntryReadPermission = "inventory.entry.read";
/// <summary>Permission to post movements, stock takes and the rebuild.</summary>
public const string PostPermission = "inventory.entry.post";
private readonly IUnitOfWorkFactory _factory;
private readonly PermissionService _permissions;
/// <summary>Creates the service.</summary>
/// <param name="factory">The units of work.</param>
/// <param name="permissions">The permissions.</param>
public InventoryService(IUnitOfWorkFactory factory, PermissionService permissions)
{
ArgumentNullException.ThrowIfNull(factory);
ArgumentNullException.ThrowIfNull(permissions);
_factory = factory;
_permissions = permissions;
}
/// <summary>The stock of the items, in a warehouse or in all.</summary>
/// <param name="actor">Who reads.</param>
/// <param name="companyCode">The company.</param>
/// <param name="filter">What to show.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The rows, by code.</returns>
public async Task<IReadOnlyList<StockRow>> StockAsync(Actor actor, string companyCode, StockFilter filter, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(filter);
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, StockPermission, cancellationToken).ConfigureAwait(false);
var costs = await CostsAsync(actor, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
var query = Query.For<Item>().Where(i => i.Stocked && i.Kind == ItemKind.Goods && !i.Disabled);
if (filter.CategoryId is { } category)
{
query = query.Where(i => i.CategoryId == category);
}
if (filter.Search?.Trim() is { Length: > 0 } text)
{
query = query.Where(i => i.Code.Contains(text) || i.Description.Contains(text) || (i.Brand != null && i.Brand.Contains(text)));
}
var items = (await uow.Repository<Item, long>().ListAsync(query.OrderBy(i => i.Code), cancellationToken).ConfigureAwait(false)).Items;
var balances = await BalancesByItemAsync(uow, filter.WarehouseId, cancellationToken).ConfigureAwait(false);
var rows = new List<StockRow>();
foreach (var item in items)
{
var mine = balances.GetValueOrDefault(item.Id) ?? [];
var row = RowOf(item, mine, costs);
if (!filter.IncludeEmpty && mine.Count == 0)
{
// No movement and no order: shown only when asked, or when it has a minimum to keep.
if (row.Level == StockLevel.Ok)
{
continue;
}
}
if (filter.UnderstockOnly && row.Level == StockLevel.Ok)
{
continue;
}
rows.Add(row);
}
return rows;
}
/// <summary>The balances of an item in each warehouse.</summary>
/// <param name="actor">Who reads.</param>
/// <param name="companyCode">The company.</param>
/// <param name="itemId">The item.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The balances, costs hidden without the permission.</returns>
public async Task<IReadOnlyList<ItemBalance>> BalancesAsync(Actor actor, string companyCode, long itemId, CancellationToken cancellationToken = default)
{
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, StockPermission, cancellationToken).ConfigureAwait(false);
var costs = await CostsAsync(actor, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
var rows = (await uow.Repository<ItemBalance, long>().ListAsync(Query.For<ItemBalance>().Where(b => b.ItemId == itemId), cancellationToken).ConfigureAwait(false)).Items;
if (!costs)
{
foreach (var row in rows)
{
row.AverageCost = 0m;
row.Value = 0m;
row.LastCost = null;
}
}
return rows;
}
/// <summary>The movements of an item in a period, with the running balance (mockup 036, dialog of the item).</summary>
/// <param name="actor">Who reads.</param>
/// <param name="companyCode">The company.</param>
/// <param name="itemId">The item.</param>
/// <param name="warehouseId">One warehouse, or all.</param>
/// <param name="from">The first day, or the beginning.</param>
/// <param name="to">The last day, or today.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The movements, oldest first; the balance starts from what was on hand before <paramref name="from"/>.</returns>
public async Task<IReadOnlyList<MovementRow>> MovementsAsync(
Actor actor, string companyCode, long itemId, long? warehouseId, DateOnly? from, DateOnly? to, CancellationToken cancellationToken = default)
{
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, EntryReadPermission, cancellationToken).ConfigureAwait(false);
var costs = await CostsAsync(actor, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
var query = Query.For<InventoryEntryLine>().Where(l => l.ItemId == itemId);
if (warehouseId is { } warehouse)
{
query = query.Where(l => l.WarehouseId == warehouse);
}
var lines = (await uow.Repository<InventoryEntryLine, long>().ListAsync(query.OrderBy(l => l.EntryDate).OrderBy(l => l.EntryId).OrderBy(l => l.SortOrder), cancellationToken)
.ConfigureAwait(false)).Items;
var entryIds = lines.Select(l => l.EntryId).Distinct().ToList();
var entries = entryIds.Count == 0 ? [] : (await uow.Repository<InventoryEntry, long>().ListAsync(Query.For<InventoryEntry>().Where(e => entryIds.Contains(e.Id)), cancellationToken)
.ConfigureAwait(false)).Items.ToDictionary(e => e.Id);
var reasons = (await uow.Repository<InventoryReason, long>().ListAsync(Query.For<InventoryReason>(), cancellationToken).ConfigureAwait(false)).Items.ToDictionary(r => r.Id, r => r.Code);
var partyIds = entries.Values.Where(e => e.PartyId is not null).Select(e => e.PartyId!.Value).Distinct().ToList();
var parties = partyIds.Count == 0 ? [] : (await uow.Repository<Party, long>().ListAsync(Query.For<Party>().Where(p => partyIds.Contains(p.Id)), cancellationToken)
.ConfigureAwait(false)).Items.ToDictionary(p => p.Id, p => p.Name);
var result = new List<MovementRow>();
var balance = 0m;
foreach (var line in lines)
{
balance += line.Quantity;
if ((from is { } first && line.EntryDate < first) || (to is { } last && line.EntryDate > last))
{
continue;
}
var entry = entries.GetValueOrDefault(line.EntryId);
result.Add(new MovementRow(
line.Id, line.EntryDate, entry?.SourceFamily, entry?.SourceDocumentId, entry?.SourceKind, entry?.SourceNumber,
entry?.InventoryReasonId is { } r ? reasons.GetValueOrDefault(r) : null,
entry?.PartyId is { } p ? parties.GetValueOrDefault(p) : null,
line.WarehouseId, line.Quantity, costs ? line.UnitCost : null, costs ? line.Value : null, balance));
}
return result;
}
/// <summary>
/// The value of the stock at a date (closing stock, libro inventari): the history of each item up to that day,
/// valued with a method, with its ABC class by value.
/// </summary>
/// <param name="actor">Who reads: needs the permission on costs too.</param>
/// <param name="companyCode">The company.</param>
/// <param name="date">The day.</param>
/// <param name="warehouseId">One warehouse, or all.</param>
/// <param name="method">The cost used.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The items with something on hand, by value.</returns>
public async Task<IReadOnlyList<ValuationRow>> ValuationAsync(
Actor actor, string companyCode, DateOnly date, long? warehouseId, StockValuationMethod method, CancellationToken cancellationToken = default)
{
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, StockPermission, cancellationToken).ConfigureAwait(false);
await _permissions.DemandAsync(actor, ItemService.CostPermission, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
var lines = (await uow.Repository<InventoryEntryLine, long>().ListAsync(
Query.For<InventoryEntryLine>().Where(l => l.EntryDate <= date).OrderBy(l => l.EntryDate).OrderBy(l => l.EntryId).OrderBy(l => l.SortOrder), cancellationToken)
.ConfigureAwait(false)).Items;
var itemIds = lines.Select(l => l.ItemId).Distinct().ToList();
var items = itemIds.Count == 0 ? [] : (await uow.Repository<Item, long>().ListAsync(Query.For<Item>().Where(i => itemIds.Contains(i.Id)), cancellationToken)
.ConfigureAwait(false)).Items.ToDictionary(i => i.Id);
var rows = new List<ValuationRow>();
foreach (var group in lines.GroupBy(l => l.ItemId))
{
if (!items.TryGetValue(group.Key, out var item))
{
continue;
}
// The costs written on the movements are those of the last run: the history up to the day gives the average then.
var history = StockCostCalculator.Run(group.Select(l => new CostedMovement(l.Id, l.EntryDate, l.WarehouseId, l.Quantity, l.Valued, l.Valued ? l.UnitCost : 0m)), item.StandardCost ?? 0m);
var quantity = warehouseId is { } w ? history.Warehouses.GetValueOrDefault(w)?.OnHand ?? 0m : history.OnHand;
if (quantity == 0m)
{
continue;
}
var cost = method switch
{
StockValuationMethod.LastCost => history.LastCost ?? history.AverageCost,
StockValuationMethod.StandardCost => item.StandardCost ?? history.AverageCost,
_ => history.AverageCost,
};
rows.Add(new ValuationRow(item.Id, item.Code, item.Description, quantity, cost, StockCostCalculator.Value(quantity, cost), 'C'));
}
return Classify(rows);
}
/// <summary>The items under their thresholds, the most urgent first (dashboard widget and reorder).</summary>
/// <param name="actor">Who reads.</param>
/// <param name="companyCode">The company.</param>
/// <param name="limit">How many.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The rows.</returns>
public async Task<IReadOnlyList<StockRow>> UnderstockAsync(Actor actor, string companyCode, int limit = 10, CancellationToken cancellationToken = default)
{
var rows = await StockAsync(actor, companyCode, new StockFilter { UnderstockOnly = true }, cancellationToken).ConfigureAwait(false);
return [.. rows.OrderByDescending(r => r.Level).ThenBy(r => r.Available - (r.MinimumStock ?? r.ReorderPoint ?? 0m)).ThenBy(r => r.Code, StringComparer.Ordinal).Take(limit)];
}
/// <summary>
/// Rebuilds the warehouse of the company from its documents (SPEC §11.6): every movement is written again and every
/// item computed again, in one transaction.
/// </summary>
/// <param name="actor">Who rebuilds: needs <c>inventory.entry.post</c>.</param>
/// <param name="companyCode">The company.</param>
/// <param name="progress">How far it is.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The documents posted and the items computed.</returns>
public async Task<(int Documents, int Items)> RebuildAsync(Actor actor, string companyCode, IProgress<RebuildProgress>? progress = null, CancellationToken cancellationToken = default)
{
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, PostPermission, cancellationToken).ConfigureAwait(false);
return await RebuildCompanyAsync(_factory, company, progress, cancellationToken).ConfigureAwait(false);
}
/// <summary>Rebuilds the warehouse of a company, without checks (the scheduled job).</summary>
/// <param name="factory">The units of work.</param>
/// <param name="company">The company.</param>
/// <param name="progress">How far it is.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The documents posted and the items computed.</returns>
internal static async Task<(int Documents, int Items)> RebuildCompanyAsync(
IUnitOfWorkFactory factory, string company, IProgress<RebuildProgress>? progress, CancellationToken cancellationToken)
{
await using var uow = await factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
var result = await InventoryPoster.RebuildAsync(uow, progress, cancellationToken).ConfigureAwait(false);
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
return result;
}
/// <summary>
/// The level of an item: out when nothing is available (or less than nothing), under stock below the minimum,
/// to reorder when what is available and on order no longer covers the reorder point.
/// </summary>
/// <param name="available">On hand less committed.</param>
/// <param name="ordered">Ordered from suppliers.</param>
/// <param name="minimum">The minimum stock.</param>
/// <param name="reorderPoint">The reorder point.</param>
/// <returns>The level.</returns>
public static StockLevel LevelOf(decimal available, decimal ordered, decimal? minimum, decimal? reorderPoint)
{
var watched = minimum is not null || reorderPoint is not null;
if (available < 0m || (watched && available <= 0m))
{
return StockLevel.Out;
}
if (minimum is { } min && available < min)
{
return StockLevel.Understock;
}
return reorderPoint is { } point && available + ordered <= point ? StockLevel.Reorder : StockLevel.Ok;
}
/// <summary>Gives the ABC class by value: A up to 80% of the total, B up to 95%, C the rest.</summary>
/// <param name="rows">The rows.</param>
/// <returns>The rows by value, with their class.</returns>
public static IReadOnlyList<ValuationRow> Classify(IEnumerable<ValuationRow> rows)
{
ArgumentNullException.ThrowIfNull(rows);
var sorted = rows.OrderByDescending(r => r.Value).ThenBy(r => r.Code, StringComparer.Ordinal).ToList();
var total = sorted.Where(r => r.Value > 0m).Sum(r => r.Value);
var running = 0m;
var result = new List<ValuationRow>(sorted.Count);
foreach (var row in sorted)
{
// The class of an item is where its value starts: the first item is always A.
var share = total <= 0m ? 1m : running / total;
running += Math.Max(row.Value, 0m);
result.Add(row with { AbcClass = share < 0.80m ? 'A' : share < 0.95m ? 'B' : 'C' });
}
return result;
}
internal static StockRow RowOf(Item item, IReadOnlyList<ItemBalance> balances, bool costs)
{
var onHand = balances.Sum(b => b.OnHand);
var committed = balances.Sum(b => b.Committed);
var ordered = balances.Sum(b => b.Ordered);
var available = onHand - committed;
var average = balances.Count > 0 ? balances[0].AverageCost : item.AverageCost ?? 0m;
return new StockRow(
item.Id, item.Code, item.Description, item.CategoryId, item.UnitOfMeasureId, onHand, committed, ordered, available, item.MinimumStock, item.ReorderPoint,
costs ? average : null, costs ? balances.Sum(b => b.Value) : null,
balances.Max(b => b.LastLoadDate), balances.Max(b => b.LastUnloadDate),
LevelOf(available, ordered, item.MinimumStock, item.ReorderPoint));
}
internal static async Task<Dictionary<long, List<ItemBalance>>> BalancesByItemAsync(IUnitOfWork uow, long? warehouseId, CancellationToken cancellationToken)
{
var query = Query.For<ItemBalance>();
if (warehouseId is { } warehouse)
{
query = query.Where(b => b.WarehouseId == warehouse);
}
return (await uow.Repository<ItemBalance, long>().ListAsync(query, cancellationToken).ConfigureAwait(false)).Items
.GroupBy(b => b.ItemId).ToDictionary(g => g.Key, g => g.ToList());
}
private async Task<bool> CostsAsync(Actor actor, CancellationToken cancellationToken) =>
(await _permissions.CheckAsync(actor, ItemService.CostPermission, cancellationToken).ConfigureAwait(false)).Allowed;
}
@@ -0,0 +1,183 @@
using Khaemhat.Application.Documents;
using Khaemhat.Application.Security;
using Khaemhat.Application.Tables;
using Khaemhat.Core.Documents;
using Khaemhat.Core.Items;
using Khaemhat.Core.Parties;
using Khaemhat.Data;
using Khaemhat.Data.Querying;
namespace Khaemhat.Application.Inventory;
/// <summary>An item to reorder (mockup 039).</summary>
/// <param name="ItemId">The item.</param>
/// <param name="Code">Its code.</param>
/// <param name="Description">Its description.</param>
/// <param name="UnitOfMeasureId">Its unit.</param>
/// <param name="Available">On hand less committed.</param>
/// <param name="Ordered">Already ordered.</param>
/// <param name="MinimumStock">The minimum stock.</param>
/// <param name="ReorderPoint">The reorder point.</param>
/// <param name="Quantity">The quantity proposed.</param>
/// <param name="SupplierId">The usual supplier, if any.</param>
/// <param name="SupplierName">Its name.</param>
/// <param name="Price">Its price.</param>
/// <param name="ExpectedDate">When it would arrive, from the lead time.</param>
public sealed record ReorderProposal(
long ItemId, string Code, string Description, long? UnitOfMeasureId, decimal Available, decimal Ordered, decimal? MinimumStock, decimal? ReorderPoint,
decimal Quantity, long? SupplierId, string? SupplierName, decimal? Price, DateOnly? ExpectedDate);
/// <summary>A proposal the user accepts, perhaps with another quantity or supplier.</summary>
/// <param name="ItemId">The item.</param>
/// <param name="SupplierId">The supplier.</param>
/// <param name="Quantity">The quantity.</param>
public sealed record ReorderChoice(long ItemId, long SupplierId, decimal Quantity);
/// <summary>
/// The reorder proposal (SPEC §11.6, mockup 039): the items whose available and ordered quantity no longer covers the
/// reorder point (or the minimum stock), with the quantity to order (the lot, or what brings back to the threshold, at
/// least the minimum of the supplier) and the usual supplier; accepted, the proposals become draft supplier orders,
/// one per supplier.
/// </summary>
public sealed class ReorderService
{
/// <summary>Error: a chosen line without a supplier or a quantity.</summary>
public const string ChoiceInvalid = "inventory.reorder.choice-invalid";
private readonly IUnitOfWorkFactory _factory;
private readonly PermissionService _permissions;
private readonly DocumentEngine _engine;
private readonly DocumentEditor _editor;
private readonly TimeProvider _clock;
/// <summary>Creates the service.</summary>
/// <param name="factory">The units of work.</param>
/// <param name="permissions">The permissions.</param>
/// <param name="engine">The document engine.</param>
/// <param name="editor">The editor (prices and terms of the supplier).</param>
/// <param name="clock">The clock.</param>
public ReorderService(IUnitOfWorkFactory factory, PermissionService permissions, DocumentEngine engine, DocumentEditor editor, TimeProvider clock)
{
ArgumentNullException.ThrowIfNull(factory);
ArgumentNullException.ThrowIfNull(permissions);
ArgumentNullException.ThrowIfNull(engine);
ArgumentNullException.ThrowIfNull(editor);
ArgumentNullException.ThrowIfNull(clock);
_factory = factory;
_permissions = permissions;
_engine = engine;
_editor = editor;
_clock = clock;
}
/// <summary>The items to reorder, by supplier and code.</summary>
/// <param name="actor">Who reads.</param>
/// <param name="companyCode">The company.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The proposals.</returns>
public async Task<IReadOnlyList<ReorderProposal>> ProposalsAsync(Actor actor, string companyCode, CancellationToken cancellationToken = default)
{
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, InventoryService.StockPermission, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
var items = (await uow.Repository<Item, long>().ListAsync(
Query.For<Item>().Where(i => i.Stocked && i.Kind == ItemKind.Goods && !i.Disabled && (i.MinimumStock != null || i.ReorderPoint != null)).OrderBy(i => i.Code), cancellationToken)
.ConfigureAwait(false)).Items;
if (items.Count == 0)
{
return [];
}
var balances = await InventoryService.BalancesByItemAsync(uow, null, cancellationToken).ConfigureAwait(false);
var ids = items.Select(i => i.Id).ToList();
var suppliers = (await uow.Repository<ItemSupplier, long>().ListAsync(Query.For<ItemSupplier>().Where(s => ids.Contains(s.ItemId)), cancellationToken)
.ConfigureAwait(false)).Items.GroupBy(s => s.ItemId).ToDictionary(g => g.Key, g => g.OrderByDescending(s => s.IsDefault).ThenBy(s => s.Id).First());
var partyIds = suppliers.Values.Select(s => s.PartyId).Distinct().ToList();
var names = partyIds.Count == 0 ? [] : (await uow.Repository<Party, long>().ListAsync(Query.For<Party>().Where(p => partyIds.Contains(p.Id)), cancellationToken)
.ConfigureAwait(false)).Items.ToDictionary(p => p.Id, p => p.Name);
var today = DateOnly.FromDateTime(_clock.GetLocalNow().DateTime);
var result = new List<ReorderProposal>();
foreach (var item in items)
{
var mine = balances.GetValueOrDefault(item.Id) ?? [];
var available = mine.Sum(b => b.OnHand - b.Committed);
var ordered = mine.Sum(b => b.Ordered);
var supplier = suppliers.GetValueOrDefault(item.Id);
var quantity = Quantity(available + ordered, item.MinimumStock, item.ReorderPoint, item.ReorderLot, supplier?.MinimumQuantity);
if (quantity <= 0m)
{
continue;
}
result.Add(new ReorderProposal(
item.Id, item.Code, item.Description, item.UnitOfMeasureId, available, ordered, item.MinimumStock, item.ReorderPoint, quantity,
supplier?.PartyId, supplier is null ? null : names.GetValueOrDefault(supplier.PartyId), supplier?.Price ?? item.LastCost,
supplier?.LeadTimeDays is { } days ? today.AddDays(days) : null));
}
return [.. result.OrderBy(r => r.SupplierName is null).ThenBy(r => r.SupplierName, StringComparer.CurrentCulture).ThenBy(r => r.Code, StringComparer.Ordinal)];
}
/// <summary>
/// The quantity to order: nothing while what is available and ordered covers the reorder point (or the minimum);
/// otherwise the lot of the item, or what brings back to the higher of the two thresholds, at least the minimum
/// quantity of the supplier.
/// </summary>
/// <param name="cover">Available plus ordered.</param>
/// <param name="minimum">The minimum stock.</param>
/// <param name="reorderPoint">The reorder point.</param>
/// <param name="lot">The reorder lot.</param>
/// <param name="supplierMinimum">The minimum of the supplier.</param>
/// <returns>The quantity.</returns>
public static decimal Quantity(decimal cover, decimal? minimum, decimal? reorderPoint, decimal? lot, decimal? supplierMinimum)
{
var threshold = reorderPoint ?? minimum;
if (threshold is not { } point || cover > point || (reorderPoint is null && cover >= point))
{
return 0m;
}
var target = Math.Max(minimum ?? 0m, reorderPoint ?? 0m);
var quantity = lot is > 0m ? lot.Value : Math.Max(target - cover, 0m);
if (lot is > 0m && cover + quantity < target)
{
// One lot is not enough: as many lots as it takes.
quantity = Math.Ceiling((target - cover) / lot.Value) * lot.Value;
}
return Math.Max(quantity, supplierMinimum ?? 0m);
}
/// <summary>Creates the draft supplier orders of the chosen proposals, one per supplier.</summary>
/// <param name="actor">Who orders: needs <c>purchases.order.write</c>.</param>
/// <param name="companyCode">The company.</param>
/// <param name="choices">The proposals accepted.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The orders, saved as drafts.</returns>
public async Task<IReadOnlyList<DocumentRecord>> CreateOrdersAsync(Actor actor, string companyCode, IReadOnlyList<ReorderChoice> choices, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(choices);
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, "purchases.order.write", cancellationToken).ConfigureAwait(false);
if (choices.Any(c => c.Quantity <= 0m || c.SupplierId <= 0))
{
throw new ValidationFailedException([":" + ChoiceInvalid]);
}
var result = new List<DocumentRecord>();
foreach (var group in choices.GroupBy(c => c.SupplierId))
{
var order = await _engine.NewAsync(actor, company, "OF", cancellationToken).ConfigureAwait(false);
await _editor.ApplyPartyAsync(actor, company, order, group.Key, cancellationToken).ConfigureAwait(false);
foreach (var choice in group)
{
var line = new PurchaseOrderLine { Kind = DocumentLineKind.Item, ItemId = choice.ItemId, Quantity = choice.Quantity };
order.Lines.Add(line);
await _editor.FillLineAsync(actor, company, order, line, choice.ItemId, cancellationToken).ConfigureAwait(false);
line.Quantity = choice.Quantity;
}
result.Add(await _engine.SaveAsync(actor, company, order, cancellationToken).ConfigureAwait(false));
}
return result;
}
}
@@ -0,0 +1,405 @@
using System.Globalization;
using System.Text;
using Khaemhat.Application.Documents;
using Khaemhat.Application.Security;
using Khaemhat.Application.Tables;
using Khaemhat.Core.Documents;
using Khaemhat.Core.Inventory;
using Khaemhat.Core.Items;
using Khaemhat.Core.Tables;
using Khaemhat.Data;
using Khaemhat.Data.Querying;
namespace Khaemhat.Application.Inventory;
/// <summary>A line of a stock take with its item.</summary>
/// <param name="Line">The line.</param>
/// <param name="Code">The code of the item.</param>
/// <param name="Description">Its description.</param>
/// <param name="UnitOfMeasureId">Its base unit.</param>
public sealed record StockTakeLineView(StockTakeLine Line, string Code, string Description, long? UnitOfMeasureId);
/// <summary>A stock take with its lines.</summary>
/// <param name="Take">The stock take.</param>
/// <param name="Lines">Its lines, by code.</param>
public sealed record StockTakeView(StockTake Take, IReadOnlyList<StockTakeLineView> Lines)
{
/// <summary>How many lines are counted.</summary>
public int Counted => Lines.Count(l => l.Line.CountedQuantity is not null);
/// <summary>The value of the differences at the cost of the lines.</summary>
public decimal DifferenceValue => Lines.Sum(l => StockCostCalculator.Value(l.Line.Difference, l.Line.UnitCost));
}
/// <summary>What the import of the counts found.</summary>
/// <param name="Applied">The lines counted.</param>
/// <param name="Unknown">The codes not on the list, with their row.</param>
public sealed record StockCountImport(int Applied, IReadOnlyList<string> Unknown);
/// <summary>
/// The physical inventory (SPEC §11.6, mockup 038): a list of the items of a warehouse with what the books say at the
/// date, the counts typed or read from a file, and the posting that writes the differences as two warehouse movements
/// (gains with reason INVP, losses with INVN) through the document engine.
/// </summary>
/// <remarks>Permissions <c>inventory.entry.read</c>, <c>write</c> (lists and counts) and <c>post</c>.</remarks>
public sealed class StockTakeService
{
/// <summary>Error: the stock take is no longer open.</summary>
public const string NotOpen = "inventory.stock-take.not-open";
/// <summary>Error: nothing is counted.</summary>
public const string NothingCounted = "inventory.stock-take.nothing-counted";
/// <summary>Error: a counted quantity below zero.</summary>
public const string NegativeCount = "inventory.stock-take.negative";
/// <summary>Error: the reasons of the adjustments are missing from the base tables.</summary>
public const string ReasonMissing = "inventory.stock-take.reason-missing";
/// <summary>The reason of the gains.</summary>
public const string GainReason = "INVP";
/// <summary>The reason of the losses.</summary>
public const string LossReason = "INVN";
private readonly IUnitOfWorkFactory _factory;
private readonly PermissionService _permissions;
private readonly DocumentEngine _engine;
private readonly TimeProvider _clock;
/// <summary>Creates the service.</summary>
/// <param name="factory">The units of work.</param>
/// <param name="permissions">The permissions.</param>
/// <param name="engine">The document engine, for the adjustments.</param>
/// <param name="clock">The clock.</param>
public StockTakeService(IUnitOfWorkFactory factory, PermissionService permissions, DocumentEngine engine, TimeProvider clock)
{
ArgumentNullException.ThrowIfNull(factory);
ArgumentNullException.ThrowIfNull(permissions);
ArgumentNullException.ThrowIfNull(engine);
ArgumentNullException.ThrowIfNull(clock);
_factory = factory;
_permissions = permissions;
_engine = engine;
_clock = clock;
}
/// <summary>The stock takes, the latest first.</summary>
/// <param name="actor">Who reads.</param>
/// <param name="companyCode">The company.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The stock takes.</returns>
public async Task<IReadOnlyList<StockTake>> ListAsync(Actor actor, string companyCode, CancellationToken cancellationToken = default)
{
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, InventoryService.EntryReadPermission, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
return (await uow.Repository<StockTake, long>().ListAsync(Query.For<StockTake>().OrderByDescending(t => t.TakeDate).OrderByDescending(t => t.Id), cancellationToken)
.ConfigureAwait(false)).Items;
}
/// <summary>A stock take with its lines.</summary>
/// <param name="actor">Who reads.</param>
/// <param name="companyCode">The company.</param>
/// <param name="id">The stock take.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The stock take, or none.</returns>
public async Task<StockTakeView?> GetAsync(Actor actor, string companyCode, long id, CancellationToken cancellationToken = default)
{
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, InventoryService.EntryReadPermission, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
return await ViewAsync(uow, id, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Opens a stock take: the stocked goods of the warehouse (of a category, if given) with the quantity the books
/// give at the date and the average cost.
/// </summary>
/// <param name="actor">Who opens it.</param>
/// <param name="companyCode">The company.</param>
/// <param name="warehouseId">The warehouse.</param>
/// <param name="date">The day of the count.</param>
/// <param name="categoryId">Only a category.</param>
/// <param name="description">A description; the warehouse and date when empty.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The new stock take.</returns>
public async Task<StockTakeView> CreateAsync(
Actor actor, string companyCode, long warehouseId, DateOnly date, long? categoryId, string? description, CancellationToken cancellationToken = default)
{
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, "inventory.entry.write", cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
var warehouse = await uow.Repository<Warehouse, long>().GetAsync(warehouseId, cancellationToken).ConfigureAwait(false)
?? throw new ValidationFailedException([nameof(StockTake.WarehouseId) + ":" + "inventory.warehouse.missing"]);
var query = Query.For<Item>().Where(i => i.Stocked && i.Kind == ItemKind.Goods && !i.Disabled);
if (categoryId is { } category)
{
query = query.Where(i => i.CategoryId == category);
}
var items = (await uow.Repository<Item, long>().ListAsync(query.OrderBy(i => i.Code), cancellationToken).ConfigureAwait(false)).Items;
var book = await BookAsync(uow, warehouseId, date, cancellationToken).ConfigureAwait(false);
var balances = (await uow.Repository<ItemBalance, long>().ListAsync(Query.For<ItemBalance>().Where(b => b.WarehouseId == warehouseId), cancellationToken)
.ConfigureAwait(false)).Items.ToDictionary(b => b.ItemId);
var take = new StockTake
{
TakeDate = date,
WarehouseId = warehouseId,
CategoryId = categoryId,
Description = string.IsNullOrWhiteSpace(description)
? "Inventario " + warehouse.Code + " al " + date.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture)
: description.Trim()[..Math.Min(description.Trim().Length, 100)],
Status = StockTakeStatus.Open,
};
await uow.Repository<StockTake, long>().InsertAsync(take, cancellationToken).ConfigureAwait(false);
var lines = uow.Repository<StockTakeLine, long>();
var order = 0;
foreach (var item in items)
{
await lines.InsertAsync(
new StockTakeLine
{
StockTakeId = take.Id,
ItemId = item.Id,
BookQuantity = book.GetValueOrDefault(item.Id),
UnitCost = balances.TryGetValue(item.Id, out var balance) ? balance.AverageCost : item.AverageCost ?? item.StandardCost ?? 0m,
SortOrder = ++order,
},
cancellationToken).ConfigureAwait(false);
}
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
return (await ViewAsync(uow, take.Id, cancellationToken).ConfigureAwait(false))!;
}
/// <summary>Writes the counts typed on the list; an empty count means not counted yet.</summary>
/// <param name="actor">Who counts.</param>
/// <param name="companyCode">The company.</param>
/// <param name="id">The stock take.</param>
/// <param name="counts">The counted quantity of each line, by line.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The stock take.</returns>
public async Task<StockTakeView> SaveCountsAsync(
Actor actor, string companyCode, long id, IReadOnlyDictionary<long, decimal?> counts, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(counts);
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, "inventory.entry.write", cancellationToken).ConfigureAwait(false);
if (counts.Values.Any(v => v < 0m))
{
throw new ValidationFailedException(["CountedQuantity:" + NegativeCount]);
}
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
await OpenTakeAsync(uow, id, cancellationToken).ConfigureAwait(false);
var repository = uow.Repository<StockTakeLine, long>();
foreach (var line in (await repository.ListAsync(Query.For<StockTakeLine>().Where(l => l.StockTakeId == id), cancellationToken).ConfigureAwait(false)).Items)
{
if (counts.TryGetValue(line.Id, out var counted) && counted != line.CountedQuantity)
{
line.CountedQuantity = counted;
await repository.UpdateAsync(line, cancellationToken).ConfigureAwait(false);
}
}
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
return (await ViewAsync(uow, id, cancellationToken).ConfigureAwait(false))!;
}
/// <summary>
/// Reads the counts from a text file (from a barcode reader or a spreadsheet): one row per item, the code and the
/// quantity separated by semicolon, tab or comma; a header and empty rows are skipped; the same code twice adds up.
/// </summary>
/// <param name="actor">Who counts.</param>
/// <param name="companyCode">The company.</param>
/// <param name="id">The stock take.</param>
/// <param name="content">The file.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>How many lines were counted and the codes not on the list.</returns>
public async Task<StockCountImport> ImportCountsAsync(Actor actor, string companyCode, long id, Stream content, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(content);
var view = await GetAsync(actor, companyCode, id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(NotOpen);
var byCode = view.Lines.ToDictionary(l => l.Code, l => l.Line.Id, StringComparer.OrdinalIgnoreCase);
var counts = new Dictionary<long, decimal?>();
var unknown = new List<string>();
using var reader = new StreamReader(content, Encoding.UTF8, detectEncodingFromByteOrderMarks: true);
var row = 0;
while (await reader.ReadLineAsync(cancellationToken).ConfigureAwait(false) is { } text)
{
row++;
if (ParseCount(text) is not { } parsed)
{
continue;
}
var (code, quantity) = parsed;
if (byCode.TryGetValue(code, out var lineId))
{
counts[lineId] = (counts.GetValueOrDefault(lineId) ?? 0m) + quantity;
}
else
{
unknown.Add(row.ToString(CultureInfo.InvariantCulture) + ": " + code);
}
}
if (counts.Count > 0)
{
await SaveCountsAsync(actor, companyCode, id, counts, cancellationToken).ConfigureAwait(false);
}
return new StockCountImport(counts.Count, unknown);
}
/// <summary>
/// Posts a stock take: the counted lines that differ from the books become a movement of gains (INVP, at the cost
/// of the line) and one of losses (INVN), confirmed at the date of the count. The lines not counted are left as
/// they are.
/// </summary>
/// <param name="actor">Who posts: needs <c>inventory.entry.post</c>.</param>
/// <param name="companyCode">The company.</param>
/// <param name="id">The stock take.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The stock take as posted.</returns>
public async Task<StockTakeView> PostAsync(Actor actor, string companyCode, long id, CancellationToken cancellationToken = default)
{
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, InventoryService.PostPermission, cancellationToken).ConfigureAwait(false);
StockTakeView view;
long? gainReason, lossReason;
await using (var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false))
{
await OpenTakeAsync(uow, id, cancellationToken).ConfigureAwait(false);
view = (await ViewAsync(uow, id, cancellationToken).ConfigureAwait(false))!;
var reasons = (await uow.Repository<InventoryReason, long>().ListAsync(Query.For<InventoryReason>(), cancellationToken).ConfigureAwait(false)).Items;
gainReason = reasons.FirstOrDefault(r => r.Code == GainReason)?.Id;
lossReason = reasons.FirstOrDefault(r => r.Code == LossReason)?.Id;
}
if (view.Counted == 0)
{
throw new ValidationFailedException([":" + NothingCounted]);
}
if (gainReason is null || lossReason is null)
{
throw new ValidationFailedException([":" + ReasonMissing]);
}
var take = view.Take;
var gains = view.Lines.Where(l => l.Line.CountedQuantity is not null && l.Line.Difference > 0m).ToList();
var losses = view.Lines.Where(l => l.Line.CountedQuantity is not null && l.Line.Difference < 0m).ToList();
take.AdjustmentDocumentId = await AdjustAsync(actor, company, take, gainReason.Value, gains, cancellationToken).ConfigureAwait(false);
take.LossDocumentId = await AdjustAsync(actor, company, take, lossReason.Value, losses, cancellationToken).ConfigureAwait(false);
take.Status = StockTakeStatus.Posted;
take.PostedAt = _clock.GetUtcNow().UtcDateTime;
take.PostedBy = actor.UserName;
await using (var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false))
{
await uow.Repository<StockTake, long>().UpdateAsync(take, cancellationToken).ConfigureAwait(false);
return (await ViewAsync(uow, id, cancellationToken).ConfigureAwait(false))!;
}
}
/// <summary>Cancels an open stock take; its counts stay for the record.</summary>
/// <param name="actor">Who cancels.</param>
/// <param name="companyCode">The company.</param>
/// <param name="id">The stock take.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
public async Task CancelAsync(Actor actor, string companyCode, long id, CancellationToken cancellationToken = default)
{
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, "inventory.entry.write", cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
var take = await OpenTakeAsync(uow, id, cancellationToken).ConfigureAwait(false);
take.Status = StockTakeStatus.Cancelled;
await uow.Repository<StockTake, long>().UpdateAsync(take, cancellationToken).ConfigureAwait(false);
}
/// <summary>A code and a quantity from a row of a count file, or none for a header or an empty row.</summary>
/// <param name="text">The row.</param>
/// <returns>The code and the quantity.</returns>
public static (string Code, decimal Quantity)? ParseCount(string? text)
{
if (string.IsNullOrWhiteSpace(text))
{
return null;
}
var separator = text.Contains(';', StringComparison.Ordinal) ? ';' : text.Contains('\t', StringComparison.Ordinal) ? '\t' : ',';
var parts = text.Split(separator, StringSplitOptions.TrimEntries);
if (parts.Length < 2 || parts[0].Length == 0)
{
return null;
}
var number = parts[1].Trim('"');
// With a comma as separator the quantity is in the invariant form; otherwise the Italian one is accepted too.
var parsed = separator == ','
? decimal.TryParse(number, NumberStyles.Number, CultureInfo.InvariantCulture, out var value)
: decimal.TryParse(number.Replace(".", string.Empty, StringComparison.Ordinal), NumberStyles.Number, CultureInfo.GetCultureInfo("it-IT"), out value);
return parsed && value >= 0m ? (parts[0].Trim('"'), value) : null;
}
// The quantity of each item in a warehouse at the end of a day.
internal static async Task<Dictionary<long, decimal>> BookAsync(IUnitOfWork uow, long warehouseId, DateOnly date, CancellationToken cancellationToken) =>
(await uow.Repository<InventoryEntryLine, long>().ListAsync(
Query.For<InventoryEntryLine>().Where(l => l.WarehouseId == warehouseId && l.EntryDate <= date), cancellationToken).ConfigureAwait(false)).Items
.GroupBy(l => l.ItemId).ToDictionary(g => g.Key, g => g.Sum(l => l.Quantity));
private async Task<long?> AdjustAsync(
Actor actor, string company, StockTake take, long reasonId, List<StockTakeLineView> lines, CancellationToken cancellationToken)
{
if (lines.Count == 0)
{
return null;
}
var entry = await _engine.NewAsync(actor, company, "MM", cancellationToken).ConfigureAwait(false);
entry.Header.DocumentDate = take.TakeDate;
entry.Header.InventoryReasonId = reasonId;
entry.Header.WarehouseId = take.WarehouseId;
entry.Header.ExternalReference = take.Description.Length > 40 ? take.Description[..40] : take.Description;
entry.Header.IsDemo = take.IsDemo;
foreach (var line in lines)
{
entry.Lines.Add(new InventoryDocumentLine
{
Kind = DocumentLineKind.Item,
ItemId = line.Line.ItemId,
Description = line.Description,
UnitOfMeasureId = line.UnitOfMeasureId,
Quantity = Math.Abs(line.Line.Difference),
Price = line.Line.UnitCost,
WarehouseId = take.WarehouseId,
});
}
entry = await _engine.SaveAsync(actor, company, entry, cancellationToken).ConfigureAwait(false);
return (await _engine.ConfirmAsync(actor, company, DocumentFamily.InventoryDocument, entry.Header.Id, cancellationToken).ConfigureAwait(false)).Header.Id;
}
private static async Task<StockTake> OpenTakeAsync(IUnitOfWork uow, long id, CancellationToken cancellationToken)
{
var take = await uow.Repository<StockTake, long>().GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(NotOpen);
return take.Status == StockTakeStatus.Open ? take : throw new ValidationFailedException([":" + NotOpen]);
}
private static async Task<StockTakeView?> ViewAsync(IUnitOfWork uow, long id, CancellationToken cancellationToken)
{
if (await uow.Repository<StockTake, long>().GetAsync(id, cancellationToken).ConfigureAwait(false) is not { } take)
{
return null;
}
var lines = (await uow.Repository<StockTakeLine, long>().ListAsync(Query.For<StockTakeLine>().Where(l => l.StockTakeId == id).OrderBy(l => l.SortOrder), cancellationToken)
.ConfigureAwait(false)).Items;
var ids = lines.Select(l => l.ItemId).Distinct().ToList();
var items = ids.Count == 0 ? [] : (await uow.Repository<Item, long>().ListAsync(Query.For<Item>().Where(i => ids.Contains(i.Id)), cancellationToken).ConfigureAwait(false))
.Items.ToDictionary(i => i.Id);
return new StockTakeView(take, [.. lines.Select(l => items.TryGetValue(l.ItemId, out var item)
? new StockTakeLineView(l, item.Code, item.Description, item.UnitOfMeasureId)
: new StockTakeLineView(l, "?", string.Empty, null))]);
}
}
@@ -50,7 +50,7 @@ public sealed record SystemTaskDefinition(string Code, string Name, string JobTy
/// </summary>
public sealed class JobScheduler
{
/// <summary>The system tasks (M2, attachments trash from M3, ECB rates from M4).</summary>
/// <summary>The system tasks (M2, attachments trash from M3, ECB rates from M4, warehouse rebuild from M6).</summary>
public static readonly IReadOnlyList<SystemTaskDefinition> SystemTasks =
[
new("system.sessions-cleanup", "Pulizia sessioni scadute", SessionCleanupJob.JobType, "15 * * * *", 300),
@@ -58,6 +58,8 @@ public sealed class JobScheduler
new("system.log-retention", "Conservazione del log", LogRetentionJob.JobType, "30 3 * * *", 1800),
new("system.attachments-trash", "Svuotamento cestino allegati", Files.AttachmentTrashPurgeJob.JobType, "45 3 * * *", 1800),
new("system.ecb-rates", "Cambi di riferimento BCE", Tables.EcbRatesJob.JobType, "30 16 * * 1-5", 300, UsesNetwork: true),
new("inventory.rebuild", "Ricostruzione del magazzino", Inventory.InventoryRebuildJob.JobType, "15 2 * * 0", 3600),
new("ledger.recurring", "Registrazioni ricorrenti", Ledger.RecurringEntriesJob.JobType, "0 5 * * *", 1800),
];
private readonly IUnitOfWorkFactory _factory;
@@ -0,0 +1,562 @@
using Khaemhat.Application.Audit;
using Khaemhat.Application.Security;
using Khaemhat.Application.Tables;
using Khaemhat.Core.Accounting;
using Khaemhat.Core.Parties;
using Khaemhat.Core.Tables;
using Khaemhat.Data;
using Khaemhat.Data.Querying;
namespace Khaemhat.Application.Ledger;
/// <summary>An entry with its lines and VAT lines.</summary>
/// <param name="Entry">The entry.</param>
/// <param name="Lines">The lines.</param>
/// <param name="Vat">The VAT lines.</param>
/// <param name="PartyName">The name of the customer or supplier of the entry.</param>
public sealed record EntryView(GlEntry Entry, IReadOnlyList<GlEntryLine> Lines, IReadOnlyList<GlEntryVat> Vat, string? PartyName)
{
/// <summary>Debit minus credit.</summary>
public decimal Difference => Lines.Sum(l => l.Debit - l.Credit);
}
/// <summary>An entry as the journal lists it.</summary>
/// <param name="Entry">The entry.</param>
/// <param name="PartyName">The customer or supplier.</param>
public sealed record EntryRow(GlEntry Entry, string? PartyName);
/// <summary>What the journal list shows.</summary>
/// <param name="From">From this day.</param>
/// <param name="To">Up to this day.</param>
/// <param name="Status">Only this state.</param>
/// <param name="TemplateCode">Only this template.</param>
/// <param name="Text">Text in the description or the document number.</param>
/// <param name="Offset">The first row.</param>
/// <param name="Limit">How many rows.</param>
public sealed record EntryFilter(
DateOnly? From = null, DateOnly? To = null, GlEntryStatus? Status = null, string? TemplateCode = null, string? Text = null, int Offset = 0, int Limit = 50);
/// <summary>An entry typed in the journal.</summary>
/// <param name="Id">The entry, for a change.</param>
/// <param name="EntryDate">The date of registration.</param>
/// <param name="Description">The description.</param>
/// <param name="Lines">The lines.</param>
public sealed record EntryInput(long? Id, DateOnly EntryDate, string Description, IReadOnlyList<EntryLineDraft> Lines)
{
/// <summary>The template.</summary>
public long? JournalTemplateId { get; init; }
/// <summary>The date of competence.</summary>
public DateOnly? CompetenceDate { get; init; }
/// <summary>The number of the document.</summary>
public string? DocumentNumber { get; init; }
/// <summary>The date of the document.</summary>
public DateOnly? DocumentDate { get; init; }
/// <summary>The customer or supplier.</summary>
public long? PartyId { get; init; }
/// <summary>The VAT register.</summary>
public long? VatRegisterId { get; init; }
/// <summary>The VAT date.</summary>
public DateOnly? VatDate { get; init; }
/// <summary>The VAT lines.</summary>
public IReadOnlyList<EntryVatDraft> Vat { get; init; } = [];
/// <summary>Notes.</summary>
public string? Notes { get; init; }
/// <summary>Post it (it must balance) rather than keep it as a draft.</summary>
public bool Post { get; init; }
}
/// <summary>A journal template with its lines, for the guided entry.</summary>
/// <param name="Template">The template.</param>
/// <param name="Lines">Its lines.</param>
public sealed record TemplateView(JournalTemplate Template, IReadOnlyList<JournalTemplateLine> Lines);
/// <summary>
/// The journal (prima nota, SPEC §11.7, issue #63, mockups 040-041, ADR 0036): drafts that may not balance, posted
/// entries (provvisorie) numbered per year in the order of registration, final entries (definitive) numbered on the
/// general journal in date order and never changed again; a reversal corrects them. The guided entry starts from the
/// lines of a template; the manual one shows the imbalance while it is typed. The period must be open (for VAT too when
/// the entry has VAT lines). Entries of documents change only through their document.
/// </summary>
public sealed class JournalEntryService
{
private readonly IUnitOfWorkFactory _factory;
private readonly PermissionService _permissions;
private readonly FiscalYearService _fiscal;
private readonly AuditTrail _audit;
private readonly TimeProvider _clock;
/// <summary>Creates the service.</summary>
/// <param name="factory">The units of work.</param>
/// <param name="permissions">The permissions.</param>
/// <param name="fiscal">The fiscal calendar.</param>
/// <param name="audit">The history.</param>
/// <param name="clock">The clock.</param>
public JournalEntryService(IUnitOfWorkFactory factory, PermissionService permissions, FiscalYearService fiscal, AuditTrail audit, TimeProvider clock)
{
ArgumentNullException.ThrowIfNull(factory);
ArgumentNullException.ThrowIfNull(permissions);
ArgumentNullException.ThrowIfNull(fiscal);
ArgumentNullException.ThrowIfNull(audit);
ArgumentNullException.ThrowIfNull(clock);
_factory = factory;
_permissions = permissions;
_fiscal = fiscal;
_audit = audit;
_clock = clock;
}
/// <summary>The entries, the latest first.</summary>
/// <param name="actor">Who reads.</param>
/// <param name="companyCode">The company.</param>
/// <param name="filter">The filter and the page.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The page and the total.</returns>
public async Task<(IReadOnlyList<EntryRow> Rows, int Total)> ListAsync(Actor actor, string companyCode, EntryFilter filter, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(filter);
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.EntryRead, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
var query = Query.For<GlEntry>();
if (filter.From is { } from)
{
query = query.Where(e => e.EntryDate >= from);
}
if (filter.To is { } to)
{
query = query.Where(e => e.EntryDate <= to);
}
if (filter.Status is { } status)
{
query = query.Where(e => e.Status == status);
}
if (!string.IsNullOrWhiteSpace(filter.TemplateCode))
{
var code = filter.TemplateCode;
query = query.Where(e => e.TemplateCode == code);
}
if (!string.IsNullOrWhiteSpace(filter.Text))
{
var text = filter.Text.Trim();
query = query.Where(e => e.Description.Contains(text) || e.DocumentNumber!.Contains(text) || e.EntryNumber!.Contains(text));
}
var repository = uow.Repository<GlEntry, long>();
var total = await repository.CountAsync(query, cancellationToken).ConfigureAwait(false);
var page = (await repository.ListAsync(
query.OrderByDescending(e => e.EntryDate).OrderByDescending(e => e.Id).Page(Math.Max(0, filter.Offset), Math.Clamp(filter.Limit, 1, 500)),
cancellationToken).ConfigureAwait(false)).Items;
var names = await PartyNamesAsync(uow, page.Select(e => e.PartyId), cancellationToken).ConfigureAwait(false);
return ([.. page.Select(e => new EntryRow(e, e.PartyId is { } p && names.TryGetValue(p, out var n) ? n : null))], total);
}
/// <summary>An entry with its lines.</summary>
/// <param name="actor">Who reads.</param>
/// <param name="companyCode">The company.</param>
/// <param name="id">The entry.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The entry, or none.</returns>
public async Task<EntryView?> GetAsync(Actor actor, string companyCode, long id, CancellationToken cancellationToken = default)
{
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.EntryRead, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
return await ViewAsync(uow, id, cancellationToken).ConfigureAwait(false);
}
/// <summary>The journal templates with their lines, for the guided entry.</summary>
/// <param name="actor">Who reads.</param>
/// <param name="companyCode">The company.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The active templates, by code.</returns>
public async Task<IReadOnlyList<TemplateView>> TemplatesAsync(Actor actor, string companyCode, CancellationToken cancellationToken = default)
{
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.EntryRead, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
var templates = (await uow.Repository<JournalTemplate, long>().ListAsync(Query.For<JournalTemplate>().Where(t => !t.Disabled).OrderBy(t => t.Code), cancellationToken)
.ConfigureAwait(false)).Items;
var lines = (await uow.Repository<JournalTemplateLine, long>().ListAsync(Query.For<JournalTemplateLine>().OrderBy(l => l.SortOrder), cancellationToken).ConfigureAwait(false)).Items;
return [.. templates.Select(t => new TemplateView(t, [.. lines.Where(l => l.JournalTemplateId == t.Id)]))];
}
/// <summary>
/// Saves an entry typed in the journal: a draft may not balance, a posted entry must and gets its number. Final
/// entries and entries of documents cannot change.
/// </summary>
/// <param name="actor">Who writes.</param>
/// <param name="companyCode">The company.</param>
/// <param name="input">The entry.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The entry as saved.</returns>
public async Task<EntryView> SaveAsync(Actor actor, string companyCode, EntryInput input, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(input);
ArgumentNullException.ThrowIfNull(actor);
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.EntryWrite, cancellationToken).ConfigureAwait(false);
if (input.EntryDate == default)
{
throw new ValidationFailedException(["EntryDate:" + LedgerErrors.DateRequired]);
}
if (input.Post)
{
await _fiscal.DemandOpenAsync(company, input.EntryDate, input.Vat.Count > 0 ? PeriodUse.Vat : PeriodUse.NoVat, 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 entries = uow.Repository<GlEntry, long>();
GlEntry? before = null;
if (input.Id is { } existingId)
{
before = await entries.GetAsync(existingId, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(LedgerErrors.NotFound);
if (before.Status == GlEntryStatus.Final)
{
throw new ValidationFailedException(["Status:" + LedgerErrors.Final]);
}
if (before.Source == GlEntrySource.Document)
{
throw new ValidationFailedException(["Source:" + LedgerErrors.FromDocument]);
}
}
var accounts = await LedgerStore.AccountsAsync(uow, cancellationToken).ConfigureAwait(false);
var lines = input.Lines.Where(l => l.AccountId is not null || l.Debit != 0m || l.Credit != 0m).ToList();
var errors = JournalEntryValidator.Check(
input.Description,
[.. lines.Select(l => new EntryLineCheck(l.AccountId, l.PartyId, l.Debit, l.Credit))],
input.Vat.Count,
input.VatRegisterId is not null,
LedgerStore.Rules(accounts),
input.Post).ToList();
if (input.Post)
{
await CheckFinalOrderAsync(uow, input.EntryDate, errors, cancellationToken).ConfigureAwait(false);
}
if (errors.Count > 0)
{
throw new ValidationFailedException(errors);
}
var template = input.JournalTemplateId is { } templateId
? await uow.Repository<JournalTemplate, long>().GetAsync(templateId, cancellationToken).ConfigureAwait(false)
: null;
var entry = before is null ? new GlEntry { Source = GlEntrySource.Manual } : Clone(before);
entry.EntryDate = input.EntryDate;
entry.CompetenceDate = input.CompetenceDate;
entry.JournalTemplateId = template?.Id;
entry.TemplateCode = template?.Code;
entry.Description = LedgerStore.Trim(input.Description.Trim(), 200)!;
entry.DocumentNumber = LedgerStore.Trim(input.DocumentNumber, 30);
entry.DocumentDate = input.DocumentDate;
entry.PartyId = input.PartyId;
entry.VatRegisterId = input.VatRegisterId;
entry.VatDate = input.VatRegisterId is null ? null : input.VatDate ?? input.EntryDate;
entry.Notes = LedgerStore.Trim(input.Notes, 500);
entry.Status = input.Post ? GlEntryStatus.Posted : before?.Status ?? GlEntryStatus.Draft;
if (before is not null && before.Number is not null && before.Year != input.EntryDate.Year)
{
entry.Number = null;
entry.EntryNumber = null;
}
if (before is null)
{
entry = await LedgerStore.InsertAsync(uow, entry, lines, input.Vat, cancellationToken).ConfigureAwait(false);
await _audit.RecordAsync(uow, AuditAction.Insert, entry.Id, null, entry, actor.UserName, cancellationToken).ConfigureAwait(false);
}
else
{
await LedgerStore.UpdateAsync(uow, entry, lines, input.Vat, cancellationToken).ConfigureAwait(false);
await _audit.RecordAsync(uow, AuditAction.Update, entry.Id, before, entry, actor.UserName, cancellationToken).ConfigureAwait(false);
}
id = entry.Id;
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
}
return await GetAsync(actor, company, id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(LedgerErrors.NotFound);
}
/// <summary>Removes an entry that is not final and does not come from a document.</summary>
/// <param name="actor">Who removes it.</param>
/// <param name="companyCode">The company.</param>
/// <param name="id">The entry.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
public async Task DeleteAsync(Actor actor, string companyCode, long id, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(actor);
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.EntryWrite, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
var entry = await uow.Repository<GlEntry, long>().GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(LedgerErrors.NotFound);
if (entry.Status == GlEntryStatus.Final)
{
throw new ValidationFailedException(["Status:" + LedgerErrors.Final]);
}
if (entry.Source == GlEntrySource.Document)
{
throw new ValidationFailedException(["Source:" + LedgerErrors.FromDocument]);
}
await uow.ExecuteAsync(SqlFragment.Of($"UPDATE gl_recurring_entries SET last_entry_id = NULL WHERE last_entry_id = {id}"), cancellationToken).ConfigureAwait(false);
if (await uow.Repository<RecurringEntry, long>().CountAsync(Query.For<RecurringEntry>().Where(r => r.ModelEntryId == id), cancellationToken).ConfigureAwait(false) > 0)
{
throw new ValidationFailedException(["Id:" + LedgerErrors.RecurringModel]);
}
await LedgerStore.DeleteAsync(uow, id, cancellationToken).ConfigureAwait(false);
await _audit.RecordAsync(uow, AuditAction.Delete, id, entry, (GlEntry?)null, actor.UserName, cancellationToken).ConfigureAwait(false);
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Reverses an entry (storno): a new posted entry with the same lines on the other side and the VAT with the
/// opposite sign; the open items of the entry not yet settled are removed.
/// </summary>
/// <param name="actor">Who reverses.</param>
/// <param name="companyCode">The company.</param>
/// <param name="id">The entry.</param>
/// <param name="date">The date of the reversal.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The reversal.</returns>
public async Task<EntryView> ReverseAsync(Actor actor, string companyCode, long id, DateOnly date, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(actor);
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.EntryWrite, cancellationToken).ConfigureAwait(false);
await _fiscal.DemandOpenAsync(company, date, PeriodUse.NoVat, cancellationToken).ConfigureAwait(false);
long reversalId;
await using (var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false))
{
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
var entry = await uow.Repository<GlEntry, long>().GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(LedgerErrors.NotFound);
if (entry.Source == GlEntrySource.Document && entry.Status != GlEntryStatus.Final)
{
throw new ValidationFailedException(["Source:" + LedgerErrors.FromDocument]);
}
var reversal = await ReverseAsync(uow, entry, date, actor.UserName, cancellationToken).ConfigureAwait(false);
await _audit.RecordAsync(uow, AuditAction.Insert, reversal.Id, null, reversal, actor.UserName, cancellationToken).ConfigureAwait(false);
reversalId = reversal.Id;
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
}
return await GetAsync(actor, company, reversalId, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(LedgerErrors.NotFound);
}
/// <summary>
/// Makes final the posted entries up to a day (stampa definitiva del libro giornale): in date order each gets the
/// next number of the journal of its fiscal year, then never changes again.
/// </summary>
/// <param name="actor">Who does it: needs <c>ledger.entry.finalize</c>.</param>
/// <param name="companyCode">The company.</param>
/// <param name="upTo">The last day.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>How many entries became final.</returns>
public async Task<int> FinalizeAsync(Actor actor, string companyCode, DateOnly upTo, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(actor);
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.EntryFinalize, cancellationToken).ConfigureAwait(false);
var done = 0;
await using (var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false))
{
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
var drafts = await uow.Repository<GlEntry, long>().CountAsync(
Query.For<GlEntry>().Where(e => e.Status == GlEntryStatus.Draft && e.EntryDate <= upTo), cancellationToken).ConfigureAwait(false);
if (drafts > 0)
{
throw new ValidationFailedException(["UpTo:" + LedgerErrors.DraftsBeforeFinal]);
}
var entries = (await uow.Repository<GlEntry, long>().ListAsync(
Query.For<GlEntry>().Where(e => e.Status == GlEntryStatus.Posted && e.EntryDate <= upTo).OrderBy(e => e.EntryDate).OrderBy(e => e.Number).OrderBy(e => e.Id),
cancellationToken).ConfigureAwait(false)).Items;
var years = (await uow.Repository<FiscalYear, long>().ListAsync(Query.For<FiscalYear>(), cancellationToken).ConfigureAwait(false)).Items;
var now = _clock.GetUtcNow().UtcDateTime;
foreach (var entry in entries)
{
var year = years.FirstOrDefault(y => y.StartDate <= entry.EntryDate && y.EndDate >= entry.EntryDate)
?? throw new ValidationFailedException(["UpTo:" + LedgerErrors.NoFiscalYear]);
year.LastFinalEntryNumber++;
year.LastFinalEntryDate = entry.EntryDate;
entry.JournalNumber = year.LastFinalEntryNumber;
entry.FinalizedAt = now;
entry.FinalizedBy = actor.UserName;
await LedgerStore.SetStatusAsync(uow, entry, GlEntryStatus.Final, cancellationToken).ConfigureAwait(false);
done++;
}
foreach (var year in years.Where(y => entries.Any(e => y.StartDate <= e.EntryDate && y.EndDate >= e.EntryDate)))
{
await uow.Repository<FiscalYear, long>().UpdateAsync(year, cancellationToken).ConfigureAwait(false);
}
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
}
await _fiscal.InvalidateAsync(company, cancellationToken).ConfigureAwait(false);
return done;
}
/// <summary>Posts a draft: it must balance.</summary>
/// <param name="actor">Who posts.</param>
/// <param name="companyCode">The company.</param>
/// <param name="id">The entry.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The entry as posted.</returns>
public async Task<EntryView> PostAsync(Actor actor, string companyCode, long id, CancellationToken cancellationToken = default)
{
var view = await GetAsync(actor, companyCode, id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(LedgerErrors.NotFound);
var e = view.Entry;
return await SaveAsync(actor, companyCode, new EntryInput(e.Id, e.EntryDate, e.Description, [.. view.Lines.Select(Draft)])
{
JournalTemplateId = e.JournalTemplateId,
CompetenceDate = e.CompetenceDate,
DocumentNumber = e.DocumentNumber,
DocumentDate = e.DocumentDate,
PartyId = e.PartyId,
VatRegisterId = e.VatRegisterId,
VatDate = e.VatDate,
Vat = [.. view.Vat.Select(Draft)],
Notes = e.Notes,
Post = true,
}, cancellationToken).ConfigureAwait(false);
}
/// <summary>A line of an entry as a draft line.</summary>
/// <param name="line">The line.</param>
/// <returns>The draft.</returns>
public static EntryLineDraft Draft(GlEntryLine line)
{
ArgumentNullException.ThrowIfNull(line);
return new EntryLineDraft(line.AccountId, line.PartyId, line.Description, line.Debit, line.Credit, line.CostCenterId, line.JobId);
}
/// <summary>A VAT line of an entry as a draft line.</summary>
/// <param name="line">The line.</param>
/// <returns>The draft.</returns>
public static EntryVatDraft Draft(GlEntryVat line)
{
ArgumentNullException.ThrowIfNull(line);
return new EntryVatDraft(line.TaxCodeId, line.Rate, line.Nature, line.Taxable, line.Tax, line.NonDeductibleTax, line.Exigibility, line.VatRegisterId);
}
/// <summary>Writes the reversal of an entry in the open transaction.</summary>
internal static async Task<GlEntry> ReverseAsync(IUnitOfWork uow, GlEntry entry, DateOnly date, string? userName, CancellationToken cancellationToken)
{
if (entry.ReversedById is not null)
{
throw new ValidationFailedException(["Id:" + LedgerErrors.AlreadyReversed]);
}
if (entry.Status == GlEntryStatus.Draft)
{
throw new ValidationFailedException(["Status:" + LedgerErrors.NotPosted]);
}
var lines = await LedgerStore.LinesAsync(uow, entry.Id, cancellationToken).ConfigureAwait(false);
var vat = await LedgerStore.VatAsync(uow, entry.Id, cancellationToken).ConfigureAwait(false);
var reversal = new GlEntry
{
EntryDate = date < entry.EntryDate ? entry.EntryDate : date,
JournalTemplateId = entry.JournalTemplateId,
TemplateCode = entry.TemplateCode,
Description = LedgerStore.Trim("Storno " + (entry.EntryNumber ?? string.Empty) + " " + entry.Description, 200)!,
Status = GlEntryStatus.Posted,
Source = GlEntrySource.Reversal,
SourceFamily = entry.SourceFamily,
SourceDocumentId = entry.SourceDocumentId,
SourceKind = entry.SourceKind,
DocumentNumber = entry.DocumentNumber,
DocumentDate = entry.DocumentDate,
PartyId = entry.PartyId,
VatRegisterId = entry.VatRegisterId,
VatProtocol = entry.VatProtocol,
VatDate = date < entry.EntryDate ? entry.VatDate : date,
ReversalOfId = entry.Id,
IsDemo = entry.IsDemo,
Notes = userName is null ? null : "Storno di " + userName,
};
reversal = await LedgerStore.InsertAsync(
uow,
reversal,
[.. lines.Select(l => new EntryLineDraft(l.AccountId, l.PartyId, l.Description, l.Credit, l.Debit, l.CostCenterId, l.JobId))],
[.. vat.Select(v => new EntryVatDraft(v.TaxCodeId, v.Rate, v.Nature, -v.Taxable, -v.Tax, -v.NonDeductibleTax, v.Exigibility, v.VatRegisterId))],
cancellationToken).ConfigureAwait(false);
entry.ReversedById = reversal.Id;
await uow.Repository<GlEntry, long>().UpdateAsync(entry, cancellationToken).ConfigureAwait(false);
await uow.ExecuteAsync(SqlFragment.Of($"DELETE FROM gl_open_items WHERE entry_id = {entry.Id} AND paid_amount = 0"), cancellationToken).ConfigureAwait(false);
return reversal;
}
internal static async Task<EntryView?> ViewAsync(IUnitOfWork uow, long id, CancellationToken cancellationToken)
{
if (await uow.Repository<GlEntry, long>().GetAsync(id, cancellationToken).ConfigureAwait(false) is not { } entry)
{
return null;
}
var lines = await LedgerStore.LinesAsync(uow, id, cancellationToken).ConfigureAwait(false);
var vat = await LedgerStore.VatAsync(uow, id, cancellationToken).ConfigureAwait(false);
var names = await PartyNamesAsync(uow, [entry.PartyId], cancellationToken).ConfigureAwait(false);
return new EntryView(entry, lines, vat, entry.PartyId is { } p && names.TryGetValue(p, out var name) ? name : null);
}
internal static async Task<Dictionary<long, string>> PartyNamesAsync(IUnitOfWork uow, IEnumerable<long?> ids, CancellationToken cancellationToken)
{
var list = ids.Where(i => i is not null).Select(i => i!.Value).Distinct().ToList();
if (list.Count == 0)
{
return [];
}
return (await uow.Repository<Party, long>().ListAsync(Query.For<Party>().Where(p => list.Contains(p.Id)), cancellationToken).ConfigureAwait(false)).Items
.ToDictionary(p => p.Id, p => p.Name);
}
private static async Task CheckFinalOrderAsync(IUnitOfWork uow, DateOnly date, List<string> errors, CancellationToken cancellationToken)
{
var year = await uow.Repository<FiscalYear, long>().FindAsync(
Query.For<FiscalYear>().Where(y => y.StartDate <= date && y.EndDate >= date), cancellationToken).ConfigureAwait(false);
if (year?.LastFinalEntryDate is { } last && date < last)
{
errors.Add("EntryDate:" + LedgerErrors.FinalOrder);
}
}
private static GlEntry Clone(GlEntry entry) => new()
{
Id = entry.Id,
Year = entry.Year,
Number = entry.Number,
EntryNumber = entry.EntryNumber,
JournalNumber = entry.JournalNumber,
EntryDate = entry.EntryDate,
Description = entry.Description,
Status = entry.Status,
Source = entry.Source,
IsDemo = entry.IsDemo,
RowVersion = entry.RowVersion,
CreatedAt = entry.CreatedAt,
CreatedBy = entry.CreatedBy,
UpdatedAt = entry.UpdatedAt,
UpdatedBy = entry.UpdatedBy,
};
}
@@ -0,0 +1,448 @@
using Khaemhat.Application.Documents;
using Khaemhat.Application.Licensing;
using Khaemhat.Application.Modules;
using Khaemhat.Application.Security;
using Khaemhat.Core.Accounting;
using Khaemhat.Core.Documents;
using Khaemhat.Core.Items;
using Khaemhat.Core.Parties;
using Khaemhat.Core.Tables;
using Khaemhat.Data;
using Khaemhat.Data.Querying;
namespace Khaemhat.Application.Ledger;
/// <summary>
/// Posts the documents to the ledger (SPEC §11.7, issue #64, ADR 0037) inside the transaction of the document engine,
/// like <see cref="Inventory.InventoryPoster"/> does with the warehouse: an invoice, credit note or self-invoice in
/// force writes its entry (with the VAT lines of its register, the open items of its installments and its
/// withholding); a change writes it again with the same number; a cancelled document loses it, or gets a reversal when
/// its entry is already final. Nothing is posted while the module ACCT is not licensed: the documents can be posted
/// later in bulk (<see cref="LedgerService.PostPendingAsync"/>).
/// </summary>
public sealed class LedgerPoster
{
private readonly ILicenseGate _licence;
/// <summary>Creates the poster.</summary>
/// <param name="licence">The licence (module ACCT).</param>
public LedgerPoster(ILicenseGate licence)
{
ArgumentNullException.ThrowIfNull(licence);
_licence = licence;
}
/// <summary>Whether the documents post to the ledger.</summary>
public bool Active => _licence.IsModuleActive(ModuleCodes.Accounting);
/// <summary>What a kind of document posts, if anything.</summary>
/// <param name="kind">The kind.</param>
/// <returns>The posting kind and whether the sides are reversed, or <see langword="null"/>.</returns>
public static (PostingKind Kind, bool Reverse)? PostingOf(DocumentKind kind) => kind switch
{
DocumentKind.ImmediateInvoice or DocumentKind.AccompanyingInvoice or DocumentKind.DeferredInvoice or DocumentKind.DownPaymentInvoice
or DocumentKind.DebitNote or DocumentKind.Fee => (PostingKind.Sale, false),
DocumentKind.CreditNote => (PostingKind.Sale, true),
DocumentKind.SelfInvoice => (PostingKind.SelfInvoice, false),
DocumentKind.PurchaseInvoice => (PostingKind.Purchase, false),
DocumentKind.PurchaseCreditNote => (PostingKind.Purchase, true),
_ => null,
};
/// <summary>Writes again the entry of a document from its current state.</summary>
/// <param name="uow">The unit of work of the company, in a transaction.</param>
/// <param name="family">The family.</param>
/// <param name="documentId">The document.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The entry, or <see langword="null"/> when the document posts nothing.</returns>
public async Task<GlEntry?> SyncAsync(IUnitOfWork uow, DocumentFamily family, long documentId, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(uow);
if (!Active || family is not (DocumentFamily.SaleDocument or DocumentFamily.PurchaseDocument))
{
return null;
}
return await PostAsync(uow, family, documentId, cancellationToken).ConfigureAwait(false);
}
/// <summary>Posts or removes the entry of a document whatever the licence (bulk posting, tests).</summary>
/// <param name="uow">The unit of work of the company, in a transaction.</param>
/// <param name="family">The family.</param>
/// <param name="documentId">The document.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The entry, or <see langword="null"/>.</returns>
internal static async Task<GlEntry?> PostAsync(IUnitOfWork uow, DocumentFamily family, long documentId, CancellationToken cancellationToken)
{
var store = DocumentStores.Of(family);
var header = await store.GetAsync(uow, documentId, cancellationToken).ConfigureAwait(false);
var existing = await CurrentEntryAsync(uow, family, documentId, cancellationToken).ConfigureAwait(false);
var posting = header is null ? null : PostingOf(header.Kind);
if (header is null || posting is null || !DocumentStateMachine.IsInForce(header.Status))
{
await RemoveAsync(uow, existing, cancellationToken).ConfigureAwait(false);
await RemoveWithholdingsAsync(uow, family, documentId, cancellationToken).ConfigureAwait(false);
if (header is not null && (header.Posted || header.GlEntryId is not null))
{
header.Posted = false;
header.GlEntryId = null;
await store.UpdateAsync(uow, header, cancellationToken).ConfigureAwait(false);
}
return null;
}
var built = await BuildAsync(uow, family, header, posting.Value, cancellationToken).ConfigureAwait(false);
if (built is null)
{
return null;
}
var (entry, lines, vat) = built.Value;
GlEntry result;
if (existing is null)
{
result = await LedgerStore.InsertAsync(uow, entry, lines, vat, cancellationToken).ConfigureAwait(false);
}
else if (existing.Status != GlEntryStatus.Final)
{
Copy(entry, existing);
await LedgerStore.UpdateAsync(uow, existing, lines, vat, cancellationToken).ConfigureAwait(false);
await uow.ExecuteAsync(SqlFragment.Of($"DELETE FROM gl_open_items WHERE entry_id = {existing.Id}"), cancellationToken).ConfigureAwait(false);
result = existing;
}
else if (await SameAsync(uow, existing, lines, cancellationToken).ConfigureAwait(false))
{
return existing;
}
else
{
// A final entry never changes: the reversal cancels it and a new entry posts the document as it is now.
await JournalEntryService.ReverseAsync(uow, existing, existing.EntryDate, null, cancellationToken).ConfigureAwait(false);
result = await LedgerStore.InsertAsync(uow, entry, lines, vat, cancellationToken).ConfigureAwait(false);
}
await OpenItemsAsync(uow, family, header, posting.Value, result, lines, cancellationToken).ConfigureAwait(false);
await WithholdingAsync(uow, family, header, result, cancellationToken).ConfigureAwait(false);
if (!header.Posted || header.GlEntryId != result.Id)
{
header.Posted = true;
header.GlEntryId = result.Id;
await store.UpdateAsync(uow, header, cancellationToken).ConfigureAwait(false);
}
return result;
}
/// <summary>The entry of a document that is not reversed, if any.</summary>
internal static async Task<GlEntry?> CurrentEntryAsync(IUnitOfWork uow, DocumentFamily family, long documentId, CancellationToken cancellationToken)
{
var entries = (await uow.Repository<GlEntry, long>().ListAsync(
Query.For<GlEntry>().Where(e => e.SourceFamily == family && e.SourceDocumentId == documentId && e.Source == GlEntrySource.Document)
.OrderByDescending(e => e.Id), cancellationToken).ConfigureAwait(false)).Items;
return entries.FirstOrDefault(e => e.ReversedById is null);
}
private static async Task RemoveAsync(IUnitOfWork uow, GlEntry? existing, CancellationToken cancellationToken)
{
if (existing is null)
{
return;
}
if (existing.Status == GlEntryStatus.Final)
{
await JournalEntryService.ReverseAsync(uow, existing, existing.EntryDate, null, cancellationToken).ConfigureAwait(false);
}
else
{
await LedgerStore.DeleteAsync(uow, existing.Id, cancellationToken).ConfigureAwait(false);
}
}
private static async Task RemoveWithholdingsAsync(IUnitOfWork uow, DocumentFamily family, long documentId, CancellationToken cancellationToken)
{
var waiting = nameof(WithholdingStatus.Waiting);
var suffered = nameof(WithholdingStatus.Suffered);
var text = family.ToString();
await uow.ExecuteAsync(
SqlFragment.Of($"DELETE FROM withholdings WHERE source_family = {text} AND source_document_id = {documentId} AND status IN ({waiting}, {suffered})"),
cancellationToken).ConfigureAwait(false);
}
private static void Copy(GlEntry from, GlEntry to)
{
to.EntryDate = from.EntryDate;
to.JournalTemplateId = from.JournalTemplateId;
to.TemplateCode = from.TemplateCode;
to.Description = from.Description;
to.SourceKind = from.SourceKind;
to.DocumentNumber = from.DocumentNumber;
to.DocumentDate = from.DocumentDate;
to.PartyId = from.PartyId;
to.VatRegisterId = from.VatRegisterId;
to.VatProtocol = from.VatProtocol;
to.VatDate = from.VatDate;
to.IsDemo = from.IsDemo;
if (to.Year != from.EntryDate.Year)
{
// A new year means a new number.
to.Number = null;
to.EntryNumber = null;
}
}
private static async Task<bool> SameAsync(IUnitOfWork uow, GlEntry existing, IReadOnlyList<EntryLineDraft> lines, CancellationToken cancellationToken)
{
var stored = await LedgerStore.LinesAsync(uow, existing.Id, cancellationToken).ConfigureAwait(false);
static string Key(long? account, long? party, decimal debit, decimal credit) => $"{account}|{party}|{debit:0.00}|{credit:0.00}";
var left = stored.Select(l => Key(l.AccountId, l.PartyId, l.Debit, l.Credit)).Order(StringComparer.Ordinal);
var right = lines.Select(l => Key(l.AccountId, l.PartyId, l.Debit, l.Credit)).Order(StringComparer.Ordinal);
return left.SequenceEqual(right, StringComparer.Ordinal);
}
private static async Task<(GlEntry Entry, List<EntryLineDraft> Lines, List<EntryVatDraft> Vat)?> BuildAsync(
IUnitOfWork uow, DocumentFamily family, DocumentHeader header, (PostingKind Kind, bool Reverse) posting, CancellationToken cancellationToken)
{
var type = await uow.Repository<DocumentType, long>().GetAsync(header.DocumentTypeId, cancellationToken).ConfigureAwait(false);
var templateCode = type?.JournalTemplateCode ?? DefaultTemplate(posting);
if (await LedgerStore.TemplateAsync(uow, templateCode, cancellationToken).ConfigureAwait(false) is not { } found)
{
return null;
}
var (template, templateLines) = found;
PartyPurchaseTerms? purchaseTerms = null;
if (posting.Kind == PostingKind.Purchase && header.PartyId is { } supplierId)
{
purchaseTerms = await uow.Repository<PartyPurchaseTerms, long>().FindAsync(
Query.For<PartyPurchaseTerms>().Where(t => t.PartyId == supplierId), cancellationToken).ConfigureAwait(false);
}
var registerCode = purchaseTerms?.VatRegisterCode ?? type?.VatRegisterCode ?? template.VatRegisterCode;
var register = await LedgerStore.RegisterAsync(uow, registerCode, cancellationToken).ConfigureAwait(false);
var accounts = (await uow.Repository<GlAccount, long>().ListAsync(Query.For<GlAccount>(), cancellationToken).ConfigureAwait(false)).Items;
var byCode = accounts.ToDictionary(a => a.Code, StringComparer.Ordinal);
long? Of(string? code) => code is not null && byCode.TryGetValue(code, out var account) && account.Postable ? account.Id : null;
long? Role(PostingRole role) => templateLines.FirstOrDefault(l => l.Role == role && l.AccountId is not null)?.AccountId;
var party = header.PartyId is { } partyId ? await uow.Repository<Party, long>().GetAsync(partyId, cancellationToken).ConfigureAwait(false) : null;
var record = await DocumentEngine.LoadAsync(uow, family, header.Id, cancellationToken).ConfigureAwait(false);
if (record is null)
{
return null;
}
var sale = posting.Kind == PostingKind.Sale;
var items = await ItemsAsync(uow, record.Lines, cancellationToken).ConfigureAwait(false);
var taxCodes = (await uow.Repository<TaxCode, long>().ListAsync(Query.For<TaxCode>(), cancellationToken).ConfigureAwait(false)).Items.ToDictionary(t => t.Id);
var inputLines = new List<PostingLineInput>();
foreach (var line in record.Lines.Where(l => l.Kind != DocumentLineKind.Description && l.TaxableAmount != 0m))
{
var item = line.ItemId is { } itemId && items.TryGetValue(itemId, out var found2) ? found2 : null;
var tax = line.TaxCodeId is { } taxId && taxCodes.TryGetValue(taxId, out var code) ? code : null;
var account = Of(line.AccountCode)
?? Of(sale ? item?.RevenueAccountCode : item?.CostAccountCode)
?? Of(purchaseTerms?.CostAccountCode)
?? Of(sale ? tax?.SalesAccountCode : tax?.PurchaseAccountCode);
inputLines.Add(new PostingLineInput(account, line.TaxableAmount, line.TaxCodeId, line.CostCenterId, line.JobId));
}
var taxes = record.Figures.Summary
.Select(s => new PostingTaxInput(s.TaxCodeId, s.Rate, s.Nature, s.Exigibility, s.Taxable, s.Tax, s.NonDeductibleTax))
.ToList();
var stamp = header.StampDutyCharged ? header.StampDuty : 0m;
var total = taxes.Sum(t => t.Taxable) + taxes.Sum(t => t.Tax) + stamp;
var partyAccount = posting.Kind switch
{
PostingKind.Sale => Of(party?.CustomerAccountCode) ?? Role(PostingRole.Customer),
PostingKind.Purchase => Of(party?.SupplierAccountCode) ?? Role(PostingRole.Supplier),
_ => null,
};
var accountsOfPosting = new PostingAccounts(
partyAccount,
Role(sale ? PostingRole.Revenue : PostingRole.Cost),
Role(PostingRole.SalesVat),
Role(PostingRole.PurchaseVat),
Role(PostingRole.StampDuty),
Role(PostingRole.SocialSecurity));
PostingResult result;
try
{
result = PostingEngine.Post(
new PostingInput(posting.Kind, posting.Reverse, header.PartyId, inputLines, taxes, total, stamp, sale ? header.SocialSecurityAmount : 0m),
accountsOfPosting);
}
catch (PostingAccountMissingException exception)
{
throw new ValidationFailedException("Ledger:" + LedgerErrors.RoleAccountMissing, exception);
}
if (result.Vat.Count > 0 && register is null)
{
throw new ValidationFailedException(["VatRegisterId:" + LedgerErrors.VatRegisterRequired]);
}
// A self-invoice is annotated also in the purchase register of reverse charge (double annotation, §11.5).
VatRegister? purchaseRegister = null;
if (posting.Kind == PostingKind.SelfInvoice)
{
var registers = (await uow.Repository<VatRegister, long>().ListAsync(Query.For<VatRegister>(), cancellationToken).ConfigureAwait(false)).Items;
purchaseRegister = registers.FirstOrDefault(r => r.Kind == VatRegisterKind.Purchases && r.ReverseCharge && !r.Disabled)
?? registers.FirstOrDefault(r => r.Kind == VatRegisterKind.Purchases && !r.Disabled);
}
var purchase = family == DocumentFamily.PurchaseDocument;
var documentNumber = purchase ? header.ExternalReference ?? header.DocumentNumber : header.DocumentNumber;
var documentDate = purchase ? header.ExternalDate ?? header.DocumentDate : header.DocumentDate;
var entryDate = purchase ? header.VatDate ?? header.DocumentDate : header.DocumentDate;
var entry = new GlEntry
{
EntryDate = entryDate,
JournalTemplateId = template.Id,
TemplateCode = template.Code,
Description = LedgerStore.Trim(Describe(template.Description, documentNumber, documentDate, party), 200)!,
Status = GlEntryStatus.Posted,
Source = GlEntrySource.Document,
SourceFamily = family,
SourceDocumentId = header.Id,
SourceKind = header.Kind,
DocumentNumber = LedgerStore.Trim(documentNumber, 30),
DocumentDate = documentDate,
PartyId = header.PartyId,
VatRegisterId = result.Vat.Count > 0 ? register?.Id : null,
VatProtocol = purchase ? header.VatProtocol ?? header.Number : header.Number,
VatDate = header.VatDate ?? entryDate,
IsDemo = header.IsDemo,
};
var description = LedgerStore.Trim(documentNumber is null ? template.Description : template.Description + " " + documentNumber, 200);
var lines = result.Lines
.Select(l => new EntryLineDraft(l.AccountId, l.PartyId, description, l.Debit, l.Credit, l.CostCenterId, l.JobId))
.ToList();
var vat = result.Vat
.Select(v => new EntryVatDraft(
v.Tax.TaxCodeId, v.Tax.Rate, v.Tax.Nature, v.Tax.Taxable, v.Tax.Tax, v.Tax.NonDeductibleTax, v.Tax.Exigibility,
v.RegisterKind == VatRegisterKind.Purchases && purchaseRegister is not null ? purchaseRegister.Id : register?.Id))
.ToList();
return (entry, lines, vat);
}
private static string DefaultTemplate((PostingKind Kind, bool Reverse) posting) => posting switch
{
(PostingKind.Sale, false) => "FV",
(PostingKind.Sale, true) => "NCV",
(PostingKind.Purchase, false) => "FA",
(PostingKind.Purchase, true) => "NCA",
_ => "AFRC",
};
private static string Describe(string template, string? number, DateOnly date, Party? party)
{
var text = template;
if (number is not null)
{
text += " n. " + number;
}
text += " del " + date.ToString("dd/MM/yyyy", System.Globalization.CultureInfo.InvariantCulture);
if (party is not null)
{
text += " - " + party.Name;
}
return text;
}
private static async Task<Dictionary<long, Item>> ItemsAsync(IUnitOfWork uow, IReadOnlyList<DocumentLine> lines, CancellationToken cancellationToken)
{
var ids = lines.Where(l => l.ItemId is not null).Select(l => l.ItemId!.Value).Distinct().ToList();
if (ids.Count == 0)
{
return [];
}
return (await uow.Repository<Item, long>().ListAsync(Query.For<Item>().Where(i => ids.Contains(i.Id)), cancellationToken).ConfigureAwait(false)).Items.ToDictionary(i => i.Id);
}
private static async Task OpenItemsAsync(
IUnitOfWork uow, DocumentFamily family, DocumentHeader header, (PostingKind Kind, bool Reverse) posting, GlEntry entry,
IReadOnlyList<EntryLineDraft> lines, CancellationToken cancellationToken)
{
if (posting.Kind == PostingKind.SelfInvoice || header.PartyId is not { } partyId)
{
return;
}
var partyLine = lines.FirstOrDefault(l => l.PartyId == partyId);
if (partyLine?.AccountId is not { } accountId)
{
return;
}
var installments = (await uow.Repository<DocumentInstallment, long>().ListAsync(
Query.For<DocumentInstallment>().Where(i => i.Family == family && i.DocumentId == header.Id).OrderBy(i => i.Number), cancellationToken).ConfigureAwait(false)).Items;
var sign = posting.Reverse ? -1m : 1m;
var rows = installments.Count > 0
? installments.Select(i => (i.Number, i.DueDate, i.Amount, i.PaymentMethodId)).ToList()
: [(1, header.DocumentDate, header.NetAmount != 0m ? header.NetAmount : header.TotalAmount, header.PaymentMethodId)];
var repository = uow.Repository<OpenItem, long>();
foreach (var (number, due, amount, method) in rows)
{
await repository.InsertAsync(new OpenItem
{
Direction = posting.Kind == PostingKind.Sale ? OpenItemDirection.Receivable : OpenItemDirection.Payable,
PartyId = partyId,
AccountId = accountId,
EntryId = entry.Id,
SourceFamily = family,
SourceDocumentId = header.Id,
DocumentNumber = entry.DocumentNumber,
DocumentDate = entry.DocumentDate ?? header.DocumentDate,
Installment = number,
DueDate = due,
Amount = sign * amount,
PaymentMethodId = method,
IsDemo = header.IsDemo,
}, cancellationToken).ConfigureAwait(false);
}
}
private static async Task WithholdingAsync(IUnitOfWork uow, DocumentFamily family, DocumentHeader header, GlEntry entry, CancellationToken cancellationToken)
{
await RemoveWithholdingsAsync(uow, family, header.Id, cancellationToken).ConfigureAwait(false);
if (header.WithholdingAmount == 0m || header.PartyId is not { } partyId)
{
return;
}
var existing = await uow.Repository<Withholding, long>().CountAsync(
Query.For<Withholding>().Where(w => w.SourceFamily == family && w.SourceDocumentId == header.Id), cancellationToken).ConfigureAwait(false);
if (existing > 0)
{
// Already due or paid: the payment stays as it was.
return;
}
var operated = family == DocumentFamily.PurchaseDocument;
var sign = header.Kind is DocumentKind.CreditNote or DocumentKind.PurchaseCreditNote ? -1m : 1m;
await uow.Repository<Withholding, long>().InsertAsync(new Withholding
{
Direction = operated ? WithholdingDirection.Operated : WithholdingDirection.Suffered,
SourceFamily = family,
SourceDocumentId = header.Id,
DocumentNumber = entry.DocumentNumber,
DocumentDate = entry.DocumentDate ?? header.DocumentDate,
PartyId = partyId,
WithholdingType = header.WithholdingType,
Reason = header.WithholdingReason,
Taxable = sign * (header.TaxableAmount - header.SocialSecurityAmount),
SocialSecurityFund = header.SocialSecurityFund,
SocialSecurityAmount = sign * header.SocialSecurityAmount,
Rate = header.WithholdingRate ?? 0m,
BasePercent = header.WithholdingBasePercent,
Amount = sign * header.WithholdingAmount,
Status = operated ? WithholdingStatus.Waiting : WithholdingStatus.Suffered,
IsDemo = header.IsDemo,
}, cancellationToken).ConfigureAwait(false);
}
}
@@ -0,0 +1,436 @@
using System.Globalization;
using Khaemhat.Application.Security;
using Khaemhat.Application.Tables;
using Khaemhat.Core.Accounting;
using Khaemhat.Core.Tables;
using Khaemhat.Data;
using Khaemhat.Data.Querying;
namespace Khaemhat.Application.Ledger;
/// <summary>A movement of an account (or of a party on an account), with the running balance.</summary>
/// <param name="EntryId">The entry, for the drill-down.</param>
/// <param name="EntryNumber">The number of the entry.</param>
/// <param name="EntryDate">The date.</param>
/// <param name="Description">The description of the line, or of the entry.</param>
/// <param name="DocumentNumber">The number of the document.</param>
/// <param name="DocumentDate">The date of the document.</param>
/// <param name="TemplateCode">The journal template.</param>
/// <param name="AccountCode">The account (when the view is of a party).</param>
/// <param name="Debit">The debit.</param>
/// <param name="Credit">The credit.</param>
/// <param name="Balance">The balance after the movement, debit positive.</param>
/// <param name="Status">The state of the entry.</param>
public sealed record LedgerMovement(
long EntryId, string? EntryNumber, DateOnly EntryDate, string? Description, string? DocumentNumber, DateOnly? DocumentDate, string? TemplateCode, string? AccountCode,
decimal Debit, decimal Credit, decimal Balance, GlEntryStatus Status);
/// <summary>A page of the movements of an account or a party.</summary>
/// <param name="Opening">The balance before the period.</param>
/// <param name="Movements">The movements of the page.</param>
/// <param name="TotalCount">How many movements the period has.</param>
/// <param name="TotalDebit">The debits of the period.</param>
/// <param name="TotalCredit">The credits of the period.</param>
/// <param name="Closing">The balance at the end of the period.</param>
public sealed record LedgerPage(decimal Opening, IReadOnlyList<LedgerMovement> Movements, long TotalCount, decimal TotalDebit, decimal TotalCredit, decimal Closing);
/// <summary>What the movements are asked for.</summary>
/// <param name="AccountId">The account; with <paramref name="PartyId"/>, its sub-ledger.</param>
/// <param name="PartyId">The customer or supplier (partitario, estratto conto).</param>
/// <param name="From">From this day.</param>
/// <param name="To">Up to this day.</param>
/// <param name="IncludeDrafts">Count the drafts too.</param>
/// <param name="Offset">The first movement of the page.</param>
/// <param name="Limit">The size of the page.</param>
public sealed record LedgerFilter(long? AccountId, long? PartyId, DateOnly From, DateOnly To, bool IncludeDrafts = false, int Offset = 0, int Limit = 50);
/// <summary>A line of the trial balance.</summary>
/// <param name="AccountId">The account.</param>
/// <param name="Code">The code.</param>
/// <param name="Description">The description.</param>
/// <param name="Level">The level (1 mastro, 2 conto, 3 sottoconto).</param>
/// <param name="Nature">The nature.</param>
/// <param name="Opening">The balance before the period.</param>
/// <param name="Debit">The debits of the period.</param>
/// <param name="Credit">The credits of the period.</param>
/// <param name="Closing">The balance at the end, debit positive.</param>
public sealed record TrialBalanceLine(long AccountId, string Code, string Description, int Level, AccountNature Nature, decimal Opening, decimal Debit, decimal Credit, decimal Closing);
/// <summary>The trial balance of a period.</summary>
/// <param name="Lines">The accounts with movements or a balance, with the totals of their parents.</param>
/// <param name="TotalDebit">The debits of the period.</param>
/// <param name="TotalCredit">The credits of the period.</param>
/// <param name="Result">The result of the period (revenues minus costs).</param>
public sealed record TrialBalance(IReadOnlyList<TrialBalanceLine> Lines, decimal TotalDebit, decimal TotalCredit, decimal Result)
{
/// <summary>Whether debits and credits match.</summary>
public bool Balanced => TotalDebit == TotalCredit;
}
/// <summary>A party with a balance on the customer or supplier accounts.</summary>
/// <param name="PartyId">The party.</param>
/// <param name="Name">The name.</param>
/// <param name="Debit">The debits.</param>
/// <param name="Credit">The credits.</param>
/// <param name="Balance">The balance, debit positive.</param>
/// <param name="OpenItems">The open items not closed.</param>
public sealed record PartyBalance(long PartyId, string Name, decimal Debit, decimal Credit, decimal Balance, int OpenItems);
/// <summary>
/// What the ledger tells (SPEC §11.7, issue #67, mockup 044): the movements of an account (mastrino) and of a customer
/// or supplier (partitario, estratto conto) with the running balance and the way to the entry; the open items; the
/// trial balance of a period, by cost center too, with the balances of the parents; the general journal (libro
/// giornale), provisional or as numbered. All the lists are paged in the database.
/// </summary>
public sealed class LedgerQueryService
{
private readonly IUnitOfWorkFactory _factory;
private readonly PermissionService _permissions;
/// <summary>Creates the service.</summary>
/// <param name="factory">The units of work.</param>
/// <param name="permissions">The permissions.</param>
public LedgerQueryService(IUnitOfWorkFactory factory, PermissionService permissions)
{
ArgumentNullException.ThrowIfNull(factory);
ArgumentNullException.ThrowIfNull(permissions);
_factory = factory;
_permissions = permissions;
}
/// <summary>The movements of an account or of a party in a period, with the running balance.</summary>
/// <param name="actor">Who reads.</param>
/// <param name="companyCode">The company.</param>
/// <param name="filter">The account or party, the period, the page.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The page.</returns>
public async Task<LedgerPage> MovementsAsync(Actor actor, string companyCode, LedgerFilter filter, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(filter);
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.EntryRead, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
return await MovementsAsync(uow, filter, cancellationToken).ConfigureAwait(false);
}
/// <summary>The customers or suppliers with their balance on the sub-ledger accounts.</summary>
/// <param name="actor">Who reads.</param>
/// <param name="companyCode">The company.</param>
/// <param name="type">Customers or suppliers.</param>
/// <param name="to">Up to this day.</param>
/// <param name="search">Part of the name.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The parties, by name.</returns>
public async Task<IReadOnlyList<PartyBalance>> PartyBalancesAsync(
Actor actor, string companyCode, AccountType type, DateOnly to, string? search = null, CancellationToken cancellationToken = default)
{
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.EntryRead, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
var draft = nameof(GlEntryStatus.Draft);
var typeText = type.ToString();
var direction = (type == AccountType.Suppliers ? OpenItemDirection.Payable : OpenItemDirection.Receivable).ToString();
var like = "%" + (search ?? string.Empty).Trim().ToUpperInvariant() + "%";
var rows = await uow.QueryAsync<PartyRow>(SqlFragment.Of($"""
SELECT l.party_id AS party_id, p.name AS name, SUM(l.debit) AS debit, SUM(l.credit) AS credit,
(SELECT COUNT(*) FROM gl_open_items o WHERE o.party_id = l.party_id AND o.direction = {direction} AND o.closed = {false}) AS open_items
FROM gl_entry_lines l JOIN gl_accounts a ON a.id = l.account_id JOIN parties p ON p.id = l.party_id
WHERE a.type = {typeText} AND l.status <> {draft} AND l.entry_date <= {to} AND UPPER(p.name) LIKE {like}
GROUP BY l.party_id, p.name
ORDER BY p.name
"""), cancellationToken).ConfigureAwait(false);
return [.. rows.Select(r => new PartyBalance(r.PartyId, r.Name, r.Debit ?? 0m, r.Credit ?? 0m, (r.Debit ?? 0m) - (r.Credit ?? 0m), (int)r.OpenItems))];
}
/// <summary>The open items of a party (or of all), by due date.</summary>
/// <param name="actor">Who reads.</param>
/// <param name="companyCode">The company.</param>
/// <param name="partyId">The party, or <see langword="null"/> for all.</param>
/// <param name="direction">Receivables or payables.</param>
/// <param name="includeClosed">Show the closed items too.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The items.</returns>
public async Task<IReadOnlyList<OpenItem>> OpenItemsAsync(
Actor actor, string companyCode, long? partyId, OpenItemDirection direction, bool includeClosed = false, CancellationToken cancellationToken = default)
{
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.EntryRead, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
var query = Query.For<OpenItem>().Where(o => o.Direction == direction);
if (partyId is { } id)
{
query = query.Where(o => o.PartyId == id);
}
if (!includeClosed)
{
query = query.Where(o => !o.Closed);
}
return (await uow.Repository<OpenItem, long>().ListAsync(query.OrderBy(o => o.DueDate).OrderBy(o => o.Id), cancellationToken).ConfigureAwait(false)).Items;
}
/// <summary>The trial balance of a period (bilancio di verifica), optionally of one cost center.</summary>
/// <param name="actor">Who reads.</param>
/// <param name="companyCode">The company.</param>
/// <param name="from">From this day.</param>
/// <param name="to">Up to this day.</param>
/// <param name="costCenterId">Only the lines of this cost center.</param>
/// <param name="includeDrafts">Count the drafts too.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The trial balance.</returns>
public async Task<TrialBalance> TrialBalanceAsync(
Actor actor, string companyCode, DateOnly from, DateOnly to, long? costCenterId = null, bool includeDrafts = false, CancellationToken cancellationToken = default)
{
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.EntryRead, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
return await TrialBalanceAsync(uow, from, to, costCenterId, includeDrafts, cancellationToken).ConfigureAwait(false);
}
/// <summary>The trial balance as PDF.</summary>
/// <param name="actor">Who prints.</param>
/// <param name="companyCode">The company.</param>
/// <param name="from">From this day.</param>
/// <param name="to">Up to this day.</param>
/// <param name="costCenterId">Only the lines of this cost center.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The file.</returns>
public async Task<LedgerFile> PrintTrialBalanceAsync(Actor actor, string companyCode, DateOnly from, DateOnly to, long? costCenterId = null, CancellationToken cancellationToken = default)
{
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.EntryRead, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
var balance = await TrialBalanceAsync(uow, from, to, costCenterId, includeDrafts: false, cancellationToken).ConfigureAwait(false);
var profile = await uow.Repository<CompanyProfile, long>().FindAsync(Query.For<CompanyProfile>(), cancellationToken).ConfigureAwait(false);
var center = costCenterId is { } c ? await uow.Repository<CostCenter, long>().GetAsync(c, cancellationToken).ConfigureAwait(false) : null;
var rows = new List<IReadOnlyList<string?>>();
foreach (var line in balance.Lines)
{
var bold = line.Level < 3 ? "**" : string.Empty;
rows.Add([
bold + line.Code, new string(' ', (line.Level - 1) * 2) + line.Description, LedgerReport.Money(line.Opening), LedgerReport.Money(line.Debit),
LedgerReport.Money(line.Credit), line.Closing > 0m ? LedgerReport.Money(line.Closing) : null, line.Closing < 0m ? LedgerReport.Money(-line.Closing) : null,
]);
}
rows.Add(["**Totali", null, null, LedgerReport.Money(balance.TotalDebit), LedgerReport.Money(balance.TotalCredit), null, null]);
rows.Add(["**Risultato", balance.Result >= 0m ? "Utile del periodo" : "Perdita del periodo", null, null, null, null, LedgerReport.Money(Math.Abs(balance.Result))]);
var (file, _) = await LedgerReport.WriteAsync(
VatService.CompanyLine(profile),
"Bilancio di verifica" + (center is null ? string.Empty : " - centro di costo " + center.Code + " " + center.Description),
"Dal " + LedgerReport.Date(from) + " al " + LedgerReport.Date(to),
[new("Conto", 70), new("Descrizione", 260), new("Saldo iniziale", 85, true), new("Dare", 85, true), new("Avere", 85, true), new("Saldo dare", 85, true),
new("Saldo avere", 85, true)],
rows,
to.Year,
1,
cancellationToken).ConfigureAwait(false);
return new LedgerFile(string.Create(CultureInfo.InvariantCulture, $"bilancio_verifica_{from:yyyyMMdd}_{to:yyyyMMdd}.pdf"), Infrastructure.Files.PdfWriter.MediaType, file);
}
/// <summary>The movements of an account or party as PDF (mastrino, estratto conto).</summary>
/// <param name="actor">Who prints.</param>
/// <param name="companyCode">The company.</param>
/// <param name="filter">The account or party and the period (the page is ignored).</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The file.</returns>
public async Task<LedgerFile> PrintMovementsAsync(Actor actor, string companyCode, LedgerFilter filter, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(filter);
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.EntryRead, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
var page = await MovementsAsync(uow, filter with { Offset = 0, Limit = 100_000 }, cancellationToken).ConfigureAwait(false);
var profile = await uow.Repository<CompanyProfile, long>().FindAsync(Query.For<CompanyProfile>(), cancellationToken).ConfigureAwait(false);
var account = filter.AccountId is { } a ? await uow.Repository<GlAccount, long>().GetAsync(a, cancellationToken).ConfigureAwait(false) : null;
var party = filter.PartyId is { } p ? await uow.Repository<Core.Parties.Party, long>().GetAsync(p, cancellationToken).ConfigureAwait(false) : null;
var title = party is not null ? "Estratto conto " + party.Name : "Mastrino " + account?.Code + " " + account?.Description;
var rows = new List<IReadOnlyList<string?>> { new[] { "**Saldo iniziale", null, null, null, null, null, Signed(page.Opening) } };
foreach (var m in page.Movements)
{
rows.Add([LedgerReport.Date(m.EntryDate), m.EntryNumber, m.DocumentNumber, m.Description, LedgerReport.Money(m.Debit), LedgerReport.Money(m.Credit), Signed(m.Balance)]);
}
rows.Add(["**Totali", null, null, null, LedgerReport.Money(page.TotalDebit), LedgerReport.Money(page.TotalCredit), Signed(page.Closing)]);
var (file, _) = await LedgerReport.WriteAsync(
VatService.CompanyLine(profile), title, "Dal " + LedgerReport.Date(filter.From) + " al " + LedgerReport.Date(filter.To),
[new("Data", 55), new("Registrazione", 70), new("Documento", 80), new("Descrizione", 300), new("Dare", 80, true), new("Avere", 80, true), new("Saldo", 90, true)],
rows, filter.To.Year, 1, cancellationToken).ConfigureAwait(false);
return new LedgerFile(
string.Create(CultureInfo.InvariantCulture, $"{(party is not null ? "estratto_conto_" + party.Code : "mastrino_" + account?.Code)}_{filter.To:yyyyMMdd}.pdf"),
Infrastructure.Files.PdfWriter.MediaType,
file);
}
/// <summary>
/// The general journal (libro giornale) of a period: every entry in date order with its lines. The provisional
/// print shows the posted entries too; the final one only the final entries, with their journal numbers and the
/// pages numbered from the first page of the year.
/// </summary>
/// <param name="actor">Who prints.</param>
/// <param name="companyCode">The company.</param>
/// <param name="from">From this day.</param>
/// <param name="to">Up to this day.</param>
/// <param name="final">Only the final entries.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The file.</returns>
public async Task<LedgerFile> PrintJournalAsync(Actor actor, string companyCode, DateOnly from, DateOnly to, bool final = false, CancellationToken cancellationToken = default)
{
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.EntryRead, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
var profile = await uow.Repository<CompanyProfile, long>().FindAsync(Query.For<CompanyProfile>(), cancellationToken).ConfigureAwait(false);
var fiscalYear = await uow.Repository<FiscalYear, long>().FindAsync(Query.For<FiscalYear>().Where(y => y.StartDate <= to && y.EndDate >= to), cancellationToken).ConfigureAwait(false);
var draft = nameof(GlEntryStatus.Draft);
var finalText = nameof(GlEntryStatus.Final);
var condition = final ? SqlFragment.Of($"e.status = {finalText}") : SqlFragment.Of($"e.status <> {draft}");
var lines = await uow.QueryAsync<JournalRow>(SqlFragment.Of($"""
SELECT e.id AS entry_id, e.entry_number AS entry_number, e.journal_number AS journal_number, e.entry_date AS entry_date, e.description AS entry_description,
e.document_number AS document_number, a.code AS account_code, a.description AS account_description, p.name AS party_name,
l.description AS description, l.debit AS debit, l.credit AS credit
FROM gl_entries e JOIN gl_entry_lines l ON l.entry_id = e.id JOIN gl_accounts a ON a.id = l.account_id LEFT JOIN parties p ON p.id = l.party_id
WHERE e.entry_date >= {from} AND e.entry_date <= {to} AND {condition}
ORDER BY e.entry_date, e.journal_number, e.number, e.id, l.line_number
"""), cancellationToken).ConfigureAwait(false);
var rows = new List<IReadOnlyList<string?>>();
long? current = null;
foreach (var line in lines)
{
if (line.EntryId != current)
{
current = line.EntryId;
rows.Add([
"**" + LedgerReport.Date(line.EntryDate), line.JournalNumber?.ToString(CultureInfo.InvariantCulture) ?? line.EntryNumber, null,
line.EntryDescription + (line.DocumentNumber is { Length: > 0 } d ? " - doc. " + d : string.Empty), null, null,
]);
}
rows.Add([null, null, line.AccountCode, line.AccountDescription + (line.PartyName is { Length: > 0 } n ? " - " + n : string.Empty) + (line.Description is { Length: > 0 } t && t != line.EntryDescription ? " (" + t + ")" : string.Empty),
LedgerReport.Money(line.Debit), LedgerReport.Money(line.Credit)]);
}
rows.Add(["**Totali del periodo", null, null, null, LedgerReport.Money(lines.Sum(l => l.Debit)), LedgerReport.Money(lines.Sum(l => l.Credit))]);
var (file, _) = await LedgerReport.WriteAsync(
VatService.CompanyLine(profile),
"Libro giornale",
(final ? "Registrazioni definitive" : "Stampa provvisoria") + " dal " + LedgerReport.Date(from) + " al " + LedgerReport.Date(to),
[new("Data", 60), new("Numero", 65), new("Conto", 65), new("Descrizione", 400), new("Dare", 90, true), new("Avere", 90, true)],
rows,
to.Year,
final ? Math.Max(1, fiscalYear?.JournalFirstPage ?? 1) : 1,
cancellationToken).ConfigureAwait(false);
return new LedgerFile(
string.Create(CultureInfo.InvariantCulture, $"libro_giornale_{from:yyyyMMdd}_{to:yyyyMMdd}{(final ? "_definitivo" : "_provvisorio")}.pdf"),
Infrastructure.Files.PdfWriter.MediaType,
file);
}
/// <summary>The movements of an account or party, paged in the database, with the running balance.</summary>
internal static async Task<LedgerPage> MovementsAsync(IUnitOfWork uow, LedgerFilter filter, CancellationToken cancellationToken)
{
if (filter.AccountId is null && filter.PartyId is null)
{
throw new ValidationFailedException(["AccountId:" + LedgerErrors.AccountRequired]);
}
var where = Condition(filter);
var from = filter.From;
var to = filter.To;
var opening = await uow.QuerySingleAsync<decimal?>(SqlFragment.Of($"SELECT SUM(l.debit - l.credit) FROM gl_entry_lines l WHERE {where} AND l.entry_date < {from}"), cancellationToken)
.ConfigureAwait(false) ?? 0m;
var totals = (await uow.QueryAsync<TotalsRow>(SqlFragment.Of($"""
SELECT COUNT(*) AS lines, SUM(l.debit) AS debit, SUM(l.credit) AS credit FROM gl_entry_lines l
WHERE {where} AND l.entry_date >= {from} AND l.entry_date <= {to}
"""), cancellationToken).ConfigureAwait(false))[0];
var offset = Math.Max(0, filter.Offset);
var limit = Math.Clamp(filter.Limit, 1, 100_000);
var before = offset == 0
? 0m
: await uow.QuerySingleAsync<decimal?>(SqlFragment.Of($"""
SELECT SUM(x.amount) FROM (
SELECT l.debit - l.credit AS amount FROM gl_entry_lines l JOIN gl_entries e ON e.id = l.entry_id
WHERE {where} AND l.entry_date >= {from} AND l.entry_date <= {to}
ORDER BY l.entry_date, e.number, l.entry_id, l.line_number LIMIT {offset}) x
"""), cancellationToken).ConfigureAwait(false) ?? 0m;
var rows = await uow.QueryAsync<MovementRow>(SqlFragment.Of($"""
SELECT l.entry_id AS entry_id, e.entry_number AS entry_number, l.entry_date AS entry_date, COALESCE(l.description, e.description) AS description,
e.document_number AS document_number, e.document_date AS document_date, e.template_code AS template_code, a.code AS account_code,
l.debit AS debit, l.credit AS credit, l.status AS status
FROM gl_entry_lines l JOIN gl_entries e ON e.id = l.entry_id JOIN gl_accounts a ON a.id = l.account_id
WHERE {where} AND l.entry_date >= {from} AND l.entry_date <= {to}
ORDER BY l.entry_date, e.number, l.entry_id, l.line_number
LIMIT {limit} OFFSET {offset}
"""), cancellationToken).ConfigureAwait(false);
var balance = opening + before;
var movements = new List<LedgerMovement>(rows.Count);
foreach (var r in rows)
{
balance += r.Debit - r.Credit;
movements.Add(new LedgerMovement(r.EntryId, r.EntryNumber, r.EntryDate, r.Description, r.DocumentNumber, r.DocumentDate, r.TemplateCode, r.AccountCode, r.Debit, r.Credit, balance, r.Status));
}
var debit = totals.Debit ?? 0m;
var credit = totals.Credit ?? 0m;
return new LedgerPage(opening, movements, totals.Lines, debit, credit, opening + debit - credit);
}
/// <summary>The trial balance, with the totals of the parent accounts.</summary>
internal static async Task<TrialBalance> TrialBalanceAsync(IUnitOfWork uow, DateOnly from, DateOnly to, long? costCenterId, bool includeDrafts, CancellationToken cancellationToken)
{
var draft = nameof(GlEntryStatus.Draft);
var status = includeDrafts ? SqlFragment.Literal("1 = 1") : SqlFragment.Of($"l.status <> {draft}");
var center = costCenterId is { } c ? SqlFragment.Of($"l.cost_center_id = {c}") : SqlFragment.Literal("1 = 1");
var sums = await uow.QueryAsync<BalanceRow>(SqlFragment.Of($"""
SELECT l.account_id AS account_id,
SUM(CASE WHEN l.entry_date < {from} THEN l.debit - l.credit ELSE 0 END) AS opening,
SUM(CASE WHEN l.entry_date >= {from} THEN l.debit ELSE 0 END) AS debit,
SUM(CASE WHEN l.entry_date >= {from} THEN l.credit ELSE 0 END) AS credit
FROM gl_entry_lines l
WHERE l.entry_date <= {to} AND {status} AND {center}
GROUP BY l.account_id
"""), cancellationToken).ConfigureAwait(false);
var accounts = await LedgerStore.AccountsAsync(uow, cancellationToken).ConfigureAwait(false);
var totals = new Dictionary<long, (decimal Opening, decimal Debit, decimal Credit)>();
foreach (var s in sums)
{
var id = (long?)s.AccountId;
while (id is { } current && accounts.TryGetValue(current, out var account))
{
totals.TryGetValue(current, out var t);
totals[current] = (t.Opening + (s.Opening ?? 0m), t.Debit + (s.Debit ?? 0m), t.Credit + (s.Credit ?? 0m));
id = account.ParentId;
}
}
var lines = totals
.Select(kv => (Account: accounts[kv.Key], kv.Value))
.Where(x => x.Value.Opening != 0m || x.Value.Debit != 0m || x.Value.Credit != 0m)
.OrderBy(x => x.Account.Code, StringComparer.Ordinal)
.Select(x => new TrialBalanceLine(
x.Account.Id, x.Account.Code, x.Account.Description, x.Account.Level, x.Account.Nature, x.Value.Opening, x.Value.Debit, x.Value.Credit,
x.Value.Opening + x.Value.Debit - x.Value.Credit))
.ToList();
var leaves = lines.Where(l => accounts[l.AccountId].Postable).ToList();
var result = -leaves.Where(l => l.Nature is AccountNature.Revenue or AccountNature.Cost).Sum(l => l.Debit - l.Credit);
return new TrialBalance(lines, leaves.Sum(l => l.Debit), leaves.Sum(l => l.Credit), result);
}
private static SqlFragment Condition(LedgerFilter filter)
{
var draft = nameof(GlEntryStatus.Draft);
var status = filter.IncludeDrafts ? SqlFragment.Literal("1 = 1") : SqlFragment.Of($"l.status <> {draft}");
var account = filter.AccountId is { } a ? SqlFragment.Of($"l.account_id = {a}") : SqlFragment.Literal("1 = 1");
var party = filter.PartyId is { } p ? SqlFragment.Of($"l.party_id = {p}") : SqlFragment.Literal("1 = 1");
return SqlFragment.Of($"{status} AND {account} AND {party}");
}
private static string? Signed(decimal amount) => amount == 0m ? "0,00" : LedgerReport.Money(Math.Abs(amount)) + (amount > 0m ? " D" : " A");
private sealed record MovementRow(
long EntryId, string? EntryNumber, DateOnly EntryDate, string? Description, string? DocumentNumber, DateOnly? DocumentDate, string? TemplateCode, string? AccountCode,
decimal Debit, decimal Credit, GlEntryStatus Status);
private sealed record TotalsRow(long Lines, decimal? Debit, decimal? Credit);
private sealed record BalanceRow(long AccountId, decimal? Opening, decimal? Debit, decimal? Credit);
private sealed record PartyRow(long PartyId, string Name, decimal? Debit, decimal? Credit, long OpenItems);
private sealed record JournalRow(
long EntryId, string? EntryNumber, long? JournalNumber, DateOnly EntryDate, string EntryDescription, string? DocumentNumber, string AccountCode, string AccountDescription,
string? PartyName, string? Description, decimal Debit, decimal Credit);
}
@@ -0,0 +1,138 @@
using System.Globalization;
using Khaemhat.Infrastructure.Files;
namespace Khaemhat.Application.Ledger;
/// <summary>A column of a ledger print.</summary>
/// <param name="Title">The heading.</param>
/// <param name="Width">The width in points.</param>
/// <param name="Right">Aligned on the right (amounts).</param>
public sealed record ReportColumn(string Title, double Width, bool Right = false);
/// <summary>
/// The prints of the ledger (VAT registers, general journal, ledgers, trial balance, issue #65 and #67): A4 landscape,
/// the company and the title on every page, the headings repeated, the pages numbered from a first page in the form
/// <c>year/page</c> as the final prints of the books want (art. 2215-bis c.c., numbering by year).
/// </summary>
internal static class LedgerReport
{
private const double Margin = 28;
private const double LineHeight = 11;
private static readonly PdfColor Rule = PdfColor.Gray(180);
/// <summary>Writes a print.</summary>
/// <param name="company">The name, VAT number and address of the company.</param>
/// <param name="title">The title, such as <c>Registro IVA vendite</c>.</param>
/// <param name="subtitle">The period and the kind of print.</param>
/// <param name="columns">The columns.</param>
/// <param name="rows">The rows; a row whose first cell starts with <c>**</c> is a bold total.</param>
/// <param name="year">The year of the page numbers.</param>
/// <param name="firstPage">The number of the first page.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The file and the number of pages.</returns>
public static async Task<(byte[] File, int Pages)> WriteAsync(
string company, string title, string subtitle, IReadOnlyList<ReportColumn> columns, IReadOnlyList<IReadOnlyList<string?>> rows, int year, int firstPage,
CancellationToken cancellationToken)
{
using var buffer = new MemoryStream();
int pages;
await using (var pdf = new PdfWriter(buffer, new PdfDocumentInfo { Title = title }, leaveOpen: true))
{
var width = PdfWriter.A4Height;
var height = PdfWriter.A4Width;
var scale = Math.Min(1d, (width - (2 * Margin)) / Math.Max(1d, columns.Sum(c => c.Width)));
PdfPage? page = null;
var y = 0d;
var number = firstPage;
async Task NewPageAsync()
{
page = await pdf.AddPageAsync(width, height, cancellationToken).ConfigureAwait(false);
y = height - Margin;
page.DrawText(company, Margin, y, PdfFont.HelveticaBold, 9);
page.DrawTextRight(year.ToString(CultureInfo.InvariantCulture) + "/" + number.ToString(CultureInfo.InvariantCulture), width - Margin, y, PdfFont.Helvetica, 9);
y -= 14;
page.DrawText(title, Margin, y, PdfFont.HelveticaBold, 12);
y -= 12;
page.DrawText(subtitle, Margin, y, PdfFont.Helvetica, 8.5);
y -= 16;
var x = Margin;
foreach (var column in columns)
{
var w = column.Width * scale;
if (column.Right)
{
page.DrawTextRight(column.Title, x + w - 2, y, PdfFont.HelveticaBold, 7.5);
}
else
{
page.DrawText(column.Title, x + 2, y, PdfFont.HelveticaBold, 7.5);
}
x += w;
}
page.DrawLine(Margin, y - 3, width - Margin, y - 3, 0.6, Rule);
y -= LineHeight + 2;
number++;
}
await NewPageAsync().ConfigureAwait(false);
foreach (var row in rows)
{
if (y < Margin + LineHeight)
{
await NewPageAsync().ConfigureAwait(false);
}
var bold = row.Count > 0 && row[0] is { } first && first.StartsWith("**", StringComparison.Ordinal);
var font = bold ? PdfFont.HelveticaBold : PdfFont.Helvetica;
var x = Margin;
for (var i = 0; i < columns.Count; i++)
{
var w = columns[i].Width * scale;
var text = i < row.Count ? row[i] : null;
if (i == 0 && bold)
{
text = text![2..];
}
text = PdfTextLayout.Fit(text, font, 7.5, w - 4);
if (columns[i].Right)
{
page!.DrawTextRight(text, x + w - 2, y, font, 7.5);
}
else
{
page!.DrawText(text, x + 2, y, font, 7.5);
}
x += w;
}
if (bold)
{
page!.DrawLine(Margin, y + LineHeight - 2, width - Margin, y + LineHeight - 2, 0.4, Rule);
}
y -= LineHeight;
}
pages = pdf.PageCount;
await pdf.CloseAsync(cancellationToken).ConfigureAwait(false);
}
return (buffer.ToArray(), pages);
}
/// <summary>An amount as the prints show it, with the Italian separators.</summary>
/// <param name="amount">The amount.</param>
/// <returns>The text; empty for zero.</returns>
public static string Money(decimal amount) => amount == 0m ? string.Empty : amount.ToString("#,##0.00", Italian);
/// <summary>A date as the prints show it.</summary>
/// <param name="date">The date.</param>
/// <returns>The text.</returns>
public static string Date(DateOnly? date) => date?.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture) ?? string.Empty;
private static readonly CultureInfo Italian = CultureInfo.GetCultureInfo("it-IT");
}
@@ -0,0 +1,508 @@
using Khaemhat.Application.Audit;
using Khaemhat.Application.Documents;
using Khaemhat.Application.ImportExport;
using Khaemhat.Application.Security;
using Khaemhat.Application.Tables;
using Khaemhat.Core.Accounting;
using Khaemhat.Core.Documents;
using Khaemhat.Data;
using Khaemhat.Data.Querying;
namespace Khaemhat.Application.Ledger;
/// <summary>An account typed in the chart.</summary>
/// <param name="Id">The account, for a change.</param>
/// <param name="Code">The code, such as <c>05.01.003</c>.</param>
/// <param name="Description">The description.</param>
/// <param name="Nature">The statement it ends up in (taken from the parent below the first level).</param>
/// <param name="Type">What the automatic postings look for.</param>
public sealed record AccountInput(long? Id, string Code, string Description, AccountNature Nature, AccountType Type = AccountType.Generic)
{
/// <summary>The line of the legal statements.</summary>
public string? StatementLine { get; init; }
/// <summary>The line of the reclassified statements.</summary>
public string? Reclassification { get; init; }
/// <summary>The lines carry a customer or supplier.</summary>
public bool SubLedger { get; init; }
/// <summary>Relevant for VAT.</summary>
public bool VatRelevant { get; init; }
/// <summary>Closed at the year end.</summary>
public bool ClosesAutomatically { get; init; } = true;
/// <summary>No longer used.</summary>
public bool Disabled { get; init; }
}
/// <summary>A line of a journal template typed on its screen.</summary>
/// <param name="Role">What it stands for.</param>
/// <param name="Side">Debit or credit.</param>
/// <param name="AccountId">The account.</param>
/// <param name="Description">The description proposed.</param>
public sealed record TemplateLineInput(PostingRole Role, AccountSide Side, long? AccountId, string? Description);
/// <summary>A journal template typed on its screen (mockup 043).</summary>
/// <param name="Id">The template, for a change.</param>
/// <param name="Code">The code.</param>
/// <param name="Description">The description.</param>
/// <param name="Area">The kind of operations.</param>
/// <param name="Lines">The model of the lines.</param>
public sealed record TemplateInput(long? Id, string Code, string Description, JournalArea Area, IReadOnlyList<TemplateLineInput> Lines)
{
/// <summary>The VAT register.</summary>
public string? VatRegisterCode { get; init; }
/// <summary>Opens items of customers or suppliers.</summary>
public bool OpensItems { get; init; }
/// <summary>Reverses the sides (credit notes).</summary>
public bool Reverses { get; init; }
/// <summary>No longer used.</summary>
public bool Disabled { get; init; }
}
/// <summary>What a bulk posting did.</summary>
/// <param name="Posted">Documents posted or posted again.</param>
/// <param name="Failed">Documents that could not be posted, with the reason.</param>
public sealed record PostingReport(int Posted, IReadOnlyList<string> Failed);
/// <summary>
/// The chart of accounts and the journal templates (SPEC §11.7, issue #62, mockups 042-043, ADR 0036): three levels
/// where only the leaves receive postings, the nature inherited from the mastro, no removal of accounts with postings or
/// children; the import of a chart (CSV, XLSX, JSON) through the guided import; the bulk posting of the documents not yet
/// posted and the posting again of a period (issue #64).
/// </summary>
public sealed class LedgerService
{
private readonly IUnitOfWorkFactory _factory;
private readonly PermissionService _permissions;
private readonly AuditTrail _audit;
/// <summary>Creates the service.</summary>
/// <param name="factory">The units of work.</param>
/// <param name="permissions">The permissions.</param>
/// <param name="audit">The history.</param>
public LedgerService(IUnitOfWorkFactory factory, PermissionService permissions, AuditTrail audit)
{
ArgumentNullException.ThrowIfNull(factory);
ArgumentNullException.ThrowIfNull(permissions);
ArgumentNullException.ThrowIfNull(audit);
_factory = factory;
_permissions = permissions;
_audit = audit;
}
/// <summary>The chart of accounts, by code.</summary>
/// <param name="actor">Who reads.</param>
/// <param name="companyCode">The company.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>Every account.</returns>
public async Task<IReadOnlyList<GlAccount>> AccountsAsync(Actor actor, string companyCode, CancellationToken cancellationToken = default)
{
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.EntryRead, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
return [.. (await uow.Repository<GlAccount, long>().ListAsync(Query.For<GlAccount>(), cancellationToken).ConfigureAwait(false)).Items.OrderBy(a => a.Code, StringComparer.Ordinal)];
}
/// <summary>The VAT registers, by code.</summary>
/// <param name="actor">Who reads.</param>
/// <param name="companyCode">The company.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>Every register.</returns>
public async Task<IReadOnlyList<VatRegister>> RegistersAsync(Actor actor, string companyCode, CancellationToken cancellationToken = default)
{
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.EntryRead, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
// Sales first, then purchases and receipts; the ordinary register before the reverse charge one (enums are stored as text).
var registers = (await uow.Repository<VatRegister, long>().ListAsync(Query.For<VatRegister>(), cancellationToken).ConfigureAwait(false)).Items;
return [.. registers.OrderBy(r => r.Kind).ThenBy(r => r.ReverseCharge).ThenBy(r => r.Code, StringComparer.Ordinal)];
}
/// <summary>Saves an account: a new one under a leaf with postings is refused, the parent stops being postable.</summary>
/// <param name="actor">Who writes.</param>
/// <param name="companyCode">The company.</param>
/// <param name="input">The account.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The account as saved.</returns>
public async Task<GlAccount> SaveAccountAsync(Actor actor, string companyCode, AccountInput input, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(input);
ArgumentNullException.ThrowIfNull(actor);
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.AccountWrite, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
var repository = uow.Repository<GlAccount, long>();
var code = (input.Code ?? string.Empty).Trim();
var errors = new List<string>();
var level = AccountCodes.LevelOf(code);
if (level == 0)
{
errors.Add("Code:" + LedgerErrors.AccountCode);
}
if (string.IsNullOrWhiteSpace(input.Description))
{
errors.Add("Description:" + LedgerErrors.DescriptionRequired);
}
GlAccount? before = null;
if (input.Id is { } id)
{
before = await repository.GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(LedgerErrors.AccountMissing);
if (!string.Equals(before.Code, code, StringComparison.Ordinal))
{
errors.Add("Code:" + LedgerErrors.AccountUsed);
}
}
else if (level > 0 && await repository.FindAsync(Query.For<GlAccount>().Where(a => a.Code == code), cancellationToken).ConfigureAwait(false) is not null)
{
errors.Add("Code:" + LedgerErrors.AccountDuplicate);
}
GlAccount? parent = null;
if (level > 1)
{
var parentCode = AccountCodes.ParentOf(code);
parent = await repository.FindAsync(Query.For<GlAccount>().Where(a => a.Code == parentCode), cancellationToken).ConfigureAwait(false);
if (parent is null)
{
errors.Add("Code:" + LedgerErrors.AccountParent);
}
else if (before is null && parent.Postable && await UsedAsync(uow, parent.Id, cancellationToken).ConfigureAwait(false))
{
errors.Add("Code:" + LedgerErrors.AccountUsed);
}
}
if (errors.Count > 0)
{
throw new ValidationFailedException(errors);
}
var account = before is null ? new GlAccount { Code = code, Level = level, ParentId = parent?.Id } : Clone(before);
account.Description = input.Description.Trim();
account.Nature = parent?.Nature ?? input.Nature;
account.Type = input.Type;
account.StatementLine = LedgerStore.Trim(input.StatementLine?.Trim(), 20);
account.Reclassification = LedgerStore.Trim(input.Reclassification?.Trim(), 20);
account.SubLedger = input.SubLedger;
account.VatRelevant = input.VatRelevant;
account.ClosesAutomatically = input.ClosesAutomatically;
account.Disabled = input.Disabled;
if (before is null)
{
account.Postable = level > 1;
account.Id = await repository.InsertAsync(account, cancellationToken).ConfigureAwait(false);
await _audit.RecordAsync(uow, AuditAction.Insert, account.Id, null, account, actor.UserName, cancellationToken).ConfigureAwait(false);
if (parent is { Postable: true })
{
parent.Postable = false;
await repository.UpdateAsync(parent, cancellationToken).ConfigureAwait(false);
}
}
else
{
await repository.UpdateAsync(account, cancellationToken).ConfigureAwait(false);
await _audit.RecordAsync(uow, AuditAction.Update, account.Id, before, account, actor.UserName, cancellationToken).ConfigureAwait(false);
}
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
return account;
}
/// <summary>Removes an account without children, postings or use in the templates.</summary>
/// <param name="actor">Who removes it.</param>
/// <param name="companyCode">The company.</param>
/// <param name="id">The account.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
public async Task DeleteAccountAsync(Actor actor, string companyCode, long id, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(actor);
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.AccountWrite, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
var repository = uow.Repository<GlAccount, long>();
var account = await repository.GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(LedgerErrors.AccountMissing);
if (await repository.CountAsync(Query.For<GlAccount>().Where(a => a.ParentId == id), cancellationToken).ConfigureAwait(false) > 0)
{
throw new ValidationFailedException(["Id:" + LedgerErrors.AccountHasChildren]);
}
var inTemplates = await uow.Repository<JournalTemplateLine, long>().CountAsync(Query.For<JournalTemplateLine>().Where(l => l.AccountId == id), cancellationToken)
.ConfigureAwait(false);
if (inTemplates > 0 || await UsedAsync(uow, id, cancellationToken).ConfigureAwait(false))
{
throw new ValidationFailedException(["Id:" + LedgerErrors.AccountUsed]);
}
await repository.DeleteAsync(id, cancellationToken).ConfigureAwait(false);
await _audit.RecordAsync(uow, AuditAction.Delete, id, account, (GlAccount?)null, actor.UserName, cancellationToken).ConfigureAwait(false);
if (account.ParentId is { } parentId
&& await repository.CountAsync(Query.For<GlAccount>().Where(a => a.ParentId == parentId), cancellationToken).ConfigureAwait(false) == 0
&& await repository.GetAsync(parentId, cancellationToken).ConfigureAwait(false) is { Level: > 1 } parent)
{
parent.Postable = true;
await repository.UpdateAsync(parent, cancellationToken).ConfigureAwait(false);
}
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
}
/// <summary>The journal templates with their lines.</summary>
/// <param name="actor">Who reads.</param>
/// <param name="companyCode">The company.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>Every template, by code.</returns>
public async Task<IReadOnlyList<TemplateView>> TemplatesAsync(Actor actor, string companyCode, CancellationToken cancellationToken = default)
{
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.EntryRead, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
var templates = (await uow.Repository<JournalTemplate, long>().ListAsync(Query.For<JournalTemplate>().OrderBy(t => t.Code), cancellationToken).ConfigureAwait(false)).Items;
var lines = (await uow.Repository<JournalTemplateLine, long>().ListAsync(Query.For<JournalTemplateLine>().OrderBy(l => l.SortOrder), cancellationToken).ConfigureAwait(false)).Items;
return [.. templates.Select(t => new TemplateView(t, [.. lines.Where(l => l.JournalTemplateId == t.Id)]))];
}
/// <summary>Saves a journal template with its lines.</summary>
/// <param name="actor">Who writes.</param>
/// <param name="companyCode">The company.</param>
/// <param name="input">The template.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The template as saved.</returns>
public async Task<TemplateView> SaveTemplateAsync(Actor actor, string companyCode, TemplateInput input, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(input);
ArgumentNullException.ThrowIfNull(actor);
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.AccountWrite, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
var repository = uow.Repository<JournalTemplate, long>();
var code = (input.Code ?? string.Empty).Trim().ToUpperInvariant();
var errors = new List<string>();
if (code.Length is 0 or > 10)
{
errors.Add("Code:" + LedgerErrors.TemplateCode);
}
if (string.IsNullOrWhiteSpace(input.Description))
{
errors.Add("Description:" + LedgerErrors.DescriptionRequired);
}
var other = await repository.FindAsync(Query.For<JournalTemplate>().Where(t => t.Code == code), cancellationToken).ConfigureAwait(false);
if (other is not null && other.Id != input.Id)
{
errors.Add("Code:" + LedgerErrors.TemplateDuplicate);
}
if (input.VatRegisterCode is { Length: > 0 } registerCode && await LedgerStore.RegisterAsync(uow, registerCode, cancellationToken).ConfigureAwait(false) is null)
{
errors.Add("VatRegisterCode:" + LedgerErrors.VatRegisterRequired);
}
if (errors.Count > 0)
{
throw new ValidationFailedException(errors);
}
JournalTemplate? before = input.Id is { } id ? await repository.GetAsync(id, cancellationToken).ConfigureAwait(false) : null;
var template = before is null ? new JournalTemplate() : new JournalTemplate { Id = before.Id, RowVersion = before.RowVersion, CreatedAt = before.CreatedAt, CreatedBy = before.CreatedBy, IsDemo = before.IsDemo };
template.Code = code;
template.Description = input.Description.Trim();
template.Area = input.Area;
template.VatRegisterCode = string.IsNullOrWhiteSpace(input.VatRegisterCode) ? null : input.VatRegisterCode.Trim();
template.OpensItems = input.OpensItems;
template.Reverses = input.Reverses;
template.Disabled = input.Disabled;
if (before is null)
{
template.Id = await repository.InsertAsync(template, cancellationToken).ConfigureAwait(false);
await _audit.RecordAsync(uow, AuditAction.Insert, template.Id, null, template, actor.UserName, cancellationToken).ConfigureAwait(false);
}
else
{
await repository.UpdateAsync(template, cancellationToken).ConfigureAwait(false);
await _audit.RecordAsync(uow, AuditAction.Update, template.Id, before, template, actor.UserName, cancellationToken).ConfigureAwait(false);
}
var templateId = template.Id;
await uow.ExecuteAsync(SqlFragment.Of($"DELETE FROM gl_journal_template_lines WHERE journal_template_id = {templateId}"), cancellationToken).ConfigureAwait(false);
var lines = new List<JournalTemplateLine>();
for (var i = 0; i < input.Lines.Count; i++)
{
var line = input.Lines[i];
var row = new JournalTemplateLine
{
JournalTemplateId = templateId,
SortOrder = (i + 1) * 10,
Role = line.Role,
Side = line.Side,
AccountId = line.AccountId,
Description = LedgerStore.Trim(line.Description, 100),
};
row.Id = await uow.Repository<JournalTemplateLine, long>().InsertAsync(row, cancellationToken).ConfigureAwait(false);
lines.Add(row);
}
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
return new TemplateView(template, lines);
}
/// <summary>Removes a template that no entry or document type uses.</summary>
/// <param name="actor">Who removes it.</param>
/// <param name="companyCode">The company.</param>
/// <param name="id">The template.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
public async Task DeleteTemplateAsync(Actor actor, string companyCode, long id, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(actor);
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.AccountWrite, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
var template = await uow.Repository<JournalTemplate, long>().GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(LedgerErrors.TemplateMissing);
var code = template.Code;
var entries = await uow.Repository<GlEntry, long>().CountAsync(Query.For<GlEntry>().Where(e => e.JournalTemplateId == id), cancellationToken).ConfigureAwait(false);
var types = await uow.Repository<Core.Tables.DocumentType, long>().CountAsync(Query.For<Core.Tables.DocumentType>().Where(t => t.JournalTemplateCode == code), cancellationToken)
.ConfigureAwait(false);
if (entries > 0 || types > 0)
{
throw new ValidationFailedException(["Id:" + LedgerErrors.TemplateUsed]);
}
await uow.ExecuteAsync(SqlFragment.Of($"DELETE FROM gl_journal_template_lines WHERE journal_template_id = {id}"), cancellationToken).ConfigureAwait(false);
await uow.Repository<JournalTemplate, long>().DeleteAsync(id, cancellationToken).ConfigureAwait(false);
await _audit.RecordAsync(uow, AuditAction.Delete, id, template, (JournalTemplate?)null, actor.UserName, cancellationToken).ConfigureAwait(false);
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Posts the documents in force of a period that have no entry (issue #64: posting in bulk, for instance after the
/// module is licensed), or with <paramref name="again"/> writes again the entries that are not final.
/// </summary>
/// <param name="actor">Who posts.</param>
/// <param name="companyCode">The company.</param>
/// <param name="from">From this day.</param>
/// <param name="to">Up to this day.</param>
/// <param name="again">Post again also the documents already posted.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>What was posted.</returns>
public async Task<PostingReport> PostPendingAsync(Actor actor, string companyCode, DateOnly from, DateOnly to, bool again = false, CancellationToken cancellationToken = default)
{
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.EntryWrite, cancellationToken).ConfigureAwait(false);
var posted = 0;
var failed = new List<string>();
foreach (var family in new[] { DocumentFamily.SaleDocument, DocumentFamily.PurchaseDocument })
{
List<DocumentHeader> headers;
await using (var read = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false))
{
headers = [.. (await DocumentStores.Of(family).InForceAsync(read, cancellationToken).ConfigureAwait(false))
.Where(h => h.DocumentDate >= from && h.DocumentDate <= to && LedgerPoster.PostingOf(h.Kind) is not null && (again || !h.Posted))
.OrderBy(h => h.DocumentDate).ThenBy(h => h.Id)];
}
foreach (var header in headers)
{
// One transaction per document: one that cannot post does not stop the others.
try
{
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
if (await LedgerPoster.PostAsync(uow, family, header.Id, cancellationToken).ConfigureAwait(false) is not null)
{
posted++;
}
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
}
catch (ValidationFailedException exception)
{
failed.Add((header.DocumentNumber ?? header.Id.ToString(System.Globalization.CultureInfo.InvariantCulture)) + ": " + string.Join(", ", exception.Errors));
}
}
}
return new PostingReport(posted, failed);
}
/// <summary>Writes the accounts the import of a chart accepted: new codes are added, existing ones updated.</summary>
/// <param name="uow">The unit of work, in a transaction.</param>
/// <param name="accounts">The accounts, parents first or in any order.</param>
/// <param name="update">Update the accounts that exist.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>For each code, whether it was created (<see langword="true"/>) or updated.</returns>
internal static async Task<Dictionary<string, bool>> ImportAsync(IUnitOfWork uow, IReadOnlyList<ImportedAccount> accounts, bool update, CancellationToken cancellationToken)
{
var repository = uow.Repository<GlAccount, long>();
var existing = (await repository.ListAsync(Query.For<GlAccount>(), cancellationToken).ConfigureAwait(false)).Items.ToDictionary(a => a.Code, StringComparer.OrdinalIgnoreCase);
var result = new Dictionary<string, bool>(StringComparer.OrdinalIgnoreCase);
foreach (var imported in accounts.OrderBy(a => a.Level).ThenBy(a => a.Code, StringComparer.Ordinal))
{
if (existing.TryGetValue(imported.Code, out var account))
{
if (!update)
{
continue;
}
account.Description = LedgerStore.Trim(imported.Description, 100)!;
account.Nature = imported.Nature;
account.Type = imported.Type;
account.StatementLine = LedgerStore.Trim(imported.StatementLine, 20) ?? account.StatementLine;
account.Reclassification = LedgerStore.Trim(imported.Reclassification, 20) ?? account.Reclassification;
account.VatRelevant = imported.VatRelevant;
account.SubLedger = imported.SubLedger;
account.ClosesAutomatically = imported.ClosesAutomatically;
account.Disabled = imported.Disabled;
await repository.UpdateAsync(account, cancellationToken).ConfigureAwait(false);
result[imported.Code] = false;
continue;
}
account = new GlAccount
{
Code = imported.Code,
Description = LedgerStore.Trim(imported.Description, 100)!,
Level = imported.Level,
ParentId = imported.ParentCode is { } parent && existing.TryGetValue(parent, out var found) ? found.Id : null,
Nature = imported.Nature,
Type = imported.Type,
StatementLine = LedgerStore.Trim(imported.StatementLine, 20),
Reclassification = LedgerStore.Trim(imported.Reclassification, 20),
SubLedger = imported.SubLedger,
VatRelevant = imported.VatRelevant,
ClosesAutomatically = imported.ClosesAutomatically,
Disabled = imported.Disabled,
Postable = imported.Postable,
};
account.Id = await repository.InsertAsync(account, cancellationToken).ConfigureAwait(false);
existing[account.Code] = account;
result[imported.Code] = true;
}
return result;
}
internal static async Task<bool> UsedAsync(IUnitOfWork uow, long accountId, CancellationToken cancellationToken) =>
await uow.Repository<GlEntryLine, long>().CountAsync(Query.For<GlEntryLine>().Where(l => l.AccountId == accountId), cancellationToken).ConfigureAwait(false) > 0;
private static GlAccount Clone(GlAccount a) => new()
{
Id = a.Id,
Code = a.Code,
Level = a.Level,
ParentId = a.ParentId,
Postable = a.Postable,
IsDemo = a.IsDemo,
RowVersion = a.RowVersion,
CreatedAt = a.CreatedAt,
CreatedBy = a.CreatedBy,
UpdatedAt = a.UpdatedAt,
UpdatedBy = a.UpdatedBy,
};
}
@@ -0,0 +1,257 @@
using System.Globalization;
using Khaemhat.Core.Accounting;
using Khaemhat.Data;
using Khaemhat.Data.Querying;
namespace Khaemhat.Application.Ledger;
/// <summary>The permissions of the ledger (module ACCT, <see cref="Modules.BuiltInModules"/>).</summary>
public static class LedgerPermissions
{
/// <summary>See the chart of accounts and the journal templates.</summary>
public const string AccountRead = "ledger.account.read";
/// <summary>Change the chart of accounts and the journal templates.</summary>
public const string AccountWrite = "ledger.account.write";
/// <summary>See the journal, the ledgers and the balances.</summary>
public const string EntryRead = "ledger.entry.read";
/// <summary>Write entries and post documents.</summary>
public const string EntryWrite = "ledger.entry.write";
/// <summary>Make entries final (libro giornale).</summary>
public const string EntryFinalize = "ledger.entry.finalize";
/// <summary>See the VAT registers.</summary>
public const string VatRegisterRead = "vat.register.read";
/// <summary>See the settlements, withholdings, stamp duty and F24.</summary>
public const string SettlementRead = "vat.settlement.read";
/// <summary>Confirm settlements and record tax payments.</summary>
public const string SettlementConfirm = "vat.settlement.confirm";
}
/// <summary>A line of an entry being written.</summary>
/// <param name="AccountId">The account.</param>
/// <param name="PartyId">The customer or supplier.</param>
/// <param name="Description">The description.</param>
/// <param name="Debit">The debit.</param>
/// <param name="Credit">The credit.</param>
/// <param name="CostCenterId">The cost center.</param>
/// <param name="JobId">The job.</param>
public sealed record EntryLineDraft(long? AccountId, long? PartyId, string? Description, decimal Debit, decimal Credit, long? CostCenterId = null, long? JobId = null);
/// <summary>A VAT line of an entry being written.</summary>
/// <param name="TaxCodeId">The VAT code.</param>
/// <param name="Rate">The rate.</param>
/// <param name="Nature">The nature.</param>
/// <param name="Taxable">The taxable amount, with sign.</param>
/// <param name="Tax">The VAT, with sign.</param>
/// <param name="NonDeductibleTax">The VAT not deductible.</param>
/// <param name="Exigibility">When the VAT is due.</param>
/// <param name="RegisterId">The register, when different from the one of the entry (self-invoices).</param>
public sealed record EntryVatDraft(
long? TaxCodeId, decimal Rate, string? Nature, decimal Taxable, decimal Tax, decimal NonDeductibleTax = 0m,
Core.Tax.TaxExigibility Exigibility = Core.Tax.TaxExigibility.Immediate, long? RegisterId = null);
/// <summary>
/// What every writer of the ledger shares (ADR 0036): the numbering of the entries in each year, the
/// writing of an entry with its lines and VAT lines (which keep its date and state), the removal of an entry and the
/// lookups of accounts, templates and registers.
/// </summary>
internal static class LedgerStore
{
/// <summary>Writes a new entry with its lines and VAT lines; posted entries get their number.</summary>
public static async Task<GlEntry> InsertAsync(
IUnitOfWork uow, GlEntry entry, IReadOnlyList<EntryLineDraft> lines, IReadOnlyList<EntryVatDraft> vat, CancellationToken cancellationToken)
{
entry.Year = entry.EntryDate.Year;
entry.TotalDebit = lines.Sum(l => l.Debit);
entry.TotalCredit = lines.Sum(l => l.Credit);
if (entry.Status != GlEntryStatus.Draft && entry.Number is null)
{
await NumberAsync(uow, entry, cancellationToken).ConfigureAwait(false);
}
entry.Id = await uow.Repository<GlEntry, long>().InsertAsync(entry, cancellationToken).ConfigureAwait(false);
await WriteLinesAsync(uow, entry, lines, vat, cancellationToken).ConfigureAwait(false);
return entry;
}
/// <summary>Replaces the lines of an entry and updates it.</summary>
public static async Task UpdateAsync(
IUnitOfWork uow, GlEntry entry, IReadOnlyList<EntryLineDraft> lines, IReadOnlyList<EntryVatDraft> vat, CancellationToken cancellationToken)
{
entry.Year = entry.Number is null ? entry.EntryDate.Year : entry.Year;
entry.TotalDebit = lines.Sum(l => l.Debit);
entry.TotalCredit = lines.Sum(l => l.Credit);
if (entry.Status != GlEntryStatus.Draft && entry.Number is null)
{
await NumberAsync(uow, entry, cancellationToken).ConfigureAwait(false);
}
await uow.Repository<GlEntry, long>().UpdateAsync(entry, cancellationToken).ConfigureAwait(false);
await RemoveLinesAsync(uow, entry.Id, cancellationToken).ConfigureAwait(false);
await WriteLinesAsync(uow, entry, lines, vat, cancellationToken).ConfigureAwait(false);
}
/// <summary>Changes the state of an entry and of its lines.</summary>
public static async Task SetStatusAsync(IUnitOfWork uow, GlEntry entry, GlEntryStatus status, CancellationToken cancellationToken)
{
entry.Status = status;
if (status != GlEntryStatus.Draft && entry.Number is null)
{
await NumberAsync(uow, entry, cancellationToken).ConfigureAwait(false);
}
await uow.Repository<GlEntry, long>().UpdateAsync(entry, cancellationToken).ConfigureAwait(false);
var text = status.ToString();
await uow.ExecuteAsync(SqlFragment.Of($"UPDATE gl_entry_lines SET status = {text} WHERE entry_id = {entry.Id}"), cancellationToken).ConfigureAwait(false);
await uow.ExecuteAsync(SqlFragment.Of($"UPDATE gl_entry_vat SET status = {text} WHERE entry_id = {entry.Id}"), cancellationToken).ConfigureAwait(false);
}
/// <summary>Removes an entry with its lines, VAT lines and open items.</summary>
public static async Task DeleteAsync(IUnitOfWork uow, long entryId, CancellationToken cancellationToken)
{
await RemoveLinesAsync(uow, entryId, cancellationToken).ConfigureAwait(false);
await uow.ExecuteAsync(SqlFragment.Of($"DELETE FROM gl_open_items WHERE entry_id = {entryId}"), cancellationToken).ConfigureAwait(false);
await uow.ExecuteAsync(SqlFragment.Of($"UPDATE gl_entries SET reversed_by_id = NULL WHERE reversed_by_id = {entryId}"), cancellationToken).ConfigureAwait(false);
await uow.Repository<GlEntry, long>().DeleteAsync(entryId, cancellationToken).ConfigureAwait(false);
}
/// <summary>The lines of an entry, in order.</summary>
public static async Task<IReadOnlyList<GlEntryLine>> LinesAsync(IUnitOfWork uow, long entryId, CancellationToken cancellationToken) =>
(await uow.Repository<GlEntryLine, long>().ListAsync(Query.For<GlEntryLine>().Where(l => l.EntryId == entryId).OrderBy(l => l.LineNumber), cancellationToken)
.ConfigureAwait(false)).Items;
/// <summary>The VAT lines of an entry, in order.</summary>
public static async Task<IReadOnlyList<GlEntryVat>> VatAsync(IUnitOfWork uow, long entryId, CancellationToken cancellationToken) =>
(await uow.Repository<GlEntryVat, long>().ListAsync(Query.For<GlEntryVat>().Where(l => l.EntryId == entryId).OrderBy(l => l.LineNumber), cancellationToken)
.ConfigureAwait(false)).Items;
/// <summary>Every account, by id.</summary>
public static async Task<Dictionary<long, GlAccount>> AccountsAsync(IUnitOfWork uow, CancellationToken cancellationToken) =>
(await uow.Repository<GlAccount, long>().ListAsync(Query.For<GlAccount>(), cancellationToken).ConfigureAwait(false)).Items.ToDictionary(a => a.Id);
/// <summary>The rules the validator reads, by id.</summary>
public static Dictionary<long, AccountRule> Rules(IReadOnlyDictionary<long, GlAccount> accounts) =>
accounts.Values.ToDictionary(a => a.Id, a => new AccountRule(a.Id, a.Postable, a.Disabled, a.SubLedger));
/// <summary>A journal template with its lines, by code.</summary>
public static async Task<(JournalTemplate Template, IReadOnlyList<JournalTemplateLine> Lines)?> TemplateAsync(
IUnitOfWork uow, string? code, CancellationToken cancellationToken)
{
if (string.IsNullOrWhiteSpace(code))
{
return null;
}
var template = await uow.Repository<JournalTemplate, long>().FindAsync(Query.For<JournalTemplate>().Where(t => t.Code == code), cancellationToken).ConfigureAwait(false);
if (template is null)
{
return null;
}
var lines = (await uow.Repository<JournalTemplateLine, long>().ListAsync(
Query.For<JournalTemplateLine>().Where(l => l.JournalTemplateId == template.Id).OrderBy(l => l.SortOrder), cancellationToken).ConfigureAwait(false)).Items;
return (template, lines);
}
/// <summary>A VAT register by code.</summary>
public static Task<VatRegister?> RegisterAsync(IUnitOfWork uow, string? code, CancellationToken cancellationToken) =>
string.IsNullOrWhiteSpace(code)
? Task.FromResult<VatRegister?>(null)
: uow.Repository<VatRegister, long>().FindAsync(Query.For<VatRegister>().Where(r => r.Code == code), cancellationToken);
/// <summary>The account of a code, if any.</summary>
public static Task<GlAccount?> AccountAsync(IUnitOfWork uow, string? code, CancellationToken cancellationToken) =>
string.IsNullOrWhiteSpace(code)
? Task.FromResult<GlAccount?>(null)
: uow.Repository<GlAccount, long>().FindAsync(Query.For<GlAccount>().Where(a => a.Code == code), cancellationToken);
/// <summary>
/// Gives the entry the next number of its year (protocollo di prima nota). The numbers follow the order of
/// registration, not of the dates: the date order is the one of the journal, given when entries become final.
/// </summary>
public static async Task NumberAsync(IUnitOfWork uow, GlEntry entry, CancellationToken cancellationToken)
{
entry.Year = entry.EntryDate.Year;
var year = entry.Year;
var number = (await uow.QuerySingleAsync<long?>(SqlFragment.Of($"SELECT MAX(number) FROM gl_entries WHERE year = {year}"), cancellationToken).ConfigureAwait(false) ?? 0L) + 1L;
entry.Number = number;
entry.EntryNumber = Format(entry.Year, number);
}
/// <summary>The number of an entry as shown.</summary>
public static string Format(int year, long number) =>
year.ToString(CultureInfo.InvariantCulture) + "/" + number.ToString("D5", CultureInfo.InvariantCulture);
private static async Task RemoveLinesAsync(IUnitOfWork uow, long entryId, CancellationToken cancellationToken)
{
await uow.ExecuteAsync(SqlFragment.Of($"DELETE FROM gl_entry_lines WHERE entry_id = {entryId}"), cancellationToken).ConfigureAwait(false);
await uow.ExecuteAsync(SqlFragment.Of($"DELETE FROM gl_entry_vat WHERE entry_id = {entryId}"), cancellationToken).ConfigureAwait(false);
}
private static async Task WriteLinesAsync(
IUnitOfWork uow, GlEntry entry, IReadOnlyList<EntryLineDraft> lines, IReadOnlyList<EntryVatDraft> vat, CancellationToken cancellationToken)
{
var repository = uow.Repository<GlEntryLine, long>();
for (var i = 0; i < lines.Count; i++)
{
var line = lines[i];
await repository.InsertAsync(new GlEntryLine
{
EntryId = entry.Id,
LineNumber = i + 1,
EntryDate = entry.EntryDate,
Status = entry.Status,
AccountId = line.AccountId ?? 0,
PartyId = line.PartyId,
Description = Trim(line.Description, 200),
Debit = line.Debit,
Credit = line.Credit,
CostCenterId = line.CostCenterId,
JobId = line.JobId,
}, cancellationToken).ConfigureAwait(false);
}
if (vat.Count == 0)
{
return;
}
var registers = (await uow.Repository<VatRegister, long>().ListAsync(Query.For<VatRegister>(), cancellationToken).ConfigureAwait(false)).Items.ToDictionary(r => r.Id);
var vatRepository = uow.Repository<GlEntryVat, long>();
for (var i = 0; i < vat.Count; i++)
{
var line = vat[i];
var registerId = line.RegisterId ?? entry.VatRegisterId ?? 0;
if (!registers.TryGetValue(registerId, out var register))
{
continue;
}
await vatRepository.InsertAsync(new GlEntryVat
{
EntryId = entry.Id,
LineNumber = i + 1,
VatRegisterId = register.Id,
RegisterKind = register.Kind,
VatDate = entry.VatDate ?? entry.EntryDate,
Status = entry.Status,
TaxCodeId = line.TaxCodeId,
Rate = line.Rate,
Nature = line.Nature,
Exigibility = line.Exigibility,
Taxable = line.Taxable,
Tax = line.Tax,
NonDeductibleTax = line.NonDeductibleTax,
}, cancellationToken).ConfigureAwait(false);
}
}
/// <summary>A text cut to a length.</summary>
public static string? Trim(string? text, int length) => text is null || text.Length <= length ? text : text[..length];
}
@@ -0,0 +1,288 @@
using System.Globalization;
using Khaemhat.Application.Audit;
using Khaemhat.Application.Jobs;
using Khaemhat.Application.Licensing;
using Khaemhat.Application.Modules;
using Khaemhat.Application.Security;
using Khaemhat.Application.Tables;
using Khaemhat.Core.Accounting;
using Khaemhat.Core.Instance;
using Khaemhat.Data;
using Khaemhat.Data.Companies;
using Khaemhat.Data.Querying;
namespace Khaemhat.Application.Ledger;
/// <summary>A recurring entry being written.</summary>
/// <param name="Id">The recurring entry, or <see langword="null"/> for a new one.</param>
/// <param name="Description">What it is (rent, leasing, insurance).</param>
/// <param name="ModelEntryId">The entry copied each time (usually a draft kept as model).</param>
/// <param name="Frequency">How often.</param>
/// <param name="NextDate">The date of the next entry.</param>
/// <param name="EndDate">The last date, if any.</param>
/// <param name="Disabled">Suspended.</param>
public sealed record RecurringEntryInput(long? Id, string Description, long ModelEntryId, RecurrenceFrequency Frequency, DateOnly NextDate, DateOnly? EndDate, bool Disabled = false);
/// <summary>
/// The recurring entries (SPEC §11.7, issue #63): a model entry copied at each due date, posted with the date of the
/// due date; the job <c>ledger.recurring</c> writes those due every morning, and the screen can write them on demand.
/// An entry that cannot be posted (closed period, final journal after the date) stops its recurrence at that date
/// and is reported in the run.
/// </summary>
public sealed class RecurringEntryService
{
private readonly IUnitOfWorkFactory _factory;
private readonly PermissionService _permissions;
private readonly JournalEntryService _journal;
private readonly AuditTrail _audit;
/// <summary>Creates the service.</summary>
/// <param name="factory">The units of work.</param>
/// <param name="permissions">The permissions.</param>
/// <param name="journal">The journal.</param>
/// <param name="audit">The history.</param>
public RecurringEntryService(IUnitOfWorkFactory factory, PermissionService permissions, JournalEntryService journal, AuditTrail audit)
{
ArgumentNullException.ThrowIfNull(factory);
ArgumentNullException.ThrowIfNull(permissions);
ArgumentNullException.ThrowIfNull(journal);
ArgumentNullException.ThrowIfNull(audit);
_factory = factory;
_permissions = permissions;
_journal = journal;
_audit = audit;
}
/// <summary>The recurring entries, by next date.</summary>
/// <param name="actor">Who reads.</param>
/// <param name="companyCode">The company.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The recurring entries.</returns>
public async Task<IReadOnlyList<RecurringEntry>> ListAsync(Actor actor, string companyCode, CancellationToken cancellationToken = default)
{
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.EntryRead, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
return (await uow.Repository<RecurringEntry, long>().ListAsync(Query.For<RecurringEntry>().OrderBy(r => r.NextDate), cancellationToken).ConfigureAwait(false)).Items;
}
/// <summary>Writes a recurring entry.</summary>
/// <param name="actor">Who writes.</param>
/// <param name="companyCode">The company.</param>
/// <param name="input">The recurring entry.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The recurring entry.</returns>
public async Task<RecurringEntry> SaveAsync(Actor actor, string companyCode, RecurringEntryInput input, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(actor);
ArgumentNullException.ThrowIfNull(input);
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.EntryWrite, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
var errors = new List<string>();
if (string.IsNullOrWhiteSpace(input.Description))
{
errors.Add("Description:" + LedgerErrors.DescriptionRequired);
}
var model = await uow.Repository<GlEntry, long>().GetAsync(input.ModelEntryId, cancellationToken).ConfigureAwait(false);
if (model is null || model.Source == GlEntrySource.Document || model.VatRegisterId is not null)
{
errors.Add("ModelEntryId:" + LedgerErrors.RecurringModel);
}
if (input.NextDate == default)
{
errors.Add("NextDate:" + LedgerErrors.DateRequired);
}
if (errors.Count > 0)
{
throw new ValidationFailedException(errors);
}
var repository = uow.Repository<RecurringEntry, long>();
RecurringEntry? before = null;
RecurringEntry recurring;
if (input.Id is { } id)
{
recurring = await repository.GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(LedgerErrors.NotFound);
before = new RecurringEntry { Id = recurring.Id, Description = recurring.Description, NextDate = recurring.NextDate, Frequency = recurring.Frequency, Disabled = recurring.Disabled };
}
else
{
recurring = new RecurringEntry();
}
recurring.Description = LedgerStore.Trim(input.Description.Trim(), 200)!;
recurring.ModelEntryId = input.ModelEntryId;
recurring.Frequency = input.Frequency;
recurring.NextDate = input.NextDate;
recurring.EndDate = input.EndDate;
recurring.Disabled = input.Disabled;
if (before is null)
{
recurring.Id = await repository.InsertAsync(recurring, cancellationToken).ConfigureAwait(false);
}
else
{
await repository.UpdateAsync(recurring, cancellationToken).ConfigureAwait(false);
}
await _audit.RecordAsync(uow, before is null ? AuditAction.Insert : AuditAction.Update, recurring.Id, before, recurring, actor.UserName, cancellationToken).ConfigureAwait(false);
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
return recurring;
}
/// <summary>Deletes a recurring entry (the entries already written stay).</summary>
/// <param name="actor">Who deletes.</param>
/// <param name="companyCode">The company.</param>
/// <param name="id">The recurring entry.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
public async Task DeleteAsync(Actor actor, string companyCode, long id, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(actor);
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.EntryWrite, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
var recurring = await uow.Repository<RecurringEntry, long>().GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(LedgerErrors.NotFound);
await uow.Repository<RecurringEntry, long>().DeleteAsync(id, cancellationToken).ConfigureAwait(false);
await _audit.RecordAsync(uow, AuditAction.Delete, id, recurring, null, actor.UserName, cancellationToken).ConfigureAwait(false);
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
}
/// <summary>Writes the recurring entries due up to a day.</summary>
/// <param name="actor">Who writes them.</param>
/// <param name="companyCode">The company.</param>
/// <param name="upTo">Up to this day.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The entries written and the problems met.</returns>
public async Task<(int Written, IReadOnlyList<string> Problems)> GenerateAsync(Actor actor, string companyCode, DateOnly upTo, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(actor);
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.EntryWrite, cancellationToken).ConfigureAwait(false);
IReadOnlyList<RecurringEntry> due;
await using (var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false))
{
due = (await uow.Repository<RecurringEntry, long>().ListAsync(
Query.For<RecurringEntry>().Where(r => !r.Disabled && r.NextDate <= upTo).OrderBy(r => r.NextDate), cancellationToken).ConfigureAwait(false)).Items;
}
var written = 0;
var problems = new List<string>();
foreach (var recurring in due)
{
while (recurring.NextDate <= upTo && (recurring.EndDate is null || recurring.NextDate <= recurring.EndDate))
{
var model = await _journal.GetAsync(actor, company, recurring.ModelEntryId, cancellationToken).ConfigureAwait(false);
if (model is null)
{
problems.Add(recurring.Description + ": " + LedgerErrors.RecurringModel);
break;
}
EntryView entry;
try
{
entry = await _journal.SaveAsync(actor, company, new EntryInput(
null,
recurring.NextDate,
model.Entry.Description,
[.. model.Lines.Select(JournalEntryService.Draft)])
{
JournalTemplateId = model.Entry.JournalTemplateId,
PartyId = model.Entry.PartyId,
Notes = recurring.Description,
Post = true,
}, cancellationToken).ConfigureAwait(false);
}
catch (ValidationFailedException ex)
{
problems.Add(recurring.Description + " " + LedgerReport.Date(recurring.NextDate) + ": " + string.Join(", ", ex.Errors));
break;
}
await using (var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false))
{
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
var source = nameof(GlEntrySource.Recurring);
var entryId = entry.Entry.Id;
await uow.ExecuteAsync(SqlFragment.Of($"UPDATE gl_entries SET source = {source} WHERE id = {entryId}"), cancellationToken).ConfigureAwait(false);
recurring.LastEntryId = entryId;
recurring.NextDate = Next(recurring.NextDate, recurring.Frequency);
if (recurring.EndDate is { } end && recurring.NextDate > end)
{
recurring.Disabled = true;
}
await uow.Repository<RecurringEntry, long>().UpdateAsync(recurring, cancellationToken).ConfigureAwait(false);
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
}
written++;
}
}
return (written, problems);
}
/// <summary>The date after a due date.</summary>
/// <param name="date">The due date.</param>
/// <param name="frequency">How often.</param>
/// <returns>The next due date (the end of the month stays the end of the month).</returns>
public static DateOnly Next(DateOnly date, RecurrenceFrequency frequency)
{
var months = frequency switch
{
RecurrenceFrequency.Quarterly => 3,
RecurrenceFrequency.HalfYearly => 6,
RecurrenceFrequency.Yearly => 12,
_ => 1,
};
var endOfMonth = date.Day == DateTime.DaysInMonth(date.Year, date.Month);
var next = date.AddMonths(months);
return endOfMonth ? new DateOnly(next.Year, next.Month, DateTime.DaysInMonth(next.Year, next.Month)) : next;
}
}
/// <summary>Writes the recurring entries due of every active company with the ledger, every morning.</summary>
/// <param name="companies">The companies.</param>
/// <param name="service">The recurring entries.</param>
/// <param name="license">The licence.</param>
/// <param name="clock">The clock.</param>
public sealed class RecurringEntriesJob(ICompanyRegistry companies, RecurringEntryService service, ILicenseGate license, TimeProvider clock) : IScheduledJob
{
/// <summary>The job type.</summary>
public const string JobType = "ledger.recurring";
/// <inheritdoc />
public string Type => JobType;
/// <inheritdoc />
public async Task<string?> RunAsync(JobContext context, CancellationToken cancellationToken)
{
if (!license.IsModuleActive(ModuleCodes.Accounting))
{
return "Modulo contabilità non attivo.";
}
var today = DateOnly.FromDateTime(clock.GetLocalNow().DateTime);
int written = 0, done = 0;
var problems = new List<string>();
foreach (var company in await companies.ListAsync(cancellationToken).ConfigureAwait(false))
{
if (company.Status is CompanyStatus.Disabled)
{
continue;
}
var (w, p) = await service.GenerateAsync(Actor.System, company.Code, today, cancellationToken).ConfigureAwait(false);
written += w;
problems.AddRange(p.Select(x => company.Code + " - " + x));
done++;
}
return string.Create(CultureInfo.InvariantCulture, $"{done} aziende, {written} registrazioni ricorrenti scritte.")
+ (problems.Count > 0 ? " Non scritte: " + string.Join("; ", problems) : string.Empty);
}
}
@@ -0,0 +1,848 @@
using System.Globalization;
using Khaemhat.Application.Audit;
using Khaemhat.Application.Security;
using Khaemhat.Application.Tables;
using Khaemhat.Core.Accounting;
using Khaemhat.Core.Documents;
using Khaemhat.Core.Parties;
using Khaemhat.Core.Tables;
using Khaemhat.Data;
using Khaemhat.Data.Querying;
using Khaemhat.Fiscal.Abstractions;
using Khaemhat.Infrastructure.Files;
namespace Khaemhat.Application.Ledger;
/// <summary>A withholding with the name of its party.</summary>
/// <param name="Withholding">The withholding.</param>
/// <param name="PartyName">The supplier or customer.</param>
/// <param name="PartyTaxCode">Its tax code (or VAT number).</param>
public sealed record WithholdingRow(Withholding Withholding, string PartyName, string? PartyTaxCode);
/// <summary>The stamp duty on the e-invoices of a quarter.</summary>
/// <param name="Year">The year.</param>
/// <param name="Quarter">The quarter.</param>
/// <param name="Documents">The invoices with stamp duty.</param>
/// <param name="Amount">The duty.</param>
/// <param name="DueDate">When it is paid (moved to a later quarter below the threshold).</param>
/// <param name="Payment">The F24 line, once recorded.</param>
public sealed record StampDutyQuarter(int Year, int Quarter, int Documents, decimal Amount, DateOnly DueDate, TaxPayment? Payment);
/// <summary>An invoice with stamp duty.</summary>
/// <param name="DocumentId">The invoice.</param>
/// <param name="DocumentNumber">Its number.</param>
/// <param name="DocumentDate">Its date.</param>
/// <param name="PartyName">The customer.</param>
/// <param name="Taxable">The taxable amount.</param>
/// <param name="StampDuty">The duty.</param>
/// <param name="Charged">Charged to the customer (otherwise borne by the company).</param>
/// <param name="Kind">The kind of document.</param>
public sealed record StampDutyDocument(long DocumentId, string? DocumentNumber, DateOnly DocumentDate, string? PartyName, decimal Taxable, decimal StampDuty, bool Charged, DocumentKind Kind);
/// <summary>A line of the F24 written by hand.</summary>
/// <param name="Id">The line, or <see langword="null"/> for a new one.</param>
/// <param name="DueDate">The due date.</param>
/// <param name="PaymentCode">The payment code.</param>
/// <param name="ReferenceYear">The reference year.</param>
/// <param name="ReferencePeriod">The month or installment.</param>
/// <param name="Description">What it pays.</param>
/// <param name="Amount">The amount (negative for a credit used in compensation).</param>
public sealed record TaxPaymentInput(long? Id, DateOnly DueDate, string PaymentCode, int ReferenceYear, string? ReferencePeriod, string Description, decimal Amount);
/// <summary>
/// The taxes that the ledger pays and keeps (SPEC §11.7, issues #65-#66, mockups 047 and 060, ADR 0037): the lines of
/// the F24 with their data file and their payment entry; the withholdings operated on the fees received (due when the
/// invoice is paid, by the 16th of the next month) and suffered on the fees issued, with the data for the CU; the
/// quarterly stamp duty on the e-invoices.
/// </summary>
public sealed class TaxService
{
/// <summary>The stamp duty of a quarter at or below this moves to the next due date (DM 4/12/2023).</summary>
public const decimal StampDutyThreshold = 5000m;
// The sale documents that carry the stamp duty of the quarter: invoices, fees, debit and credit notes.
private static readonly SqlFragment StampKinds = SqlFragment.Join(", ", new[]
{
DocumentKind.ImmediateInvoice, DocumentKind.AccompanyingInvoice, DocumentKind.DeferredInvoice, DocumentKind.DownPaymentInvoice,
DocumentKind.CreditNote, DocumentKind.DebitNote, DocumentKind.Fee,
}.Select(k => SqlFragment.Parameter(k.ToString())));
private readonly IUnitOfWorkFactory _factory;
private readonly PermissionService _permissions;
private readonly CompanyFiscalContext _packs;
private readonly AuditTrail _audit;
private readonly TimeProvider _clock;
/// <summary>Creates the service.</summary>
/// <param name="factory">The units of work.</param>
/// <param name="permissions">The permissions.</param>
/// <param name="packs">The fiscal pack of each company.</param>
/// <param name="audit">The history.</param>
/// <param name="clock">The clock.</param>
public TaxService(IUnitOfWorkFactory factory, PermissionService permissions, CompanyFiscalContext packs, AuditTrail audit, TimeProvider clock)
{
ArgumentNullException.ThrowIfNull(factory);
ArgumentNullException.ThrowIfNull(permissions);
ArgumentNullException.ThrowIfNull(packs);
ArgumentNullException.ThrowIfNull(audit);
ArgumentNullException.ThrowIfNull(clock);
_factory = factory;
_permissions = permissions;
_packs = packs;
_audit = audit;
_clock = clock;
}
/// <summary>The F24 lines due in a year.</summary>
/// <param name="actor">Who reads.</param>
/// <param name="companyCode">The company.</param>
/// <param name="year">The year of the due dates.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The lines, by due date and code.</returns>
public async Task<IReadOnlyList<TaxPayment>> PaymentsAsync(Actor actor, string companyCode, int year, CancellationToken cancellationToken = default)
{
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.SettlementRead, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
var from = new DateOnly(year, 1, 1);
var to = new DateOnly(year, 12, 31);
return (await uow.Repository<TaxPayment, long>().ListAsync(
Query.For<TaxPayment>().Where(t => t.DueDate >= from && t.DueDate <= to).OrderBy(t => t.DueDate).OrderBy(t => t.PaymentCode), cancellationToken).ConfigureAwait(false)).Items;
}
/// <summary>Writes a line of the F24 by hand (a tax the ledger does not compute, or a credit used in compensation).</summary>
/// <param name="actor">Who writes.</param>
/// <param name="companyCode">The company.</param>
/// <param name="input">The line.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The line.</returns>
public async Task<TaxPayment> SavePaymentAsync(Actor actor, string companyCode, TaxPaymentInput input, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(actor);
ArgumentNullException.ThrowIfNull(input);
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.SettlementConfirm, cancellationToken).ConfigureAwait(false);
var errors = new List<string>();
if (string.IsNullOrWhiteSpace(input.PaymentCode) || input.PaymentCode.Trim().Length > 10)
{
errors.Add("PaymentCode:" + LedgerErrors.AmountRequired);
}
if (string.IsNullOrWhiteSpace(input.Description))
{
errors.Add("Description:" + LedgerErrors.DescriptionRequired);
}
if (input.Amount == 0m)
{
errors.Add("Amount:" + LedgerErrors.AmountRequired);
}
if (errors.Count > 0)
{
throw new ValidationFailedException(errors);
}
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
var payments = uow.Repository<TaxPayment, long>();
TaxPayment? before = null;
TaxPayment payment;
if (input.Id is { } id)
{
payment = await payments.GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(LedgerErrors.NotFound);
if (payment.PaidOn is not null || payment.Source != TaxPaymentSource.Manual)
{
throw new ValidationFailedException(["Id:" + LedgerErrors.PaymentPaid]);
}
before = Copy(payment);
}
else
{
payment = new TaxPayment { Source = TaxPaymentSource.Manual };
}
payment.DueDate = input.DueDate;
payment.PaymentCode = input.PaymentCode.Trim();
payment.ReferenceYear = input.ReferenceYear;
payment.ReferencePeriod = LedgerStore.Trim(input.ReferencePeriod?.Trim(), 10);
payment.Description = LedgerStore.Trim(input.Description.Trim(), 200)!;
payment.Amount = input.Amount;
if (before is null)
{
payment.Id = await payments.InsertAsync(payment, cancellationToken).ConfigureAwait(false);
}
else
{
await payments.UpdateAsync(payment, cancellationToken).ConfigureAwait(false);
}
await _audit.RecordAsync(uow, before is null ? AuditAction.Insert : AuditAction.Update, payment.Id, before, payment, actor.UserName, cancellationToken).ConfigureAwait(false);
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
return payment;
}
/// <summary>Deletes a line written by hand and not paid.</summary>
/// <param name="actor">Who deletes.</param>
/// <param name="companyCode">The company.</param>
/// <param name="id">The line.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
public async Task DeletePaymentAsync(Actor actor, string companyCode, long id, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(actor);
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.SettlementConfirm, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
var payment = await uow.Repository<TaxPayment, long>().GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(LedgerErrors.NotFound);
if (payment.PaidOn is not null || payment.Source != TaxPaymentSource.Manual)
{
throw new ValidationFailedException(["Id:" + LedgerErrors.PaymentPaid]);
}
await uow.Repository<TaxPayment, long>().DeleteAsync(id, cancellationToken).ConfigureAwait(false);
await _audit.RecordAsync(uow, AuditAction.Delete, id, payment, null, actor.UserName, cancellationToken).ConfigureAwait(false);
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
}
/// <summary>The F24 of a due date: its unpaid lines, one per code and period.</summary>
/// <param name="actor">Who reads.</param>
/// <param name="companyCode">The company.</param>
/// <param name="dueDate">The due date.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The form.</returns>
public async Task<TaxPaymentForm> FormAsync(Actor actor, string companyCode, DateOnly dueDate, CancellationToken cancellationToken = default)
{
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.SettlementRead, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
return await FormAsync(uow, dueDate, paid: false, cancellationToken).ConfigureAwait(false);
}
/// <summary>The data file of the F24 of a due date.</summary>
/// <param name="actor">Who asks.</param>
/// <param name="companyCode">The company.</param>
/// <param name="dueDate">The due date.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The file.</returns>
public async Task<LedgerFile> ExportFormAsync(Actor actor, string companyCode, DateOnly dueDate, CancellationToken cancellationToken = default)
{
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.SettlementRead, cancellationToken).ConfigureAwait(false);
var exporter = (await _packs.PackOfAsync(company, cancellationToken).ConfigureAwait(false)).Require<ITaxPaymentFormExporter>();
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
var form = await FormAsync(uow, dueDate, paid: null, cancellationToken).ConfigureAwait(false);
return new LedgerFile(exporter.FileName(form), "text/csv", exporter.Export(form));
}
/// <summary>
/// Records the payment of the F24 of a due date: its lines are paid, the withholdings in it are paid, and the entry
/// <c>F24</c> moves the tax accounts against the bank.
/// </summary>
/// <param name="actor">Who records it.</param>
/// <param name="companyCode">The company.</param>
/// <param name="dueDate">The due date.</param>
/// <param name="paidOn">The day of payment.</param>
/// <param name="bankAccountId">The bank account debited; <see langword="null"/> for the default one.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The payment entry, if the ledger has the template.</returns>
public async Task<GlEntry?> PayAsync(Actor actor, string companyCode, DateOnly dueDate, DateOnly paidOn, long? bankAccountId = null, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(actor);
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.SettlementConfirm, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
var payments = (await uow.Repository<TaxPayment, long>().ListAsync(
Query.For<TaxPayment>().Where(t => t.DueDate == dueDate && t.PaidOn == null).OrderBy(t => t.PaymentCode), cancellationToken).ConfigureAwait(false)).Items;
if (payments.Count == 0)
{
throw new ValidationFailedException(["DueDate:" + LedgerErrors.PaymentPaid]);
}
var bank = await BankAsync(uow, bankAccountId, cancellationToken).ConfigureAwait(false);
GlEntry? entry = null;
if (await LedgerStore.TemplateAsync(uow, "F24", cancellationToken).ConfigureAwait(false) is { } found)
{
var (template, templateLines) = found;
long? Role(PostingRole role) => templateLines.FirstOrDefault(l => l.Role == role && l.AccountId is not null)?.AccountId;
var stampAccount = templateLines.FirstOrDefault(l => l.Role == PostingRole.Account && l.AccountId is not null)?.AccountId;
var bankAccount = (await LedgerStore.AccountAsync(uow, bank?.AccountCode, cancellationToken).ConfigureAwait(false))?.Id ?? Role(PostingRole.Bank);
var lines = new List<EntryLineDraft>();
foreach (var payment in payments)
{
var account = payment.Source switch
{
TaxPaymentSource.Withholding => Role(PostingRole.WithholdingPayable),
TaxPaymentSource.StampDuty => stampAccount,
_ => Role(PostingRole.VatSettlement),
};
if (account is null)
{
throw new ValidationFailedException(["Ledger:" + LedgerErrors.RoleAccountMissing]);
}
var text = LedgerStore.Trim(payment.PaymentCode + " " + payment.Description, 200);
lines.Add(payment.Amount >= 0m
? new EntryLineDraft(account, null, text, payment.Amount, 0m)
: new EntryLineDraft(account, null, text, 0m, -payment.Amount));
}
var total = payments.Sum(p => p.Amount);
if (bankAccount is null)
{
throw new ValidationFailedException(["BankAccountId:" + LedgerErrors.BankAccountMissing]);
}
if (total != 0m)
{
lines.Add(total > 0m ? new EntryLineDraft(bankAccount, null, "Addebito F24", 0m, total) : new EntryLineDraft(bankAccount, null, "Addebito F24", -total, 0m));
}
entry = await LedgerStore.InsertAsync(uow, new GlEntry
{
EntryDate = paidOn,
JournalTemplateId = template.Id,
TemplateCode = template.Code,
Description = LedgerStore.Trim(template.Description + " scadenza " + LedgerReport.Date(dueDate), 200)!,
Status = GlEntryStatus.Posted,
Source = GlEntrySource.TaxPayment,
IsDemo = payments.All(p => p.IsDemo),
}, lines, [], cancellationToken).ConfigureAwait(false);
}
foreach (var payment in payments)
{
var before = Copy(payment);
payment.PaidOn = paidOn;
payment.BankAccountId = bank?.Id;
payment.GlEntryId = entry?.Id;
await uow.Repository<TaxPayment, long>().UpdateAsync(payment, cancellationToken).ConfigureAwait(false);
await _audit.RecordAsync(uow, AuditAction.Update, payment.Id, before, payment, actor.UserName, cancellationToken).ConfigureAwait(false);
if (payment.Source == TaxPaymentSource.Withholding)
{
var paymentId = payment.Id;
var paidStatus = nameof(WithholdingStatus.Paid);
await uow.ExecuteAsync(SqlFragment.Of($"UPDATE withholdings SET status = {paidStatus} WHERE tax_payment_id = {paymentId}"), cancellationToken).ConfigureAwait(false);
}
}
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
return entry;
}
/// <summary>Takes back the payment of an F24: the entry goes (or is reversed when final), the lines are unpaid.</summary>
/// <param name="actor">Who does it.</param>
/// <param name="companyCode">The company.</param>
/// <param name="dueDate">The due date.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
public async Task UnpayAsync(Actor actor, string companyCode, DateOnly dueDate, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(actor);
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.SettlementConfirm, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
var payments = (await uow.Repository<TaxPayment, long>().ListAsync(
Query.For<TaxPayment>().Where(t => t.DueDate == dueDate && t.PaidOn != null), cancellationToken).ConfigureAwait(false)).Items;
foreach (var entryId in payments.Select(p => p.GlEntryId).OfType<long>().Distinct())
{
if (await uow.Repository<GlEntry, long>().GetAsync(entryId, cancellationToken).ConfigureAwait(false) is not { } entry)
{
continue;
}
if (entry.Status == GlEntryStatus.Final)
{
await JournalEntryService.ReverseAsync(uow, entry, Today(), actor.UserName, cancellationToken).ConfigureAwait(false);
}
else
{
await LedgerStore.DeleteAsync(uow, entryId, cancellationToken).ConfigureAwait(false);
}
}
foreach (var payment in payments)
{
var before = Copy(payment);
payment.PaidOn = null;
payment.GlEntryId = null;
payment.BankAccountId = null;
await uow.Repository<TaxPayment, long>().UpdateAsync(payment, cancellationToken).ConfigureAwait(false);
await _audit.RecordAsync(uow, AuditAction.Update, payment.Id, before, payment, actor.UserName, cancellationToken).ConfigureAwait(false);
var paymentId = payment.Id;
var due = nameof(WithholdingStatus.Due);
await uow.ExecuteAsync(SqlFragment.Of($"UPDATE withholdings SET status = {due} WHERE tax_payment_id = {paymentId}"), cancellationToken).ConfigureAwait(false);
}
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
}
/// <summary>The withholdings of the documents of a year.</summary>
/// <param name="actor">Who reads.</param>
/// <param name="companyCode">The company.</param>
/// <param name="year">The year of the documents.</param>
/// <param name="direction">Operated or suffered; <see langword="null"/> for both.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The withholdings, by date.</returns>
public async Task<IReadOnlyList<WithholdingRow>> WithholdingsAsync(
Actor actor, string companyCode, int year, WithholdingDirection? direction = null, CancellationToken cancellationToken = default)
{
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.SettlementRead, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
var from = new DateOnly(year, 1, 1);
var to = new DateOnly(year, 12, 31);
var query = Query.For<Withholding>().Where(w => w.DocumentDate >= from && w.DocumentDate <= to);
if (direction is { } d)
{
query = query.Where(w => w.Direction == d);
}
var items = (await uow.Repository<Withholding, long>().ListAsync(query.OrderBy(w => w.DocumentDate), cancellationToken).ConfigureAwait(false)).Items;
return await RowsAsync(uow, items, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Records that the invoice of a withholding has been paid. An operated withholding becomes due: the entry
/// <c>RIT</c> moves it from the supplier to the tax authority, and it joins the F24 line of its code due on the
/// 16th of the next month. A suffered withholding: the entry <c>RITS</c> moves it from the customer to the tax credit.
/// </summary>
/// <param name="actor">Who records it.</param>
/// <param name="companyCode">The company.</param>
/// <param name="id">The withholding.</param>
/// <param name="paidOn">The day the invoice was paid.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The withholding.</returns>
public async Task<Withholding> InvoicePaidAsync(Actor actor, string companyCode, long id, DateOnly paidOn, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(actor);
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.SettlementConfirm, cancellationToken).ConfigureAwait(false);
var pack = await _packs.PackOfAsync(company, cancellationToken).ConfigureAwait(false);
var settlementRules = pack.Require<IVatSettlementRules>();
var withholdingRules = pack.GetFeature<IWithholdingRules>();
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
var withholding = await uow.Repository<Withholding, long>().GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(LedgerErrors.NotFound);
if (withholding.InvoicePaidOn is not null)
{
throw new ValidationFailedException(["Id:" + LedgerErrors.PaymentPaid]);
}
var before = Copy(withholding);
var operated = withholding.Direction == WithholdingDirection.Operated;
var entry = await PostWithholdingAsync(uow, withholding, paidOn, operated ? "RIT" : "RITS", cancellationToken).ConfigureAwait(false);
withholding.InvoicePaidOn = paidOn;
withholding.GlEntryId = entry?.Id;
if (operated)
{
withholding.Status = WithholdingStatus.Due;
withholding.PaymentCode ??= PaymentCodeOf(withholding, withholdingRules);
var due = settlementRules.WithholdingDue(paidOn.Year, paidOn.Month);
var code = withholding.PaymentCode;
var payments = uow.Repository<TaxPayment, long>();
var period = paidOn.Month.ToString("00", CultureInfo.InvariantCulture);
var year = paidOn.Year;
var payment = await payments.FindAsync(
Query.For<TaxPayment>().Where(t => t.Source == TaxPaymentSource.Withholding && t.PaymentCode == code && t.ReferenceYear == year
&& t.ReferencePeriod == period && t.PaidOn == null),
cancellationToken).ConfigureAwait(false);
if (payment is null)
{
payment = new TaxPayment
{
DueDate = due,
PaymentCode = code,
ReferenceYear = year,
ReferencePeriod = period,
Description = LedgerStore.Trim("Ritenute d'acconto " + paidOn.ToString("MMMM yyyy", CultureInfo.GetCultureInfo("it-IT")), 200)!,
Amount = withholding.Amount,
Source = TaxPaymentSource.Withholding,
IsDemo = withholding.IsDemo,
};
payment.Id = await payments.InsertAsync(payment, cancellationToken).ConfigureAwait(false);
}
else
{
payment.Amount += withholding.Amount;
await payments.UpdateAsync(payment, cancellationToken).ConfigureAwait(false);
}
withholding.TaxPaymentId = payment.Id;
}
await uow.Repository<Withholding, long>().UpdateAsync(withholding, cancellationToken).ConfigureAwait(false);
await _audit.RecordAsync(uow, AuditAction.Update, withholding.Id, before, withholding, actor.UserName, cancellationToken).ConfigureAwait(false);
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
return withholding;
}
/// <summary>Takes back the payment of the invoice of a withholding while its F24 line is not paid.</summary>
/// <param name="actor">Who does it.</param>
/// <param name="companyCode">The company.</param>
/// <param name="id">The withholding.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The withholding.</returns>
public async Task<Withholding> UndoInvoicePaidAsync(Actor actor, string companyCode, long id, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(actor);
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.SettlementConfirm, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
var withholding = await uow.Repository<Withholding, long>().GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(LedgerErrors.NotFound);
if (withholding.Status == WithholdingStatus.Paid)
{
throw new ValidationFailedException(["Id:" + LedgerErrors.PaymentPaid]);
}
var before = Copy(withholding);
if (withholding.TaxPaymentId is { } paymentId && await uow.Repository<TaxPayment, long>().GetAsync(paymentId, cancellationToken).ConfigureAwait(false) is { } payment)
{
payment.Amount -= withholding.Amount;
if (payment.Amount == 0m)
{
await uow.Repository<TaxPayment, long>().DeleteAsync(paymentId, cancellationToken).ConfigureAwait(false);
}
else
{
await uow.Repository<TaxPayment, long>().UpdateAsync(payment, cancellationToken).ConfigureAwait(false);
}
}
if (withholding.GlEntryId is { } entryId && await uow.Repository<GlEntry, long>().GetAsync(entryId, cancellationToken).ConfigureAwait(false) is { } entry)
{
if (entry.Status == GlEntryStatus.Final)
{
await JournalEntryService.ReverseAsync(uow, entry, Today(), actor.UserName, cancellationToken).ConfigureAwait(false);
}
else
{
await LedgerStore.DeleteAsync(uow, entryId, cancellationToken).ConfigureAwait(false);
}
}
withholding.InvoicePaidOn = null;
withholding.GlEntryId = null;
withholding.TaxPaymentId = null;
withholding.Status = withholding.Direction == WithholdingDirection.Operated ? WithholdingStatus.Waiting : WithholdingStatus.Suffered;
await uow.Repository<Withholding, long>().UpdateAsync(withholding, cancellationToken).ConfigureAwait(false);
await _audit.RecordAsync(uow, AuditAction.Update, withholding.Id, before, withholding, actor.UserName, cancellationToken).ConfigureAwait(false);
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
return withholding;
}
/// <summary>
/// The data for the single certifications (CU) of a year: one row per payee with the fees paid in the year, the
/// taxable amount, the withholdings and the reason, as the intermediary needs them to fill the model.
/// </summary>
/// <param name="actor">Who asks.</param>
/// <param name="companyCode">The company.</param>
/// <param name="year">The year of payment.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The CSV file.</returns>
public async Task<LedgerFile> CertificationsAsync(Actor actor, string companyCode, int year, CancellationToken cancellationToken = default)
{
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.SettlementRead, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
var from = new DateOnly(year, 1, 1);
var to = new DateOnly(year, 12, 31);
var items = (await uow.Repository<Withholding, long>().ListAsync(
Query.For<Withholding>().Where(w => w.Direction == WithholdingDirection.Operated && w.InvoicePaidOn >= from && w.InvoicePaidOn <= to).OrderBy(w => w.PartyId),
cancellationToken).ConfigureAwait(false)).Items;
var rows = await RowsAsync(uow, items, cancellationToken).ConfigureAwait(false);
using var buffer = new MemoryStream();
await using (var csv = new CsvWriter(buffer, CsvOptions.Italian, leaveOpen: true))
{
await csv.WriteRowAsync(
["codice_fiscale", "denominazione", "causale", "anno", "compenso_lordo", "somme_non_soggette", "imponibile", "ritenute", "codice_tributo", "documenti"],
cancellationToken).ConfigureAwait(false);
foreach (var group in rows.GroupBy(r => (r.Withholding.PartyId, r.Withholding.Reason, r.Withholding.PaymentCode)))
{
var first = group.First();
var gross = group.Sum(r => r.Withholding.Taxable);
var taxable = group.Sum(r => Math.Round(r.Withholding.Taxable * r.Withholding.BasePercent / 100m, 2, MidpointRounding.AwayFromZero));
await csv.WriteRowAsync(
[first.PartyTaxCode, first.PartyName, group.Key.Reason, year, gross, gross - taxable, taxable, group.Sum(r => r.Withholding.Amount), group.Key.PaymentCode,
string.Join(' ', group.Select(r => r.Withholding.DocumentNumber))],
cancellationToken).ConfigureAwait(false);
}
}
return new LedgerFile(string.Create(CultureInfo.InvariantCulture, $"CU_{year}.csv"), "text/csv", buffer.ToArray());
}
/// <summary>The stamp duty on the e-invoices of each quarter of a year.</summary>
/// <param name="actor">Who reads.</param>
/// <param name="companyCode">The company.</param>
/// <param name="year">The year.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>Four quarters.</returns>
public async Task<IReadOnlyList<StampDutyQuarter>> StampDutyAsync(Actor actor, string companyCode, int year, CancellationToken cancellationToken = default)
{
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.SettlementRead, cancellationToken).ConfigureAwait(false);
var rules = (await _packs.PackOfAsync(company, cancellationToken).ConfigureAwait(false)).Require<IVatSettlementRules>();
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
return await StampDutyAsync(uow, rules, year, cancellationToken).ConfigureAwait(false);
}
/// <summary>The sale invoices with stamp duty of a quarter.</summary>
/// <param name="actor">Who reads.</param>
/// <param name="companyCode">The company.</param>
/// <param name="year">The year.</param>
/// <param name="quarter">The quarter.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The invoices, by date.</returns>
public async Task<IReadOnlyList<StampDutyDocument>> StampDutyDocumentsAsync(Actor actor, string companyCode, int year, int quarter, CancellationToken cancellationToken = default)
{
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.SettlementRead, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
var from = new DateOnly(year, ((quarter - 1) * 3) + 1, 1);
var to = from.AddMonths(3).AddDays(-1);
var draft = nameof(DocumentStatus.Draft);
var cancelled = nameof(DocumentStatus.Cancelled);
return await uow.QueryAsync<StampDutyDocument>(SqlFragment.Of($"""
SELECT d.id AS document_id, d.document_number AS document_number, d.document_date AS document_date, p.name AS party_name,
d.taxable_amount AS taxable, d.stamp_duty AS stamp_duty, d.stamp_duty_charged AS charged, d.kind AS kind
FROM sale_documents d LEFT JOIN parties p ON p.id = d.party_id
WHERE d.stamp_duty > 0 AND d.document_date >= {from} AND d.document_date <= {to} AND d.status <> {draft} AND d.status <> {cancelled} AND d.kind IN ({StampKinds})
ORDER BY d.document_date, d.number
"""), cancellationToken).ConfigureAwait(false);
}
/// <summary>Records the F24 line of the stamp duty of a quarter (or updates it while unpaid).</summary>
/// <param name="actor">Who records it.</param>
/// <param name="companyCode">The company.</param>
/// <param name="year">The year.</param>
/// <param name="quarter">The quarter.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The line, or <see langword="null"/> when no duty is due.</returns>
public async Task<TaxPayment?> StampDutyPaymentAsync(Actor actor, string companyCode, int year, int quarter, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(actor);
ArgumentOutOfRangeException.ThrowIfLessThan(quarter, 1);
ArgumentOutOfRangeException.ThrowIfGreaterThan(quarter, 4);
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.SettlementConfirm, cancellationToken).ConfigureAwait(false);
var pack = await _packs.PackOfAsync(company, cancellationToken).ConfigureAwait(false);
var rules = pack.Require<IVatSettlementRules>();
var form = pack.Require<ITaxPaymentFormExporter>();
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
var data = (await StampDutyAsync(uow, rules, year, cancellationToken).ConfigureAwait(false))[quarter - 1];
if (data.Payment is { PaidOn: not null })
{
throw new ValidationFailedException(["Quarter:" + LedgerErrors.PaymentPaid]);
}
if (data.Amount == 0m)
{
if (data.Payment is { } stale)
{
await uow.Repository<TaxPayment, long>().DeleteAsync(stale.Id, cancellationToken).ConfigureAwait(false);
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
}
return null;
}
var payment = data.Payment ?? new TaxPayment { Source = TaxPaymentSource.StampDuty, SourceId = (year * 10L) + quarter, ReferenceYear = year };
var before = data.Payment is null ? null : Copy(payment);
payment.DueDate = data.DueDate;
payment.PaymentCode = form.StampDutyCode(quarter);
payment.Description = string.Create(CultureInfo.InvariantCulture, $"Imposta di bollo fatture elettroniche {quarter}° trimestre {year} ({data.Documents} fatture)");
payment.Amount = data.Amount;
if (before is null)
{
payment.Id = await uow.Repository<TaxPayment, long>().InsertAsync(payment, cancellationToken).ConfigureAwait(false);
}
else
{
await uow.Repository<TaxPayment, long>().UpdateAsync(payment, cancellationToken).ConfigureAwait(false);
}
await _audit.RecordAsync(uow, before is null ? AuditAction.Insert : AuditAction.Update, payment.Id, before, payment, actor.UserName, cancellationToken).ConfigureAwait(false);
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
return payment;
}
/// <summary>
/// The stamp duty of each quarter from the issued sale invoices with the duty, with the due date moved when the
/// amount stays below the threshold: the first quarter with the second, the first two with the third.
/// </summary>
internal static async Task<IReadOnlyList<StampDutyQuarter>> StampDutyAsync(IUnitOfWork uow, IVatSettlementRules rules, int year, CancellationToken cancellationToken)
{
var from = new DateOnly(year, 1, 1);
var to = new DateOnly(year, 12, 31);
var draft = nameof(DocumentStatus.Draft);
var cancelled = nameof(DocumentStatus.Cancelled);
var rows = await uow.QueryAsync<StampRow>(SqlFragment.Of($"""
SELECT document_date AS document_date, stamp_duty AS stamp_duty FROM sale_documents
WHERE stamp_duty > 0 AND document_date >= {from} AND document_date <= {to} AND status <> {draft} AND status <> {cancelled} AND kind IN ({StampKinds})
"""), cancellationToken).ConfigureAwait(false);
var payments = (await uow.Repository<TaxPayment, long>().ListAsync(
Query.For<TaxPayment>().Where(t => t.Source == TaxPaymentSource.StampDuty && t.ReferenceYear == year), cancellationToken).ConfigureAwait(false)).Items;
var result = new List<StampDutyQuarter>();
var carried = 0m;
for (var q = 1; q <= 4; q++)
{
var quarter = rows.Where(r => ((r.DocumentDate.Month - 1) / 3) + 1 == q).ToList();
var amount = quarter.Sum(r => r.StampDuty);
var due = rules.StampDutyDue(year, q);
if (q == 1 && amount <= StampDutyThreshold)
{
due = rules.StampDutyDue(year, 2);
carried = amount;
}
else if (q == 2 && carried > 0m && carried + amount <= StampDutyThreshold)
{
due = rules.StampDutyDue(year, 3);
carried += amount;
}
else
{
carried = 0m;
}
var sourceId = (year * 10L) + q;
result.Add(new StampDutyQuarter(year, q, quarter.Count, amount, due, payments.FirstOrDefault(p => p.SourceId == sourceId)));
}
// A first quarter moved to the second, when the second goes over the threshold, keeps the due date of the second.
if (result[0].DueDate == rules.StampDutyDue(year, 2) && result[1].DueDate == rules.StampDutyDue(year, 3))
{
result[0] = result[0] with { DueDate = rules.StampDutyDue(year, 3) };
}
return result;
}
private static async Task<TaxPaymentForm> FormAsync(IUnitOfWork uow, DateOnly dueDate, bool? paid, CancellationToken cancellationToken)
{
var query = Query.For<TaxPayment>().Where(t => t.DueDate == dueDate);
query = paid switch
{
true => query.Where(t => t.PaidOn != null),
false => query.Where(t => t.PaidOn == null),
_ => query,
};
var payments = (await uow.Repository<TaxPayment, long>().ListAsync(query.OrderBy(t => t.PaymentCode), cancellationToken).ConfigureAwait(false)).Items;
var profile = await uow.Repository<CompanyProfile, long>().FindAsync(Query.For<CompanyProfile>(), cancellationToken).ConfigureAwait(false);
var lines = payments
.GroupBy(p => (p.PaymentCode, p.ReferencePeriod, p.ReferenceYear))
.Select(g =>
{
var amount = g.Sum(p => p.Amount);
return new TaxPaymentFormLine(g.Key.PaymentCode, g.Key.ReferencePeriod, g.Key.ReferenceYear, Math.Max(0m, amount), Math.Max(0m, -amount), g.First().Description);
})
.ToList();
return new TaxPaymentForm(dueDate, profile?.TaxCode ?? profile?.VatNumber ?? string.Empty, profile?.LegalName ?? string.Empty, lines);
}
private static async Task<BankAccount?> BankAsync(IUnitOfWork uow, long? id, CancellationToken cancellationToken)
{
var banks = uow.Repository<BankAccount, long>();
if (id is { } bankId)
{
return await banks.GetAsync(bankId, cancellationToken).ConfigureAwait(false) ?? throw new ValidationFailedException(["BankAccountId:" + LedgerErrors.BankAccountMissing]);
}
var profile = await uow.Repository<CompanyProfile, long>().FindAsync(Query.For<CompanyProfile>(), cancellationToken).ConfigureAwait(false);
if (profile?.DefaultBankAccountId is { } defaultId && await banks.GetAsync(defaultId, cancellationToken).ConfigureAwait(false) is { } preferred)
{
return preferred;
}
return await banks.FindAsync(Query.For<BankAccount>().Where(b => b.IsDefault), cancellationToken).ConfigureAwait(false);
}
// The entry of a withholding when its invoice is paid: operated, supplier debit / withholdings payable credit;
// suffered, withholdings credit debit / customer credit. The party keeps its own account when it has one.
private static async Task<GlEntry?> PostWithholdingAsync(IUnitOfWork uow, Withholding withholding, DateOnly date, string templateCode, CancellationToken cancellationToken)
{
if (await LedgerStore.TemplateAsync(uow, templateCode, cancellationToken).ConfigureAwait(false) is not { } found)
{
return null;
}
var (template, templateLines) = found;
var operated = withholding.Direction == WithholdingDirection.Operated;
var party = await uow.Repository<Party, long>().GetAsync(withholding.PartyId, cancellationToken).ConfigureAwait(false);
var partyRole = operated ? PostingRole.Supplier : PostingRole.Customer;
var taxRole = operated ? PostingRole.WithholdingPayable : PostingRole.WithholdingCredit;
var partyAccount = (await LedgerStore.AccountAsync(uow, operated ? party?.SupplierAccountCode : party?.CustomerAccountCode, cancellationToken).ConfigureAwait(false))?.Id
?? templateLines.FirstOrDefault(l => l.Role == partyRole)?.AccountId;
var taxAccount = templateLines.FirstOrDefault(l => l.Role == taxRole)?.AccountId;
if (partyAccount is null || taxAccount is null)
{
throw new ValidationFailedException(["Ledger:" + LedgerErrors.RoleAccountMissing]);
}
var amount = Math.Abs(withholding.Amount);
var credit = withholding.Amount < 0m;
var text = LedgerStore.Trim("Ritenuta fattura " + withholding.DocumentNumber, 200);
EntryLineDraft Line(long account, long? partyId, bool debit) =>
debit != credit ? new EntryLineDraft(account, partyId, text, amount, 0m) : new EntryLineDraft(account, partyId, text, 0m, amount);
IReadOnlyList<EntryLineDraft> lines = operated
? [Line(partyAccount.Value, withholding.PartyId, debit: true), Line(taxAccount.Value, null, debit: false)]
: [Line(taxAccount.Value, null, debit: true), Line(partyAccount.Value, withholding.PartyId, debit: false)];
return await LedgerStore.InsertAsync(uow, new GlEntry
{
EntryDate = date,
JournalTemplateId = template.Id,
TemplateCode = template.Code,
Description = LedgerStore.Trim(template.Description + " " + withholding.DocumentNumber, 200)!,
Status = GlEntryStatus.Posted,
Source = GlEntrySource.Withholding,
SourceFamily = withholding.SourceFamily,
SourceDocumentId = withholding.SourceDocumentId,
DocumentNumber = withholding.DocumentNumber,
DocumentDate = withholding.DocumentDate,
PartyId = withholding.PartyId,
IsDemo = withholding.IsDemo,
}, lines, [], cancellationToken).ConfigureAwait(false);
}
private static string PaymentCodeOf(Withholding withholding, IWithholdingRules? rules)
{
var kinds = rules?.Kinds ?? [];
var kind = kinds.FirstOrDefault(k => k.InvoiceType == withholding.WithholdingType && k.Rate == withholding.Rate && k.PaymentReason == withholding.Reason)
?? kinds.FirstOrDefault(k => k.InvoiceType == withholding.WithholdingType && k.PaymentReason == withholding.Reason)
?? kinds.FirstOrDefault(k => k.InvoiceType == withholding.WithholdingType);
return kind?.PaymentCode ?? "1040";
}
private static async Task<IReadOnlyList<WithholdingRow>> RowsAsync(IUnitOfWork uow, IReadOnlyList<Withholding> items, CancellationToken cancellationToken)
{
var ids = items.Select(w => w.PartyId).Distinct().ToList();
var parties = ids.Count == 0
? []
: (await uow.Repository<Party, long>().ListAsync(Query.For<Party>().Where(p => ids.Contains(p.Id)), cancellationToken).ConfigureAwait(false)).Items.ToDictionary(p => p.Id);
return [.. items.Select(w => parties.TryGetValue(w.PartyId, out var p)
? new WithholdingRow(w, p.Name, p.TaxCode ?? p.VatNumber)
: new WithholdingRow(w, string.Empty, null))];
}
private DateOnly Today() => DateOnly.FromDateTime(_clock.GetLocalNow().DateTime);
private static TaxPayment Copy(TaxPayment p) => new()
{
Id = p.Id,
DueDate = p.DueDate,
PaymentCode = p.PaymentCode,
ReferenceYear = p.ReferenceYear,
ReferencePeriod = p.ReferencePeriod,
Description = p.Description,
Amount = p.Amount,
Source = p.Source,
PaidOn = p.PaidOn,
GlEntryId = p.GlEntryId,
};
private static Withholding Copy(Withholding w) => new()
{
Id = w.Id,
Direction = w.Direction,
DocumentNumber = w.DocumentNumber,
Amount = w.Amount,
Status = w.Status,
InvoicePaidOn = w.InvoicePaidOn,
TaxPaymentId = w.TaxPaymentId,
GlEntryId = w.GlEntryId,
};
private sealed record StampRow(DateOnly DocumentDate, decimal StampDuty);
}
@@ -0,0 +1,770 @@
using System.Globalization;
using Khaemhat.Application.Audit;
using Khaemhat.Application.Security;
using Khaemhat.Application.Tables;
using Khaemhat.Core.Accounting;
using Khaemhat.Core.Tables;
using Khaemhat.Core.Tax;
using Khaemhat.Data;
using Khaemhat.Data.Querying;
using Khaemhat.Fiscal.Abstractions;
namespace Khaemhat.Application.Ledger;
/// <summary>A line of a VAT register.</summary>
/// <param name="EntryId">The entry.</param>
/// <param name="EntryNumber">The number of the entry.</param>
/// <param name="VatProtocol">The protocol.</param>
/// <param name="VatDate">The VAT date.</param>
/// <param name="DocumentNumber">The number of the document.</param>
/// <param name="DocumentDate">The date of the document.</param>
/// <param name="PartyName">The customer or supplier.</param>
/// <param name="Rate">The rate.</param>
/// <param name="Nature">The nature.</param>
/// <param name="Exigibility">When the VAT is due.</param>
/// <param name="Taxable">The taxable amount.</param>
/// <param name="Tax">The VAT.</param>
/// <param name="NonDeductibleTax">The VAT not deductible.</param>
/// <param name="Status">The state of the entry.</param>
public sealed record VatRegisterRow(
long EntryId, string? EntryNumber, long? VatProtocol, DateOnly VatDate, string? DocumentNumber, DateOnly? DocumentDate, string? PartyName,
decimal Rate, string? Nature, TaxExigibility Exigibility, decimal Taxable, decimal Tax, decimal NonDeductibleTax, GlEntryStatus Status);
/// <summary>A total by rate of a VAT register.</summary>
/// <param name="Rate">The rate.</param>
/// <param name="Nature">The nature.</param>
/// <param name="Taxable">The taxable amount.</param>
/// <param name="Tax">The VAT.</param>
/// <param name="NonDeductibleTax">The VAT not deductible.</param>
public sealed record VatRateTotal(decimal Rate, string? Nature, decimal Taxable, decimal Tax, decimal NonDeductibleTax);
/// <summary>A VAT register in a period.</summary>
/// <param name="Register">The register.</param>
/// <param name="Rows">The lines, by date and protocol.</param>
/// <param name="Totals">The totals by rate.</param>
public sealed record VatRegisterView(VatRegister Register, IReadOnlyList<VatRegisterRow> Rows, IReadOnlyList<VatRateTotal> Totals);
/// <summary>A settlement with its lines and the names of its registers.</summary>
/// <param name="Settlement">The settlement.</param>
/// <param name="Lines">One line per register.</param>
/// <param name="Registers">The registers, by id.</param>
public sealed record VatSettlementView(VatSettlement Settlement, IReadOnlyList<VatSettlementLine> Lines, IReadOnlyDictionary<long, VatRegister> Registers);
/// <summary>A file produced by the ledger.</summary>
/// <param name="FileName">The name proposed.</param>
/// <param name="MediaType">The media type.</param>
/// <param name="Content">The content.</param>
public sealed record LedgerFile(string FileName, string MediaType, byte[] Content);
/// <summary>
/// The VAT of the ledger (SPEC §11.7, issue #65, mockups 045-046, ADR 0037): the registers read from the VAT lines of
/// the posted entries, their provisional print and their final print with the pages numbered by year; the periodic
/// settlement, monthly or quarterly as the company profile says, with the credit and the debit below the minimum
/// carried, the interest of quarterly payers, the pro rata and the December advance; its confirmation settles the
/// periods (no more VAT documents in them), posts the entry that closes the VAT accounts and writes the F24 line; the
/// communication of the settlements (LIPE) of a quarter.
/// </summary>
public sealed class VatService
{
private readonly IUnitOfWorkFactory _factory;
private readonly PermissionService _permissions;
private readonly CompanyFiscalContext _packs;
private readonly FiscalYearService _fiscal;
private readonly AuditTrail _audit;
private readonly TimeProvider _clock;
/// <summary>Creates the service.</summary>
/// <param name="factory">The units of work.</param>
/// <param name="permissions">The permissions.</param>
/// <param name="packs">The fiscal pack of each company.</param>
/// <param name="fiscal">The fiscal calendar.</param>
/// <param name="audit">The history.</param>
/// <param name="clock">The clock.</param>
public VatService(IUnitOfWorkFactory factory, PermissionService permissions, CompanyFiscalContext packs, FiscalYearService fiscal, AuditTrail audit, TimeProvider clock)
{
ArgumentNullException.ThrowIfNull(factory);
ArgumentNullException.ThrowIfNull(permissions);
ArgumentNullException.ThrowIfNull(packs);
ArgumentNullException.ThrowIfNull(fiscal);
ArgumentNullException.ThrowIfNull(audit);
ArgumentNullException.ThrowIfNull(clock);
_factory = factory;
_permissions = permissions;
_packs = packs;
_fiscal = fiscal;
_audit = audit;
_clock = clock;
}
/// <summary>A VAT register in a period.</summary>
/// <param name="actor">Who reads.</param>
/// <param name="companyCode">The company.</param>
/// <param name="registerId">The register.</param>
/// <param name="from">From this VAT date.</param>
/// <param name="to">Up to this VAT date.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The register.</returns>
public async Task<VatRegisterView> RegisterAsync(Actor actor, string companyCode, long registerId, DateOnly from, DateOnly to, CancellationToken cancellationToken = default)
{
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.VatRegisterRead, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
return await RegisterAsync(uow, registerId, from, to, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// The print of a register: provisional (any period, nothing recorded) or final (from the day after the last final
/// print, numbering the pages after the last page of the year).
/// </summary>
/// <param name="actor">Who prints.</param>
/// <param name="companyCode">The company.</param>
/// <param name="registerId">The register.</param>
/// <param name="from">From this day (for a final print, the day after the last one).</param>
/// <param name="to">Up to this day.</param>
/// <param name="final">A final print.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The PDF.</returns>
public async Task<LedgerFile> PrintRegisterAsync(Actor actor, string companyCode, long registerId, DateOnly from, DateOnly to, bool final, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(actor);
var company = await CompanyGuard.DemandAsync(
_permissions, actor, companyCode, final ? LedgerPermissions.SettlementConfirm : LedgerPermissions.VatRegisterRead, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
var register = await uow.Repository<VatRegister, long>().GetAsync(registerId, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(LedgerErrors.VatRegisterRequired);
var firstPage = 1;
if (final)
{
var expected = register.LastPrintedDate is { } last && last.Year == to.Year ? last.AddDays(1) : new DateOnly(to.Year, 1, 1);
if (from != expected || to < from || to.Year != from.Year)
{
throw new ValidationFailedException(["From:" + LedgerErrors.PrintOrder]);
}
firstPage = register.PrintYear == to.Year ? register.LastPage + 1 : 1;
}
var view = await RegisterAsync(uow, registerId, from, to, cancellationToken).ConfigureAwait(false);
var profile = await uow.Repository<CompanyProfile, long>().FindAsync(Query.For<CompanyProfile>(), cancellationToken).ConfigureAwait(false);
var rows = new List<IReadOnlyList<string?>>();
foreach (var row in view.Rows)
{
rows.Add([
row.VatProtocol?.ToString(CultureInfo.InvariantCulture), LedgerReport.Date(row.VatDate), row.DocumentNumber, LedgerReport.Date(row.DocumentDate), row.PartyName,
row.Nature ?? row.Rate.ToString("0.##", CultureInfo.InvariantCulture) + "%", LedgerReport.Money(row.Taxable), LedgerReport.Money(row.Tax),
LedgerReport.Money(row.NonDeductibleTax),
]);
}
foreach (var total in view.Totals)
{
rows.Add(["**Totale", null, null, null, null, total.Nature ?? total.Rate.ToString("0.##", CultureInfo.InvariantCulture) + "%",
LedgerReport.Money(total.Taxable), LedgerReport.Money(total.Tax), LedgerReport.Money(total.NonDeductibleTax)]);
}
rows.Add(["**Totale registro", null, null, null, null, null, LedgerReport.Money(view.Totals.Sum(t => t.Taxable)), LedgerReport.Money(view.Totals.Sum(t => t.Tax)),
LedgerReport.Money(view.Totals.Sum(t => t.NonDeductibleTax))]);
var (file, pages) = await LedgerReport.WriteAsync(
CompanyLine(profile),
register.Code + " - " + register.Description,
(final ? "Stampa definitiva" : "Stampa provvisoria") + " dal " + LedgerReport.Date(from) + " al " + LedgerReport.Date(to),
[new("Prot.", 40), new("Data reg.", 55), new("Documento", 75), new("Data doc.", 55), new("Controparte", 210), new("Aliquota", 50), new("Imponibile", 85, true),
new("Imposta", 75, true), new("Indetraibile", 70, true)],
rows,
to.Year,
firstPage,
cancellationToken).ConfigureAwait(false);
if (final)
{
var before = new VatRegister { Id = register.Id, Code = register.Code, PrintYear = register.PrintYear, LastPage = register.LastPage, LastPrintedDate = register.LastPrintedDate };
register.PrintYear = to.Year;
register.LastPage = firstPage + pages - 1;
register.LastPrintedDate = to;
await uow.Repository<VatRegister, long>().UpdateAsync(register, cancellationToken).ConfigureAwait(false);
await uow.Repository<VatRegisterPrint, long>().InsertAsync(new VatRegisterPrint
{
VatRegisterId = register.Id,
Year = to.Year,
FromDate = from,
ToDate = to,
FirstPage = firstPage,
LastPage = register.LastPage,
PrintedAt = _clock.GetUtcNow().UtcDateTime,
PrintedBy = actor.UserName,
}, cancellationToken).ConfigureAwait(false);
await _audit.RecordAsync(uow, AuditAction.Update, register.Id, before, register, actor.UserName, cancellationToken).ConfigureAwait(false);
}
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
return new LedgerFile(
string.Create(CultureInfo.InvariantCulture, $"{register.Code}_{from:yyyyMMdd}_{to:yyyyMMdd}{(final ? "_definitivo" : string.Empty)}.pdf"),
Infrastructure.Files.PdfWriter.MediaType,
file);
}
/// <summary>The settlements of a year.</summary>
/// <param name="actor">Who reads.</param>
/// <param name="companyCode">The company.</param>
/// <param name="year">The year.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The settlements, by period.</returns>
public async Task<IReadOnlyList<VatSettlement>> SettlementsAsync(Actor actor, string companyCode, int year, CancellationToken cancellationToken = default)
{
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.SettlementRead, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
return (await uow.Repository<VatSettlement, long>().ListAsync(Query.For<VatSettlement>().Where(s => s.Year == year).OrderBy(s => s.Number), cancellationToken)
.ConfigureAwait(false)).Items;
}
/// <summary>A settlement with its lines.</summary>
/// <param name="actor">Who reads.</param>
/// <param name="companyCode">The company.</param>
/// <param name="id">The settlement.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The settlement, or none.</returns>
public async Task<VatSettlementView?> SettlementAsync(Actor actor, string companyCode, long id, CancellationToken cancellationToken = default)
{
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.SettlementRead, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
return await ViewAsync(uow, id, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Computes (again) the settlement of a period from the registers: the VAT due and deductible, the credit and the
/// debit carried from the previous settlement, the advance for the last period, interest and minimum.
/// </summary>
/// <param name="actor">Who computes: needs <c>vat.settlement.read</c>.</param>
/// <param name="companyCode">The company.</param>
/// <param name="year">The year.</param>
/// <param name="number">The month or quarter.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The settlement, as a draft.</returns>
public async Task<VatSettlementView> ComputeAsync(Actor actor, string companyCode, int year, int number, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(actor);
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.SettlementRead, cancellationToken).ConfigureAwait(false);
var pack = await _packs.PackOfAsync(company, cancellationToken).ConfigureAwait(false);
var rules = pack.Require<IVatSettlementRules>();
long id;
await using (var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false))
{
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
var profile = await uow.Repository<CompanyProfile, long>().FindAsync(Query.For<CompanyProfile>(), cancellationToken).ConfigureAwait(false);
var periodicity = profile?.VatPeriodicity ?? VatPeriodicity.Monthly;
var period = TaxPeriod.Of(year, number, periodicity);
var settlements = uow.Repository<VatSettlement, long>();
var existing = await settlements.FindAsync(
Query.For<VatSettlement>().Where(s => s.Year == year && s.Number == number && s.Periodicity == periodicity), cancellationToken).ConfigureAwait(false);
if (existing is { Status: VatSettlementStatus.Confirmed })
{
throw new ValidationFailedException(["Number:" + LedgerErrors.SettlementConfirmed]);
}
var later = await settlements.CountAsync(
Query.For<VatSettlement>().Where(s => s.Status == VatSettlementStatus.Confirmed && s.StartDate > period.End), cancellationToken).ConfigureAwait(false);
if (later > 0)
{
throw new ValidationFailedException(["Number:" + LedgerErrors.SettlementLater]);
}
var previousList = (await settlements.ListAsync(
Query.For<VatSettlement>().Where(s => s.Status == VatSettlementStatus.Confirmed && s.EndDate < period.Start).OrderByDescending(s => s.EndDate).Take(1),
cancellationToken).ConfigureAwait(false)).Items;
var previous = previousList.Count > 0 ? previousList[0] : null;
var last = number == (periodicity == VatPeriodicity.Monthly ? 12 : 4);
var advance = 0m;
if (last)
{
advance = await uow.QuerySingleAsync<decimal?>(
SqlFragment.Of($"SELECT SUM(amount) FROM tax_payments WHERE source = {nameof(TaxPaymentSource.VatAdvance)} AND reference_year = {year}"),
cancellationToken).ConfigureAwait(false) ?? 0m;
}
var totals = await TotalsAsync(uow, period.Start, period.End, cancellationToken).ConfigureAwait(false);
var terms = new VatSettlementTerms(
ProRataPercent: profile?.ProRataPercent is > 0m and var p ? p : 100m,
PreviousCredit: previous?.CreditCarried ?? 0m,
PreviousDebit: previous?.DebitCarried ?? 0m,
AdvancePaid: advance,
InterestPercent: pack.Calendar.VatInterestRate(periodicity),
MinimumPayment: rules.MinimumPayment);
var result = VatSettlementCalculator.Compute(totals, terms);
var settlement = existing ?? new VatSettlement { Year = year, Number = number, Periodicity = periodicity };
settlement.StartDate = period.Start;
settlement.EndDate = period.End;
settlement.SettlementDate = period.End;
settlement.Status = VatSettlementStatus.Draft;
settlement.SalesTax = result.SalesTax;
settlement.PurchaseTax = result.PurchaseTax;
settlement.NonDeductibleTax = result.NonDeductibleTax;
settlement.DeferredTax = result.DeferredTax;
settlement.ProRataPercent = terms.ProRataPercent;
settlement.PreviousCredit = terms.PreviousCredit;
settlement.PreviousDebit = terms.PreviousDebit;
settlement.AdvancePaid = terms.AdvancePaid;
settlement.InterestPercent = terms.InterestPercent;
settlement.Interest = result.Interest;
settlement.AmountDue = result.AmountDue;
settlement.CreditCarried = result.CreditCarried;
settlement.DebitCarried = result.DebitCarried;
settlement.PaymentCode = rules.PaymentCode(period);
settlement.DueDate = pack.Calendar.VatPaymentDue(period);
if (existing is null)
{
settlement.Id = await settlements.InsertAsync(settlement, cancellationToken).ConfigureAwait(false);
}
else
{
await settlements.UpdateAsync(settlement, cancellationToken).ConfigureAwait(false);
}
var settlementId = settlement.Id;
await uow.ExecuteAsync(SqlFragment.Of($"DELETE FROM vat_settlement_lines WHERE settlement_id = {settlementId}"), cancellationToken).ConfigureAwait(false);
foreach (var total in totals)
{
await uow.Repository<VatSettlementLine, long>().InsertAsync(new VatSettlementLine
{
SettlementId = settlementId,
VatRegisterId = total.RegisterId,
RegisterKind = total.Kind,
Documents = total.Documents,
Taxable = total.Taxable,
Tax = total.Tax,
NonDeductibleTax = total.NonDeductibleTax,
DeferredTax = total.DeferredTax,
}, cancellationToken).ConfigureAwait(false);
}
id = settlementId;
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
}
return await SettlementAsync(actor, company, id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(LedgerErrors.NotFound);
}
/// <summary>
/// Confirms a settlement: the periods become settled, the entry <c>LIQ</c> closes the VAT accounts into the VAT
/// settlement account (with the interest and the pro rata) and the amount due becomes an F24 line.
/// </summary>
/// <param name="actor">Who confirms: needs <c>vat.settlement.confirm</c>.</param>
/// <param name="companyCode">The company.</param>
/// <param name="id">The settlement.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The settlement as confirmed.</returns>
public async Task<VatSettlementView> ConfirmAsync(Actor actor, string companyCode, long id, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(actor);
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.SettlementConfirm, cancellationToken).ConfigureAwait(false);
var pack = await _packs.PackOfAsync(company, cancellationToken).ConfigureAwait(false);
var rules = pack.Require<IVatSettlementRules>();
var form = pack.GetFeature<ITaxPaymentFormExporter>();
await using (var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false))
{
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
var settlements = uow.Repository<VatSettlement, long>();
var settlement = await settlements.GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(LedgerErrors.NotFound);
if (settlement.Status == VatSettlementStatus.Confirmed)
{
throw new ValidationFailedException(["Id:" + LedgerErrors.SettlementConfirmed]);
}
var start = settlement.StartDate;
var earlier = await settlements.CountAsync(
Query.For<VatSettlement>().Where(s => s.Status == VatSettlementStatus.Draft && s.StartDate < start), cancellationToken).ConfigureAwait(false);
if (earlier > 0)
{
throw new ValidationFailedException(["Id:" + LedgerErrors.SettlementPrevious]);
}
var before = Copy(settlement);
var entry = await PostSettlementAsync(uow, settlement, cancellationToken).ConfigureAwait(false);
settlement.GlEntryId = entry?.Id;
if (settlement.AmountDue > 0m)
{
var period = TaxPeriod.Of(settlement.Year, settlement.Number, settlement.Periodicity);
var paymentId = await uow.Repository<TaxPayment, long>().InsertAsync(new TaxPayment
{
DueDate = settlement.DueDate ?? settlement.EndDate,
PaymentCode = settlement.PaymentCode ?? rules.PaymentCode(period),
ReferenceYear = settlement.Year,
ReferencePeriod = rules.PaymentPeriod(period),
Description = Describe(settlement, form),
Amount = settlement.AmountDue,
Source = TaxPaymentSource.VatSettlement,
SourceId = settlement.Id,
IsDemo = settlement.IsDemo,
}, cancellationToken).ConfigureAwait(false);
settlement.TaxPaymentId = paymentId;
}
settlement.Status = VatSettlementStatus.Confirmed;
settlement.ConfirmedAt = _clock.GetUtcNow().UtcDateTime;
settlement.ConfirmedBy = actor.UserName;
await settlements.UpdateAsync(settlement, cancellationToken).ConfigureAwait(false);
var end = settlement.EndDate;
var open = nameof(FiscalPeriodStatus.Open);
var settled = nameof(FiscalPeriodStatus.Settled);
await uow.ExecuteAsync(
SqlFragment.Of($"UPDATE fiscal_periods SET status = {settled} WHERE start_date >= {start} AND end_date <= {end} AND status = {open}"),
cancellationToken).ConfigureAwait(false);
await _audit.RecordAsync(uow, AuditAction.Update, settlement.Id, before, settlement, actor.UserName, cancellationToken).ConfigureAwait(false);
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
}
await _fiscal.InvalidateAsync(company, cancellationToken).ConfigureAwait(false);
return await SettlementAsync(actor, company, id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(LedgerErrors.NotFound);
}
/// <summary>
/// Takes back the last confirmed settlement while its F24 line is not paid: the entry goes (or is reversed when
/// final), the periods open again, the settlement becomes a draft.
/// </summary>
/// <param name="actor">Who does it.</param>
/// <param name="companyCode">The company.</param>
/// <param name="id">The settlement.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The settlement as a draft.</returns>
public async Task<VatSettlementView> ReopenAsync(Actor actor, string companyCode, long id, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(actor);
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.SettlementConfirm, cancellationToken).ConfigureAwait(false);
await using (var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false))
{
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
var settlements = uow.Repository<VatSettlement, long>();
var settlement = await settlements.GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(LedgerErrors.NotFound);
var end = settlement.EndDate;
if (await settlements.CountAsync(Query.For<VatSettlement>().Where(s => s.Status == VatSettlementStatus.Confirmed && s.StartDate > end), cancellationToken)
.ConfigureAwait(false) > 0)
{
throw new ValidationFailedException(["Id:" + LedgerErrors.SettlementLater]);
}
if (settlement.TaxPaymentId is { } paymentId && await uow.Repository<TaxPayment, long>().GetAsync(paymentId, cancellationToken).ConfigureAwait(false) is { } payment)
{
if (payment.PaidOn is not null)
{
throw new ValidationFailedException(["Id:" + LedgerErrors.PaymentPaid]);
}
await uow.Repository<TaxPayment, long>().DeleteAsync(paymentId, cancellationToken).ConfigureAwait(false);
}
if (settlement.GlEntryId is { } entryId && await uow.Repository<GlEntry, long>().GetAsync(entryId, cancellationToken).ConfigureAwait(false) is { } entry)
{
if (entry.Status == GlEntryStatus.Final)
{
await JournalEntryService.ReverseAsync(uow, entry, DateOnly.FromDateTime(_clock.GetLocalNow().DateTime), actor.UserName, cancellationToken).ConfigureAwait(false);
}
else
{
await LedgerStore.DeleteAsync(uow, entryId, cancellationToken).ConfigureAwait(false);
}
}
var before = Copy(settlement);
settlement.Status = VatSettlementStatus.Draft;
settlement.GlEntryId = null;
settlement.TaxPaymentId = null;
settlement.ConfirmedAt = null;
settlement.ConfirmedBy = null;
await settlements.UpdateAsync(settlement, cancellationToken).ConfigureAwait(false);
var start = settlement.StartDate;
var open = nameof(FiscalPeriodStatus.Open);
var settled = nameof(FiscalPeriodStatus.Settled);
await uow.ExecuteAsync(
SqlFragment.Of($"UPDATE fiscal_periods SET status = {open} WHERE start_date >= {start} AND end_date <= {end} AND status = {settled}"),
cancellationToken).ConfigureAwait(false);
await _audit.RecordAsync(uow, AuditAction.Update, settlement.Id, before, settlement, actor.UserName, cancellationToken).ConfigureAwait(false);
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
}
await _fiscal.InvalidateAsync(company, cancellationToken).ConfigureAwait(false);
return await SettlementAsync(actor, company, id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(LedgerErrors.NotFound);
}
/// <summary>The base of the December advance for each method, as the ledger knows it.</summary>
/// <param name="actor">Who reads.</param>
/// <param name="companyCode">The company.</param>
/// <param name="year">The year of the advance.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The historical base (last period of the previous year, before its advance) and the actual one (VAT due from the start of the last period to 20 December).</returns>
public async Task<(decimal Historical, decimal Actual)> AdvanceBasisAsync(Actor actor, string companyCode, int year, CancellationToken cancellationToken = default)
{
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.SettlementRead, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
var profile = await uow.Repository<CompanyProfile, long>().FindAsync(Query.For<CompanyProfile>(), cancellationToken).ConfigureAwait(false);
var periodicity = profile?.VatPeriodicity ?? VatPeriodicity.Monthly;
var lastNumber = periodicity == VatPeriodicity.Monthly ? 12 : 4;
var previousYear = year - 1;
var previous = await uow.Repository<VatSettlement, long>().FindAsync(
Query.For<VatSettlement>().Where(s => s.Year == previousYear && s.Number == lastNumber && s.Status == VatSettlementStatus.Confirmed), cancellationToken).ConfigureAwait(false);
var historical = previous is null ? 0m : previous.AmountDue - previous.Interest + previous.AdvancePaid;
var period = TaxPeriod.Of(year, lastNumber, periodicity);
var totals = await TotalsAsync(uow, period.Start, new DateOnly(year, 12, 20), cancellationToken).ConfigureAwait(false);
var actual = VatSettlementCalculator.Compute(totals, new VatSettlementTerms(profile?.ProRataPercent is > 0m and var p ? p : 100m)).Balance;
return (Math.Max(0m, historical), Math.Max(0m, actual));
}
/// <summary>Records the December advance as an F24 line due on 27 December.</summary>
/// <param name="actor">Who records it.</param>
/// <param name="companyCode">The company.</param>
/// <param name="year">The year.</param>
/// <param name="method">The method.</param>
/// <param name="basis">The base of the method.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The F24 line, or <see langword="null"/> when nothing is due.</returns>
public async Task<TaxPayment?> AdvanceAsync(Actor actor, string companyCode, int year, VatAdvanceMethod method, decimal basis, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(actor);
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.SettlementConfirm, cancellationToken).ConfigureAwait(false);
var pack = await _packs.PackOfAsync(company, cancellationToken).ConfigureAwait(false);
var rules = pack.Require<IVatSettlementRules>();
var form = pack.Require<ITaxPaymentFormExporter>();
var amount = VatAdvanceCalculator.Compute(method, basis, rules.AdvancePercent, rules.AdvanceMinimum);
if (amount == 0m)
{
return null;
}
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
var profile = await uow.Repository<CompanyProfile, long>().FindAsync(Query.For<CompanyProfile>(), cancellationToken).ConfigureAwait(false);
var payments = uow.Repository<TaxPayment, long>();
var existing = await payments.FindAsync(
Query.For<TaxPayment>().Where(t => t.Source == TaxPaymentSource.VatAdvance && t.ReferenceYear == year), cancellationToken).ConfigureAwait(false);
if (existing is { PaidOn: not null })
{
throw new ValidationFailedException(["Year:" + LedgerErrors.PaymentPaid]);
}
var payment = existing ?? new TaxPayment { Source = TaxPaymentSource.VatAdvance, ReferenceYear = year };
payment.DueDate = rules.AdvanceDue(year);
payment.PaymentCode = form.VatAdvanceCode(profile?.VatPeriodicity ?? VatPeriodicity.Monthly);
payment.Description = "Acconto IVA " + year.ToString(CultureInfo.InvariantCulture) + " (metodo " + method switch
{
VatAdvanceMethod.Historical => "storico",
VatAdvanceMethod.Forecast => "previsionale",
_ => "analitico",
} + ")";
payment.Amount = amount;
if (existing is null)
{
payment.Id = await payments.InsertAsync(payment, cancellationToken).ConfigureAwait(false);
}
else
{
await payments.UpdateAsync(payment, cancellationToken).ConfigureAwait(false);
}
await _audit.RecordAsync(uow, existing is null ? AuditAction.Insert : AuditAction.Update, payment.Id, existing, payment, actor.UserName, cancellationToken).ConfigureAwait(false);
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
return payment;
}
/// <summary>The communication of the settlements of a quarter (LIPE) from its confirmed settlements.</summary>
/// <param name="actor">Who asks.</param>
/// <param name="companyCode">The company.</param>
/// <param name="year">The year.</param>
/// <param name="quarter">The quarter.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The file.</returns>
public async Task<LedgerFile> PeriodicReturnAsync(Actor actor, string companyCode, int year, int quarter, CancellationToken cancellationToken = default)
{
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.SettlementRead, cancellationToken).ConfigureAwait(false);
var pack = await _packs.PackOfAsync(company, cancellationToken).ConfigureAwait(false);
var writer = pack.Require<IPeriodicVatReturnWriter>();
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
var profile = await uow.Repository<CompanyProfile, long>().FindAsync(Query.For<CompanyProfile>(), cancellationToken).ConfigureAwait(false);
var first = new DateOnly(year, ((quarter - 1) * 3) + 1, 1);
var last = first.AddMonths(3).AddDays(-1);
var settlements = (await uow.Repository<VatSettlement, long>().ListAsync(
Query.For<VatSettlement>().Where(s => s.Status == VatSettlementStatus.Confirmed && s.StartDate >= first && s.EndDate <= last).OrderBy(s => s.StartDate),
cancellationToken).ConfigureAwait(false)).Items;
if (settlements.Count == 0)
{
throw new ValidationFailedException(["Quarter:" + LedgerErrors.SettlementPrevious]);
}
var modules = new List<PeriodicVatReturnModule>();
foreach (var s in settlements)
{
var settlementId = s.Id;
var lines = (await uow.Repository<VatSettlementLine, long>().ListAsync(Query.For<VatSettlementLine>().Where(l => l.SettlementId == settlementId), cancellationToken)
.ConfigureAwait(false)).Items;
var balance = s.AmountDue > 0m ? s.AmountDue : s.DebitCarried > 0m ? 0m : -s.CreditCarried;
modules.Add(new PeriodicVatReturnModule(
TaxPeriod.Of(s.Year, s.Number, s.Periodicity),
lines.Where(l => l.RegisterKind != VatRegisterKind.Purchases).Sum(l => l.Taxable),
lines.Where(l => l.RegisterKind == VatRegisterKind.Purchases).Sum(l => l.Taxable),
s.SalesTax,
s.PurchaseTax,
s.PreviousDebit,
s.PreviousCredit,
s.Interest,
s.AdvancePaid,
balance));
}
var data = new PeriodicVatReturn(
year, quarter, profile?.TaxCode ?? profile?.VatNumber ?? string.Empty, profile?.VatNumber ?? string.Empty, null, profile?.IntermediaryTaxCode,
DateOnly.FromDateTime(_clock.GetLocalNow().DateTime), modules);
return new LedgerFile(writer.FileName(data), "application/xml", writer.Write(data));
}
/// <summary>The VAT of each register in a period, from the posted entries.</summary>
internal static async Task<IReadOnlyList<VatRegisterTotals>> TotalsAsync(IUnitOfWork uow, DateOnly from, DateOnly to, CancellationToken cancellationToken)
{
var draft = nameof(GlEntryStatus.Draft);
var immediate = nameof(TaxExigibility.Immediate);
var rows = await uow.QueryAsync<TotalsRow>(SqlFragment.Of($"""
SELECT v.vat_register_id AS register_id, r.kind AS kind, COUNT(DISTINCT v.entry_id) AS documents,
SUM(v.taxable) AS taxable, SUM(v.tax) AS tax, SUM(v.non_deductible_tax) AS non_deductible_tax,
SUM(CASE WHEN v.exigibility <> {immediate} THEN v.tax ELSE 0 END) AS deferred_tax
FROM gl_entry_vat v JOIN vat_registers r ON r.id = v.vat_register_id
WHERE v.status <> {draft} AND v.vat_date >= {from} AND v.vat_date <= {to}
GROUP BY v.vat_register_id, r.kind
"""), cancellationToken).ConfigureAwait(false);
return [.. rows.Select(r => new VatRegisterTotals(r.RegisterId, r.Kind, (int)r.Documents, r.Taxable ?? 0m, r.Tax ?? 0m, r.NonDeductibleTax ?? 0m, r.DeferredTax ?? 0m))];
}
/// <summary>The lines and totals of a register in a period.</summary>
internal static async Task<VatRegisterView> RegisterAsync(IUnitOfWork uow, long registerId, DateOnly from, DateOnly to, CancellationToken cancellationToken)
{
var register = await uow.Repository<VatRegister, long>().GetAsync(registerId, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(LedgerErrors.VatRegisterRequired);
var draft = nameof(GlEntryStatus.Draft);
var rows = await uow.QueryAsync<VatRegisterRow>(SqlFragment.Of($"""
SELECT v.entry_id AS entry_id, e.entry_number AS entry_number, e.vat_protocol AS vat_protocol, v.vat_date AS vat_date,
e.document_number AS document_number, e.document_date AS document_date, p.name AS party_name, v.rate AS rate, v.nature AS nature,
v.exigibility AS exigibility, v.taxable AS taxable, v.tax AS tax, v.non_deductible_tax AS non_deductible_tax, v.status AS status
FROM gl_entry_vat v JOIN gl_entries e ON e.id = v.entry_id LEFT JOIN parties p ON p.id = e.party_id
WHERE v.vat_register_id = {registerId} AND v.status <> {draft} AND v.vat_date >= {from} AND v.vat_date <= {to}
ORDER BY v.vat_date, e.vat_protocol, e.id, v.line_number
"""), cancellationToken).ConfigureAwait(false);
var totals = rows.GroupBy(r => (r.Rate, r.Nature))
.Select(g => new VatRateTotal(g.Key.Rate, g.Key.Nature, g.Sum(r => r.Taxable), g.Sum(r => r.Tax), g.Sum(r => r.NonDeductibleTax)))
.OrderByDescending(t => t.Rate).ThenBy(t => t.Nature, StringComparer.Ordinal)
.ToList();
return new VatRegisterView(register, rows, totals);
}
/// <summary>The name and VAT number of the company for the heading of the prints.</summary>
internal static string CompanyLine(CompanyProfile? profile) =>
profile is null ? string.Empty : profile.LegalName + (profile.VatNumber is { Length: > 0 } vat ? " - P.IVA " + vat : string.Empty);
private static async Task<VatSettlementView?> ViewAsync(IUnitOfWork uow, long id, CancellationToken cancellationToken)
{
if (await uow.Repository<VatSettlement, long>().GetAsync(id, cancellationToken).ConfigureAwait(false) is not { } settlement)
{
return null;
}
var lines = (await uow.Repository<VatSettlementLine, long>().ListAsync(Query.For<VatSettlementLine>().Where(l => l.SettlementId == id), cancellationToken)
.ConfigureAwait(false)).Items;
var registers = (await uow.Repository<VatRegister, long>().ListAsync(Query.For<VatRegister>(), cancellationToken).ConfigureAwait(false)).Items.ToDictionary(r => r.Id);
return new VatSettlementView(settlement, [.. lines.OrderBy(l => l.RegisterKind).ThenBy(l => registers.TryGetValue(l.VatRegisterId, out var r) ? r.Code : string.Empty, StringComparer.Ordinal)], registers);
}
// The entry LIQ: VAT on sales debit, VAT on purchases credit (what is deducted and the share lost to the pro rata),
// the pro rata to its cost, the interest debit, the balance to the VAT settlement account.
private static async Task<GlEntry?> PostSettlementAsync(IUnitOfWork uow, VatSettlement settlement, CancellationToken cancellationToken)
{
if (await LedgerStore.TemplateAsync(uow, "LIQ", cancellationToken).ConfigureAwait(false) is not { } found)
{
return null;
}
var (template, templateLines) = found;
long? Role(PostingRole role, string? description = null) =>
templateLines.FirstOrDefault(l => l.Role == role && l.AccountId is not null && (description is null || l.Description == description))?.AccountId;
var salesVat = Role(PostingRole.SalesVat);
var purchaseVat = Role(PostingRole.PurchaseVat);
var settlementAccount = Role(PostingRole.VatSettlement);
var interestAccount = templateLines.FirstOrDefault(l => l.Role == PostingRole.Account && l.AccountId is not null)?.AccountId;
var proRataAccount = Role(PostingRole.Cost);
if (salesVat is null || purchaseVat is null || settlementAccount is null)
{
throw new ValidationFailedException(["Ledger:" + LedgerErrors.RoleAccountMissing]);
}
var proRata = await ProRataShareAsync(uow, settlement, cancellationToken).ConfigureAwait(false);
var lines = new List<EntryLineDraft>();
void Add(long? account, decimal amount, AccountSide side, string description)
{
if (amount == 0m || account is null)
{
return;
}
if (amount < 0m)
{
amount = -amount;
side = side == AccountSide.Debit ? AccountSide.Credit : AccountSide.Debit;
}
lines.Add(new EntryLineDraft(account, null, description, side == AccountSide.Debit ? amount : 0m, side == AccountSide.Debit ? 0m : amount));
}
Add(salesVat, settlement.SalesTax, AccountSide.Debit, "IVA a debito del periodo");
Add(purchaseVat, settlement.PurchaseTax + proRata, AccountSide.Credit, "IVA a credito del periodo");
Add(proRata == 0m ? null : proRataAccount ?? settlementAccount, proRata, AccountSide.Debit, "IVA indetraibile da pro rata");
var interest = interestAccount is null ? 0m : settlement.Interest;
Add(interestAccount, interest, AccountSide.Debit, "Interessi trimestrali");
Add(settlementAccount, settlement.SalesTax - settlement.PurchaseTax + interest, AccountSide.Credit, "Saldo della liquidazione");
if (lines.Count == 0)
{
return null;
}
var entry = new GlEntry
{
EntryDate = settlement.EndDate,
JournalTemplateId = template.Id,
TemplateCode = template.Code,
Description = LedgerStore.Trim(template.Description + " " + PeriodText(settlement), 200)!,
Status = GlEntryStatus.Posted,
Source = GlEntrySource.VatSettlement,
IsDemo = settlement.IsDemo,
};
return await LedgerStore.InsertAsync(uow, entry, lines, [], cancellationToken).ConfigureAwait(false);
}
// The VAT of the purchase registers lost to the pro rata (beyond what the codes already make non-deductible).
private static async Task<decimal> ProRataShareAsync(IUnitOfWork uow, VatSettlement settlement, CancellationToken cancellationToken)
{
if (settlement.ProRataPercent >= 100m)
{
return 0m;
}
var totals = await TotalsAsync(uow, settlement.StartDate, settlement.EndDate, cancellationToken).ConfigureAwait(false);
var byCode = totals.Where(t => t.Kind == VatRegisterKind.Purchases).Sum(t => t.NonDeductibleTax);
return settlement.NonDeductibleTax - byCode;
}
private static string PeriodText(VatSettlement settlement) =>
settlement.Periodicity == VatPeriodicity.Monthly
? settlement.StartDate.ToString("MMMM yyyy", CultureInfo.GetCultureInfo("it-IT"))
: settlement.Number.ToString(CultureInfo.InvariantCulture) + "° trimestre " + settlement.Year.ToString(CultureInfo.InvariantCulture);
private static string Describe(VatSettlement settlement, ITaxPaymentFormExporter? form)
{
var code = settlement.PaymentCode;
// The description of the code already names the month or the quarter: only the year is added.
var text = form?.Codes.FirstOrDefault(c => c.Code == code)?.Description;
return LedgerStore.Trim(text is null ? "Versamento IVA " + PeriodText(settlement) : text + " " + settlement.Year.ToString(CultureInfo.InvariantCulture), 200)!;
}
private static VatSettlement Copy(VatSettlement s) => new()
{
Id = s.Id,
Year = s.Year,
Number = s.Number,
Status = s.Status,
AmountDue = s.AmountDue,
CreditCarried = s.CreditCarried,
GlEntryId = s.GlEntryId,
TaxPaymentId = s.TaxPaymentId,
};
private sealed record TotalsRow(long RegisterId, VatRegisterKind Kind, long Documents, decimal? Taxable, decimal? Tax, decimal? NonDeductibleTax, decimal? DeferredTax);
}
@@ -0,0 +1,522 @@
using System.IO.Compression;
using Khaemhat.Application.Documents;
using Khaemhat.Application.Files;
using Khaemhat.Application.Parties;
using Khaemhat.Application.Security;
using Khaemhat.Application.Tables;
using Khaemhat.Core.Documents;
using Khaemhat.Core.Files;
using Khaemhat.Core.Items;
using Khaemhat.Core.Parties;
using Khaemhat.Core.Tables;
using Khaemhat.Core.Tax;
using Khaemhat.Data;
using Khaemhat.Data.Querying;
using Khaemhat.Fiscal.Abstractions;
namespace Khaemhat.Application.Purchases;
/// <summary>An invoice found in a received file, as the import screen shows it before registering (mockup 034).</summary>
/// <param name="FileName">The file (inside a ZIP, its entry).</param>
/// <param name="File">The file as read.</param>
/// <param name="Invoice">The invoice (a file may hold several).</param>
/// <param name="DocumentTypeCode">The purchase document type that registers it, or none.</param>
/// <param name="SupplierId">The supplier already in the archive, by VAT number or tax code.</param>
/// <param name="Duplicate">Whether the supplier already has a document with this number in this year.</param>
/// <param name="ComputedTotal">Taxable plus tax of the summary, plus rounding: what the total should be.</param>
/// <param name="Problems">What stops or warns (resource codes).</param>
public sealed record IncomingCandidate(
string FileName, IncomingInvoiceFile File, IncomingInvoice Invoice, string? DocumentTypeCode, long? SupplierId, bool Duplicate, decimal ComputedTotal,
IReadOnlyList<string> Problems)
{
/// <summary>Whether it can be registered.</summary>
public bool CanImport => DocumentTypeCode is not null && !Duplicate;
/// <summary>The total in the file, or the computed one.</summary>
public decimal Total => Invoice.Total ?? ComputedTotal;
}
/// <summary>A file that could not be read.</summary>
/// <param name="FileName">The file.</param>
/// <param name="Error">Why (resource code).</param>
public sealed record IncomingRejected(string FileName, string Error);
/// <summary>What the files hold.</summary>
/// <param name="Invoices">The invoices found.</param>
/// <param name="Rejected">The files not read.</param>
public sealed record IncomingReading(IReadOnlyList<IncomingCandidate> Invoices, IReadOnlyList<IncomingRejected> Rejected);
/// <summary>An invoice registered, or why not.</summary>
/// <param name="Candidate">The invoice.</param>
/// <param name="Record">The draft document.</param>
/// <param name="SupplierCreated">Whether the supplier was added to the archive.</param>
/// <param name="Error">Why it was not registered (resource code).</param>
/// <param name="Warnings">What to check on the draft (resource codes).</param>
public sealed record IncomingImported(IncomingCandidate Candidate, DocumentRecord? Record, bool SupplierCreated, string? Error, IReadOnlyList<string> Warnings);
/// <summary>
/// The import of supplier e-invoices (SPEC §11.5, mockup 034): XML, signed P7M and ZIP files are read by the fiscal pack;
/// each invoice finds its supplier by VAT number or tax code (or adds it), its items by the supplier code, bar code or
/// code, its tax codes by rate and nature; it becomes a draft supplier invoice or credit note with the file attached, to
/// check and confirm. Duplicates (same supplier, number and year) are refused; a total that does not match the lines is
/// reported.
/// </summary>
public sealed class PurchaseInvoiceImportService
{
/// <summary>The largest file accepted, ZIP included.</summary>
public const int MaxFileSize = 50 * 1024 * 1024;
/// <summary>Problem: the type of the invoice is not a purchase (a self-invoice).</summary>
public const string UnsupportedType = "purchase.import.unsupported-type";
/// <summary>Problem: already registered.</summary>
public const string DuplicateProblem = "purchase.import.duplicate";
/// <summary>Warning: the total in the file differs from the lines.</summary>
public const string TotalMismatch = "purchase.import.total-mismatch";
/// <summary>Warning: the signature of the file could not be verified.</summary>
public const string SignatureNotVerified = "purchase.import.signature";
/// <summary>Warning: the discounts of the whole document are not carried to the lines.</summary>
public const string DocumentDiscount = "purchase.import.document-discount";
/// <summary>Error: no tax code of the company has the rate and nature of a line.</summary>
public const string TaxCodeMissing = "purchase.import.tax-code";
/// <summary>Error: the archive is empty of invoices.</summary>
public const string EmptyArchive = "purchase.import.empty";
private readonly IUnitOfWorkFactory _factory;
private readonly PermissionService _permissions;
private readonly CompanyFiscalContext _packs;
private readonly DocumentEngine _engine;
private readonly DocumentEditor _editor;
private readonly PartyService _parties;
private readonly AttachmentService _attachments;
private readonly TimeProvider _clock;
/// <summary>Creates the service.</summary>
/// <param name="factory">The units of work.</param>
/// <param name="permissions">The permissions.</param>
/// <param name="packs">The fiscal pack of each company.</param>
/// <param name="engine">The document engine.</param>
/// <param name="editor">The editor (terms of the supplier).</param>
/// <param name="parties">The parties (new suppliers).</param>
/// <param name="attachments">The attachments (the file).</param>
/// <param name="clock">The clock.</param>
public PurchaseInvoiceImportService(
IUnitOfWorkFactory factory, PermissionService permissions, CompanyFiscalContext packs, DocumentEngine engine, DocumentEditor editor, PartyService parties,
AttachmentService attachments, TimeProvider clock)
{
ArgumentNullException.ThrowIfNull(factory);
ArgumentNullException.ThrowIfNull(permissions);
ArgumentNullException.ThrowIfNull(packs);
ArgumentNullException.ThrowIfNull(engine);
ArgumentNullException.ThrowIfNull(editor);
ArgumentNullException.ThrowIfNull(parties);
ArgumentNullException.ThrowIfNull(attachments);
ArgumentNullException.ThrowIfNull(clock);
_factory = factory;
_permissions = permissions;
_packs = packs;
_engine = engine;
_editor = editor;
_parties = parties;
_attachments = attachments;
_clock = clock;
}
/// <summary>Reads files: each XML or P7M, and those inside a ZIP.</summary>
/// <param name="actor">Who imports: needs <c>purchases.invoice.write</c>.</param>
/// <param name="companyCode">The company.</param>
/// <param name="files">The files, by name.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The invoices found and the files not read.</returns>
public async Task<IncomingReading> ReadAsync(
Actor actor, string companyCode, IReadOnlyList<(string FileName, byte[] Content)> files, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(files);
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, PurchaseService.WritePermission, cancellationToken).ConfigureAwait(false);
var pack = await _packs.PackOfAsync(company, cancellationToken).ConfigureAwait(false);
var reader = pack.GetFeature<IIncomingInvoiceReader>();
var rules = pack.GetFeature<IIncomingInvoiceRules>();
var found = new List<(string Name, IncomingInvoiceFile File)>();
var rejected = new List<IncomingRejected>();
foreach (var (name, content) in Expand(files, rejected))
{
if (reader is null || !reader.CanRead(name, content))
{
rejected.Add(new(name, IncomingInvoiceErrors.NotReadable));
continue;
}
try
{
found.Add((name, reader.Read(name, content)));
}
catch (IncomingInvoiceException ex)
{
rejected.Add(new(name, ex.Code));
}
}
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
var result = new List<IncomingCandidate>();
foreach (var (name, file) in found)
{
var supplierId = await FindSupplierAsync(uow, file.Supplier, cancellationToken).ConfigureAwait(false);
foreach (var invoice in file.Invoices)
{
var problems = new List<string>();
var typeCode = rules?.DocumentTypeCode(invoice.DocumentType);
if (typeCode is null)
{
problems.Add(UnsupportedType);
}
var duplicate = supplierId is { } supplier && await IsDuplicateAsync(uow, supplier, invoice, cancellationToken).ConfigureAwait(false);
if (duplicate)
{
problems.Add(DuplicateProblem);
}
var computed = invoice.TaxSummary.Sum(t => t.Taxable + t.Tax) + (invoice.Rounding ?? 0m);
if (invoice.Total is { } total && Math.Abs(total - computed) > 0.01m && invoice.Discounts.Count == 0)
{
problems.Add(TotalMismatch);
}
if (invoice.Discounts.Count > 0)
{
problems.Add(DocumentDiscount);
}
if (file.Signature is { Verified: false })
{
problems.Add(SignatureNotVerified);
}
result.Add(new IncomingCandidate(name, file, invoice, typeCode, supplierId, duplicate, computed, problems));
}
}
if (result.Count == 0 && rejected.Count == 0)
{
rejected.Add(new(files.Count == 1 ? files[0].FileName : string.Empty, EmptyArchive));
}
return new IncomingReading([.. result.OrderBy(c => c.Invoice.Date).ThenBy(c => c.File.Supplier.DisplayName, StringComparer.CurrentCulture)], rejected);
}
/// <summary>
/// Registers the invoices as drafts: the supplier is found or added, each line takes its item and tax code, the
/// file is attached. One invoice that fails does not stop the others.
/// </summary>
/// <param name="actor">Who imports.</param>
/// <param name="companyCode">The company.</param>
/// <param name="candidates">The invoices to register.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>What happened to each.</returns>
public async Task<IReadOnlyList<IncomingImported>> ImportAsync(
Actor actor, string companyCode, IReadOnlyList<IncomingCandidate> candidates, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(candidates);
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, PurchaseService.WritePermission, cancellationToken).ConfigureAwait(false);
var today = DateOnly.FromDateTime(_clock.GetLocalNow().DateTime);
var created = new Dictionary<string, long>(StringComparer.OrdinalIgnoreCase);
var result = new List<IncomingImported>();
foreach (var candidate in candidates)
{
if (candidate.DocumentTypeCode is not { } typeCode)
{
result.Add(new(candidate, null, false, UnsupportedType, []));
continue;
}
var supplierCreated = false;
try
{
long supplierId;
var key = KeyOf(candidate.File.Supplier);
if (candidate.SupplierId is { } known)
{
supplierId = known;
}
else if (key.Length > 0 && created.TryGetValue(key, out var made))
{
supplierId = made;
}
else
{
await using (var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false))
{
supplierId = await FindSupplierAsync(uow, candidate.File.Supplier, cancellationToken).ConfigureAwait(false) ?? 0;
}
if (supplierId == 0)
{
supplierId = await CreateSupplierAsync(actor, company, candidate.File.Supplier, cancellationToken).ConfigureAwait(false);
supplierCreated = true;
}
if (key.Length > 0)
{
created[key] = supplierId;
}
}
var (record, warnings) = await DraftAsync(actor, company, candidate, typeCode, supplierId, today, cancellationToken).ConfigureAwait(false);
result.Add(new(candidate, record, supplierCreated, null, warnings));
}
catch (ValidationFailedException ex)
{
result.Add(new(candidate, null, supplierCreated, (ex.Errors.Count > 0 ? ex.Errors[0] : null)?.Split(':', 2)[^1] ?? IncomingInvoiceErrors.Invalid, []));
}
}
return result;
}
// ZIP archives are opened (one level, entries .xml and .p7m); other files pass as they are.
private static List<(string Name, byte[] Content)> Expand(IReadOnlyList<(string FileName, byte[] Content)> files, List<IncomingRejected> rejected)
{
var result = new List<(string, byte[])>();
foreach (var (name, content) in files)
{
if (content.Length > MaxFileSize)
{
rejected.Add(new(name, IncomingInvoiceErrors.NotReadable));
continue;
}
if (content.Length < 4 || content[0] != (byte)'P' || content[1] != (byte)'K')
{
result.Add((name, content));
continue;
}
try
{
using var archive = new ZipArchive(new MemoryStream(content, writable: false), ZipArchiveMode.Read);
long total = 0;
foreach (var entry in archive.Entries.Where(e => e.Length > 0 && !e.FullName.EndsWith('/')))
{
var entryName = Path.GetFileName(entry.FullName);
if (!entryName.EndsWith(".xml", StringComparison.OrdinalIgnoreCase) && !entryName.EndsWith(".p7m", StringComparison.OrdinalIgnoreCase))
{
continue;
}
total += entry.Length;
if (entry.Length > MaxFileSize || total > 4L * MaxFileSize)
{
rejected.Add(new(entryName, IncomingInvoiceErrors.NotReadable));
continue;
}
using var stream = entry.Open();
using var buffer = new MemoryStream();
stream.CopyTo(buffer);
result.Add((entryName, buffer.ToArray()));
}
}
catch (InvalidDataException)
{
rejected.Add(new(name, IncomingInvoiceErrors.NotReadable));
}
}
return result;
}
private static string KeyOf(IncomingParty party) =>
(party.VatNumber is { Length: > 0 } vat ? (party.CountryCode ?? "IT") + vat : party.TaxCode ?? string.Empty).ToUpperInvariant();
// The VAT number as the archive keeps it: digits only for Italy, with the country prefix abroad.
private static string? VatOf(IncomingParty party) =>
party.VatNumber is not { Length: > 0 } vat ? null
: party.CountryCode is null or "IT" ? vat
: vat.StartsWith(party.CountryCode, StringComparison.OrdinalIgnoreCase) ? vat : party.CountryCode + vat;
private static async Task<long?> FindSupplierAsync(IUnitOfWork uow, IncomingParty party, CancellationToken cancellationToken)
{
var parties = uow.Repository<Party, long>();
if (VatOf(party) is { } vat)
{
var bare = party.VatNumber!;
var byVat = (await parties.ListAsync(Query.For<Party>().Where(p => p.VatNumber == vat || p.VatNumber == bare), cancellationToken).ConfigureAwait(false)).Items;
if (Pick(byVat) is { } found)
{
return found;
}
}
if (party.TaxCode is { Length: > 0 } taxCode)
{
var byTaxCode = (await parties.ListAsync(Query.For<Party>().Where(p => p.TaxCode == taxCode), cancellationToken).ConfigureAwait(false)).Items;
return Pick(byTaxCode);
}
return null;
// A supplier first, then a customer that is also a supplier, then any party; the enabled ones first.
static long? Pick(IReadOnlyList<Party> parties) => parties
.OrderBy(p => p.Disabled).ThenBy(p => p.Kind == PartyKind.Supplier ? 0 : p.IsSupplier ? 1 : 2).ThenBy(p => p.Id).FirstOrDefault()?.Id;
}
private static async Task<bool> IsDuplicateAsync(IUnitOfWork uow, long supplierId, IncomingInvoice invoice, CancellationToken cancellationToken)
{
var number = invoice.Number.Trim();
var from = new DateOnly(invoice.Date.Year, 1, 1);
var to = new DateOnly(invoice.Date.Year, 12, 31);
return await uow.Repository<PurchaseDocument, long>().CountAsync(
Query.For<PurchaseDocument>().Where(d => d.PartyId == supplierId && d.ExternalReference == number && d.ExternalDate >= from && d.ExternalDate <= to
&& d.Status != DocumentStatus.Cancelled
&& (d.Kind == DocumentKind.PurchaseInvoice || d.Kind == DocumentKind.PurchaseCreditNote)),
cancellationToken).ConfigureAwait(false) > 0;
}
private async Task<long> CreateSupplierAsync(Actor actor, string company, IncomingParty party, CancellationToken cancellationToken)
{
var record = await _parties.NewAsync(actor, company, PartyKind.Supplier, cancellationToken).ConfigureAwait(false);
var p = record.Party;
var country = string.IsNullOrWhiteSpace(party.CountryCode) ? "IT" : party.CountryCode.Trim().ToUpperInvariant();
bool inEu;
await using (var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false))
{
inEu = (await uow.Repository<Country, long>().FindAsync(Query.For<Country>().Where(c => c.Code == country), cancellationToken).ConfigureAwait(false))?.EuMember ?? false;
}
p.CountryCode = country;
p.SubjectType = country == "IT"
? (party.Name is null && party.VatNumber is null ? SubjectType.Person : SubjectType.Company)
: inEu ? SubjectType.EuCompany : SubjectType.NonEuCompany;
p.Name = Limit(party.DisplayName, 200) ?? string.Empty;
p.FirstName = p.SubjectType == SubjectType.Person ? Limit(party.FirstName, 100) : null;
p.LastName = p.SubjectType == SubjectType.Person ? Limit(party.LastName, 100) : null;
p.VatNumber = VatOf(party);
p.TaxCode = Limit(party.TaxCode, 16);
p.Address = Limit(party.Address, 200);
p.StreetNumber = Limit(party.StreetNumber, 20);
p.PostalCode = Limit(party.PostalCode, 10);
p.City = Limit(party.City, 100);
p.Province = country == "IT" ? Limit(party.Province, 2) : null;
p.Email = Limit(party.Email, 200);
p.Phone = Limit(party.Phone, 40);
p.Rea = party.ReaOffice is null || party.ReaNumber is null ? null : Limit(party.ReaOffice + "-" + party.ReaNumber, 30);
return (await _parties.SaveAsync(actor, company, record, cancellationToken).ConfigureAwait(false)).Party.Id;
}
private static string? Limit(string? text, int length) =>
string.IsNullOrWhiteSpace(text) ? null : text.Trim() is var trimmed && trimmed.Length > length ? trimmed[..length] : text.Trim();
private async Task<(DocumentRecord Record, IReadOnlyList<string> Warnings)> DraftAsync(
Actor actor, string company, IncomingCandidate candidate, string typeCode, long supplierId, DateOnly today, CancellationToken cancellationToken)
{
var invoice = candidate.Invoice;
var record = await _engine.NewAsync(actor, company, typeCode, cancellationToken).ConfigureAwait(false);
await _editor.ApplyPartyAsync(actor, company, record, supplierId, cancellationToken).ConfigureAwait(false);
var header = record.Header;
header.DocumentDate = invoice.Date > today ? invoice.Date : today;
header.ExternalReference = Limit(invoice.Number, 50);
header.ExternalDate = invoice.Date;
if (invoice.Causals.Count > 0)
{
header.Notes = Limit(string.Join(Environment.NewLine, invoice.Causals), 2000);
}
await using (var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false))
{
var taxes = (await uow.Repository<TaxCode, long>().ListAsync(Query.For<TaxCode>().Where(t => !t.Disabled), cancellationToken).ConfigureAwait(false)).Items;
var codes = invoice.Lines.SelectMany(l => l.Codes).Select(c => c.Value.Trim()).Where(v => v.Length > 0).Distinct(StringComparer.Ordinal).ToList();
var bySupplierCode = codes.Count == 0 ? [] : (await uow.Repository<ItemSupplier, long>().ListAsync(
Query.For<ItemSupplier>().Where(s => s.PartyId == supplierId && codes.Contains(s.SupplierCode!)), cancellationToken).ConfigureAwait(false)).Items
.GroupBy(s => s.SupplierCode!, StringComparer.Ordinal).ToDictionary(g => g.Key, g => g.First().ItemId, StringComparer.Ordinal);
var byBarcode = codes.Count == 0 ? [] : (await uow.Repository<ItemBarcode, long>().ListAsync(
Query.For<ItemBarcode>().Where(b => codes.Contains(b.Code)), cancellationToken).ConfigureAwait(false)).Items
.GroupBy(b => b.Code, StringComparer.Ordinal).ToDictionary(g => g.Key, g => g.First().ItemId, StringComparer.Ordinal);
var byCode = codes.Count == 0 ? [] : (await uow.Repository<Item, long>().ListAsync(
Query.For<Item>().Where(i => codes.Contains(i.Code)), cancellationToken).ConfigureAwait(false)).Items.ToDictionary(i => i.Code, StringComparer.Ordinal);
var itemIds = bySupplierCode.Values.Concat(byBarcode.Values).Distinct().ToList();
var items = itemIds.Count == 0 ? [] : (await uow.Repository<Item, long>().ListAsync(Query.For<Item>().Where(i => itemIds.Contains(i.Id)), cancellationToken)
.ConfigureAwait(false)).Items.ToDictionary(i => i.Id);
foreach (var item in byCode.Values)
{
items.TryAdd(item.Id, item);
}
var credit = record.Header.Kind == DocumentKind.PurchaseCreditNote;
foreach (var source in invoice.Lines.OrderBy(l => l.Number))
{
var line = new PurchaseDocumentLine();
line.Kind = DocumentLineKind.Free;
line.Description = Limit(source.Description, 1000) ?? "-";
line.TaxCodeId = TaxCodeOf(taxes, source.TaxRate, source.Nature)
?? throw new ValidationFailedException([":" + TaxCodeMissing]);
var quantity = source.Quantity is { } q && q != 0m ? q : 1m;
var price = source.UnitPrice;
var discounts = source.Discounts;
if (discounts.Count > 0 && discounts.All(d => d.Percent is > 0m and <= 100m && !d.IsSurcharge))
{
line.DiscountFormula = string.Join('+', discounts.Select(d => d.Percent!.Value.ToString("0.##", System.Globalization.CultureInfo.InvariantCulture)));
}
else if (discounts.Count > 0 || (source.Quantity is null && source.TotalPrice != source.UnitPrice))
{
// Amounts or surcharges: the net price keeps the total of the line.
price = Math.Round(source.TotalPrice / quantity, 6);
}
line.Quantity = credit ? Math.Abs(quantity) : quantity;
line.Price = credit && quantity < 0m ? -price : price;
if (ItemOf(source, bySupplierCode, byBarcode, byCode) is { } itemId && items.TryGetValue(itemId, out var item) && !item.Disabled)
{
line.Kind = DocumentLineKind.Item;
line.ItemId = item.Id;
line.UnitOfMeasureId = item.UnitOfMeasureId;
}
record.Lines.Add(line);
}
}
var saved = await _engine.SaveAsync(actor, company, record, cancellationToken).ConfigureAwait(false);
await _attachments.AddAsync(
actor, company, DocumentPrintService.EntityOf(saved.Family), saved.Header.Id, new AttachmentFile(AttachmentKind.EInvoice, candidate.File.FileName, null),
(stream, ct) => stream.WriteAsync(candidate.File.Xml, ct).AsTask(), cancellationToken).ConfigureAwait(false);
var warnings = candidate.Problems.Where(p => p is TotalMismatch or SignatureNotVerified or DocumentDiscount).ToList();
if (invoice.Total is { } total && Math.Abs(total - saved.Header.TotalAmount) > 0.01m && !warnings.Contains(TotalMismatch))
{
warnings.Add(TotalMismatch);
}
return (saved, warnings);
}
private static long? ItemOf(IncomingLine line, Dictionary<string, long> bySupplierCode, Dictionary<string, long> byBarcode, Dictionary<string, Item> byCode)
{
foreach (var code in line.Codes.Select(c => c.Value.Trim()))
{
if (bySupplierCode.TryGetValue(code, out var id) || byBarcode.TryGetValue(code, out id))
{
return id;
}
}
return line.Codes.Select(c => c.Value.Trim()).FirstOrDefault(byCode.ContainsKey) is { } own ? byCode[own].Id : null;
}
// The tax code with the rate and nature of the line: the exact nature first, then the family of the nature (N3 for
// N3.2), then for an ordinary rate the ordinary codes before the others.
private static long? TaxCodeOf(IReadOnlyList<TaxCode> taxes, decimal rate, string? nature)
{
var withRate = taxes.Where(t => t.Rate == rate).OrderBy(t => t.ValidTo is not null).ThenBy(t => t.Code, StringComparer.Ordinal).ToList();
if (nature is null)
{
return (withRate.FirstOrDefault(t => t.Nature is null && t.Kind == TaxCodeKind.Taxable) ?? withRate.FirstOrDefault(t => t.Nature is null))?.Id;
}
return (withRate.FirstOrDefault(t => string.Equals(t.Nature, nature, StringComparison.OrdinalIgnoreCase))
?? withRate.FirstOrDefault(t => t.Nature is not null && t.Nature.StartsWith(nature.Split('.')[0], StringComparison.OrdinalIgnoreCase)))?.Id;
}
}
Loaded 100 of 217 files, more files were not shown because too many files have changed in this diff. Show more