Compare commits

..
Author SHA1 Message Date
Alby96 f7b5cfb1bd Merge decisioni del titolare su mockup, banche e canali SDI (#130)
Wiki / Publish the wiki (push) Successful in 11s
2026-11-16 17:27:17 +01:00
Alby96andClaude Opus 5.5 83ef60fce2 docs: record owner decisions on mockups, bank list and SDI channels (#35 #45 #78)
CI / Build and test (SQLite) (pull_request) Successful in 5m27s
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 1m59s
The owner confirmed that no further high-resolution mockups exist, gave up
the preloaded ABI/CAB bank list and set aside real SDI intermediaries,
SdICoop accreditation and a test PEC mailbox. ADR 0044 records this so the
next milestones stop waiting on that material: thumbnail-only screens are
designed from the thumbnail and the existing UI, bank name and BIC come
from a company account or are typed once, and #78 moves to the backlog.
CLAUDE.md E4, the mockup index, related ADRs, status, changelog and the
user guide are updated accordingly.

Closes #35
Closes #45

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 17:19:01 +01:00
Alby96 a8f00cbae0 Merge M10 · Cespiti, Intrastat, chiusura, bilancio (v0.10.0) (#129)
Wiki / Publish the wiki (push) Successful in 9s
Release / Image and release (push) Successful in 3m32s
CI / PostgreSQL 16 integration (push) Successful in 2m17s
CI / Build and test (SQLite) (push) Successful in 4m38s
CI / Docker image (push) Skipped
CI / YAML check (push) Successful in 6s
CI / PostgreSQL 17 integration (push) Successful in 1m58s
2026-11-13 20:26:03 +01:00
Alby96andClaude Opus 5.5 51007d68ca feat: fixed assets, Intrastat, intent declarations, year-end closing and statements (#82 #83 #84 #85 #86 #87)
CI / Build and test (SQLite) (pull_request) Successful in 4m35s
CI / PostgreSQL 16 integration (pull_request) Skipped
CI / PostgreSQL 17 integration (pull_request) Skipped
CI / YAML check (pull_request) Successful in 5s
CI / Docker image (pull_request) Successful in 1m24s
M10 gives the ledger its year end. Fixed assets get categories with the
ministerial coefficients, a civil and a fiscal plan, depreciation posted
per category and undoable, disposals with gain or loss and the register
print (ADR 0041). Intrastat lists are generated from confirmed invoices
with the due periodicity and the SCAMBI.CEE file; declarations of intent
get their own register and the N3.5 ceiling is checked when an invoice is
confirmed (ADR 0042). Accruals, deferrals and exchange differences feed a
nine-step guided closing that can repeat or undo its last step until the
final prints, reopens the next year and locks the closed one; the CEE
statements (ordinary, abbreviated, micro), the reclassified statements,
the ratios and the accountant export read the year's balances (ADR 0043).

The demo seed now opens the year with assets, stock, bank and capital, so
the integration test closes the demo year from the checks to the lock on
SQLite and PostgreSQL. Docs: wiki pages with screenshots, ADR 0041-0043,
MODULES, STATUS, DATA-MODEL and the 0.10.0 changelog.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 19:31:26 +01:00
Alby96andClaude Opus 5.5 836a316b05 Merge M9 · Fatturazione elettronica (v0.9.0) (#128)
Wiki / Publish the wiki (push) Successful in 10s
Release / Image and release (push) Successful in 3m25s
CI / PostgreSQL 16 integration (push) Successful in 1m45s
CI / Build and test (SQLite) (push) Successful in 4m14s
CI / Docker image (push) Skipped
CI / YAML check (push) Successful in 4s
CI / PostgreSQL 17 integration (push) Successful in 1m46s
E-invoicing: FatturaPA files checked offline with the SDI codes, four channels with routing and fallback, notifications, inbox, conservation packages, demo e-invoices and schema-driven demo removal.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 13:31:14 +01:00
Alby96andClaude Opus 5.5 246d6f9357 docs: e-invoicing guide, ADR 0039-0040 and 0.9.0 changelog (#81)
CI / Build and test (SQLite) (pull_request) Successful in 4m27s
CI / PostgreSQL 16 integration (pull_request) Skipped
CI / PostgreSQL 17 integration (pull_request) Skipped
CI / YAML check (pull_request) Successful in 7s
CI / Docker image (pull_request) Successful in 1m30s
The wiki page "Fatturazione elettronica" becomes a complete guide for 0.9 with
nine screenshots of the real screens, and the pages that pointed to M9 now
describe what shipped (demo data and their removal, scheduled jobs, sales,
purchases, Italian tax rules, user guide). ADR 0039 records the e-invoice
design (file rows, progressive, offline checks with SDI codes and in-house
schema, notification dedup, safe polling, routing, SdICoop push with channel
key) and ADR 0040 the generic intermediary contracts and the schema-driven
removal of demo data. Screen polish: dashboard actions in the header, filters
on two rows, tables no longer squeezed, report titles and notification errors;
demo e-invoices get realistic send times and a rejection in the history.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 13:24:31 +01:00
Alby96andClaude Opus 5.5 b78260beb0 feat: e-invoice screens and SdICoop push endpoint (#74 #75 #76 #77 #79)
The SDI dashboard (mockup 058) with its six counters, the documents to
generate, generate+send, manual receipts import, history, courtesy copy
and mark-as-sent; the channels page (mockup 059) with settings, test,
pause and routing rules; the received invoices, the notifications and
the conservation packages. The SdICoop web service receives pushes at
/sdicoop/{company}, authenticated by the key of the channel, through a
new IEInvoicePushReader feature so the web layer stays country-neutral.
The menu gives each e-invoice page its own permission and keeps the
intent declarations under M10.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 12:54:09 +01:00
Alby96andClaude Opus 5.5 9d7cb9e71f feat: demo e-invoices, demo data removal and e-invoice integration tests (#79 #80)
The demo company now has its electronic invoices: a paused PEC channel and an
intermediary, routing rules, the files of the demo invoices with the notifications
the SDI would send (delivered, one rejected, one not delivered, some waiting) read
by the fiscal pack as real ones, and three supplier invoices in the inbox with their
metadata. Every demo seeder now marks as demo also the rows the services write for
it (entries, open items, payments, mandates, statements), so the new
DemoDataRemover, driven by the schema of the migrations, removes the demo data and
only them; it stops and names the tables when rows entered by users still refer to
demo rows. `scripts/seed.sh --remove-demo` exposes it and the seed prints its time.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 12:33:07 +01:00
Alby96andClaude Opus 5.5 fb12411404 feat: e-invoice services, SDI channels, inbox, polling and conservation (#74 #75 #76 #77 #79)
Adds the company tables of the electronic invoice and the services that drive them:
the builder turns an issued document into the FatturaPA model, the service generates,
checks and sends the file through the channel chosen by the routing rules (with a
fallback) and applies the SDI notifications to the e-invoice and its document. The
channel settings keep their secrets protected and out of the audit trail; a job reads
the PEC mailbox and the intermediaries every 15 minutes, storing supplier invoices in
the inbox and acknowledging a message only once all its files are kept. The inbox
registers received invoices through the purchase import, and the conservation export
packs a period with a SHA-256 index. A rejected invoice can now be corrected and
generated again; the courtesy PDF embeds the XML.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 12:20:59 +01:00
Alby96andClaude Opus 5.5 709bb13532 feat: FatturaPA writer, validator, SDI receipts and transport channels (#74 #75 #76 #77)
The Italian pack can now produce and check the e-invoice and talk to the SDI:
- FatturaPaWriter writes FPR12/FPA12 v1.2 with SDI file naming; FatturaPaValidator
  checks it against an embedded schema and the AdE semantic rules (official codes).
- SdiReceiptReader reads RC, NS, MC, NE, DT, AT, MT and SE notifications.
- The incoming-invoice model becomes the shared EInvoice* model, read and written.
- In-house ImapClient and MimeParser (no external libraries) back the PEC channel;
  SdICoop (SOAP/MTOM with client certificate) and two generic REST intermediaries
  sit behind the same IEInvoiceTransport contract, with fake-server tests.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 11:51:31 +01:00
Alby96 0debd82983 Merge M8 · Scadenzario e tesoreria (v0.8.0) (#127)
Wiki / Publish the wiki (push) Successful in 7s
Release / Image and release (push) Successful in 2m43s
CI / PostgreSQL 16 integration (push) Successful in 1m39s
CI / Build and test (SQLite) (push) Successful in 3m47s
CI / Docker image (push) Skipped
CI / YAML check (push) Successful in 4s
CI / PostgreSQL 17 integration (push) Successful in 1m29s
Closes #69 #70 #71 #72 #73
2026-11-13 10:09:45 +01:00
Alby96andClaude Opus 5.5 f38b5894ce docs: close M8 with treasury wiki, screenshots and screen fixes (#69 #70 #71 #72 #73)
CI / Build and test (SQLite) (pull_request) Successful in 3m51s
CI / PostgreSQL 16 integration (pull_request) Skipped
CI / PostgreSQL 17 integration (pull_request) Skipped
CI / YAML check (pull_request) Successful in 5s
CI / Docker image (pull_request) Successful in 1m22s
Rewrite the Scadenzario wiki page from the real screens and services, add
ADR 0038, the 0.8.0 changelog, STATUS, MODULES and the regenerated data
model, and update the pages that still pointed to M8.

The browser check found a few screen defects, fixed here: reminder
channels are flags, so they show as "e-mail + PEC" and are edited with
check boxes; icon buttons in grids stay on one row; the summary strip no
longer collapses on long pages; the customers/suppliers switch uses the
right style; the cash flow bars scale between the lowest and highest
balance. The late payment rate of the second half of 2026 is 2.40 (MEF,
GU 163 of 16 July 2026), now covered by tests, and the mapping test
knows the ten treasury tables.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 09:59:57 +01:00
Alby96andClaude Opus 5.5 aef0a0d233 feat: schedule and treasury screens (#69 #70 #71 #72)
The pages of the Scadenzario area follow mockups 053-057: open items with aging,
the collection and payment dialog, collections and payments of a period,
remittances (new, file, presentation, credit, unpaid), SDD mandates, reminders
with levels and history, bank reconciliation with rules, and the cash flow
forecast. The dashboard shows the items due among the deadlines and the overdue
receivables among the things to do. Texts are in Treasury.json; the menu lists
the new pages and no longer marks the area as coming.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 09:36:33 +01:00
Alby96andClaude Opus 5.5 4014373797 feat: demo treasury and integration tests for the schedule (#69 #70 #71 #72)
The demo company gets a bank account with the capital paid in, collections and
supplier payments (one customer pays only half), a RiBa remittance presented,
credited and with one effect back unpaid, a draft remittance for the next weeks,
a direct debit mandate, a CSV statement to reconcile with a rule for the bank
fees, and a first reminder already sent. The seeder runs only when FIN is
licensed and only once.

The tests run the demo on a real instance: collections registered and cancelled,
the CBI file written, the statement reconciled, reminders and cash flow, with the
trial balance checked after every flow.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 09:17:29 +01:00
Alby96andClaude Opus 5.5 5bbc2120a1 feat: remittances, SDD mandates, bank reconciliation, dunning and cash flow services (#70 #71 #72)
Remittances draft the items due, write the RiBa CBI or SEPA pain.001/pain.008
file, present them (bills account and advance, or supplier payments), credit
them and record unpaid effects with their fees. The reconciliation imports
CSV, CBI and CAMT.053 statements without duplicates and proposes matches with
open items, payments, F24, remittances and saved rules. Reminders follow three
levels with late interest, e-mail/PEC/letter and customer block, also from a
scheduled task; the cash flow forecasts 90 days by week.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 09:06:04 +01:00
Alby96andClaude Opus 5.5 562bf98092 feat: schedule and payments services; posting keeps settled open items (#69)
The schedule lists the open items with aging, disputes and statement of
account; a collection or payment settles items with allowances, exchange
differences and fees, writes its INC/PAG entry and makes the withholding of a
fully paid invoice due. Reposting a document now updates its items by
installment and refuses to drop what was already collected.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 08:53:21 +01:00
Alby96andClaude Opus 5.5 5fbbe4d3a4 feat: SEPA, RiBa and bank statement file formats for treasury (#70 #71)
Remittances need files the banks accept and statements need readers for
reconciliation, without external libraries:

- SepaXmlWriter writes pain.001.001.09 credit transfers and pain.008.001.08
  direct debits (one PmtInf per sequence and collection date), reducing texts
  to the SEPA Latin set and refusing what a bank would reject.
- Camt053Reader reads any camt.053.001.xx by local names; CsvStatementReader
  reads home banking exports (UTF-8 or Windows-1252, Italian or English
  numbers) and guesses the layout from the header row.
- The Italian pack gains RibaCbiWriter (CBI Ricevute bancarie, 120-character
  records IB/14/20/30/40/50/51/70/EF) and CbiStatementReader (RH/61-64/EF).
- Tests validate the SEPA files against hand-written subsets of the ISO 20022
  schemas, to be replaced by the official XSDs when available.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 08:51:09 +01:00
Alby96andClaude Opus 5.5 b12dc79317 feat: treasury data model, rules and migration (#69 #70 #71 #72)
Open items gain their schedule state; payments, remittances, mandates, bank
statements, match rules and dunning get their tables. Pure rules for aging,
allocation, payment posting, late interest, bank matching, dunning levels and
cash flow periods. The Italian pack adds the treasury accounts, templates and
the late payment rates of D.Lgs. 231/2002.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 08:42:48 +01:00
Alby96andClaude Opus 5.5 88a0c8ce9c feat: bank file contracts for remittances and statements (#70 #71)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 08:32:59 +01:00
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
241 changed files with 40113 additions and 957 deletions

No files matched your search

+167
View File
@@ -7,6 +7,173 @@ un'immagine `gitea.encke-hake.ts.net/balbosoft/khaemhat:X.Y.Z`.
## [Unreleased]
### Changed
- Decisioni del titolare (ADR 0044): le schermate con sola miniatura si disegnano dalla miniatura e dalla grafica del
gestionale, senza attendere altri PNG (#35); nessun elenco ABI/CAB precaricato, nome della banca e BIC dal conto
dell'azienda o a mano (#45); intermediari reali, accreditamento SdICoop e PEC di prova rimandati (#78). La guida
*Fatturazione elettronica* spiega quale canale usare.
## [0.10.0] - 2026-11-13
M10 - Cespiti, Intrastat, chiusura, bilancio. I beni ammortizzabili hanno il loro registro con il piano civilistico e
fiscale; gli elenchi Intrastat nascono dalle fatture con il file per le Dogane; le dichiarazioni d'intento hanno un
registro e il plafond è controllato quando si conferma la fattura; a fine anno ratei, risconti e una chiusura guidata
in nove passi portano al bilancio CEE con riclassificato, indici ed export per il commercialista.
### Added
- Cespiti (#82, ADR 0041, mockup 048): categorie con i coefficienti del DM 31/12/1988 (*Categorie standard*), conti e
aliquote civilistica e fiscale; registro con piano di ammortamento per anno, movimenti, beni già in uso con i fondi
iniziali; ammortamenti dell'anno registrati per categoria e annullabili finché non definitivi; dismissioni totali e
parziali con plusvalenza o minusvalenza; stampa del registro dei beni ammortizzabili.
- Intrastat (#83, ADR 0042, mockup 049): elenchi di cessioni e acquisti generati da fatture e note confermate (beni
raggruppati, servizi per fattura, rettifiche), righe manuali che sopravvivono alla rigenerazione, controlli di
nomenclatura, massa, partita IVA e codice CPA, periodicità dovuta dalle soglie dei quattro trimestri precedenti,
file `SCAMBI.CEE` e invio registrato con il protocollo.
- Dichiarazioni d'intento (#83, ADR 0042, mockup 061): registro cronologico delle dichiarazioni ricevute ed emesse
con protocollo telematico, plafond, utilizzato ricalcolato dalle vendite in N3.5, avviso dal 90 %, revoca e stampa;
la conferma di una fattura in N3.5 è rifiutata senza dichiarazione valida o oltre il plafond.
- Ratei e risconti (#84): inserimento con calcolo per giorni, proposta dei risconti dalle fatture di acquisto sui
costi tipicamente a cavallo dell'anno, differenze di cambio al 31/12 sulle partite in valuta.
- Chiusura guidata (#85, ADR 0043, mockup 050): controlli, ammortamenti, ratei e risconti, rimanenze al costo medio
ponderato, accantonamenti (svalutazione crediti 0,5 %, TFR), chiusura dei conti economici e patrimoniali, apertura
dell'esercizio successivo con lo storno dei ratei, stampe definitive (libro giornale, registri IVA, registro
cespiti, bilancio); ogni passo si ripete o si annulla fino alle stampe; blocco dell'esercizio.
- Bilancio (#86, ADR 0043, mockup 051): schede *CEE*, *Riclassificato* e *Indici* nella pagina *Bilancio*; schema
ordinario, abbreviato e micro con l'anno precedente e la variazione, dettaglio dei conti di ogni voce, avviso dei
conti senza voce, stato patrimoniale finanziario e conto economico a valore aggiunto, undici indici, stampa PDF ed
export ZIP per il commercialista (cinque CSV).
- Dati di esempio di fine anno (#87): apertura dei conti al 1° gennaio con cespiti, rimanenze, banca e capitale,
quattro cespiti, un risconto, la dichiarazione d'intento in uso e una cessione intracomunitaria; prova di
integrazione che chiude l'anno demo dal passo 1 al blocco su SQLite e PostgreSQL.
- Permessi `assets.asset.read`, `assets.asset.write`, `assets.depreciation.post`, `intrastat.list.read`,
`intrastat.list.write`, `intrastat.list.export`, `sales.intent.read`, `sales.intent.write`, `ledger.year.close`,
`reports.accountant.export`.
- Tabelle `fixed_asset_categories`, `fixed_assets`, `fixed_asset_movements`, `accruals`, `closing_runs`,
`closing_steps`, `closing_prints`, `intrastat_lists`, `intrastat_list_lines`, `intent_declarations` (migrazione
`create_year_end`).
- ADR 0041, 0042 e 0043; pagine wiki *Cespiti*, *Intrastat*, *Dichiarazioni d'intento* e *Chiusura e bilancio* con
le schermate.
### Changed
- Menu *Contabilità* con *Ratei e risconti* e *Chiusura esercizio*; menu *Cespiti* con *Categorie*; *Intrastat* e
*Dichiarazioni d'intento* attivi nel menu *Fatturazione elettronica*.
- La dichiarazione d'intento nei dati fiscali del cliente è lo specchio di quella corrente del registro; quelle
scritte prima della 0.10 entrano nel registro alla prima lettura.
- Il pacchetto fiscale espone le regole di cespiti, chiusura, Intrastat, dichiarazioni d'intento e lo schema del
bilancio CEE.
### Known issues
- Il file `SCAMBI.CEE` non è ancora stato verificato con il software di controllo delle Dogane: controllarlo prima
del primo invio.
- Le differenze di cambio usano il residuo attuale della partita; il TFR della chiusura è una stima.
## [0.9.0] - 2026-11-13
M9 - Fatturazione elettronica. Le fatture emesse diventano file FatturaPA controllati prima dell'invio con i codici
dello SDI e partono dal canale scelto dalle regole di instradamento (PEC, SdICoop o due intermediari); le notifiche
aggiornano da sole file e documenti, gli scarti si correggono e si rigenerano, le fatture dei fornitori arrivano in
una casella da registrare e i file di un periodo si esportano per la conservazione.
### Added
- File FatturaPA (#74, ADR 0039): `FatturaPaWriter` scrive `FPR12`, `FPA12` e `FSM10` v1.2 con nome
`IT<identificativo>_<progressivo>.xml` e progressivo in base 36 mai riusato; il modello del documento viene da
`EInvoiceBuilder` (cedente, cessionario, ritenute, cassa, bollo, sconti, riferimenti, DDT, riepilogo IVA,
pagamenti, allegati).
- Controllo prima dell'invio (#74): `FatturaPaValidator` ripete offline i controlli dello SDI con lo stesso codice
(00305-00473) e le tolleranze delle specifiche 1.9.1, più la struttura contro uno schema incorporato;
*Controlla senza generare* sul cruscotto.
- Notifiche SDI (#75): `SdiReceiptReader` legge RC, NS, MC, NE, DT, AT, SE e MT; ogni notifica è conservata una sola
volta, abbinata al file e applicata al file e al documento nella stessa transazione; import manuale di XML, P7M e
ZIP del portale; pagina *Notifiche SDI* con filtri e download.
- Canali (#76, #77): PEC con SMTP e un client IMAP e un lettore MIME scritti in casa (primo invio a
`sdi01@pec.fatturapa.it`, poi l'indirizzo appreso dallo SDI, cartella di archivio), SdICoop SOAP/MTOM con
certificato client, Intermediario A (chiave API) e Intermediario B (utente e password) dietro lo stesso contratto
`IEInvoiceTransport` (ADR 0040); prova di connessione, pausa, segreti cifrati.
- Instradamento (#77): regole *Sempre*, *Cliente PA*, *Cliente specifico*, *Tipo documento* e *Volume giornaliero*
con canale di riserva (`SdiRouter`); pagina *Canali di trasmissione* (mockup 059).
- Lettura dei canali (#76): attività `einvoice.poll` ogni 15 minuti e *Leggi i canali ora*; un messaggio si conferma
solo quando tutti i suoi file sono salvati. Ricezione push di SdICoop su `POST /sdicoop/{azienda}` con la chiave
di ricezione nell'intestazione `X-Khaemhat-SdiCoop-Key` e il certificato reciproco sul reverse proxy.
- Cruscotto SDI (#74, #75, mockup 058): sei contatori, viste *Emesse*, *Autofatture* e *Da fare*, filtri e
ricerca, documenti da generare, *Genera + invia*, *Invia*, *Correggi*, *Segna come inviata*, download dell'XML,
storico del file con le versioni sostituite, esito della trasmissione; avvisi sulla Home per scarti e file da
inviare (`EInvoiceFeedSource`).
- Copia di cortesia (#74): il PDF del documento con il file FatturaPA allegato (`/AF`).
- Fatture ricevute (#79): casella delle fatture dei fornitori dai canali o caricate (XML, P7M, metadati, ZIP) senza
doppioni, registrazione singola o in blocco con l'import del ciclo passivo, scarto e ripristino, download.
- Conservazione (#79): pacchetto ZIP di un periodo (fino a due anni) con `emesse/`, `ricevute/`, `notifiche/`,
`indice.csv` con SHA-256 e `LEGGIMI.txt`, e l'elenco dei pacchetti preparati.
- Fatturazione elettronica nei dati di esempio con il modulo EINV (#80): canale PEC in pausa, Intermediario A
disattivato, tre regole, i file delle fatture demo con consegne, uno scarto corretto, una mancata consegna e file
in attesa, tre fatture di fornitori da registrare.
- Rimozione dei dati di esempio (#80, ADR 0040): `DemoDataRemover` guidato dallo schema delle migrazioni elimina le
righe `is_demo` e quelle che appartengono loro in una transazione e si ferma se dati dell'utente vi fanno
riferimento; `scripts/seed.sh --remove-demo [--company CODICE]`; il seed stampa il tempo impiegato.
- Permessi `einvoice.document.read`, `einvoice.document.send`, `einvoice.inbox.read`, `einvoice.inbox.import`,
`einvoice.channel.manage`; testi in `Resources/it-IT/EInvoicing.json`.
- Tabelle `e_invoices`, `e_invoice_notifications`, `e_invoice_inbox`, `e_invoice_channels`, `e_invoice_routing`,
`e_invoice_conservation` (migrazione `M20261113_004`).
- ADR 0039 e 0040; pagina wiki *Fatturazione elettronica* completa con le schermate (#81).
### Changed
- Il menu *Fatturazione elettronica* ha le voci *Cruscotto SDI*, *Fatture ricevute*, *Notifiche SDI*,
*Conservazione* e *Canali di trasmissione*, ognuna con il suo permesso; *Dichiarazioni d'intento* resta in M10.
- Una fattura scartata dallo SDI torna modificabile e si rigenera con un nuovo file.
- I seeder dimostrativi marcano come demo anche le righe scritte dai servizi per loro (registrazioni, partite,
pagamenti, mandati, estratti conto).
- Il modello delle fatture ricevute è condiviso con quello delle emesse (`EInvoice*` nelle astrazioni fiscali).
## [0.8.0] - 2026-11-13
M8 - Scadenzario e tesoreria. Le partite aperte di clienti e fornitori si chiudono con incassi e pagamenti che si
contabilizzano da soli; distinte RiBa, SDD e bonifici SEPA con il file per l'home banking, presentazione, accredito
e insoluti; riconciliazione dell'estratto conto con abbinamento automatico; solleciti con interessi di mora e flusso
di cassa.
### Added
- Scadenzario (#69, ADR 0038): partite aperte di clienti e fornitori dalla contabilità con stati, aging in cinque
fasce, filtri, modifica di scadenza, metodo, banca e contestazione, estratto conto della controparte con gli
interessi di mora, export CSV.
- Incassi e pagamenti (#69): su più partite della stessa controparte, totali o parziali, con abbuoni, spese bancarie,
differenze cambio e note di credito; registrazione `INC` o `PAG` nella stessa transazione; annullamento con storno;
la ritenuta d'acconto di una parcella diventa dovuta quando la fattura è saldata. Elenchi *Incassi* e *Pagamenti*.
- Distinte (#70): RiBa nel tracciato CBI (`RibaCbiWriter`), SDD core e B2B in `pain.008.001.08` e bonifici SEPA in
`pain.001.001.09` (`SepaXmlWriter`); candidati con controllo di IBAN, ABI/CAB e mandato; bozza, file, presentazione
su *Effetti all'incasso* o con anticipo *salvo buon fine*, accredito, insoluto con riapertura della partita e
spese come nuova partita del cliente.
- Mandati SDD (#70) con riferimento univoco, schema core o B2B, firma, revoca, sequenza FRST/RCUR.
- Riconciliazione bancaria (#71): import di estratti CSV (colonne riconosciute dall'intestazione), CBI e CAMT.053
senza doppioni (impronta dei movimenti); proposte con confidenza da partite, incassi e pagamenti registrati, F24,
accrediti e insoluti di distinte e regole salvate (`BankMatcher`); conferma singola o di tutte le proposte dal
90%; abbinamento manuale, registrazione su conto con regola, *Ignora*, *Annulla abbinamento*; saldo banca, saldo
contabile e differenza.
- Solleciti (#72): tre livelli modificabili con giorni, modello, canali (e-mail, PEC, lettera PDF), interessi di
mora, avviso all'agente e blocco del cliente; proposta di invio che esclude PA, partite contestate e in distinta;
anteprima PDF, invio con la coda di posta, lettere in un PDF unico, registro degli invii; attività programmata
`finance.dunning` nei giorni feriali alle 7:00 per i livelli automatici.
- Interessi di mora del D.Lgs. 231/2002 nel pacchetto italiano (`LatePaymentRulesIt`): tasso BCE del semestre più
8 punti, 10,15% nel primo semestre 2026 e 10,40% nel secondo.
- Flusso di cassa (#72) a 30-365 giorni per settimana o mese da partite, effetti presentati, ordini non fatturati,
registrazioni ricorrenti e F24, con le fonti selezionabili e il punto più basso.
- Scadenze di incassi e pagamenti e crediti scaduti sulla Home (`TreasuryFeedSource`).
- Menu *Scadenzario* con otto voci; testi in `Resources/it-IT/Treasury.json`; permessi `finance.schedule.*`,
`finance.payment.*`, `finance.bank.reconcile`.
- Tesoreria nei dati di esempio con il modulo FIN (#73): banca, versamento dei soci, incassi e pagamenti, distinta
accreditata con un insoluto, distinta s.b.f. in bozza, mandato, estratto CSV da riconciliare con una regola, primo
sollecito.
- Tabelle `payments`, `payment_lines`, `remittances`, `remittance_lines`, `sdd_mandates`, `bank_statements`,
`bank_statement_lines`, `bank_match_rules`, `dunning_levels`, `dunning_letters`; nuove colonne di
`gl_open_items` e `bank_accounts.creditor_id` (migrazione `M20261113_003`).
- Conti *Perdite su cambi*, *Utili su cambi* e *Interessi di mora attivi* nel piano dei conti PMI standard (240 conti).
- ADR 0038; pagina wiki *Scadenzario* completa con le schermate.
### Changed
- La rettifica della registrazione di un documento mantiene le partite già incassate o pagate.
- Il menu *Fatturazione elettronica* mostra M9 come milestone.
### Fixed
- Le strisce di riepilogo non si schiacciano più nelle pagine più alte della finestra.
## [0.7.0] - 2026-11-13
M7 - Contabilità generale e IVA. Ogni fattura, nota e autofattura si contabilizza da sola nella stessa transazione,
+3 -2
View File
@@ -76,8 +76,9 @@ validi.
`docs/mockups/png/` più la galleria completa `000-galleria-mockup.png`; per **tutte le 88** esiste una miniatura
401x241 ritagliata dalla galleria in `docs/mockups/thumbs/`. Per le schermate senza PNG ad alta risoluzione si
lavora da miniatura + `mockup.css` + descrizione in SPEC §10-§12, scegliendo i mattoni della schermata più simile
in alta risoluzione (§10.1 regola 4). I PNG mancanti vanno chiesti all'utente quando servono, senza bloccare il
lavoro (issue con etichetta `Status/In attesa utente`).
in alta risoluzione (§10.1 regola 4). Il titolare ha confermato il 2026-11-16 che altri PNG non esistono
(ADR [0044](docs/adr/0044-schermate-senza-png-banche-e-canali-sdi.md)): la miniatura è la specifica finale e i dettagli
che non mostra si decidono seguendo la grafica del gestionale già costruita, senza chiederli.
**E5 — Avvio dello sviluppo.** La specifica (§0, §23) dice di lavorare in autonomia senza chiedere conferme. Vale,
**dopo** il via esplicito dell'utente: la documentazione e la pianificazione su Gitea sono state preparate il
+728
View File
@@ -732,6 +732,38 @@ Migrazioni applicate in ordine:
- `core` 20261112003 `create_documents` (M20261112_003_CreateDocuments)
- `core` 20261113001 `create_inventory` (M20261113_001_CreateInventory)
- `core` 20261113002 `create_ledger` (M20261113_002_CreateLedger)
- `core` 20261113003 `create_treasury` (M20261113_003_CreateTreasury)
- `core` 20261113004 `create_einvoicing` (M20261113_004_CreateEInvoicing)
- `core` 20261113005 `create_year_end` (M20261113_005_CreateYearEnd)
#### `accruals`
| Colonna | Tipo | Null | Default | Note |
|---|---|---|---|---|
| `id` | Int64 | no | | chiave primaria, identity |
| `year` | Int32 | no | | |
| `kind` | String(40) | no | | |
| `description` | String(200) | no | | |
| `account_id` | Int64 | no | | -> `gl_accounts` (Restrict) |
| `amount` | Decimal(19,6) | no | `0` | |
| `period_start` | Date | no | | |
| `period_end` | Date | no | | |
| `year_end` | Date | no | | |
| `adjustment` | Decimal(19,6) | no | `0` | |
| `source_family` | String(40) | sì | | |
| `source_document_id` | Int64 | sì | | |
| `document_number` | String(40) | sì | | |
| `party_id` | Int64 | sì | | |
| `gl_entry_id` | Int64 | sì | | -> `gl_entries` (Restrict) |
| `reversal_entry_id` | Int64 | sì | | -> `gl_entries` (Restrict) |
| `is_demo` | Bool | no | `false` | |
| `created_at` | DateTimeUtc | no | | |
| `created_by` | String(100) | sì | | |
| `updated_at` | DateTimeUtc | sì | | |
| `updated_by` | String(100) | sì | | |
| `row_version` | Int64 | no | `1` | |
- indice `ix_accruals_year` su `year`
#### `attachments`
@@ -799,9 +831,91 @@ Migrazioni applicate in ordine:
| `updated_at` | DateTimeUtc | sì | | |
| `updated_by` | String(100) | sì | | |
| `row_version` | Int64 | no | `1` | |
| `creditor_id` | String(35) | sì | | |
- indice unico `ux_bank_accounts_code` su `code`
#### `bank_match_rules`
| Colonna | Tipo | Null | Default | Note |
|---|---|---|---|---|
| `id` | Int64 | no | | chiave primaria, identity |
| `name` | String(100) | no | | |
| `pattern` | String(100) | no | | |
| `direction` | String(40) | no | | |
| `account_id` | Int64 | no | | -> `gl_accounts` (Restrict) |
| `template_code` | String(10) | sì | | |
| `entry_description` | String(200) | sì | | |
| `disabled` | Bool | no | `false` | |
| `uses` | Int32 | no | `0` | |
| `is_demo` | Bool | no | `false` | |
| `created_at` | DateTimeUtc | no | | |
| `created_by` | String(100) | sì | | |
| `updated_at` | DateTimeUtc | sì | | |
| `updated_by` | String(100) | sì | | |
| `row_version` | Int64 | no | `1` | |
#### `bank_statement_lines`
| Colonna | Tipo | Null | Default | Note |
|---|---|---|---|---|
| `id` | Int64 | no | | chiave primaria, identity |
| `statement_id` | Int64 | no | | -> `bank_statements` (Cascade) |
| `bank_account_id` | Int64 | no | | |
| `booking_date` | Date | no | | |
| `value_date` | Date | sì | | |
| `amount` | Decimal(19,6) | no | `0` | |
| `description` | String(500) | no | | |
| `reference` | String(60) | sì | | |
| `counterparty_name` | String(140) | sì | | |
| `counterparty_iban` | String(34) | sì | | |
| `bank_code` | String(40) | sì | | |
| `fingerprint` | String(64) | no | | |
| `status` | String(40) | no | | |
| `match_kind` | String(40) | no | | |
| `confidence` | Int32 | no | `0` | |
| `proposal` | String(300) | sì | | |
| `targets` | String(300) | sì | | |
| `party_id` | Int64 | sì | | |
| `rule_id` | Int64 | sì | | |
| `payment_id` | Int64 | sì | | |
| `gl_entry_id` | Int64 | sì | | |
| `matched_at` | DateTimeUtc | sì | | |
| `matched_by` | String(100) | sì | | |
| `is_demo` | Bool | no | `false` | |
| `created_at` | DateTimeUtc | no | | |
| `created_by` | String(100) | sì | | |
| `updated_at` | DateTimeUtc | sì | | |
| `updated_by` | String(100) | sì | | |
| `row_version` | Int64 | no | `1` | |
- indice `ix_bank_statement_lines_date` su `bank_account_id`, `booking_date`
- indice `ix_bank_statement_lines_statement` su `statement_id`
- indice unico `ux_bank_statement_lines_fingerprint` su `bank_account_id`, `fingerprint`
#### `bank_statements`
| Colonna | Tipo | Null | Default | Note |
|---|---|---|---|---|
| `id` | Int64 | no | | chiave primaria, identity |
| `bank_account_id` | Int64 | no | | -> `bank_accounts` (Restrict) |
| `format` | String(40) | no | | |
| `file_name` | String(200) | sì | | |
| `from_date` | Date | no | | |
| `to_date` | Date | no | | |
| `opening_balance` | Decimal(19,6) | sì | | |
| `closing_balance` | Decimal(19,6) | sì | | |
| `movement_count` | Int32 | no | `0` | |
| `attachment_id` | Int64 | sì | | |
| `is_demo` | Bool | no | `false` | |
| `created_at` | DateTimeUtc | no | | |
| `created_by` | String(100) | sì | | |
| `updated_at` | DateTimeUtc | sì | | |
| `updated_by` | String(100) | sì | | |
| `row_version` | Int64 | no | `1` | |
- indice `ix_bank_statements_account` su `bank_account_id`, `to_date`
#### `carriers`
| Colonna | Tipo | Null | Default | Note |
@@ -825,6 +939,65 @@ Migrazioni applicate in ordine:
- indice unico `ux_carriers_code` su `code`
#### `closing_prints`
| Colonna | Tipo | Null | Default | Note |
|---|---|---|---|---|
| `id` | Int64 | no | | chiave primaria, identity |
| `run_id` | Int64 | no | | -> `closing_runs` (Cascade) |
| `kind` | String(20) | no | | |
| `file_name` | String(100) | no | | |
| `pages` | Int32 | no | `0` | |
| `content` | Bytes | no | | |
| `created_at` | DateTimeUtc | no | | |
| `created_by` | String(100) | sì | | |
| `updated_at` | DateTimeUtc | sì | | |
| `updated_by` | String(100) | sì | | |
| `row_version` | Int64 | no | `1` | |
- indice `ix_closing_prints_run` su `run_id`
#### `closing_runs`
| Colonna | Tipo | Null | Default | Note |
|---|---|---|---|---|
| `id` | Int64 | no | | chiave primaria, identity |
| `fiscal_year_id` | Int64 | no | | -> `fiscal_years` (Restrict) |
| `year_code` | String(10) | no | | |
| `status` | String(40) | no | | |
| `next_fiscal_year_id` | Int64 | sì | | |
| `result` | Decimal(19,6) | no | `0` | |
| `locked_at` | DateTimeUtc | sì | | |
| `locked_by` | String(100) | sì | | |
| `created_at` | DateTimeUtc | no | | |
| `created_by` | String(100) | sì | | |
| `updated_at` | DateTimeUtc | sì | | |
| `updated_by` | String(100) | sì | | |
| `row_version` | Int64 | no | `1` | |
- indice unico `ux_closing_runs_year` su `fiscal_year_id`
#### `closing_steps`
| Colonna | Tipo | Null | Default | Note |
|---|---|---|---|---|
| `id` | Int64 | no | | chiave primaria, identity |
| `run_id` | Int64 | no | | -> `closing_runs` (Cascade) |
| `number` | Int32 | no | | |
| `status` | String(40) | no | | |
| `entries` | Int32 | no | `0` | |
| `amount` | Decimal(19,6) | no | `0` | |
| `messages` | Text | sì | | |
| `executed_at` | DateTimeUtc | sì | | |
| `executed_by` | String(100) | sì | | |
| `created_at` | DateTimeUtc | no | | |
| `created_by` | String(100) | sì | | |
| `updated_at` | DateTimeUtc | sì | | |
| `updated_by` | String(100) | sì | | |
| `row_version` | Int64 | no | `1` | |
- indice unico `ux_closing_steps_number` su `run_id`, `number`
#### `code_sequences`
| Colonna | Tipo | Null | Default | Note |
@@ -1109,6 +1282,229 @@ Migrazioni applicate in ordine:
- indice unico `ux_document_types_code` su `code`
#### `dunning_letters`
| Colonna | Tipo | Null | Default | Note |
|---|---|---|---|---|
| `id` | Int64 | no | | chiave primaria, identity |
| `party_id` | Int64 | no | | -> `parties` (Restrict) |
| `level` | Int32 | no | | |
| `sent_on` | Date | no | | |
| `channel` | String(60) | no | | |
| `recipients` | String(300) | sì | | |
| `subject` | String(200) | no | | |
| `item_count` | Int32 | no | `0` | |
| `overdue_amount` | Decimal(19,6) | no | `0` | |
| `interest` | Decimal(19,6) | no | `0` | |
| `status` | String(40) | no | | |
| `attachment_id` | Int64 | sì | | |
| `mail_id` | Int64 | sì | | |
| `sent_by` | String(100) | sì | | |
| `is_demo` | Bool | no | `false` | |
| `created_at` | DateTimeUtc | no | | |
| `created_by` | String(100) | sì | | |
| `updated_at` | DateTimeUtc | sì | | |
| `updated_by` | String(100) | sì | | |
| `row_version` | Int64 | no | `1` | |
- indice `ix_dunning_letters_party` su `party_id`, `sent_on`
#### `dunning_levels`
| Colonna | Tipo | Null | Default | Note |
|---|---|---|---|---|
| `id` | Int64 | no | | chiave primaria, identity |
| `level` | Int32 | no | | |
| `days_after_due` | Int32 | no | | |
| `name` | String(100) | no | | |
| `subject` | String(200) | no | | |
| `body` | Text | no | | |
| `channel` | String(60) | no | | |
| `charge_interest` | Bool | no | `false` | |
| `action` | String(40) | no | | |
| `automatic` | Bool | no | `false` | |
| `created_at` | DateTimeUtc | no | | |
| `created_by` | String(100) | sì | | |
| `updated_at` | DateTimeUtc | sì | | |
| `updated_by` | String(100) | sì | | |
| `row_version` | Int64 | no | `1` | |
- indice unico `ux_dunning_levels_level` su `level`
#### `e_invoice_channels`
| Colonna | Tipo | Null | Default | Note |
|---|---|---|---|---|
| `id` | Int64 | no | | chiave primaria, identity |
| `code` | String(20) | no | | |
| `enabled` | Bool | no | `false` | |
| `paused` | Bool | no | `false` | |
| `mailbox` | String(254) | sì | | |
| `smtp_host` | String(200) | sì | | |
| `smtp_port` | Int32 | no | `465` | |
| `imap_host` | String(200) | sì | | |
| `imap_port` | Int32 | no | `993` | |
| `tls` | Bool | no | `true` | |
| `user_name` | String(254) | sì | | |
| `protected_password` | Text | sì | | |
| `exchange_address` | String(254) | sì | | |
| `archive_folder` | String(100) | sì | | |
| `endpoint` | String(300) | sì | | |
| `protected_certificate` | Text | sì | | |
| `protected_certificate_password` | Text | sì | | |
| `protected_api_key` | Text | sì | | |
| `test_environment` | Bool | no | `false` | |
| `last_check_at` | DateTimeUtc | sì | | |
| `last_check_ok` | Bool | sì | | |
| `last_check_message` | String(1000) | sì | | |
| `last_poll_at` | DateTimeUtc | sì | | |
| `last_poll_message` | String(1000) | sì | | |
| `last_poll_failed` | Bool | no | `false` | |
| `is_demo` | Bool | no | `false` | |
| `created_at` | DateTimeUtc | no | | |
| `created_by` | String(100) | sì | | |
| `updated_at` | DateTimeUtc | sì | | |
| `updated_by` | String(100) | sì | | |
| `row_version` | Int64 | no | `1` | |
- indice unico `ux_e_invoice_channels_code` su `code`
#### `e_invoice_conservation`
| Colonna | Tipo | Null | Default | Note |
|---|---|---|---|---|
| `id` | Int64 | no | | chiave primaria, identity |
| `from_date` | Date | no | | |
| `to_date` | Date | no | | |
| `file_count` | Int32 | no | `0` | |
| `file_name` | String(100) | no | | |
| `hash` | String(64) | no | | |
| `size` | Int64 | no | `0` | |
| `created_at` | DateTimeUtc | no | | |
| `created_by` | String(100) | sì | | |
| `updated_at` | DateTimeUtc | sì | | |
| `updated_by` | String(100) | sì | | |
| `row_version` | Int64 | no | `1` | |
#### `e_invoice_inbox`
| Colonna | Tipo | Null | Default | Note |
|---|---|---|---|---|
| `id` | Int64 | no | | chiave primaria, identity |
| `file_name` | String(100) | no | | |
| `hash` | String(64) | no | | |
| `content` | Bytes | no | | |
| `metadata_file_name` | String(100) | sì | | |
| `metadata` | Bytes | sì | | |
| `exchange_id` | String(40) | sì | | |
| `received_at` | DateTimeUtc | no | | |
| `channel_code` | String(20) | sì | | |
| `supplier_vat` | String(30) | sì | | |
| `supplier_name` | String(200) | sì | | |
| `document_type` | String(10) | sì | | |
| `number` | String(40) | sì | | |
| `document_date` | Date | sì | | |
| `total_amount` | Decimal(19,6) | sì | | |
| `party_id` | Int64 | sì | | |
| `status` | String(40) | no | | |
| `purchase_document_id` | Int64 | sì | | |
| `error` | String(500) | sì | | |
| `is_demo` | Bool | no | `false` | |
| `created_at` | DateTimeUtc | no | | |
| `created_by` | String(100) | sì | | |
| `updated_at` | DateTimeUtc | sì | | |
| `updated_by` | String(100) | sì | | |
| `row_version` | Int64 | no | `1` | |
- indice `ix_e_invoice_inbox_file` su `file_name`
- indice `ix_e_invoice_inbox_status` su `status`, `received_at`
- indice unico `ux_e_invoice_inbox_hash` su `hash`
#### `e_invoice_notifications`
| Colonna | Tipo | Null | Default | Note |
|---|---|---|---|---|
| `id` | Int64 | no | | chiave primaria, identity |
| `e_invoice_id` | Int64 | sì | | -> `e_invoices` (Cascade) |
| `code` | String(4) | no | | |
| `file_name` | String(100) | no | | |
| `invoice_file_name` | String(100) | sì | | |
| `exchange_id` | String(40) | sì | | |
| `received_at` | DateTimeUtc | no | | |
| `outcome` | String(10) | sì | | |
| `description` | String(1000) | sì | | |
| `errors` | Text | sì | | |
| `channel_code` | String(20) | sì | | |
| `content` | Bytes | no | | |
| `is_demo` | Bool | no | `false` | |
| `created_at` | DateTimeUtc | no | | |
| `created_by` | String(100) | sì | | |
| `updated_at` | DateTimeUtc | sì | | |
| `updated_by` | String(100) | sì | | |
| `row_version` | Int64 | no | `1` | |
- indice `ix_e_invoice_notifications_invoice` su `e_invoice_id`
- indice unico `ux_e_invoice_notifications_file` su `file_name`
#### `e_invoice_routing`
| Colonna | Tipo | Null | Default | Note |
|---|---|---|---|---|
| `id` | Int64 | no | | chiave primaria, identity |
| `position` | Int32 | no | `0` | |
| `condition` | String(40) | no | | |
| `value` | String(40) | sì | | |
| `channel_code` | String(20) | no | | |
| `fallback_channel_code` | String(20) | sì | | |
| `disabled` | Bool | no | `false` | |
| `is_demo` | Bool | no | `false` | |
| `created_at` | DateTimeUtc | no | | |
| `created_by` | String(100) | sì | | |
| `updated_at` | DateTimeUtc | sì | | |
| `updated_by` | String(100) | sì | | |
| `row_version` | Int64 | no | `1` | |
#### `e_invoices`
| Colonna | Tipo | Null | Default | Note |
|---|---|---|---|---|
| `id` | Int64 | no | | chiave primaria, identity |
| `family` | String(40) | no | | |
| `document_id` | Int64 | no | | |
| `kind` | String(40) | no | | |
| `document_number` | String(40) | sì | | |
| `document_date` | Date | no | | |
| `party_id` | Int64 | sì | | |
| `document_type` | String(10) | no | | |
| `file_name` | String(60) | no | | |
| `progressive` | Int64 | no | | |
| `format` | String(10) | no | | |
| `recipient_code` | String(7) | sì | | |
| `recipient_pec` | String(254) | sì | | |
| `total_amount` | Decimal(19,6) | no | `0` | |
| `status` | String(40) | no | | |
| `channel_code` | String(20) | sì | | |
| `exchange_id` | String(40) | sì | | |
| `message_id` | String(200) | sì | | |
| `generated_at` | DateTimeUtc | no | | |
| `sent_at` | DateTimeUtc | sì | | |
| `last_notification_at` | DateTimeUtc | sì | | |
| `last_message` | String(1000) | sì | | |
| `send_attempts` | Int32 | no | `0` | |
| `content` | Bytes | no | | |
| `superseded` | Bool | no | `false` | |
| `is_demo` | Bool | no | `false` | |
| `created_at` | DateTimeUtc | no | | |
| `created_by` | String(100) | sì | | |
| `updated_at` | DateTimeUtc | sì | | |
| `updated_by` | String(100) | sì | | |
| `row_version` | Int64 | no | `1` | |
- indice `ix_e_invoices_document` su `family`, `document_id`
- indice `ix_e_invoices_exchange` su `exchange_id`
- indice `ix_e_invoices_status` su `superseded`, `status`
- indice unico `ux_e_invoices_file` su `file_name`
#### `exchange_rates`
| Colonna | Tipo | Null | Default | Note |
@@ -1166,6 +1562,95 @@ Migrazioni applicate in ordine:
- indice unico `ux_fiscal_years_code` su `code`
- indice unico `ux_fiscal_years_start_date` su `start_date`
#### `fixed_asset_categories`
| Colonna | Tipo | Null | Default | Note |
|---|---|---|---|---|
| `id` | Int64 | no | | chiave primaria, identity |
| `code` | String(20) | no | | |
| `description` | String(100) | no | | |
| `disabled` | Bool | no | `false` | |
| `class` | String(40) | no | | |
| `ministerial_group` | String(20) | sì | | |
| `civil_rate` | Decimal(19,6) | no | `0` | |
| `fiscal_rate` | Decimal(19,6) | no | `0` | |
| `civil_half_first_year` | Bool | no | `true` | |
| `asset_account_id` | Int64 | sì | | -> `gl_accounts` (Restrict) |
| `fund_account_id` | Int64 | sì | | -> `gl_accounts` (Restrict) |
| `depreciation_account_id` | Int64 | sì | | -> `gl_accounts` (Restrict) |
| `deductible_percent` | Decimal(19,6) | no | `100` | |
| `cost_limit` | Decimal(19,6) | sì | | |
| `is_demo` | Bool | no | `false` | |
| `created_at` | DateTimeUtc | no | | |
| `created_by` | String(100) | sì | | |
| `updated_at` | DateTimeUtc | sì | | |
| `updated_by` | String(100) | sì | | |
| `row_version` | Int64 | no | `1` | |
- indice unico `ux_fixed_asset_categories_code` su `code`
#### `fixed_asset_movements`
| Colonna | Tipo | Null | Default | Note |
|---|---|---|---|---|
| `id` | Int64 | no | | chiave primaria, identity |
| `asset_id` | Int64 | no | | -> `fixed_assets` (Cascade) |
| `kind` | String(40) | no | | |
| `movement_date` | Date | no | | |
| `year` | Int32 | no | | |
| `cost_amount` | Decimal(19,6) | no | `0` | |
| `civil_amount` | Decimal(19,6) | no | `0` | |
| `fiscal_amount` | Decimal(19,6) | no | `0` | |
| `proceeds` | Decimal(19,6) | no | `0` | |
| `gain_loss` | Decimal(19,6) | no | `0` | |
| `description` | String(200) | sì | | |
| `gl_entry_id` | Int64 | sì | | -> `gl_entries` (Restrict) |
| `is_demo` | Bool | no | `false` | |
| `created_at` | DateTimeUtc | no | | |
| `created_by` | String(100) | sì | | |
| `updated_at` | DateTimeUtc | sì | | |
| `updated_by` | String(100) | sì | | |
| `row_version` | Int64 | no | `1` | |
- indice `ix_fixed_asset_movements_asset` su `asset_id`, `movement_date`
- indice `ix_fixed_asset_movements_year` su `year`, `kind`
#### `fixed_assets`
| Colonna | Tipo | Null | Default | Note |
|---|---|---|---|---|
| `id` | Int64 | no | | chiave primaria, identity |
| `code` | String(20) | no | | |
| `description` | String(200) | no | | |
| `category_id` | Int64 | no | | -> `fixed_asset_categories` (Restrict) |
| `purchase_date` | Date | no | | |
| `in_service_date` | Date | no | | |
| `supplier_id` | Int64 | sì | | -> `parties` (Restrict) |
| `document_reference` | String(60) | sì | | |
| `location` | String(100) | sì | | |
| `serial_number` | String(60) | sì | | |
| `quantity` | Decimal(19,6) | no | `1` | |
| `cost` | Decimal(19,6) | no | `0` | |
| `civil_fund` | Decimal(19,6) | no | `0` | |
| `fiscal_fund` | Decimal(19,6) | no | `0` | |
| `civil_rate` | Decimal(19,6) | sì | | |
| `fiscal_rate` | Decimal(19,6) | sì | | |
| `residual_value` | Decimal(19,6) | no | `0` | |
| `low_value` | Bool | no | `false` | |
| `status` | String(40) | no | | |
| `disposal_date` | Date | sì | | |
| `last_depreciation_year` | Int32 | sì | | |
| `notes` | String(500) | sì | | |
| `is_demo` | Bool | no | `false` | |
| `created_at` | DateTimeUtc | no | | |
| `created_by` | String(100) | sì | | |
| `updated_at` | DateTimeUtc | sì | | |
| `updated_by` | String(100) | sì | | |
| `row_version` | Int64 | no | `1` | |
- indice `ix_fixed_assets_category` su `category_id`
- indice unico `ux_fixed_assets_code` su `code`
#### `gl_accounts`
| Colonna | Tipo | Null | Default | Note |
@@ -1232,6 +1717,7 @@ Migrazioni applicate in ordine:
| `updated_at` | DateTimeUtc | sì | | |
| `updated_by` | String(100) | sì | | |
| `row_version` | Int64 | no | `1` | |
| `closing_step` | Int32 | sì | | |
- indice `ix_gl_entries_date` su `entry_date`, `number`
- indice `ix_gl_entries_register` su `vat_register_id`, `vat_date`
@@ -1359,10 +1845,20 @@ Migrazioni applicate in ordine:
| `updated_at` | DateTimeUtc | sì | | |
| `updated_by` | String(100) | sì | | |
| `row_version` | Int64 | no | `1` | |
| `status` | String(40) | no | `'Open'` | |
| `disputed` | Bool | no | `false` | |
| `bank_account_id` | Int64 | sì | | |
| `remittance_id` | Int64 | sì | | |
| `unpaid_count` | Int32 | no | `0` | |
| `parent_id` | Int64 | sì | | |
| `dunning_level` | Int32 | no | `0` | |
| `last_dunning_date` | Date | sì | | |
| `notes` | String(200) | sì | | |
- indice `ix_gl_open_items_due` su `closed`, `due_date`
- indice `ix_gl_open_items_entry` su `entry_id`
- indice `ix_gl_open_items_party` su `party_id`, `closed`, `due_date`
- indice `ix_gl_open_items_schedule` su `direction`, `status`, `due_date`
#### `gl_recurring_entries`
@@ -1402,6 +1898,104 @@ Migrazioni applicate in ordine:
- indice unico `ux_goods_appearances_code` su `code`
#### `intent_declarations`
| Colonna | Tipo | Null | Default | Note |
|---|---|---|---|---|
| `id` | Int64 | no | | chiave primaria, identity |
| `direction` | String(40) | no | | |
| `register_number` | Int32 | no | | |
| `year` | Int32 | no | | |
| `party_id` | Int64 | no | | -> `parties` (Restrict) |
| `number` | String(40) | no | | |
| `declaration_date` | Date | no | | |
| `protocol` | String(40) | no | | |
| `ceiling` | Decimal(19,6) | no | `0` | |
| `used` | Decimal(19,6) | no | `0` | |
| `valid_from` | Date | no | | |
| `valid_to` | Date | no | | |
| `tax_code_id` | Int64 | sì | | -> `tax_codes` (Restrict) |
| `status` | String(40) | no | | |
| `notes` | String(500) | sì | | |
| `is_demo` | Bool | no | `false` | |
| `created_at` | DateTimeUtc | no | | |
| `created_by` | String(100) | sì | | |
| `updated_at` | DateTimeUtc | sì | | |
| `updated_by` | String(100) | sì | | |
| `row_version` | Int64 | no | `1` | |
- indice `ix_intent_declarations_party` su `party_id`, `valid_from`
- indice unico `ux_intent_declarations_register` su `direction`, `year`, `register_number`
#### `intrastat_list_lines`
| Colonna | Tipo | Null | Default | Note |
|---|---|---|---|---|
| `id` | Int64 | no | | chiave primaria, identity |
| `list_id` | Int64 | no | | -> `intrastat_lists` (Cascade) |
| `section` | String(40) | no | | |
| `source_family` | String(40) | sì | | |
| `source_document_id` | Int64 | sì | | |
| `document_number` | String(40) | sì | | |
| `document_date` | Date | sì | | |
| `party_id` | Int64 | sì | | |
| `country_code` | String(2) | no | | |
| `vat_number` | String(20) | sì | | |
| `amount` | Decimal(19,6) | no | `0` | |
| `currency_amount` | Decimal(19,6) | sì | | |
| `statistical_value` | Decimal(19,6) | sì | | |
| `nomenclature_code` | String(10) | sì | | |
| `description` | String(200) | sì | | |
| `transaction_nature` | String(2) | sì | | |
| `delivery_terms` | String(3) | sì | | |
| `transport_mode` | String(1) | sì | | |
| `net_mass` | Decimal(19,6) | sì | | |
| `supplementary_units` | Decimal(19,6) | sì | | |
| `origin_country` | String(2) | sì | | |
| `province` | String(2) | sì | | |
| `supply_mode` | String(1) | sì | | |
| `payment_mode` | String(1) | sì | | |
| `payment_country` | String(2) | sì | | |
| `corrected_year` | Int32 | sì | | |
| `corrected_period` | Int32 | sì | | |
| `correction_sign` | String(1) | sì | | |
| `check` | String(40) | no | | |
| `manual` | Bool | no | `false` | |
| `is_demo` | Bool | no | `false` | |
| `created_at` | DateTimeUtc | no | | |
| `created_by` | String(100) | sì | | |
| `updated_at` | DateTimeUtc | sì | | |
| `updated_by` | String(100) | sì | | |
| `row_version` | Int64 | no | `1` | |
- indice `ix_intrastat_list_lines_list` su `list_id`, `section`
#### `intrastat_lists`
| Colonna | Tipo | Null | Default | Note |
|---|---|---|---|---|
| `id` | Int64 | no | | chiave primaria, identity |
| `flow` | String(40) | no | | |
| `year` | Int32 | no | | |
| `period` | Int32 | no | | |
| `periodicity` | String(40) | no | | |
| `status` | String(40) | no | | |
| `progressive` | Int32 | no | `1` | |
| `goods_amount` | Decimal(19,6) | no | `0` | |
| `services_amount` | Decimal(19,6) | no | `0` | |
| `problems` | Int32 | no | `0` | |
| `file_name` | String(60) | sì | | |
| `protocol` | String(40) | sì | | |
| `generated_at` | DateTimeUtc | sì | | |
| `is_demo` | Bool | no | `false` | |
| `created_at` | DateTimeUtc | no | | |
| `created_by` | String(100) | sì | | |
| `updated_at` | DateTimeUtc | sì | | |
| `updated_by` | String(100) | sì | | |
| `row_version` | Int64 | no | `1` | |
- indice unico `ux_intrastat_lists_period` su `flow`, `year`, `periodicity`, `period`
#### `inventory_document_lines`
| Colonna | Tipo | Null | Default | Note |
@@ -2107,6 +2701,25 @@ Migrazioni applicate in ordine:
- indice unico `ux_party_sales_terms_party` su `party_id`
#### `payment_lines`
| Colonna | Tipo | Null | Default | Note |
|---|---|---|---|---|
| `id` | Int64 | no | | chiave primaria, identity |
| `payment_id` | Int64 | no | | -> `payments` (Cascade) |
| `open_item_id` | Int64 | no | | -> `gl_open_items` (Restrict) |
| `amount` | Decimal(19,6) | no | `0` | |
| `allowance` | Decimal(19,6) | no | `0` | |
| `exchange_difference` | Decimal(19,6) | no | `0` | |
| `created_at` | DateTimeUtc | no | | |
| `created_by` | String(100) | sì | | |
| `updated_at` | DateTimeUtc | sì | | |
| `updated_by` | String(100) | sì | | |
| `row_version` | Int64 | no | `1` | |
- indice `ix_payment_lines_item` su `open_item_id`
- indice `ix_payment_lines_payment` su `payment_id`
#### `payment_methods`
| Colonna | Tipo | Null | Default | Note |
@@ -2165,6 +2778,38 @@ Migrazioni applicate in ordine:
- indice unico `ux_payment_terms_code` su `code`
#### `payments`
| Colonna | Tipo | Null | Default | Note |
|---|---|---|---|---|
| `id` | Int64 | no | | chiave primaria, identity |
| `direction` | String(40) | no | | |
| `party_id` | Int64 | no | | -> `parties` (Restrict) |
| `payment_date` | Date | no | | |
| `payment_method_id` | Int64 | sì | | |
| `bank_account_id` | Int64 | sì | | |
| `account_id` | Int64 | sì | | |
| `amount` | Decimal(19,6) | no | `0` | |
| `allowance_amount` | Decimal(19,6) | no | `0` | |
| `exchange_difference` | Decimal(19,6) | no | `0` | |
| `fees` | Decimal(19,6) | no | `0` | |
| `reference` | String(60) | sì | | |
| `template_code` | String(10) | sì | | |
| `notes` | String(500) | sì | | |
| `origin` | String(40) | no | | |
| `remittance_id` | Int64 | sì | | -> `remittances` (Restrict) |
| `statement_line_id` | Int64 | sì | | |
| `gl_entry_id` | Int64 | sì | | |
| `is_demo` | Bool | no | `false` | |
| `created_at` | DateTimeUtc | no | | |
| `created_by` | String(100) | sì | | |
| `updated_at` | DateTimeUtc | sì | | |
| `updated_by` | String(100) | sì | | |
| `row_version` | Int64 | no | `1` | |
- indice `ix_payments_date` su `direction`, `payment_date`
- indice `ix_payments_party` su `party_id`, `payment_date`
#### `price_lists`
| Colonna | Tipo | Null | Default | Note |
@@ -2474,6 +3119,64 @@ Migrazioni applicate in ordine:
- indice `ix_purchase_orders_status` su `status`
- indice unico `ux_purchase_orders_number` su `numerator_id`, `number`
#### `remittance_lines`
| Colonna | Tipo | Null | Default | Note |
|---|---|---|---|---|
| `id` | Int64 | no | | chiave primaria, identity |
| `remittance_id` | Int64 | no | | -> `remittances` (Cascade) |
| `open_item_id` | Int64 | no | | -> `gl_open_items` (Restrict) |
| `party_id` | Int64 | no | | |
| `amount` | Decimal(19,6) | no | `0` | |
| `due_date` | Date | no | | |
| `iban` | String(34) | sì | | |
| `mandate_id` | Int64 | sì | | -> `sdd_mandates` (Restrict) |
| `end_to_end_id` | String(35) | sì | | |
| `status` | String(40) | no | | |
| `unpaid_on` | Date | sì | | |
| `unpaid_fees` | Decimal(19,6) | no | `0` | |
| `unpaid_entry_id` | Int64 | sì | | |
| `payment_id` | Int64 | sì | | |
| `created_at` | DateTimeUtc | no | | |
| `created_by` | String(100) | sì | | |
| `updated_at` | DateTimeUtc | sì | | |
| `updated_by` | String(100) | sì | | |
| `row_version` | Int64 | no | `1` | |
- indice `ix_remittance_lines_item` su `open_item_id`
- indice `ix_remittance_lines_remittance` su `remittance_id`
#### `remittances`
| Colonna | Tipo | Null | Default | Note |
|---|---|---|---|---|
| `id` | Int64 | no | | chiave primaria, identity |
| `year` | Int32 | no | | |
| `number` | Int32 | no | | |
| `kind` | String(40) | no | | |
| `bank_account_id` | Int64 | no | | -> `bank_accounts` (Restrict) |
| `presentation_date` | Date | no | | |
| `due_until` | Date | no | | |
| `advance` | Bool | no | `false` | |
| `status` | String(40) | no | | |
| `total_amount` | Decimal(19,6) | no | `0` | |
| `item_count` | Int32 | no | `0` | |
| `message_id` | String(35) | sì | | |
| `attachment_id` | Int64 | sì | | |
| `file_name` | String(100) | sì | | |
| `gl_entry_id` | Int64 | sì | | |
| `credited_on` | Date | sì | | |
| `credit_entry_id` | Int64 | sì | | |
| `notes` | String(500) | sì | | |
| `is_demo` | Bool | no | `false` | |
| `created_at` | DateTimeUtc | no | | |
| `created_by` | String(100) | sì | | |
| `updated_at` | DateTimeUtc | sì | | |
| `updated_by` | String(100) | sì | | |
| `row_version` | Int64 | no | `1` | |
- indice unico `ux_remittances_number` su `year`, `number`
#### `role_permissions`
| Colonna | Tipo | Null | Default | Note |
@@ -2939,6 +3642,31 @@ Migrazioni applicate in ordine:
Chiave primaria: `module`, `version`.
#### `sdd_mandates`
| Colonna | Tipo | Null | Default | Note |
|---|---|---|---|---|
| `id` | Int64 | no | | chiave primaria, identity |
| `party_id` | Int64 | no | | -> `parties` (Restrict) |
| `reference` | String(35) | no | | |
| `signature_date` | Date | no | | |
| `scheme` | String(40) | no | | |
| `iban` | String(34) | no | | |
| `bic` | String(11) | sì | | |
| `one_off` | Bool | no | `false` | |
| `last_collection_date` | Date | sì | | |
| `revoked` | Bool | no | `false` | |
| `notes` | String(200) | sì | | |
| `is_demo` | Bool | no | `false` | |
| `created_at` | DateTimeUtc | no | | |
| `created_by` | String(100) | sì | | |
| `updated_at` | DateTimeUtc | sì | | |
| `updated_by` | String(100) | sì | | |
| `row_version` | Int64 | no | `1` | |
- indice `ix_sdd_mandates_party` su `party_id`
- indice unico `ux_sdd_mandates_reference` su `reference`
#### `shipping_terms`
| Colonna | Tipo | Null | Default | Note |
+28 -26
View File
@@ -57,10 +57,11 @@ conservati; ogni accesso residuo risponde `module_not_licensed`.
| Purchases | CORE | Documenti | [Acquisti](wiki/Acquisti.md) | M6 |
| Inventory | CORE | Magazzino | [Magazzino](wiki/Magazzino.md) | M6 |
| Ledger | ACCT | Contabilità | [Contabilita](wiki/Contabilita.md) | M7, M10 |
| Vat | ACCT, INTRA | Contabilità | [IVA](wiki/IVA.md), [Intrastat](wiki/Intrastat.md) | M7, M10 |
| Vat | ACCT, INTRA | Contabilità | [IVA](wiki/IVA.md), [Intrastat](wiki/Intrastat.md) | M7, M10 (Intrastat) |
| YearEnd | ACCT (chiusura, bilancio), INTRA (Intrastat), CORE (dichiarazioni d'intento) | Contabilità | [Chiusura-e-bilancio](wiki/Chiusura-e-bilancio.md), [Dichiarazioni-d-intento](wiki/Dichiarazioni-d-intento.md) | M10 |
| Assets | ASSET | Contabilità | [Cespiti](wiki/Cespiti.md) | M10 |
| Finance | FIN | Contabilità (proposta) | [Scadenzario](wiki/Scadenzario.md) | M8 |
| EInvoicing | EINV | SDI/e-invoicing; E-mail/PEC | [Fatturazione-elettronica](wiki/Fatturazione-elettronica.md) | M9 (dichiarazioni d'intento: M10) |
| EInvoicing | EINV | SDI/e-invoicing; E-mail/PEC | [Fatturazione-elettronica](wiki/Fatturazione-elettronica.md) | M9 |
| Crm | CRM | CRM | [CRM](wiki/CRM.md) | M11 |
| Services | SVC | CRM (proposta) | [Servizi](wiki/Servizi.md) | M14 (fase 2) |
| Channels | CHAN | Integrazioni | [Canali-e-commerce](wiki/Canali-e-commerce.md) | M14 (fase 2) |
@@ -161,12 +162,12 @@ conservati; ogni accesso residuo risponde `module_not_licensed`.
|---|---|
| Licenza | `ACCT` |
| Responsabilità | piano dei conti (precaricato e importabile CSV/XLSX/JSON), causali, prima nota con quadratura, contabilizzazione automatica, partitari e mastrini, registrazioni ricorrenti e in valuta, ritenute e casse, ratei/risconti, chiusura e apertura, libri definitivi, bilancio di verifica, CEE e riclassificati, export per il commercialista |
| Entità | `GlAccount`, `JournalTemplate(+Line)`, `GlEntry`, `GlEntryLine`, `GlEntryVat`, `WithholdingTax`, `SocialSecurityCharge`, `AccrualDeferral`, `ClosingRun(+Step)`, `FinancialStatementLine`, `RecurringEntryTemplate` |
| Servizi | `JournalService`, `PostingEngine`, `LedgerPoster`, `PeriodLockService`, `LedgerQueries`, `PartitarioService`, `WithholdingService`, `AccrualDeferralService`, `ClosingProcedure`, `TrialBalanceService`, `FinancialStatementsService`, `RecurringEntriesService`, `ExchangeDifferenceService`, `ChartOfAccountsImportService` |
| Entità | `GlAccount`, `JournalTemplate(+Line)`, `GlEntry`, `GlEntryLine`, `GlEntryVat`, `WithholdingTax`, `SocialSecurityCharge`, `RecurringEntryTemplate`; dalla M10 (cartella `YearEnd`) `AccrualDeferral`, `ClosingRun`, `ClosingStep`, `ClosingPrint` |
| Servizi | `JournalService`, `PostingEngine`, `LedgerPoster`, `PeriodLockService`, `LedgerQueries`, `PartitarioService`, `WithholdingService`, `TrialBalanceService`, `RecurringEntriesService`, `ChartOfAccountsImportService`; dalla M10 `AccrualService` (ratei, risconti, differenze di cambio), `ClosingService` (nove passi, stampe, blocco), `FinancialStatementsService` (CEE, riclassificati, indici, export); nel pacchetto paese `ClosingRulesIt`, `CeeSchemaIt` |
| Maschere e mockup | prima nota (040, 041), piano dei conti e mastrino (042), causali (043), partitario/estratto conto (044), ritenute e F24 (047), chiusura esercizio (050), bilancio CEE (051), esercizi e periodi (052) |
| Permessi | **`ledger.entry.finalize`**; proposte: `ledger.entry.read`, `ledger.entry.write`, `ledger.entry.reopen`, `ledger.account.write`, `ledger.closing.run` |
| Permessi | **`ledger.entry.finalize`**, `ledger.entry.read`, `ledger.entry.write`, `ledger.account.write`; dalla M10 `ledger.year.close` (ratei e risconti, chiusura, blocco) e `reports.accountant.export` |
| Log | Contabilità |
| Wiki | [Contabilita](wiki/Contabilita.md) |
| Wiki | [Contabilita](wiki/Contabilita.md), [Chiusura-e-bilancio](wiki/Chiusura-e-bilancio.md) |
| Milestone | M7 `v0.7.0` (piano dei conti, causali, prima nota, partitari, ritenute, bilancio di verifica); M10 `v0.10.0` (ratei/risconti, chiusura/apertura, libri definitivi, bilancio CEE, export commercialista) |
### 3.8 Vat — IVA, adempimenti e Intrastat
@@ -175,28 +176,29 @@ conservati; ogni accesso residuo risponde `module_not_licensed`.
|---|---|
| Licenza | `ACCT`; parte Intrastat `INTRA` |
| Responsabilità | registri IVA con protocollo e stampe definitive, liquidazione periodica (differita, per cassa, pro-rata, acconto, interessi, minimo), dati F24 e LIPE XML, bollo virtuale (dati per F24), dichiarazioni d'intento, elenchi Intrastat |
| Entità | `VatRegister`, `VatSettlement(+Line)`, `StampDutyEntry`, `IntentDeclaration`, `IntrastatDeclaration(+Line)` |
| Entità | `VatRegister`, `VatSettlement(+Line)`, `StampDutyEntry`; dalla M10 `IntentDeclaration`, `IntrastatList(+Line)` |
| Servizi | `VatRegisterService`, `VatSettlementService`, `StampDutyService`, `IntentDeclarationService`, `IntrastatService`; nel pacchetto paese `VatSettlementRules`, `VatAdvanceCalculator`, `LipeWriter`, `F24Exporter`, `IntrastatExporterIt` |
| Maschere e mockup | registri IVA (045, `VatRegistersPage`), liquidazione IVA/F24/LIPE (046, `VatSettlementPage`), Intrastat (049, `IntrastatPage`) |
| Permessi | **`vat.settlement.confirm`**; proposte: `vat.register.print`, `vat.register.finalize`, `vat.settlement.read`, `vat.intrastat.export` |
| Permessi | **`vat.settlement.confirm`**; proposte: `vat.register.print`, `vat.register.finalize`, `vat.settlement.read`; dalla M10 `intrastat.list.read`, `intrastat.list.write`, `intrastat.list.export`, `sales.intent.read`, `sales.intent.write` |
| Log | Contabilità |
| Wiki | [IVA](wiki/IVA.md), [Intrastat](wiki/Intrastat.md), [Fiscalita-italiana](wiki/Fiscalita-italiana.md) |
| Milestone | M7 `v0.7.0` (registri, liquidazione, F24, LIPE, bollo); M10 `v0.10.0` (Intrastat, dichiarazioni d'intento) |
Nota: SPEC elenca bollo virtuale e dichiarazioni d'intento sia in `ACCT` sia in `EINV` (§8.1), e le loro maschere
(060, 061) sotto *Fatturazione elettronica*. Proposta: i servizi stanno in `Vat`, le maschere sono raggiungibili dal
menu *Fatturazione elettronica* se `EINV` è attivo e da *Contabilità* se è attivo solo `ACCT`. Da fissare con ADR.
(060, 061) sotto *Fatturazione elettronica*. Deciso in M10 (ADR 0042): le dichiarazioni d'intento sono nel modulo base
`CORE` perché riguardano la normale fatturazione, Intrastat in `INTRA`; entrambe le pagine stanno nel menu
*Fatturazione elettronica* come nei mockup, i servizi in `Khaemhat.Application/YearEnd`.
### 3.9 Assets — Cespiti
| Voce | Contenuto |
|---|---|
| Licenza | `ASSET` |
| Responsabilità | categorie con coefficienti ministeriali, registro beni ammortizzabili, piano di ammortamento (primo anno 50%, limiti autovetture, beni < €516,46), dismissioni con plus/minusvalenza (TD26), rivalutazioni, piano simulato, contabilizzazione annuale |
| Responsabilità | categorie con coefficienti ministeriali, registro beni ammortizzabili, piano di ammortamento civilistico e fiscale (primo anno 50%, limiti autovetture, beni < €516,46), dismissioni totali e parziali con plus/minusvalenza, registrazione annuale per categoria annullabile, stampa del registro |
| Entità | `FixedAsset`, `FixedAssetCategory`, `FixedAssetMovement` |
| Servizi | `FixedAssetService`, `DepreciationService`; `DepreciationCalculator` (Core), `FixedAssetRulesIt`, `MinisterialCoefficients` |
| Maschere e mockup | registro cespiti e piano di ammortamento (048, `FixedAssetsPage`) |
| Permessi | proposte: `assets.asset.read`, `assets.asset.write`, `assets.depreciation.post` |
| Servizi | `FixedAssetService`; `DepreciationCalculator` (Core); nel pacchetto paese le regole dei cespiti e `MinisterialCoefficients` (ADR 0041) |
| Maschere e mockup | registro cespiti e piano di ammortamento (048, `AssetsPage`), ammortamenti (`DepreciationPage`), categorie (`CategoriesPage`) |
| Permessi | `assets.asset.read`, `assets.asset.write`, `assets.depreciation.post` |
| Log | Contabilità |
| Wiki | [Cespiti](wiki/Cespiti.md) |
| Milestone | M10 `v0.10.0` |
@@ -206,28 +208,28 @@ menu *Fatturazione elettronica* se `EINV` è attivo e da *Contabilità* se è at
| Voce | Contenuto |
|---|---|
| Licenza | `FIN` |
| Responsabilità | partite aperte e aging, incassi e pagamenti con abbuoni e differenze cambio, insoluti, distinte RiBa (CBI), SDD (`pain.008`), bonifici SEPA (`pain.001`), riconciliazione bancaria (CSV/CBI/CAMT.053), solleciti a livelli con interessi di mora, flusso di cassa 90 giorni |
| Entità | `OpenItem`, `Payment(+Line)`, `Remittance(+Line)`, `SddMandate`, `BankStatement(+Line)`, `BankMatchRule`, `DunningRun(+Line)`, `DunningLevel` |
| Servizi | `OpenItemService`, `PaymentService`, `RemittanceService`, `SddMandateService`, `BankStatementImportService`, `BankReconciliationService`, `DunningService`, `CashFlowForecastService`, `AgingReportService`, `InstallmentPoster` |
| Maschere e mockup | partite e aging (053, `OpenItemsPage`), registra incasso (054, `PaymentDialog`), distinte (055, `RemittancePage`), solleciti (056, `DunningPage`), riconciliazione (057, `BankReconciliationPage`) |
| Permessi | proposte: `finance.open_item.read`, `finance.payment.write`, `finance.remittance.write`, `finance.dunning.run`, `finance.reconciliation.write` |
| Responsabilità | partite aperte (le `gl_open_items` della contabilità) e aging, incassi e pagamenti con abbuoni, spese e differenze cambio, insoluti, distinte RiBa (CBI), SDD (`pain.008.001.08`), bonifici SEPA (`pain.001.001.09`), mandati, riconciliazione bancaria (CSV/CBI/CAMT.053), solleciti a livelli con interessi di mora, flusso di cassa 30-365 giorni, scadenze sulla Home |
| Entità | `OpenItem` (Ledger), `Payment(+Line)`, `Remittance(+Line)`, `SddMandate`, `BankStatement(+Line)`, `BankMatchRule`, `DunningLevel`, `DunningLetter` |
| Servizi | `ScheduleService`, `PaymentService`, `RemittanceService`, `MandateService`, `BankReconciliationService`, `DunningService` (+ job `finance.dunning`), `CashFlowService`, `TreasuryFeedSource`, `DemoTreasurySeeder`; nel core `AgingCalculator`, `PaymentAllocator`, `BankMatcher`, `SepaXmlWriter`, `CsvStatementReader`, `Camt053Reader`; nel pacchetto italiano `RibaCbiWriter`, `CbiStatementReader`, `LatePaymentRulesIt` (ADR 0038) |
| Maschere e mockup | partite e aging (053, `SchedulePage`), registra incasso (054, `PaymentDialog`), incassi e pagamenti (`PaymentsPage`), distinte (055, `RemittancesPage`), mandati (`MandatesPage`), solleciti (056, `DunningPage`), riconciliazione (057, `ReconciliationPage`), flusso di cassa (`CashFlowPage`) |
| Permessi | `finance.schedule.read`, `finance.schedule.write`, `finance.payment.read`, `finance.payment.write`, `finance.bank.reconcile` |
| Log | Contabilità (proposta: SPEC §9.5 non ha una sezione "Tesoreria"); invio solleciti in E-mail/PEC |
| Wiki | [Scadenzario](wiki/Scadenzario.md) |
| Milestone | M8 `v0.8.0` |
| Milestone | M8 `v0.8.0` (consegnata) |
### 3.11 EInvoicing — Fatturazione elettronica
| Voce | Contenuto |
|---|---|
| Licenza | `EINV` |
| Responsabilità | generazione e validazione XML FatturaPA (`FPR12`/`FPA12`/`FSM10`), lettura passive e P7M, notifiche SDI, quattro canali (PEC integrata, SdICoop, Intermediario A, Intermediario B) con instradamento, cruscotto, inbox, export per la conservazione, autofatture da inviare |
| Entità | `EInvoice`, `SdiNotification`, `EInvoiceInboxFile`, `SdiChannel`, `SdiRoutingRule`, `ConservationPackage` |
| Servizi | `EInvoiceService`, `EInvoiceExportService`, `SdiChannelService`, `SdiInboxService`, `SdiNotificationImportService`, `PurchaseInvoiceImportService`, `ConservationExportService`; nel pacchetto paese `FatturaPaWriter`, `FatturaPaValidator`, `FatturaPaReader`, `SdiRouter`, i quattro `ISdiTransport` |
| Maschere e mockup | cruscotto SDI (058, `EInvoiceDashboard`), canali SDI (059, `SdiChannelsPage`), bollo virtuale (060, `StampDutyPage`), dichiarazioni d'intento e plafond (061, `IntentDeclarationsPage`) |
| Permessi | proposte: `einvoicing.invoice.generate`, `einvoicing.invoice.send`, `einvoicing.channel.write`, `einvoicing.inbox.import` |
| Responsabilità | file FatturaPA (`FPR12`/`FPA12`/`FSM10`) con controlli offline e codici dello SDI, quattro canali (PEC, SdICoop, Intermediario A, Intermediario B) con instradamento e canale di riserva, lettura dei canali programmata e push SdICoop, notifiche, correzione degli scarti, copia di cortesia PDF con l'XML allegato, fatture ricevute da registrare, pacchetti per la conservazione, autofatture da inviare, rimozione dei dati di esempio |
| Entità | `EInvoice` (`e_invoices`), `EInvoiceNotification` (`e_invoice_notifications`), `EInvoiceInboxFile` (`e_invoice_inbox`), `EInvoiceChannelSetting` (`e_invoice_channels`), `SdiRoutingRule` (`e_invoice_routing`), `ConservationExport` (`e_invoice_conservation`) |
| Servizi | `EInvoiceService`, `EInvoiceChannelService`, `EInvoicePollingService` (+ job `einvoice.poll`), `SdiPushService` (endpoint `POST /sdicoop/{azienda}`), `SdiInboxService`, `ConservationExportService`, `EInvoiceFeedSource`, `DemoEInvoiceSeeder`, `DemoDataRemover`; nel core `SdiRouter`, `EInvoiceStates`; nel pacchetto italiano `FatturaPaWriter`, `FatturaPaValidator`, `FatturaPaReader`, `SdiReceiptReader`, `PecSdiTransport`, `SdiCoopTransport`, `IntermediaryATransport`, `IntermediaryBTransport`, `SdiCoopPushReader` (ADR 0039, 0040) |
| Maschere e mockup | cruscotto SDI (058, `EInvoiceDashboardPage`), canali e instradamento (059, `EInvoiceChannelsPage`), fatture ricevute (`EInvoiceInboxPage`), notifiche (`EInvoiceNotificationsPage`), conservazione (`ConservationPage`); dichiarazioni d'intento e plafond (061) in M10; bollo virtuale (060) in *IVA* dalla 0.7 |
| Permessi | `einvoice.document.read`, `einvoice.document.send`, `einvoice.inbox.read`, `einvoice.inbox.import`, `einvoice.channel.manage` |
| Log | SDI/e-invoicing; invio e lettura PEC in E-mail/PEC; intermediari in Integrazioni |
| Wiki | [Fatturazione-elettronica](wiki/Fatturazione-elettronica.md) |
| Milestone | M9 `v0.9.0` (con seed demo completo); dichiarazioni d'intento in M10 |
| Milestone | M9 `v0.9.0` (consegnata); dichiarazioni d'intento in M10 |
### 3.12 Crm — CRM
+43 -12
View File
@@ -2,24 +2,34 @@
> Punto di ripresa per ogni sessione. Aggiornare a fine sessione.
**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).
**Ultimo aggiornamento:** 2026-11-16
**Milestone corrente:** M11 — CRM e servizi (issue #88-#91), da iniziare. M10 chiusa: PR in `main`, tag `v0.10.0`,
immagine e release.
**Prossimo passo:** M11 dall'issue #88. Decisioni del titolare del 2026-11-16 (ADR 0044): le schermate senza PNG si
disegnano dalla miniatura e dalla grafica del gestionale (#35 chiusa); niente elenco banche ABI/CAB precaricato (#45
chiusa); intermediari, SdICoop e PEC reale rimandati (#78 nel backlog).
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).
bilancio dal file `khaemhat-coa.json`; libro inventari (M13); IVA per cassa (fase 2).
Da M8: tracciati CBI e SEPA da provare con un home banking reale; tabella semestrale dei tassi di mora da aggiornare a
gennaio e luglio (ADR 0038); blocco per fido su ordini e documenti; report di tesoreria in *Report* (M12).
Da M9: schema XSD ufficiale FatturaPA al posto di quello scritto in casa (serve il permesso di scaricarlo);
intermediari reali e accreditamento SdICoop (#78 nel backlog, ADR 0040 e 0044); conformità PDF/A-3 dichiarata della copia di cortesia;
pulsanti *Carica* e *Rimuovi dati di esempio* nell'interfaccia (M12).
Da M10: file `SCAMBI.CEE` da verificare con il software di controllo delle Dogane prima del primo invio (ADR 0042);
differenze di cambio calcolate sul residuo attuale della partita (ADR 0043); TFR stimato (retribuzioni / 13,5);
annullare il passo 2 della chiusura toglie tutti gli ammortamenti dell'anno (ADR 0041); il gruppo dichiarazione
d'intento nei dati fiscali del cliente è ora uno specchio del registro (si potrebbe renderlo di sola lettura con un
collegamento al registro); rivalutazioni senza regole guidate.
## Fatto
- Specifica normativa in `docs/SPEC.md`; `CLAUDE.md` con emendamenti E1-E7.
- ADR 0001-0037.
- ADR 0001-0043.
- 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`,
@@ -88,6 +98,29 @@ incassi e pagamenti e IVA per cassa (M8).
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).
- **M8 (chiusa, `v0.8.0`):** scadenzario sulle partite della contabilità con aging, incassi e pagamenti multipli e
parziali con abbuoni, spese, cambi e storno (#69, ADR 0038); distinte RiBa CBI, SDD `pain.008` e bonifici
`pain.001` con presentazione, anticipo s.b.f., accredito e insoluti, mandati SDD (#70); riconciliazione bancaria
CSV/CBI/CAMT.053 senza doppioni con confidenza e regole (#71); solleciti a tre livelli con interessi di mora e job
automatico, flusso di cassa, scadenze sulla Home (#72); tesoreria nei dati di esempio con FIN, wiki *Scadenzario*
con le schermate (#73). Test: 823 verdi in locale, anche quelli di PostgreSQL (18) con un container locale.
- **M9 (chiusa, `v0.9.0`):** file FatturaPA `FPR12`/`FPA12`/`FSM10` con controllo offline dei codici SDI e schema
scritto in casa (#74, ADR 0039); notifiche RC/NS/MC/NE/DT/AT/SE/MT senza doppioni che muovono file e documento,
correzione degli scarti, copia di cortesia PDF con l'XML allegato (#75); canali PEC (IMAP e MIME in casa),
SdICoop SOAP/MTOM e due intermediari generici con instradamento e riserva, job `einvoice.poll` e push SdICoop su
`/sdicoop/{azienda}` (#76, #77, ADR 0040); fatture ricevute da registrare e pacchetti di conservazione (#79);
fatturazione nei dati di esempio e rimozione dei dati di esempio guidata dallo schema (#80); wiki *Fatturazione
elettronica* con le schermate (#81). #78 (scelta degli intermediari, accreditamento SdICoop) resta aperta.
Test: 874 verdi in locale, anche quelli di PostgreSQL (18) con un container locale.
- **M10 (chiusa, `v0.10.0`):** cespiti con categorie ministeriali, piano civilistico e fiscale, ammortamenti per
categoria annullabili, dismissioni e registro (#82, ADR 0041); elenchi Intrastat dai documenti con periodicità dalle
soglie e file `SCAMBI.CEE`, registro delle dichiarazioni d'intento con controllo del plafond alla conferma (#83,
ADR 0042); ratei e risconti per giorni e differenze di cambio (#84); chiusura guidata in nove passi ripetibili e
annullabili con riapertura, stampe definitive e blocco (#85); bilancio CEE ordinario, abbreviato e micro con
riclassificato, indici, stampa ed export per il commercialista (#86, ADR 0043); dati di esempio di fine anno e
chiusura completa dell'anno demo come prova di accettazione (#87); wiki *Cespiti*, *Intrastat*, *Dichiarazioni
d'intento*, *Chiusura e bilancio* con le schermate. Test: 907 verdi in locale, anche quelli di PostgreSQL con un
container locale.
- 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,
@@ -106,8 +139,6 @@ Rilevato il 2026-11-11 sulla macchina di sviluppo (Windows 11, Git Bash per gli
## In attesa del titolare
- PNG ad alta risoluzione delle 66 schermate disponibili solo come miniatura (issue #35, non bloccante).
- Scelta degli intermediari SDI e accreditamento SdICoop (issue #78, non bloccante).
- Prova del template su Unraid (issue #106).
- Un contatto privato per la segnalazione di vulnerabilità (vedi `SECURITY.md`).
@@ -137,8 +168,8 @@ Emersi durante la stesura della documentazione. Si decidono con un ADR quando si
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. **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).
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. **Deciso in M10: dichiarazioni d'intento in CORE, Intrastat in INTRA nel menu e-fattura, export commercialista in ACCT con il permesso `reports.accountant.export` (ADR 0042, 0043).**
16. Stato "Provvisorio" dell'esercizio nel mockup 052, non previsto da SPEC (aperto / in chiusura / chiuso). **Deciso in M10: restano i tre stati di SPEC; "in chiusura" dal passo 6, "chiuso" con il blocco (ADR 0043).**
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.
@@ -28,6 +28,7 @@
- Per le schermate con sola miniatura valgono SPEC §10.1 regola 4 (comporre con i mattoni della più simile) e le
descrizioni testuali; se un dettaglio non è ricostruibile si chiede il PNG all'utente con un'issue
`Status/In attesa utente`, senza fermare il resto.
`Status/In attesa utente`, senza fermare il resto. *Aggiornato dall'ADR 0044:* altri PNG non esistono, i dettagli
mancanti si decidono seguendo la grafica del gestionale.
- Quando arrivano gli screenshot reali dell'applicazione sostituiscono progressivamente i mockup nella wiki
(`docs/wiki/img/`), come da SPEC §17.
@@ -37,6 +37,8 @@ grandi (8.000 comuni, decine di migliaia di sportelli) che non sono nel reposito
via dell'utente al download. Fino ad allora le tabelle si riempiono a mano o con l'import CSV.
*Aggiornato dall'ADR 0028:* province e comuni ISTAT, con i CAP di GeoNames, sono nei dati di base dalla
versione `IT 2026.3`; le banche restano fuori.
*Aggiornato dall'ADR 0044:* il titolare rinuncia all'elenco precaricato delle banche; nome e BIC si scrivono a mano
o vengono da un conto dell'azienda presso la stessa banca.
7. **Riga di comando.** `scripts/seed.sh --base [--company CODICE]` esegue la sequenza di avvio senza servire pagine
(migrazioni, prima azienda) e aggiunge i dati di base a un'azienda o a tutte quelle attive. Nel container lo
script è in `/app/scripts/` e passa da `entrypoint.sh` con il verbo `seed`; in sviluppo usa `dotnet run`.
@@ -41,6 +41,7 @@ caricati dopo il via dell'utente. Il via è arrivato il 2026-11-12 per due fonti
6. **Strumento di rigenerazione.** `tools/Khaemhat.PlacesTool` (non distribuito, solo framework) legge il foglio ISTAT
e `IT.zip` e riscrive `Data/province.csv` e `Data/comuni.csv`; i file scaricati restano fuori dal repository.
7. **Banche ABI/CAB** restano fuori finché non c'è una fonte aperta con licenza chiara (ADR 0026, ADR 0027 punto 6).
Il titolare ha rinunciato ai dati precaricati (ADR 0044).
## Conseguenze
+70
View File
@@ -0,0 +1,70 @@
# ADR 0038 - Scadenzario, distinte, riconciliazione bancaria e solleciti
- **Stato:** accettata
- **Data:** 2026-11-13
- **Modifica:** SPEC §11.8, §10.3; milestone M8, issue #69, #70, #71, #72
## Contesto
SPEC §11.8 chiede lo scadenzario di clienti e fornitori con incassi e pagamenti (abbuoni, differenze cambio,
insoluti), le distinte RiBa, SDD e bonifici SEPA, i mandati, la riconciliazione bancaria con import CSV/CBI/CAMT.053
e abbinamento automatico, i solleciti con interessi di mora e il flusso di cassa. Restavano aperti: dove vivono le
partite, come si contabilizzano distinte e insoluti, quali versioni dei tracciati produrre senza librerie esterne
(SPEC §1), come evitare i doppioni dell'estratto conto, come stimare la confidenza degli abbinamenti, dove stanno i
tassi di mora e cosa fa la demo senza licenza FIN.
## Decisione
1. **Le partite sono quelle della contabilità.** Lo scadenzario non ha una tabella sua: legge e aggiorna
`gl_open_items`, scritte dalla contabilizzazione dei documenti (ADR 0037). Incassi e pagamenti (`payments`,
`payment_lines`) chiudono le partite e scrivono **subito** la registrazione INC o PAG nella stessa transazione,
con abbuoni, spese e differenze cambio sui conti dei ruoli di registrazione del pacchetto fiscale
(`AllowanceIncome`, `AllowanceExpense`, `BankCharges`, `ExchangeGain`, `ExchangeLoss`). La rettifica di una
registrazione mantiene le partite già saldate. L'annullamento di un incasso storna la registrazione e riapre le
partite; la ritenuta d'acconto di una parcella diventa dovuta quando la fattura è saldata del tutto.
2. **Distinte in quattro passi.** Bozza (le partite passano *In distinta*) → file generato → presentazione → accredito.
RiBa e SDD alla presentazione spostano il credito da *Clienti* a *Effetti all'incasso* (`BillsForCollection`); con
il *salvo buon fine* la banca accredita subito su *Banche c/anticipi* (`BankAdvances`). L'accredito chiude il conto
effetti o l'anticipo. I bonifici SEPA pagano i fornitori già alla presentazione. L'**insoluto** riapre la partita
come *Insoluta*, riprende l'importo dalla banca e trasforma le spese in una **nuova partita** del cliente, così il
recupero passa dallo scadenzario come ogni altra rata.
3. **Tracciati scritti in casa.** RiBa nel tracciato CBI a record di 120 caratteri (IB, 14, 20, 30, 40, 50, 51, 70,
EF), scritto dal pacchetto italiano (`RibaCbiWriter`); SDD in `pain.008.001.08` e bonifici in `pain.001.001.09`
con `XmlWriter` (`SepaXmlWriter`, nel core perché SEPA non è solo italiano). Le specifiche CBI e gli schemi
ISO 20022 non si possono scaricare durante lo sviluppo: i tracciati seguono la documentazione pubblica nota e i
test controllano lunghezze, posizioni, totali e struttura. Il file va caricato a mano nell'home banking; il
collegamento diretto (CBI online, PSD2) è fuori da M8.
4. **Estratti conto senza doppioni.** Ogni movimento importato ha un'**impronta** SHA-256 di conto, data contabile,
importo, descrizione e riferimento normalizzati e del numero di movimenti uguali che lo precedono nello stesso
file; l'impronta è unica per conto, quindi rimportare un file o file sovrapposti salta i movimenti già presenti.
Il CSV si riconosce dalla riga di intestazione (separatore, nomi italiani o inglesi, colonne di entrate e uscite
o importo con segno); il CBI dai record RH/61-64/EF; CAMT.053 dallo spazio dei nomi.
5. **Confidenza a punti.** `BankMatcher` (core) assegna 50 punti all'importo esatto (40 se entro la tolleranza del
candidato, per esempio un insoluto con spese), +30 per un numero di documento, CRO o riferimento trovato nella
descrizione, +30 per le parole chiave del candidato, +25 per l'IBAN della controparte, +20 per il nome, e +10/+5/0/-10
per la distanza fra le date (≤3, ≤15, ≤60, oltre). Una **regola** salvata che riconosce il testo vale 98. La
proposta si conferma a mano o in blocco sopra la soglia di **90**: sotto, la scelta resta all'utente.
6. **Interessi di mora nel pacchetto.** `ILatePaymentRules` (astrazioni) e `LatePaymentRulesIt` portano il tasso
del D.Lgs. 231/2002: tasso BCE di riferimento del semestre più 8 punti, da una **tabella semestrale** nel codice
(2,15% nel primo semestre 2026, 2,40% nel secondo) che va aggiornata a ogni comunicato del MEF; dopo l'ultima riga
vale l'ultimo tasso. Gli interessi si mostrano nei solleciti e nell'estratto conto, non si contabilizzano.
7. **Solleciti.** Tre livelli predefiniti (7, 20 e 45 giorni) modificabili; canali come flag (e-mail, PEC, lettera
PDF); esclusi PA, partite contestate e in distinta. L'invio usa la coda di posta dell'invio documenti (ADR 0034); le lettere si
scaricano in un PDF unico. L'attività `finance.dunning` (giorni feriali alle 7:00) invia solo i livelli
*Automatico* e solo per e-mail e PEC.
8. **Permessi.** Cinque codici: `finance.schedule.read`/`write`, `finance.payment.read`/`write`,
`finance.bank.reconcile`, tutti nel modulo `FIN`; le registrazioni chiedono anche `ACCT`.
9. **Demo solo con FIN.** `DemoTreasurySeeder` usa gli stessi servizi del programma, che controllano la licenza:
senza il modulo FIN attivo la demo salta la tesoreria invece di scrivere dati che l'azienda non potrebbe vedere.
10. **Flusso di cassa calcolato al momento.** Nessuna tabella: saldo contabile di banche e cassa, partite aperte,
effetti presentati senza anticipo, residuo degli ordini (30 giorni dopo la consegna), registrazioni ricorrenti
che muovono la banca e F24 non pagati; lo scaduto cade nel primo periodo.
## Conseguenze
- Contabilità e scadenzario non possono divergere: c'è una sola fonte delle partite.
- La tabella dei tassi di mora è una manutenzione semestrale del pacchetto italiano (gennaio e luglio).
- I tracciati vanno provati con l'home banking reale alla prima installazione; le differenze si correggono nel
pacchetto senza toccare i servizi.
- Il piano dei conti PMI standard guadagna *Perdite su cambi*, *Utili su cambi* e *Interessi di mora attivi*
(240 conti).
+81
View File
@@ -0,0 +1,81 @@
# ADR 0039 - Fatturazione elettronica: file, stati, canali e ricezione
- **Stato:** accettata
- **Data:** 2026-11-13
- **Modifica:** SPEC §11.9, §10.3 (mockup 058 e 059); milestone M9, issue #74, #75, #76, #77, #79
## Contesto
SPEC §11.9 chiede il file FatturaPA delle fatture emesse con controllo prima dell'invio, la trasmissione allo SDI
attraverso quattro canali (PEC integrata, SdICoop, due intermediari) con regole di instradamento, le notifiche che
aggiornano lo stato dei documenti, le fatture ricevute, la correzione degli scarti, la copia di cortesia e il
pacchetto per la conservazione. Restavano aperti: dove sta il file e come convive con il documento, come si
numerano i file, come si controlla il file senza librerie esterne né lo schema ufficiale (SPEC §1, nessun download
durante lo sviluppo), come si evitano doppioni di notifiche e fatture ricevute, come si leggono i canali senza perdere
messaggi, come riceve SdICoop e come si proteggono le credenziali.
## Decisione
1. **Il file sta nel database.** Ogni file è una riga di `e_invoices` con il contenuto XML, nome, progressivo,
canale, identificativo SDI e stato. Lo stato del documento di vendita segue quello del file nella stessa
transazione, attraverso il motore dei documenti (`AdvanceExchangeAsync`, azioni `GenerateXml`, `Send`,
`MarkDelivered`, `MarkRejected`, `MarkNotDelivered`). Un file scartato **non si cancella**: resta come
*sostituito* e il documento torna modificabile; la nuova generazione prende un nuovo progressivo. Un file
generato e non ancora inviato si riscrive con lo stesso nome.
2. **Nome e progressivo.** `IT<identificativo>_<progressivo>.xml`, progressivo di cinque caratteri in base 36 da un
contatore dell'azienda, mai riusato (60.466.175 file per trasmittente).
3. **Tutto ciò che è italiano nel pacchetto.** Le astrazioni (`IEInvoiceWriter`, `IEInvoiceValidator`,
`IEInvoiceReceiptReader`, `IEInvoiceChannels`, `IEInvoicePushReader`) sono in `Khaemhat.Fiscal.Abstractions`;
scrittura, controlli, lettura delle ricevute e i quattro trasporti sono in `Khaemhat.Fiscal.Italy`. Il web non
dipende dal pacchetto italiano.
4. **Controlli con i codici dello SDI e schema scritto in casa.** `FatturaPaValidator` ripete offline i controlli
documentati dall'Agenzia con lo **stesso codice di errore** (00400, 00423, 00471…), con le tolleranze delle
specifiche (un centesimo su `PrezzoTotale` e `Imposta`, un euro su `ImponibileImporto`); ciò che richiede i
registri dell'Agenzia (partita IVA esistente, codice destinatario accreditato, indice IPA) si controlla solo nella
forma. La struttura si controlla contro uno schema XSD **scritto per Khaemhat** sulle regole del formato 1.2
(risorsa incorporata `FatturaPA_v1.2_khaemhat.xsd`), perché il file ufficiale non si può scaricare durante lo
sviluppo; le specifiche seguite sono la 1.9.1 (`FatturaPaCodeLists.SpecVersion`). Sostituire lo schema con
quello ufficiale non cambia il codice.
5. **Una notifica entra una volta.** Il nome del file della notifica è unico in `e_invoice_notifications`; un
doppione è riconosciuto e segnalato, non applicato due volte. La notifica si abbina al file per nome del file
fattura o per identificativo SDI; quella non abbinata resta registrata ed evidenziata. MT e SE si conservano
senza cambiare stato. Le fatture ricevute entrano in `e_invoice_inbox` una volta sola (impronta SHA-256 del
contenuto).
6. **Lettura dei canali senza perdite.** L'attività `einvoice.poll` (ogni 15 minuti) legge i canali attivi e non in
pausa; ogni messaggio è **confermato** (archiviato in PEC, `ack` o cancellazione presso l'intermediario) solo dopo
che tutti i suoi file sono stati salvati, così un arresto a metà rilegge il messaggio e la deduplicazione scarta
ciò che c'è già. Per la PEC si leggono solo i messaggi con mittente `fatturapa.it` e gli allegati `.xml`/`.p7m`
del messaggio originale; la cartella di archivio è l'impostazione consigliata.
7. **Instradamento a regole.** `SdiRouter` (core) sceglie la prima regola attiva che si applica, nell'ordine:
*Sempre*, *Cliente PA*, *Cliente specifico*, *Tipo documento*, *Volume giornaliero*. Ogni regola ha un canale di
riserva usato se il primo è in pausa, disattivato o fallisce l'invio. Senza regole vale il primo canale attivo.
8. **SdICoop in push.** Lo SDI consegna notifiche e fatture con chiamate SOAP verso l'azienda. Khaemhat espone
`POST /sdicoop/{azienda}` (anonimo per l'autenticazione dell'applicazione, senza antiforgery, al massimo 16 MB);
`SdiPushService` accetta la chiamata solo se il canale SDICOOP è attivo e l'intestazione
`X-Khaemhat-SdiCoop-Key` corrisponde alla chiave di ricezione (confronto a tempo costante delle impronte SHA-256).
Il certificato reciproco richiesto dall'Agenzia si verifica sul **reverse proxy**, che aggiunge l'intestazione:
Kestrel resta senza configurazione TLS speciale. Il pacchetto legge la busta (`IEInvoicePushReader`) e prepara la
risposta SOAP. Risposte: 404 azienda sconosciuta o senza modulo, 401 canale non attivo o chiave errata, 400 corpo
illeggibile, 200 dopo il salvataggio.
9. **Credenziali cifrate.** Password, chiavi API, chiave di ricezione e certificato PKCS#12 sono cifrati con
`ISecretProtector` (scopo `einvoice.channel`) e non tornano mai nell'interfaccia: un campo vuoto mantiene il valore.
Gli indirizzi dei servizi devono essere `https` (`http` solo verso `localhost`).
10. **Copia di cortesia in PDF.** La stampa del documento con il file FatturaPA come file associato (`/AF`,
struttura PDF/A-3). Non si dichiara la conformità PDF/A, che richiederebbe profili colore e font incorporati
certificati.
11. **Conservazione come esportazione.** Khaemhat non è un conservatore: `ConservationExportService` prepara uno ZIP
(`emesse/`, `ricevute/`, `notifiche/`, `indice.csv` con SHA-256, `LEGGIMI.txt`) per al massimo 731 giorni e
registra in `e_invoice_conservation` periodo, numero di file, dimensione e impronta.
12. **Permessi.** `einvoice.document.read`, `einvoice.document.send`, `einvoice.inbox.read`, `einvoice.inbox.import`,
`einvoice.channel.manage`, tutti nel modulo `EINV`.
## Conseguenze
- La fattura e i suoi file viaggiano insieme in backup e ripristino; il database cresce di qualche kB per fattura.
- Gli scarti più comuni si vedono prima dell'invio, con il messaggio che lo SDI darebbe.
- Lo schema scritto in casa può essere meno severo di quello ufficiale su dettagli di struttura: quando l'utente
autorizza il download, il file ufficiale va messo al posto della risorsa e i test di scrittura rieseguiti.
- SdICoop e gli intermediari sono pronti ma vanno attivati solo dopo l'accreditamento e la scelta del fornitore
(issue #78, ADR 0040); la PEC funziona da subito.
- Le dichiarazioni d'intento (M10) e il formato EN 16931 / UBL arriveranno come altre implementazioni delle stesse
astrazioni.
@@ -0,0 +1,45 @@
# ADR 0040 - Contratti degli intermediari SDI e rimozione dei dati di esempio
- **Stato:** accettata
- **Data:** 2026-11-13
- **Modifica:** SPEC §11.9, §14; milestone M9, issue #77, #78, #80
## Contesto
SPEC §11.9 prevede due intermediari accreditati come canali verso lo SDI, ma il titolare del progetto non ha ancora
scelto i fornitori (issue #78): non ci sono API reali da seguire. SPEC §14 chiede inoltre che i dati di esempio si
possano **rimuovere** senza toccare i dati dell'utente; finora ogni milestone aggiungeva tabelle demo e una rimozione
scritta a mano avrebbe dovuto essere aggiornata ogni volta.
## Decisione
1. **Due contratti generici.** `IntermediaryTransportBase` contiene il ciclo comune (invio, lettura dei file in
attesa, conferma, prova); le due classi derivate definiscono solo le richieste:
- **Intermediario A** (chiave API, `Authorization: Bearer`): `POST {endpoint}/invoices` con il file e
l'intestazione `X-File-Name`, risposta `{ "id", "sdiId" }`; `GET files` per notifiche e fatture in attesa;
`POST files/{id}/ack` per confermarle; `GET status` per la prova.
- **Intermediario B** (utente e password, `Authorization: Basic`): `POST api/v1/send`, `GET api/v1/inbox`,
`DELETE api/v1/inbox/{id}` come conferma, `GET api/v1/ping`.
Quando l'utente sceglie i fornitori, ogni contratto diventa l'API reale cambiando solo le richieste della classe
derivata; servizi, instradamento, interfaccia e test di integrazione restano uguali.
2. **Prima l'accreditamento.** SdICoop e intermediari sono scritti e provati con server finti nei test, ma si
attivano in produzione solo dopo accreditamento o contratto (#78). La PEC è il canale che funziona subito.
*Aggiornato dall'ADR 0044:* la scelta dei fornitori e l'accreditamento sono rimandati; #78 resta nel backlog.
3. **Rimozione guidata dallo schema.** `DemoDataRemover` legge dalle migrazioni le tabelle con la colonna `is_demo`
e le chiavi esterne: elimina le righe marcate e quelle delle tabelle senza marca che appartengono loro (righe di
documento, giacenze), in ordine di dipendenza e in **una transazione**. Se una riga dell'utente si riferisce a una
riga demo (una fattura vera a un cliente demo) non elimina nulla e restituisce le tabelle che lo impediscono.
Le entità che possono essere demo implementano `IDemoMarkable`; un nuovo modulo è coperto senza modifiche.
4. **Comando.** `scripts/seed.sh --remove-demo [--company CODICE]` (non combinabile con `--base`, `--demo`,
`--scale`) stampa le righe rimosse per tabella o le tabelle bloccanti.
5. **Demo della fatturazione solo con EINV e senza rete.** `DemoEInvoiceSeeder` usa i servizi del programma, che
controllano la licenza; il canale PEC dell'esempio è **in pausa** con credenziali finte e le notifiche sono
applicate come se fossero arrivate, così nessun dato dimostrativo raggiunge lo SDI.
## Conseguenze
- Il lavoro per un intermediario reale è limitato a una classe e ai suoi test.
- Un database creato prima della marca `is_demo` su tutte le tabelle può bloccare la rimozione: è voluto, l'utente
vede quali tabelle controllare.
- La rimozione resta un'operazione da super utente e da riga di comando; il pulsante nell'interfaccia arriva con le
pagine di amministrazione (M12).
+45
View File
@@ -0,0 +1,45 @@
# ADR 0041 - Cespiti: piani paralleli, registrazione per categoria e dismissioni
- **Stato:** accettata
- **Data:** 2026-11-13
- **Modifica:** SPEC §11.7, §21; milestone M10, issue #82; mockup 048
## Contesto
SPEC §11.7 chiede il registro dei beni ammortizzabili con piano civilistico e fiscale, il calcolo e la registrazione
delle quote di fine anno, le dismissioni con plusvalenza o minusvalenza e la stampa del registro. Le regole italiane
(coefficienti del DM 31/12/1988, primo anno al 50 % ai fini fiscali, limiti delle autovetture, beni fino a 516,46 €)
devono restare nel pacchetto fiscale. La chiusura dell'esercizio (ADR 0043) deve poter registrare gli ammortamenti
come suo passo 2 e annullarli.
## Decisione
1. **Categorie con aliquote proprie.** Il pacchetto italiano espone `IFixedAssetRules` con le categorie standard
(`MinisterialCoefficients`): materiali con i coefficienti comuni del DM 31/12/1988, immateriali con i limiti
dell'art. 103 TUIR. La categoria dell'azienda conserva aliquota civilistica e fiscale, metà aliquota civilistica
nel primo anno, limite di costo e deducibilità, conti di cespite, fondo e ammortamento: la tabella dipende dal
settore e ogni azienda la adatta.
2. **Due piani con la stessa regola.** `DepreciationCalculator` applica le quote costanti al costo, dimezzate nel
primo anno quando richiesto, senza superare il residuo; i beni con aliquota 100 % si ammortizzano nel primo anno.
Il piano fiscale dimezza sempre il primo anno dei beni materiali. Il bene conserva fondo civilistico e fiscale;
l'aliquota del bene vuota segue la categoria.
3. **Una registrazione per anno, una riga per categoria.** Gli ammortamenti si registrano al 31/12 con origine
`FixedAsset` (quota in Dare, fondo in Avere, per categoria) e un movimento `Depreciation` per bene. L'annullamento
toglie movimenti, fondi e registrazione finché la registrazione non è definitiva. Solo la quota civilistica va in
contabilità: la differenza con la fiscale è una variazione in dichiarazione.
4. **Beni già in uso.** Un bene acquistato prima dell'avvio porta i fondi iniziali e l'ultimo esercizio già
ammortizzato con un movimento `Opening`; i fondi entrano in contabilità con la scrittura di apertura dei conti.
5. **Dismissioni senza quota dell'anno.** La dismissione (totale o parziale) toglie il costo dismesso e la quota
proporzionale del fondo, porta il prezzo sul conto *altri crediti* e la differenza a plusvalenza o minusvalenza.
Nell'anno della dismissione **non** si calcola la quota: è la scelta prudente e più semplice da verificare; chi
vuole la quota fino alla data la registra prima con una scrittura manuale. Gli ammortamenti di un anno non si
registrano se esistono già quelli di un anno successivo (`assets.later-depreciation`).
## Conseguenze
- Il registro, gli ammortamenti e la stampa funzionano anche senza la chiusura guidata; il passo 2 della chiusura
riusa lo stesso servizio e non duplica le quote.
- L'annullamento del passo 2 rimuove tutti gli ammortamenti dell'anno, anche quelli registrati a mano dalla pagina
Ammortamenti prima della chiusura.
- Le rivalutazioni previste dalle singole leggi restano un movimento `Revaluation` senza regole guidate: si aggiungono
quando servono.
@@ -0,0 +1,46 @@
# ADR 0042 - Intrastat e dichiarazioni d'intento
- **Stato:** accettata
- **Data:** 2026-11-13
- **Modifica:** SPEC §11.7, §8.1; milestone M10, issue #83; mockup 049 e 061
## Contesto
SPEC §11.7 chiede gli elenchi Intrastat generati dai documenti con il file per le Dogane e le dichiarazioni d'intento
degli esportatori abituali con il controllo del plafond. Fino a M9 la dichiarazione d'intento era un gruppo di campi
nei dati fiscali del cliente (protocollo, data, plafond) usato solo dal file FatturaPA. Le soglie, il tracciato e il
formato del protocollo sono regole italiane.
## Decisione
1. **Intrastat dai documenti confermati.** `IntrastatService` legge fatture e note di credito (vendite e acquisti)
confermate nel periodo verso soggetti di un altro Stato membro: i beni sono raggruppati per controparte,
nomenclatura e natura della transazione, i servizi hanno una riga per fattura, le note di credito diventano
rettifiche. Natura `11`, consegna `DAP` e trasporto `3` sono proposti e si correggono sulla riga. Le righe manuali
sopravvivono alla rigenerazione.
2. **Periodicità e file nel pacchetto.** `IIntrastatExporter` italiano (`IntrastatExporterIt`) calcola la
periodicità dai quattro trimestri precedenti con le soglie dal 2022 (cessioni 50.000 € per categoria; acquisti di
beni 350.000 € e di servizi 100.000 €, sotto le quali non sono dovuti) e scrive il file `SCAMBI.CEE` a record di
lunghezza fissa. Un elenco con righe incomplete non si esporta; dopo l'invio, con il protocollo, è di sola lettura.
3. **Il tracciato va validato.** Il file segue le specifiche pubblicate ma non è stato provato con il software di
controllo delle Dogane: STATUS lo indica come attività aperta e la wiki chiede il controllo prima del primo invio.
4. **Registro delle dichiarazioni.** Le dichiarazioni diventano una tabella (`intent_declarations`) con direzione
(ricevute o emesse), numero di registro per anno, protocollo (`IIntentRules`: 17 cifre, trattino o barra, 6
cifre), validità, plafond, utilizzato e stato. Il cliente conserva lo **specchio** della dichiarazione corrente
nei dati fiscali, così documenti e FatturaPA (`AltriDatiGestionali` tipo `INTENTO`) non cambiano. Le dichiarazioni
scritte nei dati fiscali prima della 0.10 vengono adottate nel registro alla prima lettura o al primo controllo.
5. **Controllo alla conferma.** `DocumentEngine` chiama `IntentDeclarationService.CheckAsync` quando conferma una
vendita con righe di natura N3.5: senza dichiarazione attiva che copre la data la conferma è rifiutata
(`intent.no-declaration`), oltre il residuo pure (`intent.ceiling-exceeded`); le note di credito restituiscono
plafond e non sono controllate. Dopo ogni conferma, annullamento o eliminazione l'utilizzato si **ricalcola** da
tutte le vendite N3.5 del cliente, ognuna sulla dichiarazione più recente che ne copre la data; dal 90 % il
registro mostra l'avviso.
6. **Moduli.** Intrastat è nel modulo **INTRA**; le dichiarazioni d'intento nel modulo base **CORE**, perché
riguardano la normale fatturazione.
## Conseguenze
- Il plafond è sempre coerente con le fatture, senza contatori da mantenere a mano; il costo è un ricalcolo per
cliente a ogni conferma di una vendita in N3.5.
- Il gruppo *dichiarazione d'intento* dei dati fiscali del cliente resta come specchio; il registro è la fonte.
- La trasmissione telematica (Dogane, Agenzia delle Entrate) resta fuori da Khaemhat.
+57
View File
@@ -0,0 +1,57 @@
# ADR 0043 - Ratei e risconti, chiusura guidata e bilancio
- **Stato:** accettata
- **Data:** 2026-11-13
- **Modifica:** SPEC §11.7, §14; milestone M10, issue #84, #85, #86, #87; mockup 050 e 051
## Contesto
SPEC §11.7 chiede ratei e risconti, differenze di cambio, la chiusura dell'esercizio guidata in passi ripetibili, la
riapertura, le stampe definitive, il bilancio CEE con riclassificato e indici e l'esportazione per il commercialista.
La chiusura scrive molte registrazioni che devono poter essere tolte finché i libri non sono definitivi; il bilancio
deve leggere i saldi dell'anno anche dopo la chiusura dei conti.
## Decisione
1. **Ratei e risconti per giorni.** `AccrualDeferral` conserva tipo, conto, importo e periodo di competenza; la
rettifica è la parte del periodo fuori dall'esercizio (risconti) o dentro (ratei), in giorni. I risconti si
propongono dalle fatture di acquisto registrate sui conti di costi tipicamente a cavallo dell'anno
(`IClosingRules.PrepaidCandidates`) con un periodo di un anno dalla data: l'utente controlla il periodo.
2. **Differenze di cambio sul residuo.** Le partite aperte in valuta si valutano al cambio dell'ultimo giorno
dell'anno sul **residuo** attuale della partita, non su quello al 31/12: per la chiusura fatta a inizio anno nuovo
la differenza è un'approssimazione accettata e documentata.
3. **Nove passi in ordine.** `ClosingService` esegue controlli, ammortamenti (ADR 0041), ratei e risconti, rimanenze
al costo medio ponderato, accantonamenti (svalutazione crediti 0,5 %, art. 106 TUIR; TFR stimato come retribuzioni
/ 13,5 meno quanto già accantonato), chiusura dei conti economici con il risultato a patrimonio, chiusura dei conti
patrimoniali per conto e soggetto, apertura dell'esercizio successivo con lo storno di ratei e risconti, stampe
definitive. Ogni registrazione ha origine `Closing` (o `FixedAsset`, `Accrual`, `ExchangeDifference`) e il numero
del passo, così l'ultimo passo eseguito si **ripete** o si **annulla** togliendo esattamente le sue scritture
(prima i riferimenti, poi le registrazioni, per le chiavi esterne).
4. **Il passo 9 è il punto di non ritorno.** Rende definitive tutte le registrazioni dell'anno (numerazione del
libro giornale) e conserva i PDF di libro giornale, registri IVA, registro cespiti e bilancio CEE. Non si annulla.
Le stampe dei registri IVA nella chiusura sono quelle dell'anno: vidimazione e numerazione delle pagine restano
quelle della pagina IVA. Dopo il passo 9 il **blocco** porta l'esercizio a `Closed` e lo rende di sola lettura.
5. **Conti del pacchetto.** I conti usati (rimanenze, ratei e risconti, fondi, conti di chiusura e apertura,
risultato) sono in `IClosingRules.Accounts` del pacchetto italiano e corrispondono al piano *PMI standard*. Il
risultato si riapre nel conto *utile (perdita) dell'esercizio* (`10.02.002`); la destinazione dell'utile è una
registrazione dell'utente dopo l'approvazione.
6. **Bilancio dai saldi mappati.** `CeeSchemaIt` (`IFinancialStatementsSchema`) descrive le voci degli art. 2424 e
2425 c.c., l'abbreviato (2435-bis) e il micro (2435-ter, con le voci dell'abbreviato), e le riclassificazioni
finanziaria e a valore aggiunto. Ogni conto porta la voce ordinaria; la natura del conto dice in quale prospetto
va. `FinancialStatementsService` **esclude le scritture dei passi 6 e 7**, così un esercizio chiuso mostra i suoi
saldi; segnala i conti con saldo senza voce. Gli indici sono undici, con formula e anno precedente.
7. **Esportazione semplice.** L'export per il commercialista è uno ZIP di cinque CSV (piano dei conti, bilancio di
verifica, movimenti, stato patrimoniale, conto economico) separati da punto e virgola: nessun formato proprietario
di software terzi.
8. **Prova di accettazione.** Il test di integrazione chiude l'anno demo su SQLite e PostgreSQL: bilancio quadrato
prima e dopo l'assestamento, conti a zero dopo il passo 7, apertura quadrata con il patrimonio uguale all'anno
precedente, stampe PDF, blocco ed export.
## Conseguenze
- Una correzione dopo un passo avanzato richiede di annullare i passi a ritroso: è più lungo ma ogni stato intermedio
resta coerente e verificabile.
- L'annullamento del passo 2 toglie tutti gli ammortamenti dell'anno (ADR 0041).
- Il TFR è una stima utile solo se le paghe non lo accantonano già; con le paghe esterne la chiusura non aggiunge
nulla.
- Il libro inventari non è tra le stampe: arriva con i report (M13).
@@ -0,0 +1,54 @@
# ADR 0044 - Schermate senza PNG, banche senza elenco, canali SDI rimandati
- **Stato:** accettata
- **Data:** 2026-11-16
- **Modifica:** emendamento E4 di `CLAUDE.md`; ADR 0011, 0026, 0027 punto 6, 0028 punto 7, 0040; issue #35, #45, #78
## Contesto
Tre issue aspettavano qualcosa dal titolare:
- **#35:** i PNG ad alta risoluzione delle 66 schermate che hanno solo la miniatura.
- **#45:** una fonte con licenza compatibile per l'elenco delle banche ABI/CAB.
- **#78:** la scelta degli intermediari SDI, l'accreditamento SdICoop e una casella PEC di prova.
Il 2026-11-16 il titolare ha risposto su tutte e tre:
- **#35:** il materiale consegnato è tutto quello che esiste. Sono 22 schermate ad alta risoluzione più la galleria,
e nessun'altra fonte (repository, cartella privata, allegati delle issue) ne contiene altre.
- **#45:** rinuncia ai dati precaricati delle banche. Indicherà una fonte se e quando la troverà.
- **#78:** intermediari, SdICoop e PEC reale sono lasciati da parte per ora.
## Decisione
1. **Le miniature sono la specifica finale delle schermate senza PNG.** Nessun PNG ad alta risoluzione verrà
aggiunto alle 66 schermate *solo miniatura*. Le schermate si disegnano in base a tre fonti:
- la miniatura, che fissa disposizione, gruppi e colonne;
- SPEC §10-§12;
- i componenti dell'applicazione già costruiti, con i token di `mockup.css` e i mattoni della schermata più
simile (SPEC §10.1 regola 4).
Dove la miniatura non basta, decide chi sviluppa seguendo lo stile del gestionale, senza chiedere un PNG.
I dettagli scelti così vanno nella pagina wiki della schermata.
2. **Banche senza elenco precaricato.** I dati di base non contengono l'elenco ABI/CAB e `ItalianBankDirectory`
resta vuoto. Dall'IBAN si leggono sempre ABI e CAB. Nome della banca e BIC vengono da un conto dell'azienda
presso la stessa banca, oppure si scrivono a mano (ADR 0027 punto 6). Se il titolare indicherà una fonte con una
licenza che permette di ridistribuirla in un repository pubblico, l'elenco entrerà come nuova versione dei dati di
base, solo in aggiunta (ADR 0026 punto 3).
3. **Canali SDI reali rimandati.** Lo sviluppo continua con i canali simulati dell'ADR 0040. Fino a una scelta del
titolare valgono queste regole:
- i connettori A e B restano generici;
- l'endpoint SdICoop resta disponibile ma non accreditato;
- la PEC si prova contro il server di posta finto dei test.
L'issue #78 resta aperta nel backlog, senza milestone e senza l'etichetta `Status/In attesa utente`.
## Conseguenze
- Le issue #35 e #45 si chiudono. L'issue #78 non blocca nessuna milestone.
- Le schermate di M11-M14 non aspettano materiale dal titolare. Il rischio è che una di esse si discosti dall'idea
originale in un dettaglio che la miniatura non mostra; si corregge con un'issue quando il titolare la vede.
- Chi usa più conti presso banche diverse scrive nome e BIC una volta per banca. La compilazione automatica li
riprende poi dal conto dell'azienda.
- Prima di usare in produzione la fatturazione elettronica serve comunque una PEC o un intermediario reale. La guida
*Fatturazione elettronica* della wiki lo dice già.
+4 -4
View File
@@ -20,10 +20,10 @@ I mockup sono la **specifica visiva vincolante** dell'interfaccia (SPEC §10.1).
| `thumbs/` | Miniature 401x241 di **tutte** le 88 schermate, ritagliate dalla galleria, con lo stesso nome file |
| `mockup.css` | Token (`--kh-*`) e classi dei componenti usati per disegnare i mockup |
Le schermate segnate *solo miniatura* non sono ancora disponibili in alta risoluzione: si lavora con la miniatura,
`mockup.css` e le descrizioni di SPEC §10-§12 (regola 4). La richiesta dei PNG mancanti è tracciata da un'issue con
etichetta `Status/In attesa utente` nella milestone M3. Quando un PNG arriva va copiato in `png/` con lo stesso nome
e questa tabella va aggiornata.
Le schermate segnate *solo miniatura* non hanno e non avranno un PNG ad alta risoluzione (ADR 0044, issue #35): si
lavora con la miniatura, `mockup.css`, le descrizioni di SPEC §10-§12 e i mattoni della schermata più simile
(regola 4). I dettagli che la miniatura non mostra si decidono seguendo la grafica dei componenti già costruiti e si
descrivono nella pagina wiki della schermata.
Alcuni mockup contengono dettagli superati dagli emendamenti di `CLAUDE.md` (ad esempio 085 mostra ancora `ghcr.io`
come registro): in quei casi prevale l'emendamento (registro pacchetti di Gitea).
+4 -3
View File
@@ -11,7 +11,7 @@ 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).
> con i registri IVA (vedi [Contabilità](Contabilita) e [IVA](IVA)). Dalla 0.8 le fatture fornitore **si pagano** dallo [Scadenzario](Scadenzario), anche con le distinte di bonifici SEPA. Arrivano più avanti: il **file XML** delle autofatture e lo scarico dal canale SDI (M9).
## Dove si trova
@@ -87,7 +87,8 @@ fatturato. È un avviso: decidi tu se registrare la fattura o chiedere una nota
![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)
**Acquisti → Importa fatture** (o il link nell'elenco delle fatture passive) registra in bozza le fatture ricevute
dallo SDI o dal tuo intermediario.
dallo SDI o dal tuo intermediario. Dalla 0.9 le fatture che arrivano dai canali SDI si registrano anche da
**Fatturazione elettronica → Fatture ricevute**, con lo stesso import.
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
@@ -136,7 +137,7 @@ ordinario** al posto della natura, il numero e la data della fattura del fornito
di oggi. Controllalo ed **emettilo**: prende il numero dal numeratore `AUT` delle autofatture.
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
si fanno dalla vista *Autofatture* della [Fatturazione elettronica](Fatturazione-elettronica) (dalla 0.9); 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).
+2 -1
View File
@@ -45,7 +45,8 @@ Il radar elenca le anagrafiche con le colonne **Codice**, **Ragione sociale**, *
provincia), **Pagamento**, **Listino** (solo clienti), **Agente** e **Stato**; nei *Contatti* al posto di pagamento e
listino c'è il **Tipo** (prospect o lead). Lo stato è un badge: *Attivo*, *Disattivato*, *Bloccato*, *PA · split*,
*Privato*, *Impresa UE*, *Impresa extra-UE*, *Anche fornitore* / *Anche cliente*. Le colonne **Fatturato** e
**Scaduto** del mockup arrivano con le vendite (M5) e lo scadenzario (M9).
**Scaduto** del mockup arrivano con i report dei clienti (M12); lo scaduto di un cliente si vede già nello
[Scadenzario](Scadenzario) (*Estratto conto*).
- Ricerca libera su codice, nome, partita IVA, codice fiscale e città.
- Filtri rapidi: **Tipo** (solo contatti), **Soggetto**, **Agente**, **Stato**; all'apertura sono mostrate solo le
+2 -1
View File
@@ -50,7 +50,7 @@ Esempi presenti nel mockup (dati dimostrativi):
| `dunning` | Solleciti di pagamento | Procedura | `0 9 * * 1` |
| `vat-reminder` | Promemoria liquidazione IVA | Notifica | mensile |
| `ecb-rates` | Aggiornamento cambi BCE | Procedura | nei giorni feriali |
| `sdi-inbox` | Lettura inbox e canali SDI | Procedura | ogni 30 minuti |
| `einvoice.poll` | Lettura dei canali SDI (notifiche e fatture ricevute) | Procedura | `*/15 * * * *` |
| `report-sales-weekly` | Report vendite settimanale a direzione | Report via e-mail | `0 7 * * 1` |
| `reorder` | Proposta di riordino | Procedura | `0 6 * * *` |
| `stock-check` | Verifica coerenza giacenze | Verifica | settimanale |
@@ -148,6 +148,7 @@ Nella versione 0.7.0 i job di sistema sono questi (orari nel fuso `Europe/Rome`)
| `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 |
| `finance.dunning` | invia per e-mail e PEC i solleciti dei livelli segnati *Automatico* in ogni azienda con il modulo FIN (vedi [Scadenzario](Scadenzario#solleciti); richiede la rete) | nei giorni feriali alle 07: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,
+101 -72
View File
@@ -1,113 +1,142 @@
# Cespiti
> **Stato:** bozza · **Ultima revisione:** 2026-11-10 · **Versione software:** non ancora rilasciata (milestone M10)
> **Modulo di licenza:** ASSET · **Permessi principali:** `assets.asset.write`, `assets.depreciation.post`, `assets.asset.dispose` · **Specifica:** SPEC §11.7, §14
> **Stato:** completa per la versione 0.10 · **Ultima revisione:** 2026-11-13 · **Versione software:** 0.10.0 (M10)
> **Modulo di licenza:** ASSET · **Permessi principali:** `assets.asset.read` (registro, piano, stampe),
> `assets.asset.write` (cespiti, categorie, dismissioni), `assets.depreciation.post` (registrare e annullare gli
> ammortamenti) · **Specifica:** SPEC §11.7, §14, ADR 0041
## A cosa serve
Il modulo Cespiti tiene il **registro dei beni ammortizzabili**: anagrafica dei beni, categorie con coefficienti,
piano di ammortamento civilistico e fiscale, calcolo e contabilizzazione delle quote annuali, dismissioni con
plusvalenza o minusvalenza, rivalutazioni e stampa del registro.
Il modulo Cespiti tiene il **registro dei beni ammortizzabili**: le categorie con i coefficienti ministeriali, i beni
con il piano di ammortamento civilistico e fiscale, la registrazione delle quote di fine anno, le dismissioni con la
plusvalenza o la minusvalenza e la stampa del **registro dei beni ammortizzabili** (libro cespiti).
## Dove si trova
Menu laterale **Cespiti**, con le voci **Registro cespiti**, **Ammortamenti**, **Categorie**.
## Schermate
![048 · Registro cespiti](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/mockups/thumbs/048-cespiti-registro.png)
*Mockup 048 — registro dei beni con categoria, coefficiente, data di acquisto, costo storico, fondo, residuo, quota dell'anno e stato; sotto, il piano di ammortamento del cespite selezionato (civilistico e fiscale) e la scheda con conti, fattura di acquisto, deducibilità e ubicazione (anteprima ridotta)*
Menu laterale **Cespiti**, con tre voci: **Registro cespiti**, **Ammortamenti**, **Categorie**. Gli ammortamenti si
registrano anche dal passo 2 della [chiusura dell'esercizio](Chiusura-e-bilancio).
## Il registro
| Colonna | Significato |
![Khaemhat 0.10.0 · registro cespiti](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/cespiti-registro.png)
*Il registro dell'azienda demo: quattro beni con categoria, aliquota, entrata in funzione, costo storico, fondo e
valore netto; sotto, il piano di ammortamento del furgone selezionato e il dettaglio con i movimenti.*
La striscia in alto riassume i cespiti **attivi**, il **costo storico**, il **fondo** e il **valore netto**. Si filtra
per testo (codice, descrizione, matricola), esercizio, categoria e stato. Un clic sulla riga apre sotto:
- il **piano di ammortamento**: per ogni esercizio il fondo iniziale, l'aliquota, la quota civilistica e quella
fiscale, il fondo e il valore netto a fine anno; l'anno scelto nei filtri è evidenziato;
- il **dettaglio**: categoria, data di acquisto, fornitore e documento, ubicazione, fondo fiscale, ultimo esercizio
ammortizzato e l'elenco dei **movimenti** (acquisto, apertura, incremento, rivalutazione, ammortamento,
dismissione); da qui **Modifica**, **Dismetti** ed **Elimina**.
| Stato | Significato |
|---|---|
| **Codice** | automatico, maschera `CESP-{seq:0000}` (es. `CESP-0041`; vedi [Tabelle azienda](Tabelle-azienda)) |
| Descrizione, Categoria, Coeff. | il coefficiente viene dalla categoria |
| Acquisto | data di entrata in funzione / acquisto |
| Costo storico, Fondo, Residuo | valori alla data |
| Quota anno | quota di ammortamento dell'esercizio |
| Stato | *In uso*, *Primo anno (50 %)*, *Limite fiscale raggiunto*, *Ammortizzato*, *Dismesso* (con plus o minusvalenza) |
| **In ammortamento** | il bene ha ancora un valore da ammortizzare |
| **Ammortizzato** | il fondo ha raggiunto il costo (meno l'eventuale valore residuo) |
| **Dismesso** | il bene è uscito dal patrimonio; resta nel registro con il movimento di dismissione |
Filtri per esercizio, categoria e stato. In testa un avviso ricorda se gli ammortamenti dell'anno non sono ancora
contabilizzati. Il pannello **Dati cespite** mostra categoria e coefficiente, **conto cespite**, **conto fondo**,
**conto quota** (ammortamento), fattura di acquisto, percentuale di deducibilità e ubicazione.
## Inserire un cespite
Un cespite nasce di solito dalla **fattura di acquisto** (righe con articolo di tipo *cespite*, vedi
[Acquisti](Acquisti)) oppure si inserisce a mano con **+**.
1. **Registro cespiti → Nuovo cespite**.
2. Scegli la **categoria** (aliquote e conti vengono da lì) e scrivi la descrizione. Il **codice** vuoto prende il
prossimo numero; la matricola e l'ubicazione sono facoltative.
3. Indica **data di acquisto** e **data di entrata in funzione**: l'ammortamento parte dall'anno di entrata in
funzione, che non può precedere l'acquisto.
4. Scrivi il **costo** e, se serve, il valore residuo. Le aliquote civilistica e fiscale vuote seguono la categoria;
compilale solo per il singolo bene.
5. Per un bene acquistato **prima dell'avvio di Khaemhat** indica i **fondi iniziali** (civilistico e fiscale) e
l'**ultimo esercizio già ammortizzato** fuori da Khaemhat: i fondi entrano con la scrittura di apertura dei conti.
Facoltativi anche quantità, fornitore, documento di acquisto, ubicazione e matricola.
6. Salva. Il piano si ricalcola subito.
Un cespite con ammortamenti già registrati non si elimina: si dismette.
## Categorie e coefficienti
Le **categorie** sono caricate con i dati di base e riportano i coefficienti della tabella ministeriale (**DM 31
dicembre 1988**), per esempio fabbricati industriali, macchinari, automezzi, autovetture, macchine elettroniche
d'ufficio. Per ogni categoria si impostano:
![Khaemhat 0.10.0 · categorie cespiti](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/cespiti-categorie.png)
*Le categorie standard create dal pacchetto fiscale italiano, con le aliquote e i conti di cespite, fondo e quota.*
- coefficiente fiscale e coefficiente civilistico (possono differire);
- conti contabili (cespite, fondo, quota, plus/minusvalenze);
- eventuale **limite di costo fiscalmente rilevante** e **percentuale di deducibilità** (vedi autovetture);
- se applicare la riduzione al 50 % nel primo esercizio.
**Cespiti → Categorie → Categorie standard** crea le categorie più comuni con i coefficienti della tabella allegata
al **DM 31/12/1988** (fabbricati, impianti, attrezzature, mobili, macchine d'ufficio elettroniche, autocarri,
autovetture, software e altri beni immateriali con i limiti dell'art. 103 TUIR). La tabella dipende dal settore di
attività: ogni aliquota si può cambiare sulla propria categoria.
## Regole di ammortamento
| Campo | A cosa serve |
|---|---|
| **Tipo** | materiale o immateriale (decide la voce di bilancio del fondo) |
| **Aliquota civilistica** e **fiscale** | la quota annua in percentuale; la fiscale non supera il coefficiente ministeriale |
| **Metà aliquota civilistica nel primo esercizio** | applica la riduzione al 50 % anche al piano civilistico (quello fiscale la applica sempre) |
| **Limite di costo** e **deducibilità %** | per le autovetture (art. 164 TUIR): ad esempio 18.075,99 di costo e 20 % di deducibilità |
| **Conto del cespite**, **del fondo**, **dell'ammortamento** | i conti della scrittura di fine anno e della dismissione |
## Regole di calcolo
| Regola | Come la applica Khaemhat |
|---|---|
| **Primo anno al 50 %** | nell'esercizio di entrata in funzione la quota fiscale è la metà di quella ordinaria |
| **Civilistico e fiscale** | due piani paralleli (quota e fondo civilistici, quota e fondo fiscali); le differenze restano visibili nel piano |
| **Autovetture** | limite al costo fiscalmente rilevante e deducibilità ridotta secondo la normativa (art. 164 TUIR); i valori sono parametri della categoria, oggi € 18.075,99 di costo massimo per le autovetture a uso promiscuo, e vanno verificati a ogni aggiornamento normativo |
| **Beni di costo non superiore a € 516,46** | possono essere ammortizzati interamente nell'esercizio di acquisto |
| **Fine ammortamento** | la quota si azzera quando il residuo arriva a zero (stato *Ammortizzato*) |
| **Quote costanti** | aliquota per costo, mai più di quanto resta da ammortizzare |
| **Primo anno al 50 %** | nel piano fiscale sempre; nel civilistico se la categoria lo chiede |
| **Civilistico e fiscale** | due piani paralleli; la differenza è una variazione in dichiarazione dei redditi e non genera scritture |
| **Beni di costo unitario fino a 516,46 €** | si mettono in una categoria con aliquota 100 %: sono ammortizzati per intero nel primo anno |
| **Fine ammortamento** | quando il fondo raggiunge il costo il bene passa a *Ammortizzato* |
Il **piano di ammortamento** (riquadro in basso nel mockup) elenca per ogni esercizio quota e fondo civilistici,
quota e fondo fiscali, residuo e stato: *Contabilizzato* per gli anni registrati, *Simulato* per quelli futuri.
## Ammortamenti di fine anno
## Piano simulato
![Khaemhat 0.10.0 · ammortamenti](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/cespiti-ammortamenti.png)
*Gli ammortamenti 2026 dell'azienda demo prima della registrazione: quote civilistiche e fiscali per cespite e
totali.*
Il piano degli esercizi futuri è sempre una **simulazione**: cambia se si modificano coefficiente, valore o date.
Serve a prevedere le quote dei prossimi anni (budget, bilancio previsionale) senza produrre registrazioni.
1. **Cespiti → Ammortamenti**, scegli l'esercizio.
2. Controlla le quote: la striscia mostra il totale civilistico, quello fiscale e la loro differenza.
3. **Registra ammortamenti** scrive una registrazione al 31/12 con una riga per categoria (quota in Dare sul conto di
ammortamento, fondo in Avere) e aggiorna fondi e movimenti dei beni.
4. Finché le registrazioni non sono definitive, **Annulla registrazione** toglie la scrittura e riporta i fondi
indietro.
## Calcolo e contabilizzazione annuale
1. **Cespiti → Registro cespiti**, scegli l'esercizio e premi **Calcola ammortamenti AAAA**.
2. Controlla le quote calcolate e gli stati (primo anno, limite fiscale raggiunto…).
3. Premi **Contabilizza**: viene generata la registrazione con causale **AMM** (quote a costo, fondi in avere).
4. Le quote dell'esercizio risultano *Contabilizzate* nel piano.
Il calcolo è anche il passo 2 della [chiusura dell'esercizio](Contabilita) e la procedura **Ammortamenti** del catalogo
([Automazioni](Automazioni)). La procedura è idempotente: rieseguirla non duplica le quote.
Il passo 2 della [chiusura](Chiusura-e-bilancio) registra gli ammortamenti se non sono già stati registrati qui.
## Dismissioni
1. Apri il cespite e scegli l'azione di dismissione (per esempio vendita o eliminazione; l'elenco dei tipi di
movimento sarà fissato in sviluppo).
2. Se è una **vendita**, Khaemhat propone la fattura di **cessione cespite (TD26)** in [Vendite](Vendite).
3. Alla data di dismissione calcola la quota dell'anno, chiude fondo e costo e rileva la **plusvalenza** o la
**minusvalenza** sui conti della categoria.
4. Il cespite passa allo stato *Dismesso* e resta nel registro.
1. Seleziona il cespite e premi **Dismetti**.
2. Indica data e **prezzo** (la contropartita è il conto *altri crediti*, che si chiude con l'incasso o con la
fattura). Il **costo dismesso** vuoto significa dismissione totale; un importo minore è una dismissione parziale.
3. Khaemhat toglie dai conti il costo e la quota corrispondente del fondo, porta il prezzo sulla contropartita e la
differenza a **plusvalenza** o **minusvalenza** (conti del pacchetto fiscale).
4. Nell'anno della dismissione non si calcola la quota di ammortamento (scelta prudente spiegata nell'ADR 0041): se
serve, registra prima gli ammortamenti fino alla data con una registrazione manuale.
## Rivalutazioni
La fattura di vendita del bene si emette come una normale fattura in [Vendite](Vendite).
Le **rivalutazioni** aumentano il valore del bene (e, a seconda della norma, il fondo) da una data; il piano di
ammortamento si ricalcola da quella data. Le modalità di ogni specifica legge di rivalutazione saranno definite in
sviluppo quando servono.
## Stampa del registro
## Registro dei beni ammortizzabili
**Stampa registro** (dal registro o dagli ammortamenti) produce il PDF del registro dei beni ammortizzabili
dell'esercizio, con costo, fondo, quota e valore netto per categoria. La stampa definitiva è una delle stampe del
passo 9 della [chiusura](Chiusura-e-bilancio).
**Registro cespiti** stampa il registro dei beni ammortizzabili (provvisorio o definitivo). La stampa definitiva è
uno dei passi della [chiusura dell'esercizio](Contabilita). Il registro si esporta anche in XLSX e PDF.
## Dati di esempio
I dati dimostrativi creano le categorie standard e quattro beni (un furgone, scaffalature, arredi già in uso con i
fondi iniziali, e un server acquistato nell'anno con la sua registrazione), così il registro, gli ammortamenti e la
chiusura si possono provare subito. Vedi [Dati di base e di esempio](Dati-di-base-e-esempio).
## Permessi e licenza
Serve il modulo **ASSET**; per contabilizzare servono anche ACCT e i permessi di prima nota. I codici dei permessi in
testa sono indicativi (convenzione `modulo.entità.azione`, SPEC §7.2) e saranno fissati in sviluppo.
| Permesso | Consente |
|---|---|
| `assets.asset.read` | registro, piano, ammortamenti (sola lettura), stampe |
| `assets.asset.write` | inserire, modificare, eliminare e dismettere cespiti; categorie |
| `assets.depreciation.post` | registrare e annullare gli ammortamenti |
Serve il modulo **ASSET**; le registrazioni richiedono anche **ACCT**.
## Domande frequenti
**Ho contabilizzato e poi corretto un coefficiente.** Annulla la registrazione AMM (storno) e rilancia il calcolo:
la procedura ricalcola le quote dell'esercizio.
**Ho registrato gli ammortamenti e poi corretto un'aliquota.** Annulla la registrazione, correggi e registra di nuovo:
è possibile finché la registrazione non è definitiva.
**Il bene è in uso da metà anno: la quota fiscale è ridotta?** Sì, se la categoria applica il primo anno al 50 %.
**Perché la quota fiscale è diversa dalla civilistica?** Le aliquote possono differire e il primo anno al 50 % vale
sempre per il fiscale; la differenza si gestisce in dichiarazione dei redditi.
## Pagine correlate
[Contabilità](Contabilita) · [Acquisti](Acquisti) · [Vendite](Vendite) · [IVA](IVA) · [Automazioni](Automazioni) ·
[Report](Report) · [Fiscalità italiana](Fiscalita-italiana)
[Chiusura e bilancio](Chiusura-e-bilancio) · [Contabilità](Contabilita) · [Acquisti](Acquisti) · [Vendite](Vendite) ·
[Fiscalità italiana](Fiscalita-italiana)
+4 -1
View File
@@ -1,6 +1,6 @@
# Changelog
> **Stato:** completa per 0.7.0 · **Ultima revisione:** 2026-11-13
> **Stato:** completa per 0.10.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.10.0 | 2026-11-13 | M10 — Cespiti, Intrastat, chiusura, bilancio: categorie con i coefficienti ministeriali, registro cespiti con piano civilistico e fiscale, ammortamenti e dismissioni; elenchi Intrastat dai documenti con periodicità dalle soglie e file SCAMBI.CEE; registro delle dichiarazioni d'intento con plafond controllato alla conferma della fattura; ratei, risconti e differenze di cambio; chiusura guidata in nove passi con riapertura, stampe definitive e blocco; bilancio CEE ordinario, abbreviato e micro con riclassificato, indici ed export per il commercialista |
| 0.9.0 | 2026-11-13 | M9 — Fatturazione elettronica: file FatturaPA con controllo prima dell'invio e i codici dello SDI; canali PEC, SdICoop e due intermediari con regole di instradamento e canale di riserva; lettura dei canali ogni 15 minuti e ricezione push di SdICoop; notifiche che aggiornano file e documenti; correzione degli scarti; copia di cortesia PDF con l'XML allegato; fatture ricevute da registrare; pacchetti per la conservazione; fatturazione elettronica nei dati di esempio e rimozione dei dati di esempio. |
| 0.8.0 | 2026-11-13 | M8 — Scadenzario e tesoreria: partite aperte con aging, incassi e pagamenti con abbuoni, spese e differenze cambio; distinte RiBa, SDD e bonifici SEPA con insoluti, mandati SDD; riconciliazione bancaria CSV, CBI e CAMT.053 con abbinamento automatico; solleciti con interessi di mora; flusso di cassa; tesoreria nei dati di esempio. |
| 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. |
+157
View File
@@ -0,0 +1,157 @@
# Chiusura dell'esercizio e bilancio
> **Stato:** completa per la versione 0.10 · **Ultima revisione:** 2026-11-13 · **Versione software:** 0.10.0 (M10)
> **Modulo di licenza:** ACCT · **Permessi principali:** `ledger.year.close` (ratei e risconti, chiusura, blocco),
> `ledger.entry.read` (bilancio), `reports.accountant.export` (esportazione per il commercialista) · **Specifica:**
> SPEC §11.7, ADR 0043
A fine anno la contabilità va **assestata** (ammortamenti, ratei e risconti, rimanenze, accantonamenti), **chiusa**
(conti economici e patrimoniali) e **riaperta** nell'esercizio successivo; poi si stampano i libri definitivi e si
redige il **bilancio**. Khaemhat guida tutto in **nove passi**, ognuno ripetibile e annullabile fino alle stampe
definitive, e mostra il bilancio CEE, il riclassificato e gli indici in ogni momento dell'anno.
## Dove si trova
Menu **Contabilità**: **Ratei e risconti**, **Chiusura esercizio**, **Bilancio** (schede *Verifica*, *CEE*,
*Riclassificato*, *Indici*). Gli ammortamenti stanno in [Cespiti](Cespiti).
## Ratei e risconti
![Khaemhat 0.10.0 · ratei e risconti](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/ratei-risconti.png)
*I ratei e risconti 2026 dell'azienda demo: il risconto attivo del premio di assicurazione del furgone, pagato il
1° ottobre per dodici mesi, di cui 273 giorni su 365 sono di competenza del 2027.*
I costi e i ricavi che stanno a cavallo di due esercizi si ripartiscono **per giorni**:
| Tipo | Quando | Scrittura al 31/12 |
|---|---|---|
| **Rateo attivo** | ricavo di competenza dell'anno che si incasserà dopo | ratei attivi in Dare, ricavo in Avere |
| **Rateo passivo** | costo di competenza dell'anno che si pagherà dopo | costo in Dare, ratei passivi in Avere |
| **Risconto attivo** | costo già registrato, in parte di competenza dell'anno dopo | risconti attivi in Dare, costo in Avere |
| **Risconto passivo** | ricavo già registrato, in parte di competenza dell'anno dopo | ricavo in Dare, risconti passivi in Avere |
1. **Contabilità → Ratei e risconti**, scegli l'esercizio.
2. **Proponi dai documenti** crea i risconti delle fatture di acquisto registrate sui conti di costi che di solito
stanno a cavallo dell'anno (assicurazioni, affitti, leasing, noleggi, software, abbonamenti), con un periodo di
dodici mesi dalla data del documento: **controlla sempre il periodo**. Un costo già proposto non si ripropone.
3. **Nuovo rateo o risconto** per inserirne uno a mano: tipo, conto, descrizione, importo totale e periodo di
competenza. La **rettifica** si calcola subito (giorni fuori dall'esercizio su giorni totali).
4. Un clic sulla riga la modifica o la elimina, finché la chiusura non l'ha registrata.
Sotto, **Differenze di cambio al 31/12** elenca le partite aperte in valuta con il residuo in valuta, il cambio del
documento, il cambio dell'ultimo giorno dell'anno (da *Tabelle azienda → Valute*, aggiornato anche dai cambi BCE) e
l'**utile o perdita su cambi**. Se il cambio manca la riga lo segnala.
Il **passo 3** della chiusura registra ratei, risconti e differenze di cambio; il **passo 8** li storna il primo giorno
dell'esercizio successivo.
## La chiusura guidata
![Khaemhat 0.10.0 · chiusura esercizio](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/chiusura-esercizio.png)
*La chiusura 2026 dell'azienda demo con i nove passi eseguiti: per ognuno le registrazioni, l'importo, l'esito e chi
l'ha eseguito; sotto, le stampe definitive da scaricare.*
**Contabilità → Chiusura esercizio**, scegli l'esercizio e premi **Esegui passo N**. I passi si eseguono **in
ordine**; l'ultimo eseguito si può **ripetere** (dopo una correzione) o **annullare** (le sue registrazioni
spariscono) finché non si arriva alle stampe definitive. In alto i badge mostrano lo stato degli esercizi (*aperto*,
*in chiusura*, *chiuso*).
| # | Passo | Cosa fa |
|---|---|---|
| 1 | **Controlli preliminari** | nessuna registrazione provvisoria, registrazioni quadrate, bilancio di verifica in pareggio; segnala i conti con saldo senza voce di bilancio, l'esercizio non ancora terminato e gli esercizi precedenti ancora aperti. L'importo è il risultato provvisorio |
| 2 | **Ammortamenti** | registra le quote civilistiche dei [cespiti](Cespiti), una riga per categoria, se non sono già registrate |
| 3 | **Ratei e risconti** | registra ratei, risconti e differenze di cambio al 31/12 |
| 4 | **Rimanenze finali** | storna le rimanenze iniziali a costo e carica le rimanenze finali di [magazzino](Magazzino) al **costo medio ponderato** |
| 5 | **Accantonamenti** | svalutazione crediti dello **0,5 %** dei crediti verso clienti aperti (limite dell'art. 106 TUIR) e quota **TFR** dell'anno (retribuzioni diviso 13,5, meno quanto già accantonato dalle paghe) |
| 6 | **Chiusura conti economici** | gira costi e ricavi a *Conto economico* e porta il **risultato** (utile o perdita) a patrimonio netto; l'esercizio passa a *in chiusura* |
| 7 | **Chiusura conti patrimoniali** | chiude attività e passività a *Stato patrimoniale finale*, per conto e per cliente o fornitore |
| 8 | **Apertura esercizio successivo** | crea l'esercizio se manca, riapre i conti con *Stato patrimoniale iniziale* (partite di clienti e fornitori comprese) e storna ratei e risconti |
| 9 | **Stampe definitive** | rende **definitive** tutte le registrazioni dell'anno, numera il libro giornale e conserva le stampe: libro giornale, registri IVA, registro cespiti, bilancio CEE |
Accanto a ogni passo compaiono i messaggi: in grigio le informazioni, in arancione ciò che va verificato, in rosso gli
errori che bloccano (il passo 1 con un errore non lascia proseguire).
![Khaemhat 0.10.0 · controlli preliminari](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/chiusura-controlli.png)
*Il passo 1 eseguito a novembre: tutto quadra, ma l'esercizio non è ancora terminato e la chiusura risulta
anticipata (esito «Da verificare»).*
### Prima del passo 9
Il passo 9 **non si annulla**: prima controlla il bilancio, i registri IVA (le stampe dei registri dentro la chiusura
sono quelle dell'anno; per la vidimazione e la numerazione delle pagine fa fede [IVA](IVA)), i cespiti e i ratei.
Le registrazioni del nuovo esercizio si possono fare anche durante la chiusura.
### Blocco dell'esercizio
Dopo il passo 9 **Blocca esercizio** chiude definitivamente l'anno: diventa di **sola lettura** e non si può più
registrare nulla con data fino al 31/12. L'esercizio passa a *chiuso*.
## Bilancio CEE
![Khaemhat 0.10.0 · bilancio CEE](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/bilancio-cee.png)
*Il bilancio CEE 2026 dell'azienda demo, schema ordinario: stato patrimoniale e conto economico con l'anno
precedente e la variazione percentuale.*
**Contabilità → Bilancio → CEE** costruisce lo **stato patrimoniale** (art. 2424 c.c.) e il **conto economico**
(art. 2425 c.c.) dell'esercizio scelto, con l'anno precedente e la variazione, dai saldi dei conti a cui il piano dei
conti associa una **voce di bilancio** (vedi [Contabilità](Contabilita#piano-dei-conti)).
- **Schema**: *Ordinario*, *Abbreviato* (art. 2435-bis) o *Micro-impresa* (art. 2435-ter, stesse voci
dell'abbreviato).
- La striscia mostra totale attivo e passivo, risultato d'esercizio e quadratura.
- Se ci sono conti con saldo **senza voce**, un avviso li elenca: assegna la voce nel piano dei conti.
- Un clic su una voce mostra i **conti** che la compongono con i saldi dei due anni.
- Le scritture dei passi 6 e 7 della chiusura non entrano nel calcolo: un esercizio chiuso mostra comunque i suoi
saldi.
- **Stampa bilancio** produce il PDF; **Esporta per il commercialista** scarica uno ZIP con cinque file CSV (piano
dei conti, bilancio di verifica, movimenti, stato patrimoniale, conto economico).
## Riclassificato e indici
![Khaemhat 0.10.0 · riclassificato](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/bilancio-riclassificato.png)
*Lo stato patrimoniale riclassificato secondo il criterio finanziario.*
La scheda **Riclassificato** propone lo **stato patrimoniale finanziario** (attivo per liquidità, passivo per
esigibilità) e il **conto economico a valore aggiunto**.
![Khaemhat 0.10.0 · indici](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/bilancio-indici.png)
*Gli indici di bilancio con la formula e il valore dei due anni.*
La scheda **Indici** calcola redditività (ROE, ROI, ROS, rotazione del capitale investito), liquidità (indice di
disponibilità e di liquidità), solidità (indipendenza finanziaria, leva, copertura delle immobilizzazioni) e i giorni
medi di incasso e di pagamento. Un indice senza denominatore mostra un trattino.
## Prova con i dati di esempio
I dati dimostrativi aprono l'anno con una scrittura di apertura (cespiti e fondi, rimanenze, banca, capitale),
registrano un premio di assicurazione da riscontare e i cespiti: la chiusura dell'anno demo si può eseguire dal
passo 1 al 9 e verificare il bilancio. Le prove automatiche fanno proprio questo, su SQLite e su PostgreSQL.
## Permessi e licenza
| Permesso | Consente |
|---|---|
| `ledger.entry.read` | bilancio CEE, riclassificato, indici, stampa |
| `ledger.year.close` | ratei e risconti, chiusura guidata, blocco dell'esercizio |
| `reports.accountant.export` | esportazione per il commercialista |
Serve il modulo **ACCT**; il passo 2 usa i cespiti se è attivo **ASSET**.
## Domande frequenti
**Il passo 1 è rosso.** Leggi i messaggi: di solito ci sono registrazioni provvisorie da registrare o eliminare in
[Prima nota](Contabilita#prima-nota). Correggi e premi **Ripeti passo 1**.
**Ho dimenticato una fattura dopo il passo 6.** Annulla i passi dal più recente fino al 5 (uno alla volta), registra
la fattura e riesegui i passi.
**Dove finisce il risultato?** Nel conto *utile (perdita) dell'esercizio* del patrimonio netto; la destinazione
dell'utile si registra a mano nel nuovo esercizio dopo l'approvazione del bilancio.
**Il TFR è giusto?** È una stima (retribuzioni dell'anno diviso 13,5 meno quanto già accantonato): se le paghe sono
elaborate fuori, registra la quota del consulente e la chiusura non aggiunge nulla.
## Pagine correlate
[Contabilità](Contabilita) · [Cespiti](Cespiti) · [IVA](IVA) · [Magazzino](Magazzino) · [Scadenzario](Scadenzario) ·
[Fiscalità italiana](Fiscalita-italiana) · [Report](Report)
+12 -11
View File
@@ -1,6 +1,6 @@
# Contabilità generale
> **Stato:** completa per la versione 0.7 · **Ultima revisione:** 2026-11-13 · **Versione software:** 0.7.0 (M7)
> **Stato:** completa per la versione 0.10 · **Ultima revisione:** 2026-11-13 · **Versione software:** 0.10.0 (M10)
> **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
Il modulo **Contabilità** tiene la **contabilità generale in partita doppia** dell'azienda: piano dei conti, causali,
@@ -16,9 +16,10 @@ nella pagina [IVA](IVA); le regole italiane usate (piano dei conti modello, codi
> 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.
> Dalla 0.8 incassi, pagamenti, distinte e riconciliazione bancaria scrivono le loro registrazioni dallo
> [Scadenzario](Scadenzario). Dalla 0.10 ci sono la **chiusura guidata dell'esercizio** con ratei e risconti, il
> **bilancio CEE** con riclassificato e indici e l'export per il commercialista ([Chiusura e bilancio](Chiusura-e-bilancio)),
> e i [Cespiti](Cespiti). Non c'è ancora l'import del piano dei conti da file.
## Dove si trova
@@ -170,12 +171,12 @@ 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,
*L'albero dei 240 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
di base dell'azienda viene caricato il modello **PMI standard** del pacchetto fiscale: 240 conti con le voci di
bilancio CEE già associate (vedi [Fiscalità italiana](Fiscalita-italiana#piano-dei-conti-modello)).
| Campo | Significato |
@@ -188,7 +189,7 @@ bilancio CEE già associate (vedi [Fiscalità italiana](Fiscalita-italiana#piano
| **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) |
| **Chiuso in automatico a fine esercizio** | il conto è chiuso dalla [chiusura dell'esercizio](Chiusura-e-bilancio) |
| **Disattivato** | il conto resta nello storico ma non si usa più |
A sinistra l'**albero** con la ricerca per codice o descrizione; a destra i dati del conto scelto e, per i
@@ -244,8 +245,8 @@ Scegliendo un soggetto si vedono:
- 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).
Le partite nascono dai documenti e si chiudono con gli incassi e i pagamenti registrati nello
[Scadenzario](Scadenzario), dove ci sono anche distinte, solleciti e riconciliazione bancaria.
## Bilancio di verifica e libro giornale
@@ -270,8 +271,8 @@ Le stampe sono file PDF da scaricare:
| **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).
Le altre schede della pagina, **CEE**, **Riclassificato** e **Indici**, mostrano il bilancio d'esercizio: sono
spiegate in [Chiusura e bilancio](Chiusura-e-bilancio).
## Dati demo
+4 -1
View File
@@ -74,7 +74,10 @@ Nella versione 0.3.0 le righe vengono da:
| Fatto oggi | attività programmate riuscite oggi, una riga per attività con il numero di esecuzioni e l'ora dell'ultima |
| Scadenze 30 giorni | fine della prova o scadenza della licenza (account di istanza) |
I moduli delle prossime versioni aggiungono le loro righe (scarti SDI, liquidazioni, incassi, ordini da evadere…).
Dalla 0.8 lo [Scadenzario](Scadenzario) aggiunge alle **Scadenze** gli incassi e i pagamenti dei prossimi giorni (al
massimo 12, area *Tesoreria*) e a **Da fare oggi** il totale dei crediti scaduti, con il link ai solleciti; servono
il modulo FIN e il permesso `finance.schedule.read`. I moduli delle prossime versioni aggiungono le loro righe
(scarti SDI, ordini da evadere…).
Se una fonte non risponde, il widget mostra le altre e l'errore finisce nel [log](Log).
I **promemoria** si scrivono nel campo in fondo al widget e si aggiungono con Invio (al massimo 20, di 300 caratteri
+61 -10
View File
@@ -1,6 +1,6 @@
# Dati di base e di esempio
> **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)
> **Stato:** completa per la versione 0.10 · **Ultima revisione:** 2026-11-13 · **Versione software:** 0.10.0 (M10)
> **Modulo di licenza:** CORE · **Livello richiesto:** amministratore (rimozione dati di esempio: super utente) · **Specifica:** SPEC §6, §12.11, §14
## A cosa serve
@@ -52,7 +52,6 @@ Il pacchetto italiano fa parte del pacchetto fiscale Italia (vedi [Fiscalità it
| **Cespiti** | categorie di beni con i coefficienti di ammortamento ministeriali |
| **Codici tributo F24** | IVA, ritenute, bollo, acconti |
| **Code list SDI** | tipi documento (TD), modalità di pagamento (MP), regimi fiscali (RF) e altre liste della FatturaPA; regime RF01 predefinito |
| **Banche ABI/CAB** | tabella per ricavare banca e BIC dall'IBAN |
| **CRM** | pipeline e fasi, modelli e-mail |
| **Sistema** | ruoli predefiniti, regole di automazione predefinite, attività programmate di sistema |
@@ -76,11 +75,13 @@ intervallo come `10121-10156` per le città con più CAP.
Ai comuni rinominati o nati da fusioni recenti (ad esempio Sanremo) il CAP può mancare: si completa a mano nella
tabella *Comuni* o con l'**Importa CSV** (colonne `Code` e `PostalCodes`, più CAP separati da virgola). La
compilazione dal CAP propone solo i comuni che hanno il CAP scritto. Le **banche ABI/CAB** non sono ancora incluse: banca e BIC dall'IBAN vengono da un conto
dell'azienda presso la stessa banca. Un comune soppresso per fusione resta nella tabella finché non lo disattivi.
compilazione dal CAP propone solo i comuni che hanno il CAP scritto. L'**elenco delle banche ABI/CAB** non è incluso: dall'IBAN
Khaemhat legge ABI e CAB, mentre nome della banca e BIC vengono da un conto dell'azienda presso la stessa banca o si
scrivono a mano la prima volta. Un comune soppresso per fusione resta nella tabella finché non lo disattivi.
Le altre voci dell'elenco (piano dei conti, causali contabili, registri IVA, cespiti, codici tributo, CRM) arrivano con i
moduli che le usano.
Le categorie dei cespiti si creano da **Cespiti → Categorie → Categorie standard** (vedi [Cespiti](Cespiti)). Le altre
voci dell'elenco (piano dei conti, causali contabili, registri IVA, codici tributo, CRM) arrivano con i moduli che le
usano.
### Aggiorna tabelle di base
@@ -115,7 +116,7 @@ reale. Contiene:
| Articoli | 120 |
| Documenti | 12 mesi coerenti: ordini → DDT → fatture differite, fatture immediate e accompagnatorie, note di credito, pro-forma, parcelle; ordini fornitore → carichi → fatture di acquisto; autofatture; inventario, movimenti, trasferimenti |
| Contabilità | registrazioni dai documenti, incassi e pagamenti anche parziali, un insoluto RiBa, giroconti, liquidazioni IVA confermate fino al mese precedente, ritenute, 58 cespiti con ammortamenti, esercizio precedente chiuso con bilancio |
| Fatturazione elettronica | XML SDI in stati diversi, con notifiche |
| Fatturazione elettronica | file FatturaPA in stati diversi con le notifiche, canali e regole di instradamento, fatture ricevute da registrare |
| Tesoreria | un estratto conto da riconciliare |
| CRM | 23 lead, 18 opportunità, attività, 3 campagne, 2 ticket |
| Servizi e canali | 2 contratti di assistenza con interventi, 1 canale e-commerce generico con ordini |
@@ -160,7 +161,47 @@ l'azienda ha già documenti di vendita.
| 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.
Il caricamento non si ripete se l'azienda ha già documenti di acquisto o di magazzino.
**Da M7** documenti e fatture sono **contabilizzati** e ci sono un noleggio ricorrente, le liquidazioni IVA
confermate fino al mese precedente, le ritenute e il bollo virtuale (vedi [Contabilità](Contabilita) e [IVA](IVA)).
**Da M8**, se la licenza comprende il modulo **FIN**, c'è anche la **tesoreria** (vedi [Scadenzario](Scadenzario)):
| Dati | Che cosa mostrano |
|---|---|
| La banca *Banca Popolare Dimostrativa* | conto predefinito con IBAN, SIA, CUC e identificativo creditore; i versamenti dei soci al 1° gennaio |
| Incassi e pagamenti | i fornitori scaduti pagati con le spese, i clienti scaduti incassati (uno solo in parte), con il CRO |
| Distinte RiBa | una distinta presentata e accreditata con l'ultimo effetto **insoluto** e le spese; una distinta *salvo buon fine* in bozza con le scadenze dei prossimi 45 giorni |
| Mandato SDD | un mandato *Core* firmato da un cliente |
| Estratto conto | un CSV di quattro movimenti da riconciliare: il saldo della fattura incassata in parte, un pagamento già registrato, le commissioni riconosciute dalla regola *Canone e commissioni* e una spesa da registrare su conto |
| Solleciti | un primo sollecito già inviato al cliente con lo scaduto più vecchio |
**Da M9**, se la licenza comprende il modulo **EINV**, c'è anche la **fatturazione elettronica** (vedi
[Fatturazione elettronica](Fatturazione-elettronica)):
| Dati | Che cosa mostrano |
|---|---|
| File FatturaPA | le fatture e le note già emesse hanno il loro file: la maggior parte **consegnata** (RC), una **scartata** (NS 00305) e poi corretta e consegnata, una con **mancata consegna** (MC), le ultime in attesa o ancora da inviare |
| Notifiche | le ricevute di ogni file, scaricabili come sono arrivate |
| Canali | la PEC configurata ma **in pausa** con credenziali finte, l'Intermediario A abbozzato e disattivato: nessun dato di esempio raggiunge lo SDI |
| Instradamento | tre regole: PA su PEC, oltre 200 file al giorno sull'Intermediario A, sempre PEC con l'Intermediario A di riserva |
| Fatture ricevute | tre fatture di fornitori da registrare |
**Da M10** ci sono anche i dati di **fine anno** (vedi [Cespiti](Cespiti), [Intrastat](Intrastat),
[Dichiarazioni d'intento](Dichiarazioni-d-intento) e [Chiusura e bilancio](Chiusura-e-bilancio)):
| Dati | Che cosa mostrano |
|---|---|
| Apertura dei conti | una registrazione al 1° gennaio con cespiti e fondi, rimanenze di magazzino, banca, capitale sociale e utili portati a nuovo |
| Cespiti | le categorie standard e quattro beni: furgone, scaffalature e arredi già in uso con i fondi iniziali, un server acquistato nell'anno con la sua registrazione |
| Risconto | il premio di assicurazione del furgone pagato il 1° ottobre per dodici mesi |
| Dichiarazione d'intento | quella di Idrotermica Piemonte nel registro, con una fattura in N3.5 che consuma il plafond |
| Intrastat | una fattura non imponibile art. 41 a Bergwerk Bau (Austria) con codici doganali e pesi, se la licenza comprende **INTRA** |
Con questi dati la chiusura dell'anno si esegue dal passo 1 al 9.
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.
@@ -175,8 +216,13 @@ alternativa si caricano al primo avvio con `KHAEMHAT_SEED_DEMO=true` (solo se il
### Rimuovi dati di esempio
1. Premi **Rimuovi dati di esempio** (solo **super utente**).
2. Khaemhat elimina le righe dimostrative in ordine di dipendenza e **si rifiuta** se esistono dati reali collegati
a righe dimostrative (ad esempio una fattura vera intestata a un cliente demo).
2. Khaemhat elimina le righe dimostrative (`is_demo`) e quelle che appartengono loro (le righe di un documento demo,
le giacenze di un articolo demo) in **una sola transazione**, e **si rifiuta** se esistono dati reali collegati a
righe dimostrative (ad esempio una fattura vera intestata a un cliente demo): in quel caso elenca le tabelle
coinvolte e non tocca nulla.
Le tabelle e i loro collegamenti si leggono dalle migrazioni, quindi la rimozione copre anche i moduli aggiunti in
seguito. Da riga di comando: `scripts/seed.sh --remove-demo [--company CODICE]` (vedi sotto).
Usalo quando un'azienda nata come demo diventa l'azienda reale; per partire puliti è comunque preferibile creare
un'azienda nuova (vedi [Istanza e database](Istanza-e-database)).
@@ -203,6 +249,7 @@ docker compose run --rm --entrypoint /app/scripts/seed.sh khaemhat --base
docker compose run --rm --entrypoint /app/scripts/seed.sh khaemhat --base --company DEMO
docker compose run --rm --entrypoint /app/scripts/seed.sh khaemhat --demo --company DEMO
docker compose run --rm --entrypoint /app/scripts/seed.sh khaemhat --demo --scale 10 --company PROVA
docker compose run --rm --entrypoint /app/scripts/seed.sh khaemhat --remove-demo --company DEMO
```
In sviluppo, dalla cartella del repository: `scripts/seed.sh --base|--demo [--scale N] [--company CODICE]`.
@@ -212,8 +259,12 @@ In sviluppo, dalla cartella del repository: `scripts/seed.sh --base|--demo [--sc
| `--base` | aggiunge i codici di base mancanti |
| `--demo` | prima i dati di base, poi i dati di esempio; ogni gruppo (anagrafiche, articoli) si carica solo nell'azienda che non ne ha ancora |
| `--scale N` | solo con `--demo`: ripete il catalogo articoli N volte (da 1 a 100), per le prove di prestazione |
| `--remove-demo` | rimuove solo i dati di esempio (non si combina con le altre opzioni); stampa le righe rimosse per tabella o le tabelle che lo impediscono |
| `--company CODICE` | lavora solo su quell'azienda invece che su tutte quelle attive |
Il caricamento completo dell'azienda di esempio richiede pochi secondi su SQLite (circa 2,5 s in sviluppo) e stampa
il tempo impiegato per ogni azienda.
I dati di esempio si caricano anche al primo avvio con `KHAEMHAT_SEED_DEMO=true`.
## Migrazioni
+91
View File
@@ -0,0 +1,91 @@
# Dichiarazioni d'intento
> **Stato:** completa per la versione 0.10 · **Ultima revisione:** 2026-11-13 · **Versione software:** 0.10.0 (M10)
> **Modulo di licenza:** CORE · **Permessi principali:** `sales.intent.read` (registro e stampa), `sales.intent.write`
> (inserire, modificare, revocare) · **Specifica:** SPEC §11.7, ADR 0042
Gli **esportatori abituali** acquistano senza IVA, entro un **plafond**, presentando al fornitore una **dichiarazione
d'intento** trasmessa all'Agenzia delle Entrate. Khaemhat tiene il **registro cronologico** delle dichiarazioni
ricevute dai clienti (e di quelle emesse verso i fornitori), aggiorna l'**utilizzato** con le fatture emesse,
avvisa quando il plafond è quasi esaurito e **rifiuta la conferma** di una fattura senza dichiarazione valida o oltre
il plafond.
## Dove si trova
**Fatturazione elettronica → Dichiarazioni d'intento** (anche all'indirizzo `/vendite/dichiarazioni-intento`). La
funzione è nel modulo base CORE.
![Khaemhat 0.10.0 · dichiarazioni d'intento](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/dichiarazioni-intento.png)
*Il registro delle dichiarazioni ricevute nel 2026: la dichiarazione di Idrotermica Piemonte con protocollo
telematico, plafond, utilizzato, residuo e percentuale di utilizzo.*
## Il registro
Due schede: **Ricevute (clienti)** ed **Emesse (fornitori)**, filtrate per esercizio.
| Colonna | Significato |
|---|---|
| **Numero**, **Data** | numero progressivo del registro e data della dichiarazione |
| **Cliente** / **Fornitore**, **Codice** | la controparte |
| **Protocollo telematico** | protocollo della ricevuta dell'Agenzia: 17 cifre, trattino (o barra) e 6 cifre di progressivo |
| **Plafond**, **Utilizzato**, **Residuo** | importo dichiarato, fatture già emesse, quanto resta |
| **Esercizio** | anno di riferimento |
| **Stato** | *Attiva* (con la percentuale di utilizzo, in arancione dal 90 %), *Esaurita*, *Revocata* |
**Stampa registro** produce il PDF del registro dell'anno.
## Registrare una dichiarazione ricevuta
1. **Nuova dichiarazione**, scheda *Ricevute*.
2. Scegli il **cliente**, scrivi numero e data, il **protocollo telematico** e il **plafond**.
3. Indica il periodo di validità (**valida dal**, **valida al**): ogni fattura va sulla dichiarazione più recente che ne copre la data.
4. L'**utilizzato** si aggiorna da solo con le fatture: compilalo solo se una parte del plafond è già stata usata con
fatture emesse fuori da Khaemhat.
5. Salva. Il cliente riceve una copia della dichiarazione corrente nei suoi dati fiscali, usata dai documenti e dalla
fattura elettronica.
Una dichiarazione si **revoca** (per esempio quando il cliente la annulla) e da quel momento non copre più le
fatture. Il plafond non può scendere sotto l'utilizzato; una dichiarazione mai usata si può eliminare.
## Fatturare a un esportatore abituale
1. Nella fattura usa per le righe il codice IVA di **natura N3.5** (*non imponibile a seguito di dichiarazione
d'intento*), di solito impostato come codice IVA preferito del cliente.
2. Alla **conferma** Khaemhat cerca una dichiarazione attiva del cliente valida alla data della fattura:
- se **non c'è**, la conferma è rifiutata con il messaggio *nessuna dichiarazione d'intento valida*;
- se l'imponibile in N3.5 **supera il residuo**, la conferma è rifiutata indicando quanto resta;
- altrimenti la fattura è confermata e l'importo si aggiunge all'**utilizzato**; dal 90 % compare l'avviso.
3. La fattura elettronica riporta gli estremi della dichiarazione nel blocco *AltriDatiGestionali* con tipo
`INTENTO` (vedi [Fatturazione elettronica](Fatturazione-elettronica)).
Le note di credito in N3.5 riducono l'utilizzato; eliminare o annullare una fattura lo ricalcola.
## Dichiarazioni emesse
Se l'azienda stessa è esportatore abituale registra nella scheda **Emesse** le dichiarazioni inviate ai propri
fornitori, con lo stesso protocollo e plafond: servono come promemoria e per la stampa del registro.
## Dati di esempio
I dati dimostrativi registrano la dichiarazione di **Idrotermica Piemonte** (plafond 150.000 €) ed emettono una
fattura in N3.5 che ne consuma una parte; una fattura in N3.5 a un cliente senza dichiarazione viene rifiutata.
## Permessi e licenza
| Permesso | Consente |
|---|---|
| `sales.intent.read` | registro e stampa |
| `sales.intent.write` | inserire, modificare e revocare le dichiarazioni |
## Domande frequenti
**La fattura non si conferma: «plafond superato».** Il residuo della dichiarazione non basta. Chiedi al cliente una
nuova dichiarazione (o un'integrazione del plafond) e registrala, oppure fattura la parte eccedente con IVA.
**Avevo scritto il protocollo nell'anagrafica del cliente.** Le dichiarazioni inserite nei dati fiscali del cliente
prima della versione 0.10 diventano automaticamente righe del registro alla prima apertura.
## Pagine correlate
[Vendite](Vendite) · [Anagrafiche](Anagrafiche) · [IVA](IVA) · [Fatturazione elettronica](Fatturazione-elettronica) ·
[Intrastat](Intrastat) · [Fiscalità italiana](Fiscalita-italiana)
+270 -141
View File
@@ -1,200 +1,329 @@
# Fatturazione elettronica e canali SDI
> **Stato:** bozza · **Ultima revisione:** 2026-11-10 · **Versione software:** non ancora rilasciata (milestone M9)
> **Modulo di licenza:** EINV · **Permessi principali:** `sales.invoice.issue`, `einvoice.document.send`, `einvoice.channel.manage`, `einvoice.inbox.import` · **Specifica:** SPEC §11.9, §11.3, §11.5, §9.4
> **Stato:** completa per la versione 0.10 · **Ultima revisione:** 2026-11-13 · **Versione software:** 0.10.0 (M10)
> **Modulo di licenza:** EINV · **Permessi principali:** `einvoice.document.read` (cruscotto, notifiche,
> conservazione), `einvoice.document.send` (generare, inviare, importare notifiche), `einvoice.inbox.read` e
> `einvoice.inbox.import` (fatture ricevute), `einvoice.channel.manage` (canali e instradamento) · **Specifica:**
> SPEC §11.9, ADR 0039 e 0040
## A cosa serve
Il modulo produce il **file FatturaPA** delle fatture emesse, lo **controlla** come farebbe il Sistema di
Interscambio (SDI), lo **trasmette** attraverso il canale scelto dalle regole di instradamento e segue le
**notifiche** che tornano indietro (consegna, scarto, mancata consegna, esito della pubblica amministrazione). Dalla
stessa sezione arrivano le **fatture dei fornitori**, che si registrano come fatture di acquisto, e si prepara il
**pacchetto per la conservazione**.
Il modulo genera l'**XML FatturaPA** delle fatture emesse, lo **valida**, lo **trasmette al Sistema di
Interscambio (SDI)** attraverso uno dei canali configurati, importa le **notifiche** e le **fatture passive**,
gestisce le **autofatture** da inviare e prepara il **pacchetto per la conservazione**. Il **cruscotto SDI** riunisce
tutto in una schermata ordinata per priorità.
Lo SDI è il sistema dell'Agenzia delle Entrate e non fa parte di Khaemhat. Per raggiungerlo Khaemhat offre quattro
canali con lo stesso modo di lavorare: la **PEC dell'azienda** (nessun servizio esterno), il web service **SdICoop**
e **due intermediari** accreditati.
Lo SDI è il sistema dell'Agenzia delle Entrate e non può essere "inglobato" in un gestionale. Khaemhat include però un
**canale proprio via PEC** che non richiede alcun servizio esterno, e supporta con la stessa interfaccia **SdICoop**
(web service dell'Agenzia) e **due intermediari**.
> **In questa versione** ci sono il file FatturaPA (`FPR12`, `FPA12`, `FSM10`) con controllo prima dell'invio, i
> quattro canali con prova di connessione, pausa e regole di instradamento con canale di riserva, la lettura
> automatica dei canali ogni 15 minuti, la ricezione push di SdICoop, l'import manuale delle notifiche, la correzione
> delle fatture scartate, la copia di cortesia in PDF con l'XML allegato, le fatture ricevute con registrazione in
> blocco, l'elenco delle notifiche e i pacchetti per la conservazione. Dalla 0.10 il menu comprende anche
> [Intrastat](Intrastat) e le [dichiarazioni d'intento](Dichiarazioni-d-intento), i cui estremi entrano nel file
> (`AltriDatiGestionali` di tipo `INTENTO`). Arriva più avanti il formato europeo **EN 16931 / UBL** ([Roadmap](Roadmap)).
## Dove si trova
Menu laterale **Fatturazione elettronica**: **Cruscotto SDI**, **Fatture emesse**, **Fatture ricevute**,
**Notifiche**, **Bollo virtuale**, **Intrastat**, **LIPE**; la configurazione dei canali è in **Fatturazione
elettronica → Canali**. Il contatore accanto alla voce di menu indica i documenti che richiedono attenzione.
Bollo virtuale, dichiarazioni d'intento e LIPE sono descritti nella pagina [IVA](IVA), Intrastat in [Intrastat](Intrastat).
Menu laterale **Fatturazione elettronica** → *Cruscotto SDI*, *Fatture ricevute*, *Notifiche SDI*,
*Conservazione*, *Canali di trasmissione* (e *Dichiarazioni d'intento*, ancora da sviluppare).
## Schermate
Il menu compare solo se la licenza comprende il modulo **EINV** e l'utente ha i permessi (vedi
[Licenze e moduli](Licenze-e-moduli) e [Utenti e permessi](Utenti-e-permessi)). Ogni voce chiede il suo permesso:
chi non ha `einvoice.channel.manage`, per esempio, non vede i canali.
![058 · Cruscotto SDI](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/mockups/png/058-cruscotto-sdi.png)
*Mockup 058 — cruscotto con i contatori per stato (da generare, da inviare, inviate in attesa, consegnate, scartate, mancata consegna), azioni Genera + invia, Correggi, Importa notifiche e l'elenco dei documenti con TD, canale, stato SDI e ultima notifica o errore*
Prima di iniziare servono:
![059 · Canali di trasmissione SDI](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/mockups/png/059-canali-trasmissione-sdi.png)
*Mockup 059 — i quattro canali (PEC integrata, SdICoop, Intermediario A, Intermediario B) con il loro stato, le regole di instradamento e le impostazioni della casella PEC*
- il **profilo dell'azienda** completo in [Impostazioni](Impostazioni): partita IVA, codice fiscale, sede e
**regime fiscale** (RF01…). Senza questi dati la generazione si ferma con un messaggio che dice cosa manca;
- per ogni cliente il **codice destinatario** o la **PEC**, e per la pubblica amministrazione il **codice
ufficio IPA** di sei caratteri ([Anagrafiche](Anagrafiche));
- almeno un **canale attivo** (vedi [I canali di trasmissione](#i-canali-di-trasmissione)). Senza canali si può
comunque generare il file, caricarlo dal portale *Fatture e Corrispettivi* e segnarlo come inviato.
## Il ciclo di una fattura
1. La fattura viene **confermata ed emessa** in [Vendite](Vendite) (numero definitivo, sola lettura).
2. **Genera XML**: Khaemhat produce il file FatturaPA e lo allega al documento (bloccato dopo l'invio).
3. **Valida**: il validatore controlla il file prima dell'invio.
4. **Invia**: il canale scelto dalle regole di instradamento trasmette il file allo SDI.
5. **Notifiche**: lo SDI risponde con ricevute e notifiche che aggiornano lo stato del documento.
1. La fattura, la nota di credito, la parcella o l'autofattura viene **confermata** in [Vendite](Vendite) o in
[Acquisti](Acquisti): da quel momento ha il numero definitivo e compare fra i *documenti da generare*.
2. **Genera**: Khaemhat scrive il file FatturaPA e lo controlla. Il documento passa a *XML generato*.
3. **Invia**: il canale scelto dalle regole di instradamento trasmette il file. Il documento passa a *Inviato*.
4. **Notifiche**: lo SDI risponde e lo stato del file e del documento cambia da solo.
Il pulsante **Genera + invia** esegue i passi 2-4 sui documenti selezionati.
Il pulsante **Genera + invia** fa i passi 2 e 3 in un colpo solo sui documenti selezionati.
| Stato del documento | Quando |
|---|---|
| **Bozza** | fattura in lavorazione |
| **Emessa** | confermata, senza XML (*Da generare*) |
| **XML generato** | XML prodotto e validato (*Da inviare*) |
| **Inviata** | trasmessa allo SDI, in attesa di ricevuta |
| **Consegnata** | ricevuta di consegna (RC) |
| **Scartata** | notifica di scarto (NS): va corretta e rigenerata |
| **Mancata consegna** | lo SDI non è riuscito a recapitarla (MC) |
| Stato del file | Quando | Stato del documento |
|---|---|---|
| **Generata** | file scritto e controllato, non ancora trasmesso | XML generato |
| **Inviata** | trasmessa allo SDI, in attesa della ricevuta | Inviato |
| **Consegnata** | ricevuta di consegna (RC) | Consegnato |
| **Scartata** | notifica di scarto (NS): la fattura **non è emessa** e va corretta | Scartato |
| **Mancata consegna** | lo SDI non è riuscito a recapitarla (MC): è comunque emessa | Non consegnato |
| **Accettata** / **Rifiutata** | esito del committente PA, EC01 o EC02 (NE) | |
| **Decorrenza termini** | la PA non ha risposto entro 15 giorni (DT) | |
| **Impossibile recapitare** | attestazione di trasmissione verso una PA (AT) | |
Una fattura emessa non si modifica: se l'XML **non è ancora stato inviato** si può annullare indicando il motivo;
altrimenti si emette una nota di credito. Una fattura **scartata** non è emessa ai fini fiscali: con **Correggi** si
corregge il dato e si rigenera l'XML (nuova versione dell'allegato).
## Cruscotto SDI
## L'XML FatturaPA
![Khaemhat 0.9.0 · cruscotto SDI con i contatori, i documenti da generare e i file trasmessi](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/fatturazione-cruscotto.png)
*Khaemhat 0.9.0 — il cruscotto dell'azienda di esempio: i sei contatori, i documenti emessi senza file e i file
trasmessi con stato SDI, canale, ultima notifica e azioni.*
In alto sei **contatori**: *Da generare* (documenti emessi senza XML), *Da inviare* (file generati e controllati),
*Inviate in attesa*, *Consegnate* (RC, esito EC01, decorrenza termini), *Scartate* e *Mancata consegna*. Sopra, a
destra, il collegamento alle **fatture ricevute da registrare**, **Importa notifiche** e, per chi gestisce i canali,
**Leggi i canali ora**.
Il pannello ha tre viste:
- **Emesse**: fatture, note di credito e parcelle verso i clienti;
- **Autofatture**: i documenti TD16-TD29 nati dagli [acquisti](Acquisti) (integrazioni del reverse charge,
servizi e beni dall'estero, estrazione da deposito IVA, splafonamento…), che vanno trasmessi **entro il 15 del
mese successivo**;
- **Da fare**: solo ciò che chiede un intervento, cioè documenti da generare, file da inviare, scartati, non
consegnati e rifiutati. Gli avvisi della Home su fatture scartate o da inviare portano qui.
Sotto la vista si filtrano **stato** e **periodo** e si cerca per numero, nome del file, identificativo SDI o
controparte.
### Documenti da generare
La prima tabella elenca i documenti confermati che non hanno ancora un file. Si selezionano e si preme **Genera +
invia**; **Controlla senza generare** (icona a forma di scudo) prova il file senza salvarlo e mostra gli errori,
utile per sistemare i dati prima di trasmettere.
![Khaemhat 0.9.0 · il controllo di un documento prima della generazione](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/fatturazione-controllo.png)
*Khaemhat 0.9.0 — Controlla senza generare: il file supera i controlli dello SDI.*
### File trasmessi
La seconda tabella ha un file per riga: nome (`IT01234567890_0000A.xml`), documento, cliente, data, totale, tipo
documento, **canale**, **stato SDI** e **ultima notifica o errore** con la data. I file *Generata* hanno la casella
per **Invia (n)**. Le azioni della riga:
| Azione | Quando | Cosa fa |
|---|---|---|
| **Correggi** | file scartato | apre il documento, che torna modificabile; dopo la correzione si genera un **nuovo file** con un nuovo progressivo, il vecchio resta nello storico come *sostituito* |
| **Segna come inviata** | file generato | per chi lo ha caricato dal portale *Fatture e Corrispettivi*: si può indicare l'identificativo SDI; le notifiche si importano poi a mano |
| **XML** | sempre | scarica il file trasmesso |
| **Copia di cortesia (PDF)** | sempre | il PDF del documento con il file FatturaPA **allegato dentro il PDF**, da mandare al cliente: non sostituisce l'invio allo SDI |
| **Storico del file** | sempre | tutte le versioni del file con generazione, invio, identificativo SDI e notifiche |
![Khaemhat 0.9.0 · lo storico di un file scartato e rigenerato](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/fatturazione-storico.png)
*Khaemhat 0.9.0 — lo storico SDI di una fattura: la prima versione scartata con l'errore dello SDI, sostituita da
quella corretta e consegnata.*
Dopo **Invia** o **Genera + invia** una finestra riassume l'esito file per file: preso in carico da quale canale,
oppure il motivo per cui non è partito.
![Khaemhat 0.9.0 · l'esito della trasmissione](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/fatturazione-esito-invio.png)
*Khaemhat 0.9.0 — esito della trasmissione di due file.*
![Khaemhat 0.9.0 · la vista Da fare](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/fatturazione-da-fare.png)
*Khaemhat 0.9.0 — la vista Da fare: documenti da generare e file scartati o non consegnati.*
## Il file FatturaPA
| Formato | Uso |
|---|---|
| `FPR12` | fatture verso privati (aziende e consumatori) |
| `FPA12` | fatture verso la Pubblica Amministrazione |
| `FPA12` | fatture verso la pubblica amministrazione |
| `FSM10` | fattura semplificata |
Khaemhat segue le **specifiche tecniche dell'Agenzia delle Entrate**: alla stesura di questa pagina la **versione
1.9, in vigore dal 1° aprile 2025** (con il tipo documento TD29 e il TD20 ridefinito). La versione supportata è
indicata nel programma; prima di ogni rilascio va **sempre verificata l'ultima versione pubblicata** dall'Agenzia.
Khaemhat segue le **specifiche tecniche 1.9.1** dell'Agenzia delle Entrate (tipi documento fino a TD29). La
versione è scritta nel pacchetto fiscale italiano; prima di ogni rilascio va confrontata con l'ultima pubblicata
dall'Agenzia.
L'XML contiene, fra l'altro: dati di trasmissione, cedente e cessionario, dati generali con tipo documento (TD),
ritenuta, bollo, cassa previdenziale, sconti e causale; riferimenti a ordine d'acquisto, contratto, convenzione,
ricezione e fatture collegate (con CIG e CUP per la PA); DDT, trasporto, righe di dettaglio, riepilogo IVA,
pagamento e allegati.
Il file contiene i dati di trasmissione, cedente e cessionario (con stabile organizzazione e rappresentante fiscale
quando servono), i dati generali con tipo documento, ritenute, bollo virtuale, cassa previdenziale, sconti e
causale, i riferimenti a ordine, contratto, convenzione, ricezione e fatture collegate (con CIG e CUP per la PA),
DDT e trasporto, le righe, il riepilogo IVA con nature ed esigibilità, i pagamenti e gli allegati.
**Nome del file**: `IT<identificativo fiscale del trasmittente>_<progressivo>.xml`, con progressivo alfanumerico
univoco in base 36 (es. `IT01234567890_00A1Z.xml`).
**Nome del file**: `IT` + identificativo fiscale del trasmittente + `_` + progressivo di cinque caratteri in base 36
(per esempio `IT01234567890_0000A.xml`). Il progressivo non si ripete mai: un file rigenerato dopo uno scarto ne
prende uno nuovo.
## Validazione e scarti noti
### I controlli prima dell'invio
Prima dell'invio il validatore controlla:
Il file viene controllato **prima** di partire, con gli stessi codici di errore dello SDI, così il messaggio è
quello che si leggerebbe nello scarto:
- valori ammessi delle code list (TD, nature, modalità di pagamento, regime fiscale…) e lunghezze dei campi;
- totali coerenti con tolleranza di ± 0,01;
- **nature IVA** (`N1`…`N7` con sotto-codici) e relativi riferimenti normativi;
- codice destinatario o PEC del cliente; per la **PA** codice IPA a 6 caratteri, CIG e CUP quando servono;
- codice fiscale dei gruppi IVA;
- bollo virtuale.
- **struttura** del file contro lo schema del formato;
- **totali**: `PrezzoTotale` e imposta con tolleranza di un centesimo, imponibile del riepilogo con tolleranza di un
euro (00421, 00422, 00423);
- **riepilogo IVA** presente per ogni aliquota e natura (00419);
- **nature IVA** e aliquote su righe, cassa previdenziale e riepilogo (00400, 00401, 00413, 00414, 00429, 00430),
con i sotto-codici obbligatori al posto delle nature generiche N2, N3 e N6 (00445);
- **ritenute** (00411, 00415) e **sconti e maggiorazioni** (00437, 00438);
- **cliente**: partita IVA o codice fiscale presenti e ben formati (00305, 00306, 00417), codice destinatario e PEC
coerenti con il formato (00311, 00426, 00427);
- **autofatture**: cedente e cessionario devono essere diversi o uguali secondo il tipo (00471, 00472, 00473).
Esempi di scarto dello SDI visti nel cruscotto e usati nei test: **00311** (CodiceDestinatario non valido),
**00423** (PrezzoTotale non calcolato correttamente), **00327**. Il messaggio dell'errore compare nella colonna
*Ultima notifica / errore*.
Alcuni controlli richiedono i registri dell'Agenzia (partita IVA esistente, codice destinatario accreditato, codice
IPA presente nell'indice delle PA): Khaemhat ne verifica solo la **forma**.
## I quattro canali di trasmissione
> Lo schema usato per il controllo della struttura è scritto per Khaemhat sulle regole del formato 1.2: non è il file
> XSD ufficiale dell'Agenzia, che non è incluso. Gli scarti più comuni sono comunque coperti dai controlli di
> contenuto.
Tutti i canali hanno la stessa interfaccia (invia, stato, notifiche, scarica passive): cambiare canale non cambia il
modo di lavorare.
## Le notifiche dello SDI
| Canale | Come funziona | Pro | Contro |
|---|---|---|---|
| **PEC integrata** | l'XML parte come allegato dalla **PEC aziendale** (SMTP) verso la PEC dello SDI; notifiche e fatture passive si leggono dalla stessa casella con il client **IMAP** interno, filtrando per mittente e oggetto e archiviando in una cartella | nessun servizio esterno, nessun accreditamento, costo della sola casella PEC | più lento; i volumi elevati vanno distribuiti (regola di *throttling*); dipende dalla disponibilità della casella; non include la conservazione |
| **SdICoop** | web service dell'Agenzia; richiede l'**accreditamento** e un **certificato** rilasciato all'azienda; Khaemhat costruisce la chiamata SOAP con certificato client | notifiche e fatture passive in tempo reale; adatto ai volumi alti | procedura di accreditamento; certificato da rinnovare (il mockup ne mostra la scadenza); per ricevere, lo SDI deve raggiungere un servizio dell'azienda: i requisiti di rete saranno verificati in sviluppo |
| **Intermediario A** | connettore REST verso il servizio di un intermediario accreditato: upload dell'XML, stato, notifiche, download delle passive | semplice da attivare; la **conservazione a norma** può essere inclusa nel servizio | costo del servizio; dipendenza da un terzo; credenziali e token API con scadenza |
| **Intermediario B** | secondo connettore REST, stessa interfaccia, con la propria mappatura di stati ed errori | alternativa o riserva al primo | come l'intermediario A |
![Khaemhat 0.9.0 · elenco delle notifiche SDI](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/fatturazione-notifiche.png)
*Khaemhat 0.9.0 — Notifiche SDI: ogni ricevuta con il file a cui si riferisce, scaricabile così come è arrivata.*
Gli intermediari A e B sono i due servizi scelti dal titolare del progetto; le credenziali sono conservate cifrate.
| Sigla | Notifica | Effetto |
|---|---|---|
| **RC** | ricevuta di consegna | *Consegnata* |
| **NS** | notifica di scarto, con codice e descrizione degli errori | *Scartata*: correggi e rigenera; l'Agenzia indica di ritrasmettere entro 5 giorni |
| **MC** | mancata consegna | la fattura è emessa ma il cliente la trova nel suo cassetto fiscale: conviene mandargli la **copia di cortesia** |
| **NE** | esito del committente PA: **EC01** accettazione, **EC02** rifiuto | *Accettata* o *Rifiutata*; un rifiuto richiede una nota di credito |
| **DT** | decorrenza termini (PA) | *Decorrenza termini*: vale come consegna |
| **AT** | attestazione di avvenuta trasmissione con impossibilità di recapito (PA) | *Impossibile recapitare* |
| **SE** | scarto dell'esito inviato dal committente PA | conservata fra le notifiche |
| **MT** | file metadati di una fattura ricevuta | tenuto con la fattura in *Fatture ricevute* |
### Configurare il canale PEC
Le notifiche arrivano in tre modi:
1. **Fatturazione elettronica → Canali**, riquadro **PEC · impostazioni**.
2. Inserisci **Casella PEC**, server **SMTP** (es. porta 465) e **IMAP** (es. porta 993), la frequenza del
**Controllo notifiche** (es. ogni 15 minuti) e la **Cartella archivio**.
3. Premi **Prova connessione**, poi **Salva**. Il riquadro del canale mostra casella, ultimo controllo e notifiche lette.
- **dai canali**, con l'attività programmata *Lettura dei canali SDI* (`einvoice.poll`) **ogni 15 minuti**, o subito
con **Leggi i canali ora**;
- **in push da SdICoop**, appena lo SDI le consegna (vedi sotto);
- **a mano** con **Importa notifiche** sul cruscotto: file XML, P7M o lo ZIP scaricato dal portale. La stessa
notifica non viene importata due volte.
Il primo invio via PEC va all'indirizzo `sdi01@pec.fatturapa.it`; con la prima risposta lo SDI indica l'indirizzo
PEC da usare per gli invii successivi. La gestione di questo indirizzo sarà verificata in sviluppo.
Nella pagina **Notifiche SDI** si filtrano periodo (dal 1° gennaio a oggi in partenza) e tipo. Le righe evidenziate
sono notifiche che non corrispondono a nessun file emesso.
## Fatture ricevute
![Khaemhat 0.9.0 · fatture ricevute dai fornitori](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/fatturazione-ricevute.png)
*Khaemhat 0.9.0 — Fatture ricevute: le fatture dei fornitori da registrare, con fornitore, numero, totale, tipo,
canale e identificativo SDI.*
Le fatture dei fornitori arrivano dai canali o si caricano con **Carica file**: XML, **P7M** firmati CAdES (anche
annidati o in base64; l'XML viene estratto dalla busta), il file metadati e lo ZIP del portale. Lo stesso file non
entra due volte (impronta SHA-256).
| Stato | Significato |
|---|---|
| **Da registrare** | arrivata, da trasformare in fattura di acquisto |
| **Registrata** | diventata una fattura o nota di credito di acquisto: **Apri** la porta al documento |
| **Scartata** | messa da parte a mano (**Ripristina** la riporta indietro) |
| **Illeggibile** | il file non è una FatturaPA leggibile: l'errore è scritto sotto lo stato |
Si selezionano le fatture e si preme **Registra (n)**, oppure **Registra come fattura di acquisto** sulla riga.
La registrazione usa l'import del ciclo passivo ([Acquisti](Acquisti)): il fornitore si riconosce dalla partita
IVA e, se manca, viene creato; righe, IVA e scadenze vengono dal file. Gli avvisi dell'import compaiono nel messaggio
di esito.
## I canali di trasmissione
![Khaemhat 0.9.0 · canali di trasmissione e regole di instradamento](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/fatturazione-canali.png)
*Khaemhat 0.9.0 — i quattro canali con il loro stato, le impostazioni del canale scelto e le regole di
instradamento.*
Tutti i canali fanno le stesse cose (inviare, leggere notifiche e fatture ricevute, provare la connessione): cambiare
canale non cambia il modo di lavorare. Ogni scheda mostra lo stato (*Attivo*, *Configurato · in pausa*, *Non
configurato*), l'ultima prova e l'ultima lettura. Password, chiavi e certificati sono **cifrati** nel database; nel
modulo un campo segreto lasciato vuoto mantiene il valore memorizzato.
| Canale | Come funziona | Impostazioni |
|---|---|---|
| **PEC** | il file parte come allegato dalla PEC dell'azienda (SMTP) verso lo SDI; ricevute e fatture si leggono dalla stessa casella (IMAP) e i messaggi letti vanno nella cartella di archivio | casella, server e porte SMTP e IMAP, TLS, utente, password, indirizzo PEC dello SDI, cartella di archivio |
| **SdICoop** | web service dell'Agenzia con **certificato client**; lo SDI consegna notifiche e fatture al servizio di ricezione di Khaemhat | indirizzo del servizio, certificato PKCS#12 (`.p12`) con password, chiave di ricezione, ambiente di prova |
| **Intermediario A** | API REST di un intermediario accreditato con **chiave API** | indirizzo del servizio, chiave API, ambiente di prova |
| **Intermediario B** | API REST di un intermediario accreditato con **utente e password** | indirizzo del servizio, utente, password, ambiente di prova |
Per ogni canale: **Prova connessione**, **Metti in pausa** / **Riprendi** e **Salva**. Gli indirizzi dei servizi
devono essere `https`.
> **Quale canale usare.** Per iniziare usa la **PEC**: non richiede accreditamento né contratti. *Intermediario A* e
> *Intermediario B* sono connettori generici, provati con servizi simulati: per collegarli a un intermediario reale
> servono le sue API, quindi vanno adattati al fornitore scelto. **SdICoop** richiede l'accreditamento dell'azienda
> presso l'Agenzia delle Entrate, il certificato client e un reverse proxy con verifica reciproca dei certificati
> (mTLS): conviene solo con volumi alti.
**PEC.** Il primo invio va all'indirizzo `sdi01@pec.fatturapa.it`; con la prima risposta lo SDI comunica la casella
da usare da lì in poi, che Khaemhat ricorda e mostra nel campo *Indirizzo PEC dello SDI*. La PEC non richiede
accreditamento ma è il canale più lento: per volumi alti conviene una regola che sposti il traffico su un altro
canale.
Della casella si leggono solo i messaggi dello SDI (mittente `fatturapa.it`); le ricevute di accettazione e consegna
del gestore PEC restano dove sono. Imposta sempre la **cartella di archivio**: i messaggi elaborati vengono spostati
lì. Senza cartella vengono solo segnati come letti, e un messaggio aperto dalla webmail prima della lettura di
Khaemhat verrebbe saltato.
**SdICoop in ricezione.** Lo SDI chiama il servizio `POST /sdicoop/<codice azienda>` di Khaemhat. Il servizio
accetta solo le chiamate con l'intestazione `X-Khaemhat-SdiCoop-Key` uguale alla **chiave di ricezione** del canale.
Il certificato reciproco (mTLS) richiesto dall'Agenzia si configura sul **reverse proxy** davanti a Khaemhat, che
aggiunge l'intestazione: vedi [Installazione con Docker](Installazione-Docker).
### Instradamento
Le **regole di instradamento** decidono quale canale usa ogni documento. Esempio del mockup:
Le regole decidono quale canale usa ogni file. Vale **la prima regola attiva che si applica**, nell'ordine indicato;
il **canale di riserva** si usa se il primo è in pausa, disattivato o non risponde. Senza regole si usa il primo
canale attivo.
| Regola | Canale | Condizione |
|---|---|---|
| Predefinito | PEC | tutti i documenti |
| Clienti PA | SdICoop | cessionario PA (codice IPA) |
| Volumi > 50/giorno | SdICoop | throttling della PEC |
| Conservazione | Intermediario A | pacchetti trimestrali |
| Condizione | Si applica a |
|---|---|
| **Sempre** | tutti i file |
| **Cliente pubblica amministrazione** | i clienti con codice IPA (formato `FPA12`) |
| **Cliente specifico** | il cliente con il codice indicato |
| **Tipo documento** | un tipo (TD01, TD17…) |
| **Volume giornaliero** | i file oltre un numero di invii nella giornata |
Il canale usato è registrato su ogni documento (colonna *Canale* del cruscotto).
## Notifiche SDI
| Sigla | Notifica | Effetto in Khaemhat |
|---|---|---|
| **RC** | ricevuta di consegna | stato *Consegnata* |
| **NS** | notifica di scarto | stato *Scartata*, con codice e descrizione dell'errore; la regola predefinita avvisa l'amministrazione ([Automazioni](Automazioni)) |
| **MC** | mancata consegna | la fattura è emessa ma non recapitata: è messa a disposizione del cliente nella sua area riservata dell'Agenzia; conviene inviargli la **copia di cortesia** |
| **NE** | notifica di esito del committente PA (**EC01** accettazione, **EC02** rifiuto) | stato *Accettata* o *Rifiutata* |
| **DT** | decorrenza termini (PA) | nessun esito del committente nei termini previsti |
| **AT** | attestazione di avvenuta trasmissione con impossibilità di recapito (PA) | come la mancata consegna |
Le notifiche si importano in automatico dal canale (procedura **Import inbox SDI**, pianificata) o con **Importa
notifiche**; restano come allegati del documento ([Allegati e file](Allegati-e-file)). Sono letti anche i
**metadati** che accompagnano le fatture ricevute.
## Fatture passive
Le fatture ricevute arrivano dal canale (PEC, SdICoop o intermediario) o si caricano a mano (anche come file
**P7M** firmati CAdES: la firma viene verificata e l'XML estratto). Khaemhat le legge, riconosce il fornitore da
P.IVA o codice fiscale e prepara la **fattura di acquisto in bozza** con mappatura delle righe e confronto con
l'ordine: il dettaglio è nella pagina [Acquisti](Acquisti) (import XML). La vista **Ricevute** del cruscotto elenca
le passive e il loro stato di importazione.
## Cruscotto SDI
- **Contatori**: *Da generare* (emesse senza XML), *Da inviare* (XML validati), *Inviate · in attesa*,
*Consegnate* (nell'anno), *Scartate* (da correggere), *Mancata consegna*.
- **Elenco prioritizzato**: prima le scartate, poi le da inviare, poi quelle in attesa.
- **Viste**: **Emesse**, **Ricevute**, **Autofatture**.
- **Azioni**: genera, valida, invia, scarica, **Correggi** e rigenera, **Importa notifiche** e passive.
- In testa: canali attivi e ora dell'ultima sincronizzazione.
### Autofatture da inviare
Le autofatture e integrazioni (TD16 reverse charge interno, TD17 servizi dall'estero, TD18 beni intra-UE, TD19, TD20
e TD29, TD21, TD22/TD23, TD28) nascono da [Acquisti](Acquisti) e compaiono nella vista **Autofatture** fino all'invio.
L'XML va trasmesso **entro il 15 del mese successivo**; Khaemhat mostra un promemoria.
## Copia di cortesia
Da ogni fattura si può generare la **copia di cortesia** (PDF + XML in uno ZIP) da inviare al cliente via e-mail o
PEC. Non sostituisce l'invio allo SDI.
Le regole dell'azienda di esempio: PA → PEC; oltre 200 file al giorno → Intermediario A con PEC di riserva;
sempre → PEC con Intermediario A di riserva. Il canale usato resta scritto su ogni file.
## Conservazione
Khaemhat **non è un sistema di conservazione a norma**. Prepara per ogni periodo un **pacchetto di esportazione**
(XML, notifiche e indice) da affidare a un **conservatore** o al servizio messo a disposizione dall'Agenzia delle
Entrate. Se l'intermediario scelto include la conservazione, la regola di instradamento *Conservazione* gli invia i
pacchetti.
![Khaemhat 0.9.0 · pacchetti per la conservazione](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/fatturazione-conservazione.png)
*Khaemhat 0.9.0 — la preparazione di un pacchetto e l'elenco di quelli già preparati con l'impronta.*
## Sviluppi futuri
Khaemhat **non è un sistema di conservazione a norma**: prepara il materiale da consegnare al conservatore (o al
servizio gratuito dell'Agenzia). Si sceglie il periodo (in partenza il mese precedente, al massimo due anni) e si
preme **Prepara e scarica**: lo ZIP contiene le cartelle `emesse/`, `ricevute/` e `notifiche/`, l'indice
`indice.csv` con l'impronta SHA-256 di ogni file e un `LEGGIMI.txt`. L'elenco dei pacchetti preparati ricorda
periodo, numero di file, dimensione e impronta dello ZIP.
Il formato europeo **EN 16931 / UBL (Peppol)** è previsto come implementazione successiva della stessa interfaccia
dei formati ([Roadmap](Roadmap)).
## Dati di esempio
L'azienda di esempio ([Dati di base e di esempio](Dati-di-base-e-esempio)) ha i canali, le tre regole di
instradamento sopra, alcune fatture già trasmesse con ricevute di consegna,
uno scarto (00305) corretto e rigenerato, una mancata consegna e tre fatture di fornitori da registrare. Nessun
dato di esempio raggiunge lo SDI: il canale PEC dell'esempio è configurato ma **in pausa**, con credenziali finte,
e l'Intermediario A è solo abbozzato e disattivato.
## Permessi e licenza
Serve il modulo **EINV**. `sales.invoice.issue` è il permesso di emissione delle fatture (SPEC §7.2); gli altri
codici in testa sono indicativi e saranno fissati in sviluppo. La configurazione dei canali e delle credenziali è
riservata a chi gestisce le impostazioni dell'azienda.
| Permesso | Cosa consente |
|---|---|
| `einvoice.document.read` | cruscotto, storico, download di XML e copia di cortesia, notifiche, conservazione |
| `einvoice.document.send` | generare, inviare, segnare come inviata, importare le notifiche |
| `einvoice.inbox.read` | vedere le fatture ricevute |
| `einvoice.inbox.import` | caricare, registrare, scartare e ripristinare le fatture ricevute |
| `einvoice.channel.manage` | canali, credenziali, regole di instradamento, *Leggi i canali ora* |
Serve il modulo **EINV**. Le modifiche ai canali e alle regole finiscono nel registro delle modifiche; invii,
notifiche e letture dei canali sono scritti nel [log](Log) dell'applicazione.
## Domande frequenti
**Una fattura è scartata per codice destinatario non valido (00311).** Correggi il codice destinatario o la PEC
nella scheda fiscale del cliente ([Anagrafiche](Anagrafiche)), poi **Correggi** nel cruscotto e reinvia. Secondo le
indicazioni dell'Agenzia la fattura corretta va ritrasmessa entro 5 giorni dallo scarto.
nella scheda del cliente ([Anagrafiche](Anagrafiche)), poi **Correggi** nel cruscotto, salva il documento e genera
di nuovo il file. Secondo l'Agenzia la fattura corretta va ritrasmessa entro 5 giorni dallo scarto, con lo stesso
numero e la stessa data.
**Posso usare più canali insieme?** Sì: le regole di instradamento scelgono il canale per ogni documento.
**Ho inviato la fattura dal portale dell'Agenzia.** Usa **Segna come inviata** con l'identificativo SDI e poi
**Importa notifiche** con le ricevute scaricate dal portale.
**Dove trovo la ricevuta di consegna?** Fra gli allegati della fattura e nella voce **Notifiche**.
**Posso usare più canali insieme?** Sì: le regole di instradamento scelgono il canale per ogni file e il canale di
riserva interviene se il primo non risponde.
**Il cliente non ha ricevuto la fattura (MC).** È comunque emessa: la trova nel suo cassetto fiscale. Mandagli la
**copia di cortesia** dal cruscotto.
**Una PA ha rifiutato la fattura (EC02).** La fattura resta emessa: va stornata con una nota di credito
([Vendite](Vendite)).
## Pagine correlate
+19 -14
View File
@@ -1,7 +1,7 @@
# Fiscalità italiana
> **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
> **Stato:** completa per la versione 0.10 · **Ultima revisione:** 2026-11-13 · **Versione software:** 0.10.0 (M10)
> **Modulo di licenza:** CORE, ACCT, EINV, INTRA · **Specifica:** SPEC §11.1, §11.3-§11.9, §14, ADR 0036, ADR 0037, ADR 0038, ADR 0039
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, il **piano dei conti modello**, i **codici
@@ -16,14 +16,15 @@ fa fede il testo mostrato dal programma, non questa pagina.
> **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).
> codici tributo e le scadenze dell'F24, il tracciato LIPE, le ritenute d'acconto e il bollo virtuale. Con la 0.9 il
> file FatturaPA e le notifiche SDI sono in uso nella [Fatturazione elettronica](Fatturazione-elettronica). Con la 0.10
> sono in uso anche le regole di [Cespiti](Cespiti), [Intrastat](Intrastat),
> [dichiarazioni d'intento](Dichiarazioni-d-intento) e lo schema del bilancio CEE ([Chiusura e bilancio](Chiusura-e-bilancio)).
> **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.
> supportata (oggi la 1.9.1) è scritta nel pacchetto fiscale ed è verificata a ogni rilascio.
## Dove si trovano questi codici nel programma
@@ -178,6 +179,9 @@ fatture passive. Il codice RF03 non esiste più nelle specifiche correnti.
| MC | Mancata consegna | fattura **non consegnata**: messa a disposizione nell'area riservata del cliente |
| NE | Notifica di esito (PA: EC01 accettazione, EC02 rifiuto) | esito del committente pubblico |
| DT | Decorrenza termini | la PA non ha risposto nei termini |
| AT | Attestazione di avvenuta trasmissione con impossibilità di recapito (PA) | fattura **impossibile da recapitare** |
Il dettaglio di come Khaemhat usa ogni notifica è nella pagina [Fatturazione elettronica](Fatturazione-elettronica#le-notifiche-dello-sdi).
| AT | Attestazione di avvenuta trasmissione con impossibilità di recapito | come mancata consegna, per la PA |
I dettagli operativi sono in [Fatturazione-elettronica](Fatturazione-elettronica).
@@ -185,7 +189,7 @@ 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`
Il pacchetto fiscale porta il piano dei conti **PMI standard**: **240 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)).
@@ -312,7 +316,7 @@ si esportano in CSV; la CU si invia con i servizi dell'Agenzia o dall'intermedia
| 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 | con i solleciti dello scadenzario (M8) |
| Interessi di mora | D.Lgs. 231/2002 per i ritardi nelle transazioni commerciali: tasso BCE di riferimento del semestre + 8 punti (10,15% nel primo semestre 2026, 10,40% nel secondo) | nei solleciti e nell'estratto conto dello [Scadenzario](Scadenzario); la tabella dei tassi va aggiornata ogni semestre (ADR 0038) |
## Altri riferimenti usati dal programma
@@ -320,16 +324,17 @@ si esportano in CSV; la CU si invia con i servizi dell'Agenzia o dall'intermedia
|---|---|---|
| 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 (M10) | [Fatturazione-elettronica](Fatturazione-elettronica) |
| Dichiarazione d'intento | operazioni non imponibili N3.5 con controllo di plafond, utilizzato e residuo; protocollo di 17 + 6 cifre; avviso dal 90 % | [Dichiarazioni d'intento](Dichiarazioni-d-intento) |
| 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) |
| 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à dalle soglie (50.000 € per le cessioni, 350.000 e 100.000 € per gli acquisti), nomenclatura NC8, file SCAMBI.CEE | [Intrastat](Intrastat) |
| Bilancio | schemi CEE art. 2424 e 2425 c.c., abbreviato (art. 2435-bis) e micro (art. 2435-ter); svalutazione crediti allo 0,5 % (art. 106 TUIR) e TFR nella chiusura | [Chiusura e bilancio](Chiusura-e-bilancio) |
## Domande frequenti
**Dove vedo la versione delle specifiche SDI supportata?** In **Amministrazione → Stato sistema** e nel cruscotto
SDI: è registrata nel programma e aggiornata con i rilasci.
**Quale versione delle specifiche SDI segue Khaemhat?** La 1.9.1 (in Khaemhat 0.9.0): è scritta nel pacchetto
fiscale, riportata nelle note di ogni rilascio e aggiornata quando l'Agenzia pubblica una nuova versione. La pagina
*Stato sistema* la mostrerà con le pagine di amministrazione (M12).
**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.
+41 -12
View File
@@ -1,6 +1,6 @@
# Guida all'uso
> **Stato:** completa per la versione 0.7 · **Ultima revisione:** 2026-11-13 · **Versione software:** 0.7.0 (M7)
> **Stato:** completa per la versione 0.10 · **Ultima revisione:** 2026-11-13 · **Versione software:** 0.10.0 (M10)
Questa pagina accompagna chi usa Khaemhat ogni giorno: dall'accesso alla fattura inviata al cliente, un passo per
volta, con le schermate della versione attuale. Ogni passo rimanda alla pagina che lo spiega per intero. Chi deve
@@ -9,20 +9,21 @@ volta, con le schermate della versione attuale. Ogni passo rimanda alla pagina c
## Che cosa c'è in questa versione
| Area | In 0.7.0 | Arriva con |
| Area | In 0.10.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 |
| 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 dallo scadenzario, file FatturaPA e invio allo SDI | — |
| 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 dallo scadenzario, file e invio delle autofatture | — |
| Magazzino | giacenze per deposito, impegnato e ordinato, costo medio, movimenti e trasferimenti, inventario fisico, proposta di riordino, valorizzazione con classi ABC, ricostruzione | libro inventari M13 |
| Contabilità | piano dei conti, causali, prima nota, contabilizzazione automatica dei documenti, registrazioni ricorrenti e definitive, partitari, mastrini, bilancio di verifica, libro giornale, ratei e risconti, chiusura guidata dell'esercizio, bilancio CEE con riclassificato e indici, export per il commercialista | — |
| IVA | registri IVA, liquidazione con F24, acconto, file LIPE, ritenute d'acconto con prospetto F24 e dati CU, bollo virtuale, dichiarazioni d'intento con plafond, elenchi Intrastat | — |
| Cespiti | categorie con i coefficienti ministeriali, registro con piano civilistico e fiscale, ammortamenti registrati e annullabili, dismissioni con plus e minusvalenze, stampa del registro | rivalutazioni guidate più avanti |
| Scadenzario | partite aperte con aging, incassi e pagamenti, distinte RiBa/SDD/bonifici SEPA con insoluti, mandati SDD, riconciliazione bancaria CSV/CBI/CAMT.053, solleciti con interessi di mora, flusso di cassa | collegamento diretto con la banca e report di tesoreria M12 |
| Fatturazione elettronica | file FatturaPA con controllo prima dell'invio, canali PEC, SdICoop e due intermediari con instradamento, notifiche, correzione degli scarti, copia di cortesia, fatture ricevute da registrare, pacchetti per la conservazione | formato europeo UBL più avanti |
| 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 |
@@ -155,14 +156,42 @@ confermati muovono il magazzino da soli: non serve registrare a parte carichi e
**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
## 10. La contabilità
![Prima nota](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/contabilita-prima-nota.png)
Con il modulo contabile ogni fattura, nota e autofattura confermata scrive da sola la sua **registrazione** in
partita doppia, con le righe IVA nel registro giusto e le **partite** da incassare o pagare. **Contabilità → Prima
nota** elenca le registrazioni e serve per quelle manuali (giroconti, spese, versamenti); **Liquidazione IVA** calcola
l'IVA del periodo e prepara l'F24; **Bilancio** dà il bilancio di verifica e, nelle altre schede, il bilancio CEE,
il riclassificato e gli indici. A fine anno **Chiusura esercizio** guida ammortamenti, ratei e risconti, rimanenze,
chiusura dei conti, riapertura e stampe definitive in nove passi. Vedi [Contabilità](Contabilita), [IVA](IVA),
[Cespiti](Cespiti) e [Chiusura e bilancio](Chiusura-e-bilancio).
## 11. Incassare, pagare e la banca
![Partite aperte](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/scadenzario-partite.png)
**Scadenzario → Partite aperte** mostra che cosa devono pagarti i clienti e che cosa devi ai fornitori, con lo scaduto
per anzianità. Quando un cliente paga, seleziona le sue partite e premi **Registra incasso**: indichi data, banca e
importo (anche parziale, o con un abbuono) e Khaemhat chiude le partite e scrive la registrazione. Per i fornitori
passa a **Fornitori** e usa **Registra pagamento**.
![Riconciliazione bancaria](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/scadenzario-riconciliazione.png)
Le **Distinte RiBa/SDD** raccolgono gli effetti in scadenza e generano il file da caricare nell'home banking (anche i
bonifici ai fornitori); **Riconciliazione bancaria** importa l'estratto conto e propone per ogni movimento la partita
o la spesa corrispondente; **Solleciti** prepara i promemoria ai clienti in ritardo con gli interessi di mora;
**Flusso di cassa** mostra quanto ci sarà in banca nelle prossime settimane. Vedi [Scadenzario](Scadenzario).
## 12. 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
## 13. Importare ed esportare
![Mappatura delle colonne](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/import-export-mappatura.png)
@@ -170,7 +199,7 @@ e-mail inviata aggiunge una versione e le precedenti restano. Vedi [Allegati e f
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
## 14. Personalizzare
![Il mio profilo](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/preferenze-profilo.png)
+3 -2
View File
@@ -1,6 +1,6 @@
# Khaemhat
> **Stato:** completa per 0.7.0 · **Ultima revisione:** 2026-11-13 · **Versione software:** 0.7.0 (M7; sviluppo in corso)
> **Stato:** completa per 0.10.0 · **Ultima revisione:** 2026-11-13 · **Versione software:** 0.10.0 (M10; sviluppo in corso)
![Khaemhat](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/assets/icon-v1.0-128.png)
@@ -37,7 +37,8 @@ Il nome viene da uno scriba dell'antico Egitto che sovrintendeva ai granai del r
- **Anagrafiche e tabelle:** [Anagrafiche](Anagrafiche) · [Articoli e listini](Articoli-e-listini) ·
[Tabelle azienda](Tabelle-azienda)
- **Ciclo attivo e passivo:** [Vendite](Vendite) · [Acquisti](Acquisti) · [Magazzino](Magazzino)
- **Amministrazione e fisco:** [Contabilità](Contabilita) · [IVA](IVA) · [Cespiti](Cespiti) · [Intrastat](Intrastat) ·
- **Amministrazione e fisco:** [Contabilità](Contabilita) · [Chiusura e bilancio](Chiusura-e-bilancio) · [IVA](IVA) ·
[Cespiti](Cespiti) · [Intrastat](Intrastat) · [Dichiarazioni d'intento](Dichiarazioni-d-intento) ·
[Scadenzario](Scadenzario) · [Fatturazione elettronica](Fatturazione-elettronica) ·
[Fiscalità italiana](Fiscalita-italiana)
- **Clienti e servizi:** [CRM](CRM) · [Servizi](Servizi) · [Canali e-commerce](Canali-e-commerce)
+7 -6
View File
@@ -1,6 +1,6 @@
# IVA
> **Stato:** completa per la versione 0.7 · **Ultima revisione:** 2026-11-13 · **Versione software:** 0.7.0 (M7)
> **Stato:** completa per la versione 0.10 · **Ultima revisione:** 2026-11-13 · **Versione software:** 0.10.0 (M10)
> **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
Questa pagina descrive l'IVA e i versamenti collegati, tutti nel menu **Contabilità**:
@@ -17,9 +17,9 @@ Questa pagina descrive l'IVA e i versamenti collegati, tutti nel menu **Contabil
> **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
> dati della CU e il bollo virtuale. Dalla 0.8 il pagamento di una parcella dallo
> [Scadenzario](Scadenzario) rende dovuta la ritenuta da solo. Dalla 0.10 ci sono le [dichiarazioni d'intento](Dichiarazioni-d-intento) con il plafond e gli
> elenchi [Intrastat](Intrastat). Arriva più avanti 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
@@ -182,8 +182,9 @@ agenti), importo, data di pagamento della fattura e **stato**:
### Registrare il pagamento della fattura
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 ritenuta operata diventa dovuta **quando paghi la fattura** del professionista (criterio di cassa). Se paghi la
fattura dallo [Scadenzario](Scadenzario) succede da solo, quando la fattura è saldata del tutto. Se l'hai pagata
fuori da Khaemhat, registralo a mano:
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
+78 -56
View File
@@ -1,83 +1,105 @@
# Intrastat
> **Stato:** bozza · **Ultima revisione:** 2026-11-10 · **Versione software:** non ancora rilasciata (milestone M10)
> **Modulo di licenza:** INTRA · **Permessi principali:** `intrastat.declaration.write`, `intrastat.declaration.export` · **Specifica:** SPEC §11.7, §8.1
> **Stato:** completa per la versione 0.10 · **Ultima revisione:** 2026-11-13 · **Versione software:** 0.10.0 (M10)
> **Modulo di licenza:** INTRA · **Permessi principali:** `intrastat.list.read` (elenchi), `intrastat.list.write`
> (generare e correggere), `intrastat.list.export` (file e invio) · **Specifica:** SPEC §11.7, ADR 0042
## A cosa serve
Il modulo Intrastat prepara gli **elenchi riepilogativi delle operazioni intracomunitarie** a partire dalle fatture
di vendita e di acquisto già registrate, controlla i dati mancanti e produce il **file nel tracciato dell'Agenzia
delle Dogane**, da trasmettere con i canali telematici previsti (la trasmissione avviene fuori da Khaemhat).
Gli **elenchi riepilogativi Intrastat** raccolgono le cessioni e gli acquisti di beni e servizi con soggetti di altri
Paesi dell'Unione europea. Khaemhat li **genera dalle fatture e note di credito confermate**, controlla i dati di ogni
riga, propone la **periodicità** dovuta e produce il file **SCAMBI.CEE** nel tracciato dell'Agenzia delle Dogane, da
trasmettere con i servizi telematici (la trasmissione avviene fuori da Khaemhat).
## Dove si trova
Nel mockup la voce è **Fatturazione elettronica → Intrastat**; il modulo di licenza è comunque **INTRA**, separato
da EINV.
**Fatturazione elettronica → Intrastat** (la voce compare con il modulo **INTRA**, separato da EINV).
## Schermate
![Khaemhat 0.10.0 · elenco Intrastat](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/intrastat-elenco.png)
*L'elenco delle cessioni di novembre 2026 dell'azienda demo: la fattura a Bergwerk Bau (Austria) con nomenclatura,
natura della transazione, consegna, trasporto, ammontare e massa netta; sotto, gli elenchi dell'anno.*
![049 · Intrastat](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/mockups/png/049-intrastat.png)
*Mockup 049 — elenchi di settembre (mensile): riquadri con i totali per sezione e le anomalie, elenco delle operazioni con paese, P.IVA, NC8, natura della transazione, consegna, trasporto, valore, massa e controllo; pulsanti Genera elenco e File SCAMBI.CEE*
## Flussi e sezioni
## Gli elenchi
| Flusso | Sezione | Modello |
|---|---|---|
| **Cessioni** | Beni · Rettifiche beni · Servizi · Rettifiche servizi | INTRA-1 bis, ter, quater, quinquies |
| **Acquisti** | Beni · Rettifiche beni · Servizi · Rettifiche servizi | INTRA-2 bis, ter, quater, quinquies |
| Modello | Contenuto |
|---|---|
| **INTRA-1 bis** | cessioni di beni verso altri Paesi UE |
| **INTRA-1 ter** | rettifiche alle cessioni di beni di periodi precedenti |
| **INTRA-1 quater** | servizi resi a soggetti UE |
| **INTRA-2 bis** | acquisti di beni da altri Paesi UE |
| **INTRA-2 ter** | rettifiche agli acquisti di beni di periodi precedenti |
| **INTRA-2 quater** | servizi ricevuti da soggetti UE |
I riquadri in testa mostrano il periodo e la periodicità, i totali di ogni sezione e il numero di **anomalie**.
La striscia in alto riporta il **periodo**, i totali di cessioni e acquisti di beni, dei servizi resi e ricevuti e il
numero di righe **da completare**.
## Periodicità
La periodicità (**mensile** o **trimestrale**) è determinata dalle **soglie di legge** in base agli importi delle
operazioni, separatamente per cessioni e acquisti. Le soglie sono parametri del pacchetto fiscale italiano e vengono
aggiornate con esso; Khaemhat propone la periodicità e la mostra nel riquadro *Periodo*.
Sotto i filtri Khaemhat indica la **periodicità dovuta** in base agli importi dei quattro trimestri precedenti, per
beni e servizi separatamente, con le soglie in vigore dal 2022:
## Dati richiesti per ogni operazione
| Flusso | Mensile se in almeno un trimestre | Altrimenti |
|---|---|---|
| Cessioni (beni o servizi) | più di 50.000 € | trimestrale |
| Acquisti di beni | più di 350.000 € | non dovuto |
| Acquisti di servizi | più di 100.000 € | non dovuto |
| Dato | Da dove viene |
La periodicità dell'elenco si sceglie nei filtri (mensile o trimestrale) insieme a esercizio e periodo.
## Generare l'elenco
1. Scegli **flusso**, **esercizio**, **periodicità** e **periodo**.
2. Premi **Genera** *periodo*. Khaemhat legge le fatture e le note di credito confermate nel periodo verso soggetti con
sede in un altro Paese UE:
- i **beni** sono raggruppati per controparte, nomenclatura e natura della transazione;
- i **servizi** hanno una riga per fattura, con il codice CPA;
- le **note di credito** diventano righe di rettifica.
3. Le righe aggiunte a mano con **Aggiungi riga** restano quando rigeneri l'elenco.
| Colonna | Da dove viene |
|---|---|
| Paese e partita IVA della controparte | anagrafica (P.IVA comunitaria verificata con VIES, vedi [Anagrafiche](Anagrafiche)) |
| **NC8** (nomenclatura combinata a 8 cifre) | scheda articolo ([Articoli e listini](Articoli-e-listini)) |
| Descrizione | riga del documento |
| **Natura della transazione** | causale del documento, modificabile (es. `11` vendita) |
| **Condizioni di consegna** | Incoterms del documento (es. DAP, FCA, EXW) |
| **Modo di trasporto** | dal documento (es. 1 mare, 3 strada) |
| Valore | imponibile in euro |
| **Massa netta** e unità supplementare | peso dell'articolo x quantità |
| Controparte, Paese, Partita IVA | anagrafica (vedi [Anagrafiche](Anagrafiche)) |
| **Nomenclatura / CPA** | codice doganale della scheda articolo ([Articoli e listini](Articoli-e-listini)) |
| **Natura** | proposta `11` (vendita o acquisto a titolo definitivo) |
| **Consegna**, **Trasporto** | proposti `DAP` e `3` (strada) |
| **Ammontare €** | imponibile della riga in euro |
| **Massa netta kg** | peso netto dell'articolo per quantità |
La colonna **Controllo** segnala lo stato di ogni riga: *OK*, *Manca peso netto* (riga evidenziata), *Extra-UE:
escluso* (la controparte non è comunitaria e la riga non entra negli elenchi), *INTRA-2 quater* (servizio ricevuto).
I dati richiesti dipendono dal modello e dalla periodicità; il tracciato preciso segue le istruzioni dell'Agenzia
delle Dogane in vigore.
Un clic sulla riga apre la scheda per correggere sezione, paese, partita IVA, codice, descrizione, ammontare,
massa, natura, consegna e trasporto; le righe si possono anche eliminare finché l'elenco non è inviato.
## Come si prepara l'elenco
## Controlli
1. Apri **Intrastat**, scegli **Periodo** e **Sezione**.
2. Premi **Genera elenco** del periodo: Khaemhat raccoglie le fatture intracomunitarie registrate.
3. Correggi le **anomalie** aprendo l'articolo o il documento (NC8 o peso mancanti, P.IVA non valida…).
4. Rigenera e controlla i totali con i registri IVA ([IVA](IVA)).
5. Premi **File SCAMBI.CEE** per scaricare il file nel tracciato dell'Agenzia delle Dogane; il file resta come
allegato della dichiarazione ([Allegati e file](Allegati-e-file)).
6. Trasmetti il file con il servizio telematico e registra l'avvenuto invio.
| Controllo | Cosa fare |
|---|---|
| **Completa** | niente |
| **Manca la nomenclatura** | completa il codice doganale sull'articolo e rigenera |
| **Manca la massa netta** | completa il peso netto sull'articolo, o la massa sulla riga |
| **Manca la partita IVA** | completa la partita IVA comunitaria della controparte |
| **Manca il codice CPA** | servizio senza codice: completalo sull'articolo |
| **Fuori UE** | la controparte non è comunitaria: la riga non entra nell'elenco |
## File e invio
1. **File SCAMBI.CEE** scarica il file a lunghezza fissa (frontespizio e record per beni, servizi e rettifiche).
Un elenco con righe da completare non si esporta. L'elenco passa a *File generato*.
2. Controlla il file con il software di controllo delle Dogane e trasmettilo.
3. **Segna come inviato** chiede il **protocollo di invio**: da quel momento l'elenco è di sola lettura.
> **Attenzione.** Il tracciato segue le specifiche pubblicate ma non è ancora stato verificato con il software di
> controllo delle Dogane: prima del primo invio controlla sempre il file (vedi [Roadmap](Roadmap)).
## Dati di esempio
I dati dimostrativi emettono una fattura non imponibile (art. 41) a **Bergwerk Bau GmbH** (Austria) con articoli che
hanno codice doganale e peso netto: generando l'elenco del mese corrente si vede una riga completa.
## Permessi e licenza
Serve il modulo **INTRA**. I codici dei permessi in testa sono indicativi (convenzione `modulo.entità.azione`, SPEC
§7.2) e saranno fissati in sviluppo.
| Permesso | Consente |
|---|---|
| `intrastat.list.read` | consultare gli elenchi |
| `intrastat.list.write` | generare, aggiungere e correggere righe |
| `intrastat.list.export` | scaricare il file e segnare l'invio |
## Attenzione
- Gli elenchi dipendono dalla qualità delle anagrafiche: NC8 e peso netto sugli articoli, P.IVA comunitarie valide.
- Soglie, modelli e campi obbligatori cambiano con le determinazioni dell'Agenzia delle Dogane: verificare sempre le
istruzioni in vigore prima dell'invio.
Serve il modulo **INTRA**.
## Pagine correlate
[IVA](IVA) · [Vendite](Vendite) · [Acquisti](Acquisti) · [Articoli e listini](Articoli-e-listini) ·
[Fatturazione elettronica](Fatturazione-elettronica) · [Fiscalità italiana](Fiscalita-italiana)
[Fatturazione elettronica](Fatturazione-elettronica) · [Dichiarazioni d'intento](Dichiarazioni-d-intento) ·
[Fiscalità italiana](Fiscalita-italiana)
+6 -5
View File
@@ -1,6 +1,6 @@
# Magazzino
> **Stato:** completa per la versione 0.6 · **Ultima revisione:** 2026-11-12 · **Versione software:** 0.6.0 (M6)
> **Stato:** completa per la versione 0.10 · **Ultima revisione:** 2026-11-13 · **Versione software:** 0.10.0 (M10)
> **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
@@ -10,8 +10,9 @@ 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).
> valorizzazione con analisi ABC e ricostruzione. Dalla 0.10 la [chiusura dell'esercizio](Chiusura-e-bilancio) registra le
> rimanenze finali al costo medio ponderato. Arrivano più avanti: il **libro inventari** e i report di magazzino
> stampabili (M13), FIFO e LIFO a lotti (dopo la 1.0).
## Dove si trova
@@ -149,8 +150,8 @@ fornitore non vengono ordinate.
- 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).
- FIFO e LIFO sono previsti con la gestione a lotti. Il passo 4 della [chiusura](Chiusura-e-bilancio) registra le
rimanenze finali al costo medio ponderato.
## Ricostruzione
+1 -1
View File
@@ -30,7 +30,7 @@ volume `/data/files/<azienda>`; nel database c'è la loro scheda (nome, tipo, di
| Documenti | `sale_quotations`, `sale_orders`, `sale_documents`, `purchase_orders`, `purchase_documents`, ciascuno con righe, castelletto IVA e rate; `document_links` per l'evasione | [Vendite](Vendite), [Acquisti](Acquisti) |
| Magazzino | `inventory_entries` e righe, `item_balances` (giacenza, impegnato, ordinato per articolo e deposito) | [Magazzino](Magazzino) |
| Contabilità e IVA | `gl_accounts`, `gl_entries` e righe, `vat_registers`, `vat_settlements` | [Contabilita](Contabilita), [IVA](IVA) |
| Scadenzario | `open_items` (partite), `payments` | [Scadenzario](Scadenzario) |
| Scadenzario | `gl_open_items` (partite), `payments` e righe, `remittances` e righe, `sdd_mandates`, `bank_statements` e righe, `bank_match_rules`, `dunning_levels`, `dunning_letters` | [Scadenzario](Scadenzario) |
| CRM | `crm_leads`, `crm_opportunities`, `crm_activities`, `crm_campaigns`, `crm_tickets` | [CRM](CRM) |
| Canali | `sales_channels`, `channel_orders` | [Canali-e-commerce](Canali-e-commerce) |
| Utenti e sicurezza | `users`, `roles`, `role_permissions`, `user_sessions`, `api_keys` | [Utenti-e-permessi](Utenti-e-permessi) |
+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), M5 (0.5.0), M6 (0.6.0), M7 (0.7.0). **Prossima:** M8.
**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), M8 (0.8.0), M9 (0.9.0), M10 (0.10.0). **Prossima:** M11.
| # | Milestone | Contenuto principale | Versione |
|---|---|---|---|
+252 -105
View File
@@ -1,165 +1,312 @@
# Scadenzario e tesoreria
> **Stato:** bozza · **Ultima revisione:** 2026-11-10 · **Versione software:** non ancora rilasciata (milestone M8)
> **Modulo di licenza:** FIN · **Permessi principali:** `finance.openitem.read`, `finance.payment.post`, `finance.remittance.write`, `finance.bank.reconcile`, `finance.dunning.send` · **Specifica:** SPEC §11.8
> **Stato:** completa per la versione 0.8 · **Ultima revisione:** 2026-11-13 · **Versione software:** 0.8.0 (M8)
> **Modulo di licenza:** FIN (con ACCT per le registrazioni) · **Permessi principali:** `finance.schedule.read`/`write`
> (scadenzario, distinte, mandati, solleciti, flusso di cassa), `finance.payment.read`/`write` (incassi e pagamenti),
> `finance.bank.reconcile` (riconciliazione bancaria) · **Specifica:** SPEC §11.8, ADR 0038
## A cosa serve
Lo **scadenzario** tiene le **partite aperte** di clienti e fornitori, cioè le rate dei documenti ancora da incassare
o da pagare. Da qui si registrano **incassi e pagamenti** (con abbuoni, spese e differenze cambio), si preparano le
**distinte RiBa, SDD e bonifici SEPA** con il file per l'home banking, si gestiscono gli **insoluti**, si
**riconcilia** l'estratto conto della banca, si inviano i **solleciti** con gli interessi di mora e si guarda il
**flusso di cassa** dei prossimi mesi. Ogni operazione scrive da sola la sua registrazione in
[Contabilità](Contabilita): non serve passare dalla prima nota.
Lo scadenzario tiene le **partite aperte** di clienti e fornitori (le rate generate dai documenti), registra
**incassi e pagamenti** con abbuoni e spese, prepara le **distinte RiBa, SDD e bonifici SEPA**, gestisce gli
**insoluti**, **riconcilia** l'estratto conto della banca, invia i **solleciti** e mostra il **flusso di cassa**.
Ogni movimento genera da solo la registrazione contabile ([Contabilità](Contabilita)).
> **In questa versione** ci sono partite aperte con aging, incassi e pagamenti multipli e parziali, abbuoni, spese e
> differenze cambio, storno di un incasso, estratto conto del cliente con gli interessi di mora, distinte RiBa (CBI), SDD core e B2B
> (`pain.008`) e bonifici SEPA (`pain.001`) con presentazione, accredito e insoluti, mandati SDD, import
> dell'estratto conto CSV, CBI e CAMT.053 con abbinamento automatico e regole, solleciti su tre livelli con
> interessi di mora e invio automatico, flusso di cassa a 30-365 giorni e le scadenze sulla Home. Arrivano più
> avanti: il **blocco per fido** su ordini e documenti (con le vendite avanzate), il collegamento diretto con la
> banca (CBI online, PSD2) e le **stampe** dei report di tesoreria nella sezione [Report](Report) (M12).
## Dove si trova
Menu laterale **Scadenzario**: **Partite aperte**, **Incassi**, **Pagamenti**, **Solleciti**, **Distinte RiBa/SDD**,
**Riconciliazione bancaria**.
Menu laterale **Scadenzario** → *Partite aperte*, *Incassi*, *Pagamenti*, *Solleciti*, *Distinte RiBa/SDD*,
*Mandati SDD*, *Riconciliazione bancaria*, *Flusso di cassa*.
## Schermate
Il menu compare solo se la licenza comprende il modulo **FIN** e l'utente ha i permessi (vedi
[Licenze e moduli](Licenze-e-moduli) e [Utenti e permessi](Utenti-e-permessi)). Senza ACCT le partite esistono
comunque, ma le operazioni che scrivono in contabilità chiedono il modulo.
![053 · Partite aperte](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/mockups/thumbs/053-scadenzario-partite.png)
*Mockup 053 — partite aperte dei clienti con riquadri di aging (non scaduto, 1-30, 31-60, 61-90, oltre 90 giorni), selezione multipla e azioni Registra incasso, Sollecito, Distinta RiBa (anteprima ridotta)*
Prima di iniziare servono:
![054 · Registra incasso](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/mockups/png/054-scadenzario-incasso.png)
*Mockup 054 — dialogo Registra incasso su due partite: cliente, data, metodo, importo, banca, riferimento CRO, causale INC; abbuono di € 10,00 sulla seconda rata e anteprima della registrazione che verrà generata*
- almeno un **conto bancario dell'azienda** in **Tabelle azienda → Banche aziendali** con IBAN, conto contabile e, per le
distinte, **codice SIA** (RiBa), **CUC** e **identificativo creditore SEPA** (SDD) — vedi
[Tabelle azienda](Tabelle-azienda);
- i **metodi di pagamento** con il codice MP della fattura elettronica (MP05 bonifico, MP12 RiBa, MP19-MP21 SDD…);
- per RiBa e SDD, le **coordinate bancarie del cliente** nella sua anagrafica ([Anagrafiche](Anagrafiche)).
![055 · Distinte](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/mockups/png/055-distinte-riba-sdd-sepa.png)
*Mockup 055 — distinta RiBa con banca di presentazione, date, importo, salvo buon fine e passi guidati; a destra gli effetti con il controllo (OK, IBAN mancante, scaduta da escludere)*
## Partite aperte
![056 · Solleciti](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/mockups/png/056-solleciti-pagamento.png)
*Mockup 056 — proposta di invio dei solleciti per cliente con livello, canale e interessi di mora; sotto, la tabella dei tre livelli con giorni, modello, canale e azione*
![Khaemhat 0.8.0 · partite aperte dei clienti con aging e stati](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/scadenzario-partite.png)
*Khaemhat 0.8.0 — partite aperte dei clienti di esempio: i riquadri di aging, i filtri, la selezione per registrare
l'incasso e gli stati (parziale, insoluta, scaduta, in distinta con il numero della distinta).*
![057 · Riconciliazione bancaria](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/mockups/png/057-riconciliazione-bancaria.png)
*Mockup 057 — movimenti dell'estratto conto con stato (abbinato, suggerito, insoluto, da abbinare), abbinamento proposto e confidenza; riquadri con saldo banca, saldo contabile e differenza*
Una **partita** è una rata di un documento: controparte, documento, numero della rata, scadenza, metodo, importo,
già incassato o pagato, residuo e stato. Le partite nascono dalla registrazione contabile delle fatture e delle note
di credito ([Vendite](Vendite), [Acquisti](Acquisti), [Contabilità](Contabilita)) secondo le condizioni di
pagamento; si vedono anche nei **partitari**.
## Partite e stati
Una **partita** è una rata di un documento: controparte, documento, numero rata, scadenza, importo, pagato, residuo,
metodo di pagamento, banca, stato e registrazione collegata. Le partite nascono dalle condizioni di pagamento dei
documenti ([Vendite](Vendite), [Acquisti](Acquisti)) o dall'import delle partite di apertura
([Import-Export](Import-Export)).
In alto cinque **riquadri di aging** sommano il residuo per anzianità: *non scaduto*, *1-30*, *31-60*, *61-90* e
*oltre 90 giorni*. I badge accanto al titolo danno il totale aperto e il totale scaduto.
| Stato | Significato |
|---|---|
| **Aperta** | non ancora incassata/pagata, non scaduta |
| **Parziale** | incassata in parte |
| **Aperta** | non ancora incassata o pagata |
| **Parziale** | incassata o pagata in parte |
| **Chiusa** | saldata |
| **Insoluta** | effetto tornato insoluto, riaperta con le spese |
| **In distinta** | inserita in una distinta RiBa/SDD presentata |
| **Contestata** | esclusa dai solleciti e dalle distinte finché non si risolve |
| **Insoluta** | effetto o addebito tornato indietro: la partita è di nuovo da incassare |
| **In distinta** | inserita in una distinta RiBa, SDD o bonifici: non si incassa a mano finché resta lì |
La griglia mostra anche i **giorni** rispetto alla scadenza (positivi se scaduta) e le etichette *Scaduta*,
*In scadenza*, *Aperta · split* (fatture in split payment). Il selettore **Clienti / Fornitori** cambia lato.
Oltre allo stato la griglia segnala **Scaduta** (in rosso), **In scadenza** entro 7 giorni e **Contestata** (una
partita contestata resta fuori da distinte e solleciti). La colonna **Gg** conta i giorni dalla scadenza: positivi
se scaduta, negativi se manca ancora tempo.
**Filtri.** Ricerca per controparte o documento; **Mostra** (*Aperte*, *Scadute*, *Insolute*, *In distinta*,
*Contestate*, *Chiuse*, *Tutte*); **Metodo** di pagamento; il selettore **Clienti / Fornitori** cambia lato (dal
menu *Pagamenti → Registra pagamento* si arriva direttamente ai fornitori). **Esporta** scarica la griglia in CSV.
![Khaemhat 0.8.0 · partite aperte dei fornitori](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/scadenzario-fornitori.png)
*Khaemhat 0.8.0 — Lo stesso elenco sul lato fornitori, con il pulsante Registra pagamento.*
**Modificare una partita.** La matita apre la scheda della rata: si cambiano **scadenza**, **metodo**, **banca** e
**contestazione** (con una nota). L'importo no: si corregge il documento.
**Estratto conto.** Selezionata una partita, **Estratto conto** mostra per quella controparte le partite aperte con
lo scaduto, gli interessi di mora maturati a oggi e gli incassi o pagamenti registrati.
## Registrare un incasso o un pagamento
1. In **Partite aperte** seleziona una o più partite dello stesso cliente e premi **Registra incasso**.
2. Compila **Data**, **Metodo** (es. bonifico MP05), **Importo**, **Banca azienda**, **Riferimento** (CRO) e
**Causale** (INC per gli incassi, PAG per i pagamenti).
3. Nella tabella *Partite da chiudere* distribuisci l'importo: per ogni rata **Incassato**, **Abbuono** e
**Residuo dopo**.
4. Leggi l'anteprima della prima nota che verrà generata (banca in dare, cliente in avere, abbuono sul suo conto).
![Khaemhat 0.8.0 · dialogo Registra incasso](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/scadenzario-incasso.png)
*Khaemhat 0.8.0 — Registra incasso su una partita del cliente: data, metodo, banca, riferimento, spese, la tabella
delle partite da chiudere e l'anteprima della registrazione.*
1. In **Partite aperte** seleziona una o più partite della **stessa controparte** (le partite in distinta non si
selezionano) e premi **Registra incasso** (o **Registra pagamento** sul lato fornitori).
2. Compila **Data**, **Metodo**, **Banca** dell'azienda (o la cassa), **Riferimento** (CRO o TRN), eventuali
**Spese** bancarie e **Note**.
3. Nella tabella *Partite da chiudere* ogni rata propone tutto il residuo: abbassa l'importo per un incasso
**parziale** oppure indica un **abbuono** per chiudere la differenza (es. il cliente arrotonda per difetto).
*Residuo dopo* mostra cosa resta aperto.
4. Leggi l'anteprima: *Banca (D) / Clienti (A)* per un incasso, *Fornitori (D) / Banca (A)* per un pagamento,
con gli abbuoni sul loro conto.
5. Premi **Registra e chiudi partite**.
Regole:
Cosa succede:
- **Abbuoni**: piccola differenza fra dovuto e incassato chiusa come abbuono attivo o passivo.
- **Differenze cambio** per le partite in valuta, **spese** bancarie e **storno** dell'incasso sono gestiti nello
stesso movimento.
- Un pagamento a un professionista rileva la **ritenuta d'acconto** da versare ([IVA](IVA)).
- viene scritta la registrazione con causale **INC** (incassi) o **PAG** (pagamenti), collegata al movimento;
- gli **abbuoni** vanno su *abbuoni passivi* (concessi al cliente) o *abbuoni attivi* (ottenuti dal fornitore);
- le **spese** vanno su *spese bancarie*; per le partite in valuta la **differenza cambio** fra il cambio della
fattura e quello dell'incasso va su *utili* o *perdite su cambi*;
- le **note di credito** aperte della stessa controparte si possono selezionare insieme alle fatture: riducono
l'importo da incassare;
- per una fattura di un **professionista** con ritenuta d'acconto, quando la fattura è pagata del tutto la ritenuta
diventa **da versare** e compare in *Ritenute e F24* ([IVA](IVA)).
**Incassi** e **Pagamenti** elencano i movimenti del periodo con controparte, documenti saldati, riferimento, banca,
origine (*Manuale*, *Distinta*, *Estratto conto*), importo, abbuoni, spese e la registrazione. La freccia
**Annulla** storna il movimento: la registrazione viene annullata e le partite tornano aperte com'erano.
![Khaemhat 0.8.0 · l'elenco degli incassi](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/scadenzario-incassi.png)
*Khaemhat 0.8.0 — Incassi del periodo con documento saldato, riferimento CRO, banca e registrazione contabile.*
![Khaemhat 0.8.0 · l'elenco dei pagamenti](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/scadenzario-pagamenti.png)
*Khaemhat 0.8.0 — Pagamenti ai fornitori con le spese bancarie e la freccia per annullarli.*
## Distinte RiBa, SDD e bonifici SEPA
| Tipo | Uso | File prodotto |
|---|---|---|
| **RiBa** | incasso di ricevute bancarie dai clienti | file CBI (tracciato standard RiBa) |
| **SDD core / B2B** | addebito diretto sul conto del cliente, con **mandati** | `pain.008` |
| **Bonifici SEPA** | pagamento dei fornitori | `pain.001` |
| MAV / RAV | gestiti come semplici scadenze | — |
| **RiBa (CBI)** | incasso delle ricevute bancarie dei clienti | file CBI RiBa a record di 120 caratteri |
| **SDD Core** | addebito diretto sul conto di un privato, con mandato | XML SEPA `pain.008.001.08` |
| **SDD B2B** | addebito diretto sul conto di un'impresa, con mandato B2B | XML SEPA `pain.008.001.08` |
| **Bonifici SEPA** | pagamento dei fornitori | XML SEPA `pain.001.001.09` |
1. **Distinte RiBa/SDD**, scegli **Tipo**, **Banca di presentazione**, **Data presentazione** e **Scadenze fino al**.
2. **Selezione effetti**: Khaemhat propone gli effetti; la colonna **Controllo** segnala *IBAN mancante* o
*Scaduta: escludere?*.
3. **Controlli**: IBAN, CIN, scadenze.
4. **Genera file CBI** (o il file SEPA): il file resta come allegato della distinta.
5. **Contabilizza distinta**: effetti attivi presentati in banca, con l'opzione **Salvo buon fine (anticipo)** per gli
anticipi s.b.f.
6. **Presentazione**: carica il file nell'home banking.
![Khaemhat 0.8.0 · nuova distinta RiBa con i passi guidati](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/scadenzario-distinte.png)
*Khaemhat 0.8.0 — Nuova distinta: tipo, banca, date, salvo buon fine e i passi; a destra gli effetti candidati con il
controllo (qui due effetti scaduti da valutare).*
**Storico distinte** mostra le distinte precedenti.
### Creare una distinta
### Insoluti
1. **Distinte RiBa/SDD → Nuova distinta**: scegli **Tipo**, **Banca di presentazione**, **Data presentazione** e
**Scadenze fino al**. Per le RiBa puoi spuntare **Salvo buon fine (anticipo)** se la banca anticipa gli importi.
2. A destra compaiono gli effetti candidati (partite con metodo RiBa, SDD o bonifico, non contestate, non già in
distinta). La colonna **Controllo** segnala cosa non va: *IBAN mancante* (o ABI/CAB per le RiBa), *mandato mancante* (SDD),
*Scaduta: escludere?*. Spunta gli effetti da includere: totale e numero si aggiornano.
3. **Crea distinta**: la distinta nasce in **Bozza** con il numero dell'anno (es. 2026/002) e le partite passano
*In distinta*.
Quando un effetto torna insoluto (anche dalla riconciliazione bancaria), la partita viene **riaperta** con le
**spese** addebitate e la registrazione con causale **INS**; lo stato diventa *Insoluta*.
### Dalla bozza alla chiusura
![Khaemhat 0.8.0 · dettaglio di una distinta in bozza](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/scadenzario-distinta-dettaglio.png)
*Khaemhat 0.8.0 — Storico distinte e dettaglio di una distinta s.b.f. in bozza, con gli effetti e le azioni.*
Da **Storico distinte** si apre una distinta e si procede:
| Passo | Azione | Effetto |
|---|---|---|
| 1 | **Genera file** | crea il file CBI o XML (scaricabile e conservato come allegato); stato *File generato* |
| 2 | **Contabilizza presentazione** | RiBa e SDD: i crediti passano da *Clienti* a *Effetti all'incasso* (con anticipo s.b.f. la banca accredita subito su *Banche c/anticipi*); bonifici: i fornitori sono pagati e la distinta si chiude |
| 3 | **Accredito** | alla scadenza la banca accredita: *Banca* in dare, *Effetti all'incasso* (o *Banche c/anticipi*) in avere; la distinta si chiude |
| — | **Insoluto** su una riga | l'effetto torna indietro: la partita torna *Insoluta*, la banca riprende l'importo e le **spese** dell'insoluto diventano una nuova partita del cliente |
Finché la distinta è in bozza si può togliere una riga (la ✕) o **eliminarla** del tutto: le partite tornano
aperte. Il file va poi caricato nell'home banking: Khaemhat non lo invia alla banca.
### Mandati SDD
![Khaemhat 0.8.0 · mandati SEPA Direct Debit](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/scadenzario-mandati.png)
*Khaemhat 0.8.0 — Mandati SDD con riferimento univoco (UMR), data di firma, schema, IBAN, ultimo incasso e stato.*
Ogni cliente che paga con addebito diretto deve aver firmato un **mandato**. In **Mandati SDD → Nuovo mandato**
indica cliente, **riferimento del mandato** (UMR, unico per creditore), data di firma, **schema** (*Core* per i
privati, *B2B* per le imprese), IBAN e BIC del debitore. Il primo addebito esce come **FRST**, i successivi come
**RCUR**. Un mandato **revocato** (o un mandato *una tantum* già usato) non vale più: la distinta segnala il cliente
come *mandato mancante*.
## Riconciliazione bancaria
1. **Riconciliazione bancaria**, scegli il conto e premi **Importa estratto conto**: formati **CSV**, **CBI** e
**CAMT.053**.
2. **Abbina automatico**: Khaemhat cerca l'abbinamento per importo, data, CRO/riferimento e nome, e indica una
**confidenza** in percentuale.
3. **Conferma suggeriti ≥ 90 %** conferma in blocco gli abbinamenti più sicuri; gli altri si confermano o si
correggono riga per riga.
4. Le righe senza documento (commissioni, F24, addebiti) si registrano direttamente; con una **regola salvata**
(es. "COMMISSIONI" → spese bancarie) i movimenti ricorrenti vengono riconosciuti in automatico.
5. I riquadri **Saldo banca**, **Saldo contabile** e **Differenza** mostrano cosa resta da abbinare.
![Khaemhat 0.8.0 · riconciliazione dell'estratto conto](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/scadenzario-riconciliazione.png)
*Khaemhat 0.8.0 — Movimenti dell'estratto conto con stato, abbinamento proposto e confidenza; in alto saldo banca,
saldo contabile e differenza.*
| Stato riga | Significato |
|---|---|
| **Abbinato** | collegato a incasso/pagamento registrato |
| **Suggerito** | abbinamento proposto, da confermare |
| **Da abbinare** | più candidati o nessuno |
| **Insoluto** | riapre la partita con le spese |
1. Scegli la **Banca** e premi **Importa estratto conto**. Formati accettati:
- **CSV** dell'home banking: Khaemhat riconosce da solo separatore e colonne dalla riga di intestazione
(*Data contabile*, *Data valuta*, *Descrizione*, *Importo* oppure *Entrate*/*Uscite*, anche in inglese);
- **CBI** (rendicontazione movimenti di conto corrente, record RH/61/62/63/64/EF);
- **CAMT.053** (XML ISO 20022).
I movimenti **già importati** vengono riconosciuti e saltati, anche se carichi due volte lo stesso file o due
file che si sovrappongono.
2. Khaemhat propone per ogni movimento cosa potrebbe essere, con una **confidenza** in percentuale:
| Abbinamento | Quando |
|---|---|
| **Partite** | importo uguale al residuo di una o più partite della stessa controparte |
| **Movimento registrato** | un incasso o pagamento già registrato a mano |
| **F24** | un versamento di imposte registrato in *Ritenute e F24* |
| **Accredito distinta** / **Insoluto** | l'accredito di una distinta presentata o un effetto respinto |
| **Regola** | una **regola salvata** riconosce il testo (es. *COMMISSIONI* → spese bancarie) |
La confidenza parte dall'importo (esatto o entro la tolleranza) e sale con il numero del documento o il CRO
nella descrizione, l'IBAN e il nome della controparte e la vicinanza delle date; una regola vale 98%.
3. **Conferma suggeriti ≥ 90%** conferma in blocco le proposte più sicure; le altre si confermano con ✓ o si
correggono riga per riga:
- ☰ **Abbina a partite** — scegli le partite: viene registrato l'incasso o il pagamento;
- € **Abbina a incasso o pagamento registrato** — collega un movimento già registrato a mano;
- 📖 **Registra su conto** — per le righe senza documento (commissioni, canoni, carburante) scegli il conto e,
se vuoi, salva una **regola** per le prossime volte;
- **Ignora** — il movimento non va riconciliato.
La freccia **Annulla abbinamento** riporta la riga da riconciliare e annulla quello che aveva registrato.
4. La striscia in alto mostra **saldo banca** (dall'ultimo estratto), **saldo contabile** del conto, **differenza** e
movimenti ancora da riconciliare. Le schede **Regole** ed **Estratti importati** elencano le regole salvate (con
quante volte sono state usate) e i file caricati.
## Solleciti
**Solleciti** (mockup 056) gestisce tre **livelli**, ciascuno con giorni di ritardo, modello, canale, interessi e
azione. Esempio del mockup:
![Khaemhat 0.8.0 · proposta di invio dei solleciti](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/scadenzario-solleciti.png)
*Khaemhat 0.8.0 — Proposta di invio per cliente con prossimo livello, canale e interessi di mora; sotto i tre livelli.*
I solleciti seguono tre **livelli**, ciascuno con i giorni dopo la scadenza, il modello del messaggio, i **canali**
(e-mail, PEC, lettera PDF), gli interessi di mora e un'**azione**:
| Livello | Dopo (gg) | Modello | Canale | Interessi | Azione |
|---|---|---|---|---|---|
| 1 | 7 | Promemoria cortese | e-mail | no | — |
| 2 | 20 | Sollecito formale | PEC + e-mail | sì | notifica agente |
| 3 | 45 | Messa in mora | PEC + lettera PDF | sì | blocco cliente, notifica amministrazione |
| 2 | 20 | Sollecito | e-mail + PEC | sì | avvisa l'agente (in copia) |
| 3 | 45 | Diffida e blocco forniture | PEC + lettera PDF | sì | blocca il cliente |
- La **proposta di invio** elenca per cliente partite, scaduto, giorni massimi, ultimo sollecito, prossimo livello,
canale, interessi di mora e l'interruttore **Includi**. Sono esclusi per regola la PA e i clienti con partite
contestate.
- Gli **interessi di mora** seguono il D.Lgs. 231/2002 (transazioni commerciali); il tasso è un parametro aggiornato
periodicamente.
- **Anteprima** mostra i messaggi; **Invia N solleciti** li spedisce e li annota nel **registro invii**.
- Il livello 3 può **bloccare il cliente** (ordini e documenti richiedono un override).
- I solleciti si eseguono anche da **attività programmata** (riquadro *Prossima esecuzione*), vedi
[Automazioni](Automazioni).
![Khaemhat 0.8.0 · modifica di un livello di sollecito](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/scadenzario-sollecito-livello.png)
*Khaemhat 0.8.0 — Un livello si modifica con la matita: giorni, azione, canali, interessi, invio automatico, oggetto e
testo con i segnaposto.*
## Flusso di cassa e report
Nel testo si usano i **segnaposto** `{cliente}`, `{azienda}`, `{elenco}` (le partite scadute), `{totale}`,
`{interessi}`, `{riferimento}` e `{giorni}`.
| Report | Contenuto |
- La **Proposta di invio** elenca i clienti con partite scadute oltre i giorni del livello successivo a quello già
inviato: partite, scaduto, giorni massimi, ultimo sollecito, prossimo livello, canale e interessi. Sono esclusi per
regola la **pubblica amministrazione**, le partite **contestate** e quelle in distinta. L'interruttore
**Includi** toglie un cliente dall'invio.
- **Anteprima** scarica il PDF del sollecito del primo cliente incluso; **Invia N solleciti** mette in coda e-mail e
PEC con il PDF allegato (vedi [Impostazioni](Impostazioni) per SMTP e PEC) e scarica in un unico PDF le **lettere**
da stampare e spedire. Un cliente senza indirizzo e-mail o PEC viene saltato, con un avviso, se il livello non
prevede la lettera.
- Gli **interessi di mora** seguono il D.Lgs. 231/2002: tasso BCE di riferimento del semestre più 8 punti
(10,15% nel primo semestre 2026, 10,40% nel secondo), calcolati giorno per giorno sul residuo di ogni partita.
Gli interessi compaiono nel messaggio e nel PDF; non vengono addebitati in contabilità.
- Il livello con azione **Blocca il cliente** imposta il blocco nelle condizioni di vendita dell'anagrafica.
- Il **Registro invii** conserva ogni sollecito con data, livello, canale, destinatari, importo, interessi e stato
dell'invio.
- I livelli segnati **Automatico** partono da soli con l'attività programmata *Solleciti* (giorni feriali alle 7:00,
vedi [Attività programmate](Attivita-programmate)); solo e-mail e PEC, mai la lettera.
## Flusso di cassa
![Khaemhat 0.8.0 · flusso di cassa previsto a 90 giorni](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/scadenzario-flusso-di-cassa.png)
*Khaemhat 0.8.0 — Disponibilità di oggi, entrate e uscite previste per settimana con il saldo progressivo e i
movimenti che lo compongono.*
Il **flusso di cassa** parte dalla disponibilità di oggi (saldo contabile di banche e cassa) e aggiunge, periodo per
periodo, i movimenti attesi da sei **fonti** che si accendono e spengono con le caselle:
| Fonte | Da dove |
|---|---|
| Scadenzario | partite per scadenza, cliente/fornitore, metodo |
| Aging | crediti per fasce di ritardo (come i riquadri del mockup 053) |
| Estratto conto | per cliente/fornitore, anche in PDF da inviare |
| **Flusso di cassa 90 giorni** | entrate e uscite previste da partite, distinte e saldi bancari |
| Insoluti | effetti tornati insoluti con spese |
| Posizione bancaria | saldi dei conti e effetti presentati |
| Incassi da clienti | partite aperte dei clienti e gli effetti presentati senza anticipo, alla loro scadenza |
| Pagamenti a fornitori | partite aperte dei fornitori |
| Ordini clienti / fornitori | il residuo degli ordini non ancora fatturati, 30 giorni dopo la consegna prevista (o la data dell'ordine) |
| Ricorrenti | le registrazioni ricorrenti della contabilità (affitti, noleggi…) che muovono la banca |
| Imposte | i versamenti F24 non ancora pagati (IVA, acconto, ritenute) alla loro scadenza |
Vedi [Report](Report).
L'**orizzonte** va da 30 a 365 giorni, il **periodo** è la settimana o il mese. Le partite già scadute cadono nel
primo periodo. La striscia riassume disponibilità di oggi, entrate e uscite previste, saldo finale e **punto più
basso** (in rosso se il conto andrebbe in negativo).
## Sulla Home
Con il permesso `finance.schedule.read` la [Dashboard](Dashboard) mostra:
- nelle **Scadenze** gli incassi e i pagamenti dei prossimi giorni (al massimo 12), con il link alla partita;
- nelle **Cose da fare** il totale dei crediti scaduti, con il link ai solleciti.
## Dati di esempio
L'azienda demo (se la licenza comprende FIN) arriva con la banca *Banca Popolare Dimostrativa*, i versamenti dei
soci, incassi e pagamenti già registrati (uno parziale), una distinta RiBa accreditata con un **insoluto**, una
distinta s.b.f. in bozza, un mandato SDD, un estratto conto CSV da riconciliare con una regola per le commissioni e
un primo sollecito già inviato. Vedi [Dati di base e di esempio](Dati-di-base-e-esempio).
## Permessi e licenza
Serve il modulo **FIN** (e ACCT per le registrazioni contabili automatiche). I codici dei permessi in testa sono
indicativi (convenzione `modulo.entità.azione`, SPEC §7.2) e saranno fissati in sviluppo.
| Permesso | Cosa consente |
|---|---|
| `finance.schedule.read` | vedere partite, distinte, mandati, solleciti, flusso di cassa e le scadenze sulla Home |
| `finance.schedule.write` | modificare le partite, creare e presentare le distinte, gestire mandati e solleciti |
| `finance.payment.read` | vedere incassi e pagamenti |
| `finance.payment.write` | registrare e stornare incassi e pagamenti |
| `finance.bank.reconcile` | importare gli estratti conto, riconciliare, gestire le regole |
Serve il modulo **FIN**; le registrazioni contabili chiedono anche **ACCT**.
## Domande frequenti
**Il cliente ha pagato due fatture con un bonifico solo.** Seleziona entrambe le partite e registra un unico incasso,
distribuendo l'importo.
**Il cliente ha pagato due fatture con un bonifico solo.** Seleziona entrambe le partite e registra un unico incasso:
l'importo si distribuisce sulle rate, la più vecchia per prima. Se il bonifico arriva dall'estratto conto, *Abbina a
partite* fa la stessa cosa.
**Ho caricato l'estratto conto due volte.** Il riconoscimento dei movimenti già importati non è ancora definito
dalla specifica: sarà stabilito in sviluppo e descritto qui.
**Ho caricato l'estratto conto due volte.** Nessun problema: i movimenti già presenti vengono riconosciuti
dall'impronta (banca, data, importo, descrizione, riferimento) e saltati; il messaggio dice quanti.
**Ho registrato un incasso sbagliato.** In *Incassi* premi **Annulla** sulla riga: la registrazione viene stornata e
le partite riaperte. Se l'incasso veniva dalla riconciliazione, la riga dell'estratto torna *Da abbinare*.
**Una RiBa è tornata insoluta.** Apri la distinta in *Storico distinte* e premi **Insoluto** sulla riga (o confermalo
dalla riconciliazione): la partita torna aperta e le spese diventano una nuova partita da addebitare al cliente.
**Perché un cliente non compare tra i solleciti?** È una pubblica amministrazione, ha partite contestate o in
distinta, oppure il prossimo livello non è ancora maturato.
## Pagine correlate
[Contabilità](Contabilita) · [Vendite](Vendite) · [Acquisti](Acquisti) · [Anagrafiche](Anagrafiche) · [IVA](IVA) ·
[Automazioni](Automazioni) · [Report](Report) · [Attività programmate](Attivita-programmate)
[Contabilità](Contabilita) · [IVA](IVA) · [Vendite](Vendite) · [Acquisti](Acquisti) · [Anagrafiche](Anagrafiche) ·
[Tabelle azienda](Tabelle-azienda) · [Dashboard](Dashboard) · [Attività programmate](Attivita-programmate) ·
[Fiscalità italiana](Fiscalita-italiana) · [Report](Report)
+2 -2
View File
@@ -98,7 +98,7 @@ periodo (vedi [IVA](IVA)) e la chiusura dell'esercizio lo rende di sola lettura
| **Codici IVA** | aliquota, natura SDI, riferimento normativo, esigibilità, tipo, indetraibilità, conti IVA, validità (vedi sotto) |
| **Metodi di pagamento** | codici SDI `MP01`…`MP23` (es. MP01 contanti, MP02 assegno, MP05 bonifico, MP08 carta di pagamento, MP12 RiBa, MP19 SEPA Direct Debit) |
| **Condizioni di pagamento** | con righe: rata, giorni, fine mese, giorno fisso, percentuale, IVA sulla prima rata; tipo SDI `TP01` (a rate), `TP02` (completo), `TP03` (anticipo) |
| **Banche aziendali** | IBAN, BIC, conto contabile, codici SIA/CUC per RiBa e SDD |
| **Banche aziendali** | IBAN, BIC, conto contabile, codice SIA (RiBa), CUC e identificativo creditore SEPA (SDD), banca predefinita; usate da incassi, distinte e riconciliazione dello [Scadenzario](Scadenzario) |
| **Agenti** | provvigione, iscrizione ENASARCO |
| **Vettori** | corrieri e trasportatori |
| **Porti** (condizioni di spedizione) | franco, assegnato… |
@@ -221,7 +221,7 @@ Ogni opzione si accende o spegne con un interruttore; spenta, i campi restano da
| Comune, provincia e regione dal CAP | scrivendo il CAP propone il comune (o i comuni) con provincia e regione; scrivendo il comune propone CAP e provincia | accesa |
| Codice fiscale dai dati anagrafici | calcola il codice fiscale delle persone fisiche da cognome, nome, data, sesso e comune di nascita | accesa |
| Verifica P.IVA UE (VIES) al salvataggio | interroga il servizio VIES e salva l'esito (*valida*, *non valida*, *servizio non disponibile*) | accesa |
| Banca e BIC dall'IBAN | legge ABI e CAB dall'IBAN; banca e BIC vengono dall'elenco ABI o, finché l'elenco non è caricato, da un conto dell'azienda presso la stessa banca | accesa |
| Banca e BIC dall'IBAN | legge ABI e CAB dall'IBAN; banca e BIC vengono da un conto dell'azienda presso la stessa banca (l'elenco ABI non è precaricato) | accesa |
| Cambi BCE giornalieri | l'attività di sistema scarica i cambi nei giorni lavorativi; spenta, l'azienda usa solo cambi manuali | accesa |
| Descrizione articolo nelle righe | copia la descrizione dell'articolo nella riga del documento | accesa |
| Ultimo prezzo praticato al cliente | lo mostra come riferimento | accesa |
+4 -4
View File
@@ -11,9 +11,9 @@ 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
> **si contabilizzano** da sole (vedi [Contabilità](Contabilita)). Dalla 0.8 gli **incassi** si registrano dallo [Scadenzario](Scadenzario).
> Dalla 0.9 le fatture emesse diventano **file FatturaPA** e si trasmettono allo SDI dalla
> [Fatturazione elettronica](Fatturazione-elettronica). Arrivano più avanti: il controllo del fido e il collegamento alle opportunità del **CRM** (M11). I pulsanti di queste funzioni compaiono quando la
> funzione c'è.
## Dove si trova
@@ -277,7 +277,7 @@ Le autofatture e le integrazioni (TD16-TD29) sono negli [Acquisti](Acquisti). L'
|---|---|
| **Bozza** | modificabile |
| **Emessa** | numerata e immutabile |
| **XML generato**, **Inviata allo SdI**, **Consegnata**, **Scartata**, **Non consegnata** | gli stati della fatturazione elettronica (M9) |
| **XML generato**, **Inviata allo SdI**, **Consegnata**, **Scartata**, **Non consegnata** | gli stati della [fatturazione elettronica](Fatturazione-elettronica) |
Che cosa si può fare:
+2
View File
@@ -28,9 +28,11 @@
**Contabilità e fisco**
- [Contabilità](Contabilita)
- [Chiusura e bilancio](Chiusura-e-bilancio)
- [IVA](IVA)
- [Cespiti](Cespiti)
- [Intrastat](Intrastat)
- [Dichiarazioni d'intento](Dichiarazioni-d-intento)
- [Scadenzario](Scadenzario)
- [Fatturazione elettronica](Fatturazione-elettronica)
- [Fiscalità italiana](Fiscalita-italiana)
Binary file not shown.

After

Width:  |  Height:  |  Size: 211 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 98 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 103 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 106 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 129 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 146 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 138 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 205 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 81 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 133 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 65 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 130 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 172 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 130 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 136 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 75 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 93 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 178 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 121 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 91 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 100 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 117 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 168 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 98 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 62 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 147 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 66 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 69 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 142 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 113 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 108 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 119 KiB

+1
View File
@@ -3,6 +3,7 @@
# tables still empty (--scale N repeats the demo catalogues N times). Rows already there are never changed.
# scripts/seed.sh --base [--company CODE]
# scripts/seed.sh --demo [--scale N] [--company CODE]
# scripts/seed.sh --remove-demo [--company CODE] removes only the rows marked demo (and what belongs to them)
# In the container (shipped as /app/scripts/seed.sh, same KHAEMHAT_* variables as the service):
# docker compose run --rm --entrypoint /app/scripts/seed.sh khaemhat --base
# On a development machine it runs the project with the variables already set in the shell (see scripts/run-dev.sh).
@@ -33,6 +33,7 @@ public sealed class AuditTrail(TimeProvider clock)
{
nameof(IAuditable.CreatedAt), nameof(IAuditable.CreatedBy), nameof(IAuditable.UpdatedAt), nameof(IAuditable.UpdatedBy), "RowVersion",
"PasswordHash", "PasswordHistory", "TotpSecret", "TotpRecoveryCodes", "RecoveryTokenHash", "TokenHash", "ConnectionString",
"ProtectedPassword", "ProtectedCertificate", "ProtectedCertificatePassword", "ProtectedApiKey", "Content", "Metadata",
};
/// <summary>Writes the history row of a change, inside the caller's unit of work.</summary>
@@ -274,6 +274,7 @@ public sealed partial class DocumentEngine
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 SyncIntentAsync(uow, pack, record.Family, id, cancellationToken).ConfigureAwait(false);
}
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
@@ -308,6 +309,7 @@ public sealed partial class DocumentEngine
await _fiscal.DemandOpenAsync(company, draft.Header.DocumentDate, PeriodUse.Vat, cancellationToken).ConfigureAwait(false);
}
var pack = await _packs.PackOfAsync(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 next = DocumentStateMachine.Apply(definition.Lifecycle, record.Header.Status, definition.ConfirmAction);
@@ -318,6 +320,11 @@ public sealed partial class DocumentEngine
}
await CheckSupplierDocumentAsync(uow, record, confirming: true, errors, cancellationToken).ConfigureAwait(false);
if (pack.GetFeature<Fiscal.Abstractions.IIntentRules>() is { } intent)
{
// A sale under a declaration of intent needs the declaration and the ceiling left (ADR 0042).
await YearEnd.IntentDeclarationService.CheckAsync(uow, intent, definition.Behavior, record, errors, cancellationToken).ConfigureAwait(false);
}
if (definition.Behavior.Has(DocumentEffects.Ledger))
{
@@ -363,6 +370,7 @@ public sealed partial class DocumentEngine
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 SyncIntentAsync(uow, pack, 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);
}
@@ -451,6 +459,48 @@ public sealed partial class DocumentEngine
}, null, cancellationToken);
}
/// <summary>
/// Moves a document along the steps of the electronic invoice inside the transaction of the caller (the e-invoice
/// service and its jobs, ADR 0039), which has already checked the permission. Steps the state does not allow are
/// skipped: a late or repeated notification never fails.
/// </summary>
/// <param name="uow">The open unit of work.</param>
/// <param name="family">The family.</param>
/// <param name="id">The document.</param>
/// <param name="steps">The steps, in order, from the state the document is in.</param>
/// <param name="userName">Who, for the history.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The state reached, or <see langword="null"/> when the document does not exist.</returns>
internal async Task<DocumentStatus?> AdvanceExchangeAsync(
IUnitOfWork uow, DocumentFamily family, long id, Func<DocumentStatus, IReadOnlyList<DocumentAction>> steps, string userName, CancellationToken cancellationToken)
{
var store = DocumentStores.Of(family);
var header = await store.GetAsync(uow, id, cancellationToken).ConfigureAwait(false);
if (header is null)
{
return null;
}
var lifecycle = DocumentBehaviors.Of(header.Kind).Lifecycle;
var old = header.Clone();
foreach (var step in steps(header.Status))
{
if (DocumentStateMachine.Allows(lifecycle, header.Status, step))
{
header.Status = DocumentStateMachine.Apply(lifecycle, header.Status, step);
header.XmlGenerated |= step == DocumentAction.GenerateXml;
}
}
if (header.Status != old.Status || header.XmlGenerated != old.XmlGenerated)
{
await store.UpdateAsync(uow, header, cancellationToken).ConfigureAwait(false);
await store.RecordAsync(_audit, uow, AuditAction.Update, id, old, header, userName, cancellationToken).ConfigureAwait(false);
}
return header.Status;
}
/// <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>
@@ -686,6 +736,7 @@ public sealed partial class DocumentEngine
{
var company = Company(actor, companyCode);
var store = DocumentStores.Of(family);
var pack = await _packs.PackOfAsync(company, cancellationToken).ConfigureAwait(false);
await using (var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false))
{
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
@@ -710,6 +761,7 @@ public sealed partial class DocumentEngine
// 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 SyncIntentAsync(uow, pack, 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);
}
@@ -866,6 +918,11 @@ public sealed partial class DocumentEngine
}
// Supplier invoices and credit notes go to the purchase register with a protocol and a VAT date.
private static Task SyncIntentAsync(IUnitOfWork uow, Fiscal.Abstractions.IFiscalPack pack, DocumentFamily family, long id, CancellationToken cancellationToken) =>
pack.GetFeature<Fiscal.Abstractions.IIntentRules>() is { } intent
? YearEnd.IntentDeclarationService.SyncDocumentAsync(uow, intent, family, id, cancellationToken)
: Task.CompletedTask;
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
@@ -52,7 +52,24 @@ public sealed class DocumentPdfGenerator(DocumentPrintService prints, Attachment
{
ArgumentNullException.ThrowIfNull(context);
var model = await ModelAsync(context, cancellationToken).ConfigureAwait(false);
await WriteAsync(model, context, output, cancellationToken).ConfigureAwait(false);
await WriteAsync(model, context, output, [], cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// The courtesy copy of an e-invoice (SPEC §11.9, issue #79): the print of the document with the XML sent to the
/// exchange system embedded as an associated file (structure of PDF/A-3, <c>/AF</c>).
/// </summary>
/// <param name="context">The document.</param>
/// <param name="xmlName">The name of the XML file.</param>
/// <param name="xml">The XML file.</param>
/// <param name="output">The stream that receives the PDF.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
public async Task CourtesyCopyAsync(FileGenerationContext context, string xmlName, byte[] xml, Stream output, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(context);
var model = await ModelAsync(context, cancellationToken).ConfigureAwait(false);
await WriteAsync(model, context, output, [(xmlName, xml)], cancellationToken).ConfigureAwait(false);
}
// The file name follows the document (number and kind); without the logo, which the name does not need.
@@ -95,7 +112,8 @@ public sealed class DocumentPdfGenerator(DocumentPrintService prints, Attachment
}
}
private static async Task WriteAsync(DocumentPrintModel model, FileGenerationContext context, Stream output, CancellationToken cancellationToken)
private static async Task WriteAsync(
DocumentPrintModel model, FileGenerationContext context, Stream output, IReadOnlyList<(string Name, byte[] Content)> embedded, CancellationToken cancellationToken)
{
var info = new PdfDocumentInfo
{
@@ -111,6 +129,11 @@ public sealed class DocumentPdfGenerator(DocumentPrintService prints, Attachment
await sheet.LinesAsync().ConfigureAwait(false);
await sheet.FooterBlocksAsync().ConfigureAwait(false);
sheet.Finish();
foreach (var (name, content) in embedded)
{
pdf.AddAttachment(name, "application/xml", content, "Fattura elettronica " + model.Number, "Source");
}
await pdf.CloseAsync(cancellationToken).ConfigureAwait(false);
}
@@ -0,0 +1,194 @@
using System.Globalization;
using System.IO.Compression;
using System.Text;
using Khaemhat.Application.Security;
using Khaemhat.Application.Tables;
using Khaemhat.Core.EInvoicing;
using Khaemhat.Data;
using Khaemhat.Data.Querying;
namespace Khaemhat.Application.EInvoicing;
/// <summary>A conservation package made.</summary>
/// <param name="Export">The row that records it.</param>
/// <param name="Content">The ZIP.</param>
public sealed record ConservationPackage(ConservationExport Export, byte[] Content);
/// <summary>
/// The package for the conservation of the e-invoices of a period (issue #79): a ZIP with the files sent
/// (<c>emesse/</c>), their notifications (<c>notifiche/</c>) and the files received (<c>ricevute/</c>), each as it
/// travelled, an index <c>indice.csv</c> with the SHA-256 of every file and a <c>LEGGIMI.txt</c>. It is what a
/// conservation service (or the free service of the AdE) takes in; Khaemhat does not replace the conservation itself.
/// </summary>
/// <remarks>Permission: <c>einvoice.document.read</c>. Every package made is recorded with its hash.</remarks>
public sealed class ConservationExportService
{
private static readonly DateTimeOffset Stamp = new(2000, 1, 1, 0, 0, 0, TimeSpan.Zero);
private readonly IUnitOfWorkFactory _factory;
private readonly PermissionService _permissions;
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="clock">The clock.</param>
public ConservationExportService(IUnitOfWorkFactory factory, PermissionService permissions, TimeProvider clock)
{
ArgumentNullException.ThrowIfNull(factory);
ArgumentNullException.ThrowIfNull(permissions);
ArgumentNullException.ThrowIfNull(clock);
_factory = factory;
_permissions = permissions;
_clock = clock;
}
/// <summary>The packages made, newest first.</summary>
/// <param name="actor">Who looks: needs <c>einvoice.document.read</c>.</param>
/// <param name="companyCode">The company.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The rows.</returns>
public async Task<IReadOnlyList<ConservationExport>> ListAsync(Actor actor, string companyCode, CancellationToken cancellationToken = default)
{
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, EInvoicePermissions.Read, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
return (await uow.Repository<ConservationExport, long>().ListAsync(Query.For<ConservationExport>().OrderByDescending(e => e.Id).Take(50), cancellationToken)
.ConfigureAwait(false)).Items;
}
/// <summary>Makes the package of a period: e-invoices sent by date of the document, files received by date of arrival.</summary>
/// <param name="actor">Who makes it: needs <c>einvoice.document.read</c>.</param>
/// <param name="companyCode">The company.</param>
/// <param name="from">First day.</param>
/// <param name="to">Last day.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The package.</returns>
public async Task<ConservationPackage> ExportAsync(Actor actor, string companyCode, DateOnly from, DateOnly to, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(actor);
if (to < from || to.DayNumber - from.DayNumber > 731)
{
throw new ValidationFailedException(["To:" + EInvoiceErrors.PeriodInvalid]);
}
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, EInvoicePermissions.Read, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
var sent = (await uow.Repository<EInvoice, long>()
.ListAsync(Query.For<EInvoice>().Where(e => e.DocumentDate >= from && e.DocumentDate <= to && e.Status != EInvoiceStatus.Generated).OrderBy(e => e.Progressive), cancellationToken)
.ConfigureAwait(false)).Items;
var notifications = new List<EInvoiceNotification>();
foreach (var chunk in sent.Select(e => e.Id).Chunk(500))
{
var ids = chunk.Select(id => (long?)id).ToList();
notifications.AddRange((await uow.Repository<EInvoiceNotification, long>()
.ListAsync(Query.For<EInvoiceNotification>().Where(n => ids.Contains(n.EInvoiceId)).OrderBy(n => n.ReceivedAt), cancellationToken)
.ConfigureAwait(false)).Items);
}
var start = from.ToDateTime(TimeOnly.MinValue, DateTimeKind.Utc);
var end = to.AddDays(1).ToDateTime(TimeOnly.MinValue, DateTimeKind.Utc);
var received = (await uow.Repository<EInvoiceInboxFile, long>()
.ListAsync(Query.For<EInvoiceInboxFile>().Where(f => f.ReceivedAt >= start && f.ReceivedAt < end && f.Status != InboxFileStatus.Discarded).OrderBy(f => f.ReceivedAt), cancellationToken)
.ConfigureAwait(false)).Items;
var index = new StringBuilder("cartella;file;tipo;documento;data;controparte;identificativo_sdi;stato;sha256\r\n");
var count = 0;
using var buffer = new MemoryStream();
using (var zip = new ZipArchive(buffer, ZipArchiveMode.Create, leaveOpen: true))
{
var names = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
void Add(string folder, string name, byte[] content, string kind, string? number, string? date, string? party, string? exchange, string state)
{
var path = Unique(names, folder + "/" + Path.GetFileName(name));
var entry = zip.CreateEntry(path, CompressionLevel.Optimal);
entry.LastWriteTime = Stamp;
using (var stream = entry.Open())
{
stream.Write(content);
}
index.Append(string.Join(';', folder, Csv(Path.GetFileName(path)), kind, Csv(number), date, Csv(party), Csv(exchange), state, EInvoiceStore.Hash(content))).Append("\r\n");
count++;
}
foreach (var e in sent)
{
Add("emesse", e.FileName, e.Content, e.DocumentType, e.DocumentNumber, Date(e.DocumentDate), e.RecipientCode, e.ExchangeId, e.Status.ToString());
}
foreach (var n in notifications)
{
Add("notifiche", n.FileName, n.Content, n.Code, n.InvoiceFileName, Date(DateOnly.FromDateTime(n.ReceivedAt)), null, n.ExchangeId, n.Outcome ?? string.Empty);
}
foreach (var f in received)
{
Add("ricevute", f.FileName, f.Content, f.DocumentType ?? string.Empty, f.Number, f.DocumentDate is { } d ? Date(d) : null, f.SupplierName, f.ExchangeId, f.Status.ToString());
if (f.Metadata is { Length: > 0 } metadata && f.MetadataFileName is { } metadataName)
{
Add("ricevute", metadataName, metadata, "MT", f.Number, null, f.SupplierName, f.ExchangeId, string.Empty);
}
}
Write(zip, "indice.csv", Encoding.UTF8.GetPreamble().Concat(Encoding.UTF8.GetBytes(index.ToString())).ToArray());
Write(zip, "LEGGIMI.txt", Encoding.UTF8.GetBytes(Readme(company, from, to, sent.Count, notifications.Count, received.Count)));
}
var content = buffer.ToArray();
var fileName = string.Create(CultureInfo.InvariantCulture, $"conservazione-{company}-{from:yyyyMMdd}-{to:yyyyMMdd}.zip");
var export = new ConservationExport
{
FromDate = from,
ToDate = to,
FileCount = count,
FileName = fileName,
Hash = EInvoiceStore.Hash(content),
Size = content.LongLength,
};
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
export.Id = await uow.Repository<ConservationExport, long>().InsertAsync(export, cancellationToken).ConfigureAwait(false);
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
return new ConservationPackage(export, content);
}
private static void Write(ZipArchive zip, string name, byte[] content)
{
var entry = zip.CreateEntry(name, CompressionLevel.Optimal);
entry.LastWriteTime = Stamp;
using var stream = entry.Open();
stream.Write(content);
}
private static string Unique(HashSet<string> names, string path)
{
var candidate = path;
for (var i = 2; !names.Add(candidate); i++)
{
candidate = Path.ChangeExtension(path, null) + "-" + i.ToString(CultureInfo.InvariantCulture) + Path.GetExtension(path);
}
return candidate;
}
private static string Date(DateOnly date) => date.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture);
private static string Csv(string? value) =>
string.IsNullOrEmpty(value) ? string.Empty : value.IndexOfAny([';', '"', '\r', '\n']) >= 0 ? "\"" + value.Replace("\"", "\"\"", StringComparison.Ordinal) + "\"" : value;
private string Readme(string company, DateOnly from, DateOnly to, int sent, int notifications, int received) =>
string.Create(CultureInfo.InvariantCulture, $"""
Khaemhat - pacchetto per la conservazione delle fatture elettroniche
Azienda: {company}
Periodo: dal {from:dd/MM/yyyy} al {to:dd/MM/yyyy}
Creato il: {_clock.GetUtcNow():yyyy-MM-dd HH:mm} UTC
emesse/ {sent} fatture inviate al SDI, nel formato in cui sono state trasmesse
notifiche/ {notifications} ricevute e notifiche del SDI relative alle fatture emesse
ricevute/ {received} fatture ricevute dai fornitori, con i file metadati (MT)
indice.csv l'elenco dei file con l'impronta SHA-256 di ciascuno
I file sono quelli originali: nessuno è stato modificato. Il pacchetto va consegnato al servizio di
conservazione (ad esempio il servizio gratuito dell'Agenzia delle Entrate o un conservatore accreditato);
Khaemhat non sostituisce la conservazione a norma.
""");
}
@@ -0,0 +1,553 @@
using Khaemhat.Application.Documents;
using Khaemhat.Application.Security;
using Khaemhat.Application.Tables;
using Khaemhat.Core.Documents;
using Khaemhat.Core.Items;
using Khaemhat.Core.Parties;
using Khaemhat.Core.Tables;
using Khaemhat.Core.Tax;
using Khaemhat.Data;
using Khaemhat.Data.Querying;
using Khaemhat.Fiscal.Abstractions;
namespace Khaemhat.Application.EInvoicing;
/// <summary>
/// Turns a document into the model of the e-invoice (SPEC §11.9, ADR 0039): the company and the customer (or the
/// supplier and the company for a self-invoice), the lines with their codes, units and discounts, the summary by rate
/// and nature, stamp duty, withholding, social security fund, the documents referred to (order with CIG and CUP,
/// delivery notes, the invoice a credit note corrects) and the installments.
/// </summary>
/// <remarks>
/// <para>Amounts follow the document as computed by Khaemhat: a footer discount becomes one discount line (<c>SC</c>)
/// per rate, prices that include tax are taken back to their taxable amount, what is left by rounding goes in
/// <c>Arrotondamento</c> of the summary. A stamp duty charged to the customer is a line excluded from VAT (N1).</para>
/// <para>The file name is not set here: the service gives it with the progressive.</para>
/// </remarks>
internal static class EInvoiceBuilder
{
/// <summary>The country code of foreign customers without a VAT number (FatturaPA: eleven nines).</summary>
public const string NoVatNumber = "99999999999";
/// <summary>The recipient code of a foreign customer.</summary>
public const string ForeignRecipient = "XXXXXXX";
/// <summary>The recipient code when the file goes to a certified mailbox or to the tax drawer.</summary>
public const string NoRecipient = "0000000";
/// <summary>The type of the format of a document: the one of its document type, otherwise the default of its kind.</summary>
/// <param name="kind">The kind.</param>
/// <param name="type">The document type.</param>
/// <returns>The type (TD01 …), or <see langword="null"/> when the kind has no e-invoice.</returns>
public static string? DocumentTypeOf(DocumentKind kind, DocumentType? type)
{
if (!string.IsNullOrWhiteSpace(type?.EInvoiceType))
{
return type.EInvoiceType.Trim().ToUpperInvariant();
}
return kind switch
{
DocumentKind.ImmediateInvoice or DocumentKind.AccompanyingInvoice => "TD01",
DocumentKind.DeferredInvoice => "TD24",
DocumentKind.DownPaymentInvoice => "TD02",
DocumentKind.CreditNote => "TD04",
DocumentKind.DebitNote => "TD05",
DocumentKind.Fee => "TD06",
DocumentKind.SelfInvoice when type?.Code is { Length: 4 } code && code.StartsWith("AF", StringComparison.OrdinalIgnoreCase) => "TD" + code[2..],
_ => null,
};
}
/// <summary>Whether a kind of document goes to the exchange system.</summary>
/// <param name="kind">The kind.</param>
/// <returns><see langword="true"/> for invoices, credit and debit notes, fees and self-invoices.</returns>
public static bool IsElectronic(DocumentKind kind) => DocumentBehaviors.Of(kind).Effects.HasFlag(DocumentEffects.EInvoice);
/// <summary>Builds the file of a document.</summary>
/// <param name="uow">The unit of work of the company.</param>
/// <param name="record">The document, with lines and figures.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The model (file name empty), the party and whether it is a public administration.</returns>
public static async Task<(EInvoiceFile File, Party Party, bool PublicAdministration)> BuildAsync(IUnitOfWork uow, DocumentRecord record, CancellationToken cancellationToken)
{
var header = record.Header;
var profile = await uow.Repository<CompanyProfile, long>().FindAsync(Query.For<CompanyProfile>(), cancellationToken).ConfigureAwait(false)
?? throw new ValidationFailedException([":" + EInvoiceErrors.CompanyProfileMissing]);
var party = header.PartyId is { } partyId ? await uow.Repository<Party, long>().GetAsync(partyId, cancellationToken).ConfigureAwait(false) : null;
if (party is null)
{
throw new ValidationFailedException(["PartyId:" + DocumentErrors.PartyRequired]);
}
var fiscal = await uow.Repository<PartyFiscal, long>().FindAsync(Query.For<PartyFiscal>().Where(f => f.PartyId == party.Id), cancellationToken).ConfigureAwait(false);
var type = await uow.Repository<DocumentType, long>().GetAsync(header.DocumentTypeId, cancellationToken).ConfigureAwait(false);
var documentType = DocumentTypeOf(header.Kind, type) ?? throw new ValidationFailedException([":" + EInvoiceErrors.NotElectronic]);
var self = header.Kind == DocumentKind.SelfInvoice;
var publicAdministration = !self && party.SubjectType == SubjectType.PublicAdministration;
var company = CompanyParty(profile);
var counterpart = PartyOf(party, fiscal, self);
var foreign = !string.Equals(party.CountryCode, "IT", StringComparison.OrdinalIgnoreCase);
var (recipientCode, recipientPec) = self
? ((string Code, string? Pec))(profile.RecipientCode?.Trim().ToUpperInvariant() is { Length: > 0 } own ? own : NoRecipient, null)
: Recipient(party, fiscal, publicAdministration, foreign);
var body = await BodyAsync(uow, record, documentType, profile, fiscal, cancellationToken).ConfigureAwait(false);
var intermediary = !string.IsNullOrWhiteSpace(profile.IntermediaryTaxCode)
? new EInvoiceParty("IT", null, profile.IntermediaryTaxCode.Trim().ToUpperInvariant(), profile.IntermediaryName, null, null,
null, null, null, null, null, null, null, null, null, null, null)
: null;
var file = new EInvoiceFile(
string.Empty,
publicAdministration ? "FPA12" : "FPR12",
null,
recipientCode,
self ? counterpart : company,
self ? company with { TaxRegime = null, ReaOffice = null, ReaNumber = null, ShareCapital = null, Shareholders = null, LiquidationStatus = null } : counterpart,
[body],
null,
[])
{
TransmitterCountry = (profile.TransmitterCountry ?? "IT").Trim().ToUpperInvariant(),
TransmitterId = (profile.TransmitterId ?? profile.TaxCode ?? profile.VatNumber)?.Trim().ToUpperInvariant(),
RecipientPec = recipientPec,
Intermediary = intermediary,
IssuedBy = self ? "CC" : intermediary is not null ? "TZ" : null,
};
return (file, party, publicAdministration);
}
/// <summary>The company as it appears in the file.</summary>
/// <param name="profile">The profile.</param>
/// <returns>The party.</returns>
public static EInvoiceParty CompanyParty(CompanyProfile profile)
{
ArgumentNullException.ThrowIfNull(profile);
var country = (profile.AddressCountry ?? profile.Country ?? "IT").Trim().ToUpperInvariant();
return new EInvoiceParty(
(profile.Country ?? "IT").Trim().ToUpperInvariant(),
Digits(profile.VatNumber, profile.Country),
profile.TaxCode?.Trim().ToUpperInvariant(),
profile.LegalName,
null,
null,
profile.Address,
profile.StreetNumber,
profile.PostalCode,
profile.City,
country == "IT" ? profile.ProvinceCode : null,
country,
string.IsNullOrWhiteSpace(profile.TaxRegime) ? "RF01" : profile.TaxRegime,
profile.Email,
profile.Phone,
string.IsNullOrWhiteSpace(profile.ReaNumber) ? null : profile.ReaOffice,
string.IsNullOrWhiteSpace(profile.ReaOffice) ? null : profile.ReaNumber)
{
ShareCapital = profile.ShareCapital,
Shareholders = profile.Shareholders,
LiquidationStatus = string.IsNullOrWhiteSpace(profile.ReaNumber) ? null : profile.LiquidationStatus ?? "LN",
};
}
// The customer, or the supplier of a self-invoice.
internal static EInvoiceParty PartyOf(Party party, PartyFiscal? fiscal, bool supplier)
{
var country = (party.CountryCode ?? "IT").Trim().ToUpperInvariant();
var italian = country == "IT";
var vat = Digits(party.VatNumber, country);
var taxCode = italian ? party.TaxCode?.Trim().ToUpperInvariant() : null;
if (!italian && vat is null)
{
vat = NoVatNumber;
}
var person = party.SubjectType == SubjectType.Person && !string.IsNullOrWhiteSpace(party.LastName);
return new EInvoiceParty(
vat is null ? null : country,
vat,
taxCode,
person ? null : party.Name,
person ? party.FirstName : null,
person ? party.LastName : null,
party.Address,
party.StreetNumber,
party.PostalCode,
party.City,
italian ? party.Province : null,
country,
supplier ? (italian ? "RF01" : "RF18") : null,
null,
null,
null,
null)
{
AdministrationReference = supplier ? null : fiscal?.AdministrationReference,
};
}
// The recipient: the code of the party, its certified mailbox, the code of foreign customers, or none.
private static (string Code, string? Pec) Recipient(Party party, PartyFiscal? fiscal, bool publicAdministration, bool foreign)
{
var code = fiscal?.RecipientCode?.Trim().ToUpperInvariant();
if (!string.IsNullOrEmpty(code) && (publicAdministration ? code.Length == 6 : code.Length == 7) && code != NoRecipient)
{
return (code, null);
}
if (foreign && !publicAdministration)
{
return (ForeignRecipient, null);
}
var pec = fiscal?.RecipientPec ?? party.Pec;
return (publicAdministration ? code ?? string.Empty : NoRecipient, string.IsNullOrWhiteSpace(pec) || publicAdministration ? null : pec.Trim());
}
private static async Task<EInvoiceBody> BodyAsync(
IUnitOfWork uow, DocumentRecord record, string documentType, CompanyProfile profile, PartyFiscal? fiscal, CancellationToken cancellationToken)
{
var header = record.Header;
var taxIds = record.Lines.Select(l => l.TaxCodeId).Append(header.SocialSecurityTaxCodeId).OfType<long>().Distinct().ToList();
var taxCodes = (await uow.Repository<TaxCode, long>().ListAsync(Query.For<TaxCode>().Where(t => taxIds.Contains(t.Id)), cancellationToken).ConfigureAwait(false))
.Items.ToDictionary(t => t.Id);
var unitIds = record.Lines.Select(l => l.UnitOfMeasureId).OfType<long>().Distinct().ToList();
var units = (await uow.Repository<UnitOfMeasure, long>().ListAsync(Query.For<UnitOfMeasure>().Where(u => unitIds.Contains(u.Id)), cancellationToken).ConfigureAwait(false))
.Items.ToDictionary(u => u.Id);
var itemIds = record.Lines.Select(l => l.ItemId).OfType<long>().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 summary = record.Figures.Summary;
var first = summary.Count > 0 ? summary[0] : null;
var withholding = header.WithholdingRate is > 0m && header.WithholdingAmount != 0m;
var intent = fiscal is { IntentActive: true } && !string.IsNullOrWhiteSpace(fiscal.IntentProtocol);
var lines = new List<EInvoiceLine>();
var sourceLines = new Dictionary<int, DocumentLine>();
foreach (var line in record.Lines.OrderBy(l => l.LineNumber))
{
var tax = line.TaxCodeId is { } taxId && taxCodes.TryGetValue(taxId, out var code) ? code : null;
var rate = tax?.Rate ?? first?.Rate ?? 0m;
var nature = tax is null ? first?.Nature : tax.Nature;
var number = lines.Count + 1;
var description = string.IsNullOrWhiteSpace(line.Description) ? "-" : line.Description;
if (line.Kind == DocumentLineKind.Description)
{
lines.Add(new EInvoiceLine(number, [], description, null, null, 0m, 0m, rate, rate == 0m ? nature ?? "N2.2" : null, [], false, null, null, null, null));
continue;
}
var amount = line.TaxableAmount;
var quantity = line.Quantity;
var price = line.Price;
var discounts = DiscountsOf(line.DiscountFormula);
if (header.PricesIncludeTax && rate != 0m)
{
// The file has taxable amounts: the line becomes its taxable part, discounts included.
amount = Math.Round(amount * 100m / (100m + rate), 2, MidpointRounding.AwayFromZero);
price = quantity == 0m ? amount : Math.Round(amount / quantity, 8, MidpointRounding.AwayFromZero);
discounts = [];
if (quantity < 0m)
{
price = -price;
}
}
if (quantity < 0m)
{
// A negative quantity (a return on the invoice): the sign goes to the price.
quantity = -quantity;
price = -price;
}
var lineType = line.Kind switch
{
DocumentLineKind.Discount => "SC",
DocumentLineKind.Expense => "AC",
_ => null,
};
if (line.Kind == DocumentLineKind.Discount)
{
price = -Math.Abs(amount);
quantity = 0m;
discounts = [];
}
var codes = line.ItemId is { } itemId && items.TryGetValue(itemId, out var item) ? new[] { new EInvoiceItemCode("INTERNO", item.Code) } : [];
var unit = line.UnitOfMeasureId is { } unitId && units.TryGetValue(unitId, out var uom) ? uom.EInvoiceCode ?? uom.Code : null;
var withheld = withholding && !line.WithholdingExcluded && line.Kind != DocumentLineKind.Discount;
sourceLines[number] = line;
lines.Add(new EInvoiceLine(
number,
codes,
description,
quantity == 0m ? null : quantity,
quantity == 0m ? null : unit,
quantity == 0m ? amount : price,
amount,
rate,
rate == 0m ? nature : null,
discounts,
withheld,
lineType,
null,
null,
fiscal?.AdministrationReference)
{
OtherData = intent && nature == "N3.5"
? [new EInvoiceOtherData("INTENTO", fiscal!.IntentProtocol, null, fiscal.IntentDate)]
: [],
});
}
// The social security fund is part of the taxable of its rate, not of a line.
EInvoiceSocialSecurity? fund = null;
decimal fundRate = 0m;
string? fundNature = null;
if (header.SocialSecurityAmount != 0m && header.SocialSecurityRate is > 0m and var socialRate)
{
var fundTax = header.SocialSecurityTaxCodeId is { } fundTaxId && taxCodes.TryGetValue(fundTaxId, out var ft) ? ft : null;
fundRate = fundTax?.Rate ?? summary.Where(s => s.Rate > 0m).Select(s => s.Rate).FirstOrDefault();
fundNature = fundTax is null ? (fundRate == 0m ? first?.Nature : null) : fundTax.Nature;
fund = new EInvoiceSocialSecurity(
string.IsNullOrWhiteSpace(header.SocialSecurityFund) ? "TC22" : header.SocialSecurityFund,
socialRate,
header.SocialSecurityAmount,
Math.Round(header.SocialSecurityAmount * 100m / socialRate, 2, MidpointRounding.AwayFromZero),
fundRate,
withholding && header.SocialSecurityWithheld,
fundRate == 0m ? fundNature : null);
}
// The summary; what the lines do not explain becomes a discount line (footer discount) or the rounding.
var rows = new List<EInvoiceTaxSummary>();
foreach (var row in summary)
{
var linesSum = lines.Where(l => l.TaxRate == row.Rate && (row.Rate != 0m || l.Nature == row.Nature)).Sum(l => l.TotalPrice);
var fundPart = fund is not null && fundRate == row.Rate && (row.Rate != 0m || fundNature == row.Nature) ? fund.Amount : 0m;
var rest = row.Taxable - linesSum - fundPart;
decimal? rounding = null;
if (Math.Abs(rest) >= 0.01m && header.FooterDiscountAmount != 0m)
{
lines.Add(new EInvoiceLine(
lines.Count + 1, [], "Sconto di fine documento" + (string.IsNullOrWhiteSpace(header.FooterDiscount) ? string.Empty : " " + header.FooterDiscount + "%"),
null, null, rest, rest, row.Rate, row.Rate == 0m ? row.Nature : null, [], withholding, "SC", null, null, null));
}
else if (Math.Abs(rest) >= 0.01m)
{
rounding = rest;
}
rows.Add(new EInvoiceTaxSummary(
row.Rate,
row.Rate == 0m ? row.Nature : null,
row.Taxable,
row.Tax,
row.Rate == 0m ? null : row.Exigibility switch
{
TaxExigibility.Deferred => "D",
TaxExigibility.SplitPayment => "S",
_ => "I",
},
row.Rate == 0m ? row.LegalReference : null,
null,
rounding));
}
// Stamp duty charged to the customer: a line excluded from VAT, and its row in the summary.
if (header.StampDutyCharged && header.StampDuty > 0m)
{
lines.Add(new EInvoiceLine(lines.Count + 1, [], "Imposta di bollo", null, null, header.StampDuty, header.StampDuty, 0m, "N1", [], false, "AC", null, null, null));
var n1 = rows.FindIndex(r => r.Rate == 0m && r.Nature == "N1");
rows = n1 < 0
? [.. rows, new EInvoiceTaxSummary(0m, "N1", header.StampDuty, 0m, null, "Escluso art. 15 DPR 633/72", null, null)]
: [.. rows.Select((r, i) => i == n1 ? r with { Taxable = r.Taxable + header.StampDuty } : r)];
}
var (orders, related, deliveries) = await ReferencesAsync(uow, record, sourceLines, cancellationToken).ConfigureAwait(false);
var payments = await PaymentsAsync(uow, record, profile, cancellationToken).ConfigureAwait(false);
return new EInvoiceBody(
documentType,
header.CurrencyCode,
header.DocumentDate,
header.DocumentNumber ?? string.Empty,
header.TotalAmount,
null,
string.IsNullOrWhiteSpace(header.Notes) ? [] : [header.Notes.Trim()],
false,
withholding
? [new EInvoiceWithholding(string.IsNullOrWhiteSpace(header.WithholdingType) ? "RT01" : header.WithholdingType, header.WithholdingAmount, header.WithholdingRate!.Value,
string.IsNullOrWhiteSpace(header.WithholdingReason) ? "A" : header.WithholdingReason)]
: [],
header.StampDuty > 0m ? new EInvoiceStampDuty(true, header.StampDuty) : null,
fund is null ? [] : [fund],
[],
orders,
[],
related,
deliveries,
lines,
rows,
payments,
[])
{
Transport = await TransportAsync(uow, header, cancellationToken).ConfigureAwait(false),
PaymentConditions = payments.FirstOrDefault()?.Conditions,
};
}
// "10+5" gives two discounts in percent, in order.
private static IReadOnlyList<EInvoiceDiscount> DiscountsOf(string? formula) =>
DiscountFormula.TryParse(formula, out var steps)
? [.. steps.Select(s => s < 0m ? new EInvoiceDiscount(true, -s, null) : new EInvoiceDiscount(false, s, null))]
: [];
// The order of the customer (with CIG and CUP), the invoice corrected, the delivery notes of the lines.
private static async Task<(List<EInvoiceReference> Orders, List<EInvoiceReference> Related, List<EInvoiceReference> Deliveries)> ReferencesAsync(
IUnitOfWork uow, DocumentRecord record, Dictionary<int, DocumentLine> sourceLines, CancellationToken cancellationToken)
{
var header = record.Header;
var orders = new List<EInvoiceReference>();
if (!string.IsNullOrWhiteSpace(header.Cig) || !string.IsNullOrWhiteSpace(header.Cup) || !string.IsNullOrWhiteSpace(header.ExternalReference))
{
orders.Add(new EInvoiceReference(
string.IsNullOrWhiteSpace(header.ExternalReference) ? header.DocumentNumber : header.ExternalReference.Trim(),
header.ExternalDate,
[],
string.IsNullOrWhiteSpace(header.Cig) ? null : header.Cig.Trim().ToUpperInvariant(),
string.IsNullOrWhiteSpace(header.Cup) ? null : header.Cup.Trim().ToUpperInvariant()));
}
var related = new List<EInvoiceReference>();
if (!string.IsNullOrWhiteSpace(header.RelatedNumber))
{
related.Add(new EInvoiceReference(header.RelatedNumber.Trim(), header.RelatedDate, [], null, null));
}
else if (header.RelatedDocumentId is { } relatedId)
{
// A self-invoice integrates the supplier's invoice: its number is the one of the supplier.
var family = header.Kind == DocumentKind.SelfInvoice ? DocumentFamily.PurchaseDocument : record.Family;
if (await DocumentStores.Of(family).GetAsync(uow, relatedId, cancellationToken).ConfigureAwait(false) is { } other)
{
related.Add(family == DocumentFamily.PurchaseDocument
? new EInvoiceReference(other.ExternalReference ?? other.DocumentNumber, other.ExternalDate ?? other.DocumentDate, [], null, null)
: new EInvoiceReference(other.DocumentNumber, other.DocumentDate, [], null, null));
}
}
var deliveries = new Dictionary<long, (DocumentHeader Note, List<int> Lines)>();
var store = DocumentStores.Of(DocumentFamily.SaleDocument);
foreach (var (number, line) in sourceLines)
{
if (line.SourceFamily != DocumentFamily.SaleDocument || line.SourceLineId is not { } sourceLineId)
{
continue;
}
var source = await store.GetLineAsync(uow, sourceLineId, cancellationToken).ConfigureAwait(false);
if (source is null)
{
continue;
}
if (!deliveries.TryGetValue(source.DocumentId, out var entry))
{
if (await store.GetAsync(uow, source.DocumentId, cancellationToken).ConfigureAwait(false) is not { Kind: DocumentKind.DeliveryNote } note)
{
continue;
}
entry = (note, []);
deliveries[source.DocumentId] = entry;
}
entry.Lines.Add(number);
}
return (orders, related, [.. deliveries.Values.Select(d => new EInvoiceReference(d.Note.DocumentNumber, d.Note.DocumentDate, d.Lines, null, null))]);
}
// The installments with the method of each; the IBAN of the company for bank transfers.
private static async Task<List<EInvoicePayment>> PaymentsAsync(IUnitOfWork uow, DocumentRecord record, CompanyProfile profile, CancellationToken cancellationToken)
{
var header = record.Header;
var methodIds = record.Figures.Installments.Select(i => i.PaymentMethodId).Append(header.PaymentMethodId).OfType<long>().Distinct().ToList();
var methods = methodIds.Count == 0
? []
: (await uow.Repository<PaymentMethod, long>().ListAsync(Query.For<PaymentMethod>().Where(m => methodIds.Contains(m.Id)), cancellationToken).ConfigureAwait(false))
.Items.ToDictionary(m => m.Id);
var bankId = header.BankAccountId ?? profile.DefaultBankAccountId;
var bank = bankId is { } id ? await uow.Repository<BankAccount, long>().GetAsync(id, cancellationToken).ConfigureAwait(false) : null;
string? Code(long? methodId) => methodId is { } m && methods.TryGetValue(m, out var method) && !string.IsNullOrWhiteSpace(method.EInvoiceCode) ? method.EInvoiceCode : null;
var installments = record.Figures.Installments.OrderBy(i => i.Number).ToList();
var conditions = header.Kind == DocumentKind.DownPaymentInvoice ? "TP03" : installments.Count > 1 ? "TP01" : "TP02";
var result = new List<EInvoicePayment>();
if (installments.Count == 0)
{
if (Code(header.PaymentMethodId) is { } only)
{
result.Add(new EInvoicePayment(conditions, only, null, header.NetAmount, only == "MP05" ? bank?.Iban : null, only == "MP05" ? bank?.Bic : null, null));
}
return result;
}
foreach (var installment in installments)
{
if (Code(installment.PaymentMethodId ?? header.PaymentMethodId) is not { } method)
{
continue;
}
result.Add(new EInvoicePayment(conditions, method, installment.DueDate, installment.Amount,
method == "MP05" ? bank?.Iban?.Replace(" ", string.Empty, StringComparison.Ordinal) : null, method == "MP05" ? bank?.Bic : null, null));
}
return result;
}
// The transport of an accompanying invoice: carrier, packages, weights, start.
private static async Task<EInvoiceTransport?> TransportAsync(IUnitOfWork uow, DocumentHeader header, CancellationToken cancellationToken)
{
if (header.Kind != DocumentKind.AccompanyingInvoice && header.CarrierId is null && header.Packages is null)
{
return null;
}
var carrier = header.CarrierId is { } carrierId ? await uow.Repository<Carrier, long>().GetAsync(carrierId, cancellationToken).ConfigureAwait(false) : null;
var reason = header.TransportReasonId is { } reasonId ? await uow.Repository<TransportReason, long>().GetAsync(reasonId, cancellationToken).ConfigureAwait(false) : null;
var vat = carrier?.VatNumber?.Trim();
return new EInvoiceTransport(
carrier?.Description,
string.IsNullOrWhiteSpace(vat) ? null : "IT",
string.IsNullOrWhiteSpace(vat) ? null : Digits(vat, "IT"),
header.TransportBy switch
{
TransportResponsibility.Sender => "Mittente",
TransportResponsibility.Recipient => "Destinatario",
TransportResponsibility.Carrier => "Vettore",
_ => null,
},
reason?.Description,
header.Packages,
null,
header.GrossWeight,
header.NetWeight,
header.TransportStart,
null);
}
// A VAT number without the country prefix and spaces.
private static string? Digits(string? vat, string? country)
{
if (string.IsNullOrWhiteSpace(vat))
{
return null;
}
var value = vat.Replace(" ", string.Empty, StringComparison.Ordinal).Trim().ToUpperInvariant();
return country is { Length: 2 } prefix && value.StartsWith(prefix.ToUpperInvariant(), StringComparison.Ordinal) && value.Length > 2 ? value[2..] : value;
}
}
@@ -0,0 +1,424 @@
using System.Globalization;
using System.Net.Mail;
using Khaemhat.Application.Audit;
using Khaemhat.Application.Security;
using Khaemhat.Application.Tables;
using Khaemhat.Core.EInvoicing;
using Khaemhat.Core.Security;
using Khaemhat.Data;
using Khaemhat.Data.Querying;
using Khaemhat.Fiscal.Abstractions;
namespace Khaemhat.Application.EInvoicing;
/// <summary>A channel as the configuration page shows it: secrets never leave the service, only whether they are set.</summary>
/// <param name="Code">The code of the channel.</param>
/// <param name="Name">Its name.</param>
/// <param name="Polls">Whether Khaemhat reads it on a schedule (PEC, intermediaries) or receives a push (SdICoop).</param>
/// <param name="Setting">The settings, secrets removed (a new row when never saved).</param>
/// <param name="HasPassword">Whether a password is stored.</param>
/// <param name="HasCertificate">Whether a client certificate is stored.</param>
/// <param name="HasApiKey">Whether an API key is stored.</param>
public sealed record EInvoiceChannelView(string Code, string Name, bool Polls, EInvoiceChannelSetting Setting, bool HasPassword, bool HasCertificate, bool HasApiKey);
/// <summary>
/// What the user saves for a channel. Secrets: <see langword="null"/> keeps the stored one, an empty value removes it.
/// </summary>
public sealed record EInvoiceChannelInput
{
/// <summary>The code of the channel.</summary>
public required string Code { get; init; }
/// <summary>Whether the channel is used.</summary>
public bool Enabled { get; init; }
/// <summary>The certified mailbox.</summary>
public string? Mailbox { get; init; }
/// <summary>The SMTP server.</summary>
public string? SmtpHost { get; init; }
/// <summary>The SMTP port.</summary>
public int SmtpPort { get; init; } = 465;
/// <summary>The IMAP server.</summary>
public string? ImapHost { get; init; }
/// <summary>The IMAP port.</summary>
public int ImapPort { get; init; } = 993;
/// <summary>Whether TLS is used.</summary>
public bool Tls { get; init; } = true;
/// <summary>The user.</summary>
public string? UserName { get; init; }
/// <summary>The password: <see langword="null"/> keeps it, empty removes it.</summary>
public string? Password { get; init; }
/// <summary>The address of the SDI to write to.</summary>
public string? ExchangeAddress { get; init; }
/// <summary>The folder the processed messages go to.</summary>
public string? ArchiveFolder { get; init; }
/// <summary>The address of the web service or of the API.</summary>
public string? Endpoint { get; init; }
/// <summary>The client certificate (PKCS#12): <see langword="null"/> keeps it, empty removes it.</summary>
public byte[]? Certificate { get; init; }
/// <summary>The password of the certificate: <see langword="null"/> keeps it, empty removes it.</summary>
public string? CertificatePassword { get; init; }
/// <summary>The API key: <see langword="null"/> keeps it, empty removes it.</summary>
public string? ApiKey { get; init; }
/// <summary>Whether the test environment is used.</summary>
public bool TestEnvironment { get; init; }
}
/// <summary>
/// The channels to the SDI and the routing of the files (mockup 059, issues #76-#77): the PEC mailbox, the SdICoop web
/// service, the intermediaries; each can be tried, paused and resumed. Secrets are kept protected (SPEC §8.5) and never
/// shown again. The routing rules choose the channel of each file, with a fallback.
/// </summary>
/// <remarks>Permission: <c>einvoice.channel.manage</c>.</remarks>
public sealed class EInvoiceChannelService
{
private readonly IUnitOfWorkFactory _factory;
private readonly PermissionService _permissions;
private readonly CompanyFiscalContext _packs;
private readonly ISecretProtector _secrets;
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="secrets">Protects the secrets.</param>
/// <param name="audit">The history of the changes.</param>
/// <param name="clock">The clock.</param>
public EInvoiceChannelService(IUnitOfWorkFactory factory, PermissionService permissions, CompanyFiscalContext packs, ISecretProtector secrets, AuditTrail audit, TimeProvider clock)
{
ArgumentNullException.ThrowIfNull(factory);
ArgumentNullException.ThrowIfNull(permissions);
ArgumentNullException.ThrowIfNull(packs);
ArgumentNullException.ThrowIfNull(secrets);
ArgumentNullException.ThrowIfNull(audit);
ArgumentNullException.ThrowIfNull(clock);
_factory = factory;
_permissions = permissions;
_packs = packs;
_secrets = secrets;
_audit = audit;
_clock = clock;
}
/// <summary>The channels of the pack with their settings.</summary>
/// <param name="actor">Who looks: needs <c>einvoice.channel.manage</c>.</param>
/// <param name="companyCode">The company.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The channels, in the order of the pack.</returns>
public async Task<IReadOnlyList<EInvoiceChannelView>> ListAsync(Actor actor, string companyCode, CancellationToken cancellationToken = default)
{
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, EInvoicePermissions.ChannelManage, cancellationToken).ConfigureAwait(false);
var channels = await ChannelsAsync(company, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
var rows = (await uow.Repository<EInvoiceChannelSetting, long>().ListAsync(Query.For<EInvoiceChannelSetting>(), cancellationToken).ConfigureAwait(false)).Items
.ToDictionary(r => r.Code, StringComparer.OrdinalIgnoreCase);
return [.. channels.All.Select(c => View(c, rows.GetValueOrDefault(c.Code) ?? new EInvoiceChannelSetting { Code = c.Code }))];
}
/// <summary>Saves the settings of a channel.</summary>
/// <param name="actor">Who saves: needs <c>einvoice.channel.manage</c>.</param>
/// <param name="companyCode">The company.</param>
/// <param name="input">The settings.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The channel.</returns>
public async Task<EInvoiceChannelView> SaveAsync(Actor actor, string companyCode, EInvoiceChannelInput input, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(actor);
ArgumentNullException.ThrowIfNull(input);
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, EInvoicePermissions.ChannelManage, cancellationToken).ConfigureAwait(false);
var channel = (await ChannelsAsync(company, cancellationToken).ConfigureAwait(false)).Find(input.Code)
?? throw new ValidationFailedException(["Code:" + EInvoiceErrors.ChannelUnknown]);
Validate(input);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
var repository = uow.Repository<EInvoiceChannelSetting, long>();
var code = channel.Code;
var row = await repository.FindAsync(Query.For<EInvoiceChannelSetting>().Where(c => c.Code == code), cancellationToken).ConfigureAwait(false);
var before = row is null ? null : Copy(row);
row ??= new EInvoiceChannelSetting { Code = code };
row.Enabled = input.Enabled;
row.Mailbox = EInvoiceStore.Trim(input.Mailbox, 200);
row.SmtpHost = EInvoiceStore.Trim(input.SmtpHost, 200);
row.SmtpPort = input.SmtpPort;
row.ImapHost = EInvoiceStore.Trim(input.ImapHost, 200);
row.ImapPort = input.ImapPort;
row.Tls = input.Tls;
row.UserName = EInvoiceStore.Trim(input.UserName, 200);
row.ExchangeAddress = EInvoiceStore.Trim(input.ExchangeAddress, 200);
row.ArchiveFolder = EInvoiceStore.Trim(input.ArchiveFolder, 200);
row.Endpoint = EInvoiceStore.Trim(input.Endpoint, 500);
row.TestEnvironment = input.TestEnvironment;
row.ProtectedPassword = Secret(input.Password, row.ProtectedPassword);
row.ProtectedCertificate = input.Certificate is null
? row.ProtectedCertificate
: input.Certificate.Length == 0 ? null : _secrets.Protect(Convert.ToBase64String(input.Certificate), EInvoiceStore.SecretPurpose);
row.ProtectedCertificatePassword = Secret(input.CertificatePassword, row.ProtectedCertificatePassword);
row.ProtectedApiKey = Secret(input.ApiKey, row.ProtectedApiKey);
if (before is null)
{
row.Id = await repository.InsertAsync(row, cancellationToken).ConfigureAwait(false);
await _audit.RecordAsync<EInvoiceChannelSetting>(uow, AuditAction.Insert, row.Id, null, row, actor.UserName, cancellationToken).ConfigureAwait(false);
}
else
{
await repository.UpdateAsync(row, cancellationToken).ConfigureAwait(false);
await _audit.RecordAsync(uow, AuditAction.Update, row.Id, before, row, actor.UserName, cancellationToken).ConfigureAwait(false);
}
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
return View(channel, row);
}
/// <summary>Pauses or resumes a channel: a paused channel neither sends nor is read.</summary>
/// <param name="actor">Who does it: needs <c>einvoice.channel.manage</c>.</param>
/// <param name="companyCode">The company.</param>
/// <param name="code">The channel.</param>
/// <param name="paused">Whether to pause.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
public async Task PauseAsync(Actor actor, string companyCode, string code, bool paused, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(actor);
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, EInvoicePermissions.ChannelManage, 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<EInvoiceChannelSetting, long>();
var row = await repository.FindAsync(Query.For<EInvoiceChannelSetting>().Where(c => c.Code == code), cancellationToken).ConfigureAwait(false)
?? throw new ValidationFailedException(["Code:" + EInvoiceErrors.ChannelUnknown]);
var before = Copy(row);
row.Paused = paused;
await repository.UpdateAsync(row, cancellationToken).ConfigureAwait(false);
await _audit.RecordAsync(uow, AuditAction.Update, row.Id, before, row, actor.UserName, cancellationToken).ConfigureAwait(false);
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
}
/// <summary>Tries a channel with its saved settings (login to the mailbox, the service or the API) and keeps the outcome.</summary>
/// <param name="actor">Who tries: needs <c>einvoice.channel.manage</c>.</param>
/// <param name="companyCode">The company.</param>
/// <param name="code">The channel.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The outcome.</returns>
public async Task<EInvoiceChannelCheck> CheckAsync(Actor actor, string companyCode, string code, CancellationToken cancellationToken = default)
{
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, EInvoicePermissions.ChannelManage, cancellationToken).ConfigureAwait(false);
var channel = (await ChannelsAsync(company, cancellationToken).ConfigureAwait(false)).Find(code)
?? throw new ValidationFailedException(["Code:" + EInvoiceErrors.ChannelUnknown]);
EInvoiceChannelSetting row;
await using (var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false))
{
row = await uow.Repository<EInvoiceChannelSetting, long>().FindAsync(Query.For<EInvoiceChannelSetting>().Where(c => c.Code == channel.Code), cancellationToken)
.ConfigureAwait(false) ?? throw new ValidationFailedException(["Code:" + EInvoiceErrors.ChannelUnknown]);
}
EInvoiceChannelCheck check;
try
{
check = await channel.Transport.CheckAsync(EInvoiceStore.Settings(row, _secrets), cancellationToken).ConfigureAwait(false);
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
check = new EInvoiceChannelCheck(false, ex.Message);
}
await using (var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false))
{
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
var current = await uow.Repository<EInvoiceChannelSetting, long>().GetAsync(row.Id, cancellationToken).ConfigureAwait(false)!;
if (current is not null)
{
current.LastCheckAt = _clock.GetUtcNow().UtcDateTime;
current.LastCheckOk = check.Success;
current.LastCheckMessage = EInvoiceStore.Trim(check.Message, 1000);
await uow.Repository<EInvoiceChannelSetting, long>().UpdateAsync(current, cancellationToken).ConfigureAwait(false);
}
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
}
return check;
}
/// <summary>The routing rules, in order.</summary>
/// <param name="actor">Who looks: needs <c>einvoice.channel.manage</c>.</param>
/// <param name="companyCode">The company.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The rules.</returns>
public async Task<IReadOnlyList<SdiRoutingRule>> RulesAsync(Actor actor, string companyCode, CancellationToken cancellationToken = default)
{
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, EInvoicePermissions.ChannelManage, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
return (await uow.Repository<SdiRoutingRule, long>().ListAsync(Query.For<SdiRoutingRule>().OrderBy(r => r.Position), cancellationToken).ConfigureAwait(false)).Items;
}
/// <summary>Adds or changes a routing rule.</summary>
/// <param name="actor">Who saves: needs <c>einvoice.channel.manage</c>.</param>
/// <param name="companyCode">The company.</param>
/// <param name="rule">The rule (identifier 0 to add).</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The rule.</returns>
public async Task<SdiRoutingRule> SaveRuleAsync(Actor actor, string companyCode, SdiRoutingRule rule, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(actor);
ArgumentNullException.ThrowIfNull(rule);
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, EInvoicePermissions.ChannelManage, cancellationToken).ConfigureAwait(false);
var channels = await ChannelsAsync(company, cancellationToken).ConfigureAwait(false);
var errors = new List<string>();
if (channels.Find(rule.ChannelCode) is null)
{
errors.Add(nameof(SdiRoutingRule.ChannelCode) + ":" + EInvoiceErrors.ChannelUnknown);
}
if (!string.IsNullOrWhiteSpace(rule.FallbackChannelCode) && (channels.Find(rule.FallbackChannelCode) is null
|| string.Equals(rule.FallbackChannelCode, rule.ChannelCode, StringComparison.OrdinalIgnoreCase)))
{
errors.Add(nameof(SdiRoutingRule.FallbackChannelCode) + ":" + EInvoiceErrors.ChannelUnknown);
}
var value = rule.Value?.Trim();
var valueOk = rule.Condition switch
{
SdiRoutingCondition.Party or SdiRoutingCondition.DocumentType => !string.IsNullOrEmpty(value),
SdiRoutingCondition.DailyVolume => int.TryParse(value, NumberStyles.None, CultureInfo.InvariantCulture, out var limit) && limit > 0,
_ => true,
};
if (!valueOk)
{
errors.Add(nameof(SdiRoutingRule.Value) + ":" + EInvoiceErrors.RuleValueInvalid);
}
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 repository = uow.Repository<SdiRoutingRule, long>();
var row = rule.Id == 0 ? new SdiRoutingRule() : await repository.GetAsync(rule.Id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(EInvoiceErrors.NotFound);
var before = rule.Id == 0 ? null : CopyRule(row);
if (rule.Id == 0 && rule.Position <= 0)
{
var last = await repository.FindAsync(Query.For<SdiRoutingRule>().OrderByDescending(r => r.Position), cancellationToken).ConfigureAwait(false);
row.Position = (last?.Position ?? 0) + 10;
}
else
{
row.Position = rule.Position;
}
row.Condition = rule.Condition;
row.Value = rule.Condition is SdiRoutingCondition.Default or SdiRoutingCondition.PublicAdministration ? null : value!.ToUpperInvariant();
row.ChannelCode = rule.ChannelCode.Trim().ToUpperInvariant();
row.FallbackChannelCode = string.IsNullOrWhiteSpace(rule.FallbackChannelCode) ? null : rule.FallbackChannelCode.Trim().ToUpperInvariant();
row.Disabled = rule.Disabled;
if (before is null)
{
row.Id = await repository.InsertAsync(row, cancellationToken).ConfigureAwait(false);
await _audit.RecordAsync<SdiRoutingRule>(uow, AuditAction.Insert, row.Id, null, row, actor.UserName, cancellationToken).ConfigureAwait(false);
}
else
{
await repository.UpdateAsync(row, cancellationToken).ConfigureAwait(false);
await _audit.RecordAsync(uow, AuditAction.Update, row.Id, before, row, actor.UserName, cancellationToken).ConfigureAwait(false);
}
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
return row;
}
/// <summary>Removes a routing rule.</summary>
/// <param name="actor">Who removes: needs <c>einvoice.channel.manage</c>.</param>
/// <param name="companyCode">The company.</param>
/// <param name="id">The rule.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
public async Task DeleteRuleAsync(Actor actor, string companyCode, long id, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(actor);
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, EInvoicePermissions.ChannelManage, 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<SdiRoutingRule, long>();
var row = await repository.GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(EInvoiceErrors.NotFound);
await repository.DeleteAsync(row.Id, cancellationToken).ConfigureAwait(false);
await _audit.RecordAsync<SdiRoutingRule>(uow, AuditAction.Delete, row.Id, row, null, actor.UserName, cancellationToken).ConfigureAwait(false);
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
}
private async Task<IEInvoiceChannels> ChannelsAsync(string company, CancellationToken cancellationToken) =>
(await _packs.PackOfAsync(company, cancellationToken).ConfigureAwait(false)).GetFeature<IEInvoiceChannels>()
?? throw new ValidationFailedException([":" + EInvoiceErrors.NotSupported]);
private string? Secret(string? input, string? stored) =>
input is null ? stored : input.Length == 0 ? null : _secrets.Protect(input, EInvoiceStore.SecretPurpose);
private static void Validate(EInvoiceChannelInput input)
{
var errors = new List<string>();
if (input.SmtpPort is < 1 or > 65535)
{
errors.Add(nameof(input.SmtpPort) + ":" + EInvoiceErrors.PortInvalid);
}
if (input.ImapPort is < 1 or > 65535)
{
errors.Add(nameof(input.ImapPort) + ":" + EInvoiceErrors.PortInvalid);
}
if (!string.IsNullOrWhiteSpace(input.Mailbox) && !MailAddress.TryCreate(input.Mailbox.Trim(), out _))
{
errors.Add(nameof(input.Mailbox) + ":" + EInvoiceErrors.MailboxInvalid);
}
if (!string.IsNullOrWhiteSpace(input.ExchangeAddress) && !MailAddress.TryCreate(input.ExchangeAddress.Trim(), out _))
{
errors.Add(nameof(input.ExchangeAddress) + ":" + EInvoiceErrors.MailboxInvalid);
}
if (!string.IsNullOrWhiteSpace(input.Endpoint) && !IsServiceAddress(input.Endpoint.Trim()))
{
errors.Add(nameof(input.Endpoint) + ":" + EInvoiceErrors.EndpointInvalid);
}
if (errors.Count > 0)
{
throw new ValidationFailedException(errors);
}
}
// https, or http only to this machine (a test service).
private static bool IsServiceAddress(string value) =>
Uri.TryCreate(value, UriKind.Absolute, out var uri)
&& (uri.Scheme == Uri.UriSchemeHttps || (uri.Scheme == Uri.UriSchemeHttp && uri.IsLoopback));
private static EInvoiceChannelView View(EInvoiceChannel channel, EInvoiceChannelSetting row)
{
var shown = Copy(row);
shown.ProtectedPassword = null;
shown.ProtectedCertificate = null;
shown.ProtectedCertificatePassword = null;
shown.ProtectedApiKey = null;
return new EInvoiceChannelView(channel.Code, channel.Name, channel.Transport.Polls, shown,
!string.IsNullOrEmpty(row.ProtectedPassword), !string.IsNullOrEmpty(row.ProtectedCertificate), !string.IsNullOrEmpty(row.ProtectedApiKey));
}
private static EInvoiceChannelSetting Copy(EInvoiceChannelSetting row) => EInvoiceStore.Clone(row);
private static SdiRoutingRule CopyRule(SdiRoutingRule row) => EInvoiceStore.Clone(row);
}
@@ -0,0 +1,60 @@
using Khaemhat.Application.Dashboard;
using Khaemhat.Application.Localization;
using Khaemhat.Application.Security;
namespace Khaemhat.Application.EInvoicing;
/// <summary>
/// The electronic invoice on the dashboard (SPEC §10.3): the files rejected by the SDI or refused by a public
/// administration, the documents to generate or send, the invoices received to register. Only for who may see them.
/// </summary>
/// <param name="invoices">The e-invoices.</param>
/// <param name="permissions">The permissions, licence included.</param>
/// <param name="texts">The texts.</param>
public sealed class EInvoiceFeedSource(EInvoiceService invoices, PermissionService permissions, ITexts texts) : ITodoSource
{
/// <summary>The text key of the area.</summary>
public const string Area = "Dashboard.Areas.EInvoicing";
/// <inheritdoc />
public async Task<IReadOnlyList<FeedItem>> GetAsync(FeedContext context, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(context);
if (context.Actor.CompanyCode is not { } company
|| !(await permissions.CheckAsync(context.Actor, EInvoicePermissions.Read, cancellationToken).ConfigureAwait(false)).Allowed)
{
return [];
}
var counters = (await invoices.DashboardAsync(context.Actor, company, new EInvoiceFilter(EInvoiceView.ToDo), cancellationToken).ConfigureAwait(false)).Counters;
var result = new List<FeedItem>();
if (counters.Rejected > 0)
{
result.Add(new FeedItem("einvoice-rejected", texts.Format("Dashboard.Feed.EInvoiceRejected", counters.Rejected), Area, FeedTone.Error)
{
Priority = 30,
Href = "/fatturazione-elettronica?vista=da-fare",
});
}
if (counters.ToGenerate + counters.ToSend > 0)
{
result.Add(new FeedItem("einvoice-to-send", texts.Format("Dashboard.Feed.EInvoiceToSend", counters.ToGenerate + counters.ToSend), Area, FeedTone.Warning)
{
Priority = 50,
Href = "/fatturazione-elettronica?vista=da-fare",
});
}
if (counters.Received > 0 && (await permissions.CheckAsync(context.Actor, EInvoicePermissions.InboxRead, cancellationToken).ConfigureAwait(false)).Allowed)
{
result.Add(new FeedItem("einvoice-received", texts.Format("Dashboard.Feed.EInvoiceReceived", counters.Received), Area, FeedTone.Info)
{
Priority = 60,
Href = "/fatturazione-elettronica/ricevute",
});
}
return result;
}
}
@@ -0,0 +1,302 @@
using System.Globalization;
using Khaemhat.Application.Jobs;
using Khaemhat.Application.Security;
using Khaemhat.Application.Tables;
using Khaemhat.Core.Instance;
using Khaemhat.Core.EInvoicing;
using Khaemhat.Application.Licensing;
using Khaemhat.Application.Modules;
using Khaemhat.Core.Logging;
using Khaemhat.Core.Security;
using Khaemhat.Data;
using Khaemhat.Data.Companies;
using Khaemhat.Data.Querying;
using Khaemhat.Fiscal.Abstractions;
using Microsoft.Extensions.Logging;
namespace Khaemhat.Application.EInvoicing;
/// <summary>What reading one channel brought.</summary>
/// <param name="Channel">The channel.</param>
/// <param name="Messages">Messages read.</param>
/// <param name="Invoices">Invoices received and stored.</param>
/// <param name="Receipts">Notifications applied.</param>
/// <param name="Skipped">Files already known.</param>
/// <param name="Error">Why the channel could not be read.</param>
public sealed record EInvoicePollOutcome(string Channel, int Messages, int Invoices, int Receipts, int Skipped, string? Error);
/// <summary>
/// Reads the channels of the SDI (issue #76): the PEC mailbox and the intermediaries on a schedule, the SdICoop web
/// service when it calls. Every file is sorted: supplier invoices to the inbox, their metadata (MT) with them, the
/// notifications to the e-invoices they are about. A message is acknowledged (archived, marked as read) only when all
/// its files were kept, so nothing is lost when Khaemhat stops halfway.
/// </summary>
public sealed partial class EInvoicePollingService
{
private readonly IUnitOfWorkFactory _factory;
private readonly PermissionService _permissions;
private readonly CompanyFiscalContext _packs;
private readonly EInvoiceService _invoices;
private readonly ISecretProtector _secrets;
private readonly TimeProvider _clock;
private readonly ILogger<EInvoicePollingService> _logger;
/// <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="invoices">The e-invoices (notifications).</param>
/// <param name="secrets">Opens the secrets of the channels.</param>
/// <param name="clock">The clock.</param>
/// <param name="logger">The log (section SDI).</param>
public EInvoicePollingService(
IUnitOfWorkFactory factory, PermissionService permissions, CompanyFiscalContext packs, EInvoiceService invoices, ISecretProtector secrets, TimeProvider clock,
ILogger<EInvoicePollingService> logger)
{
ArgumentNullException.ThrowIfNull(factory);
ArgumentNullException.ThrowIfNull(permissions);
ArgumentNullException.ThrowIfNull(packs);
ArgumentNullException.ThrowIfNull(invoices);
ArgumentNullException.ThrowIfNull(secrets);
ArgumentNullException.ThrowIfNull(clock);
ArgumentNullException.ThrowIfNull(logger);
_factory = factory;
_permissions = permissions;
_packs = packs;
_invoices = invoices;
_secrets = secrets;
_clock = clock;
_logger = logger;
}
/// <summary>Reads the channels of the company now (the button <i>Leggi ora</i>).</summary>
/// <param name="actor">Who asks: needs <c>einvoice.channel.manage</c>.</param>
/// <param name="companyCode">The company.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>What each channel brought.</returns>
public async Task<IReadOnlyList<EInvoicePollOutcome>> PollNowAsync(Actor actor, string companyCode, CancellationToken cancellationToken = default)
{
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, EInvoicePermissions.ChannelManage, cancellationToken).ConfigureAwait(false);
return await PollCompanyAsync(company, cancellationToken).ConfigureAwait(false);
}
/// <summary>Reads every enabled, not paused channel of a company that is read on a schedule.</summary>
/// <param name="company">The company.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>What each channel brought.</returns>
public async Task<IReadOnlyList<EInvoicePollOutcome>> PollCompanyAsync(string company, CancellationToken cancellationToken = default)
{
var pack = await _packs.PackOfAsync(company, cancellationToken).ConfigureAwait(false);
if (pack.GetFeature<IEInvoiceChannels>() is not { } channels)
{
return [];
}
List<EInvoiceChannelSetting> rows;
await using (var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false))
{
rows = [.. (await uow.Repository<EInvoiceChannelSetting, long>().ListAsync(Query.For<EInvoiceChannelSetting>().Where(c => c.Enabled && !c.Paused), cancellationToken)
.ConfigureAwait(false)).Items];
}
var result = new List<EInvoicePollOutcome>();
foreach (var row in rows)
{
if (channels.Find(row.Code) is not { Transport.Polls: true } channel)
{
continue;
}
result.Add(await PollChannelAsync(company, pack, channel, row, cancellationToken).ConfigureAwait(false));
}
return result;
}
/// <summary>Takes the files a channel pushed (SdICoop: <c>RiceviFatture</c>, <c>RiceviNotifica</c>) for a company.</summary>
/// <param name="company">The company the endpoint belongs to.</param>
/// <param name="channel">The channel.</param>
/// <param name="files">The files.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>What the files brought.</returns>
public async Task<EInvoicePollOutcome> ReceivePushedAsync(string company, string channel, IReadOnlyList<EInvoiceIncoming> files, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(files);
var pack = await _packs.PackOfAsync(company, cancellationToken).ConfigureAwait(false);
var (invoices, receipts, skipped, _) = await ProcessAsync(company, pack, channel, files, cancellationToken).ConfigureAwait(false);
return new EInvoicePollOutcome(channel, 1, invoices, receipts, skipped, null);
}
private async Task<EInvoicePollOutcome> PollChannelAsync(string company, IFiscalPack pack, EInvoiceChannel channel, EInvoiceChannelSetting row, CancellationToken cancellationToken)
{
using var scope = _logger.BeginScope(LogSections.Scope(LogSection.EInvoicing));
var settings = EInvoiceStore.Settings(row, _secrets);
EInvoicePollOutcome outcome;
string? learned = null;
try
{
var fetched = await channel.Transport.FetchAsync(settings, cancellationToken).ConfigureAwait(false);
learned = fetched.ExchangeAddress;
var (invoices, receipts, skipped, done) = await ProcessAsync(company, pack, channel.Code, fetched.Files, cancellationToken).ConfigureAwait(false);
var keys = fetched.Files.GroupBy(f => f.MessageKey, StringComparer.Ordinal).Where(g => g.All(done.Contains)).Select(g => g.Key).ToList();
if (keys.Count > 0)
{
await channel.Transport.AcknowledgeAsync(settings, keys, cancellationToken).ConfigureAwait(false);
}
outcome = new EInvoicePollOutcome(channel.Code, fetched.MessagesRead, invoices, receipts, skipped, null);
LogPolled(_logger, channel.Code, company, fetched.MessagesRead, invoices, receipts);
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
outcome = new EInvoicePollOutcome(channel.Code, 0, 0, 0, 0, ex.Message);
LogPollFailed(_logger, ex, channel.Code, company);
}
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
if (await uow.Repository<EInvoiceChannelSetting, long>().GetAsync(row.Id, cancellationToken).ConfigureAwait(false) is { } current)
{
current.LastPollAt = _clock.GetUtcNow().UtcDateTime;
current.LastPollFailed = outcome.Error is not null;
current.LastPollMessage = EInvoiceStore.Trim(
outcome.Error ?? string.Create(CultureInfo.InvariantCulture, $"{outcome.Messages} messaggi, {outcome.Invoices} fatture, {outcome.Receipts} notifiche"), 1000);
if (!string.IsNullOrWhiteSpace(learned) && !string.Equals(current.ExchangeAddress, learned, StringComparison.OrdinalIgnoreCase))
{
current.ExchangeAddress = learned;
}
await uow.Repository<EInvoiceChannelSetting, long>().UpdateAsync(current, cancellationToken).ConfigureAwait(false);
}
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
return outcome;
}
// Invoices first, then their metadata, then the notifications: each file in its own transaction.
private async Task<(int Invoices, int Receipts, int Skipped, HashSet<EInvoiceIncoming> Done)> ProcessAsync(
string company, IFiscalPack pack, string channel, IReadOnlyList<EInvoiceIncoming> files, CancellationToken cancellationToken)
{
var reader = pack.GetFeature<IIncomingInvoiceReader>();
var receiptReader = pack.GetFeature<IEInvoiceReceiptReader>();
var sorted = files.Select(f => (File: f, Receipt: ReadReceipt(receiptReader, f)))
.OrderBy(x => x.Receipt is null ? 0 : x.Receipt.Kind == EInvoiceReceiptKind.Metadata ? 1 : 2)
.ToList();
int invoices = 0, receipts = 0, skipped = 0;
var done = new HashSet<EInvoiceIncoming>();
foreach (var (file, receipt) in sorted)
{
try
{
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
if (receipt is null)
{
var stored = await SdiInboxService.StoreCoreAsync(uow, reader, file.FileName, file.Content, file.ReceivedAt.UtcDateTime, channel, null, false, cancellationToken)
.ConfigureAwait(false);
if (stored.Error is null)
{
invoices++;
}
else
{
skipped++;
}
}
else if (receipt.Kind == EInvoiceReceiptKind.Metadata)
{
await SdiInboxService.AttachMetadataCoreAsync(uow, receipt, cancellationToken).ConfigureAwait(false);
}
else
{
var applied = await _invoices.ApplyReceiptCoreAsync(uow, receipt, channel, Actor.System.UserName, false, cancellationToken).ConfigureAwait(false);
if (applied.Error == EInvoiceErrors.ReceiptDuplicate)
{
skipped++;
}
else
{
receipts++;
}
}
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
done.Add(file);
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
LogFileFailed(_logger, ex, file.FileName, channel, company);
}
}
return (invoices, receipts, skipped, done);
}
private static EInvoiceReceipt? ReadReceipt(IEInvoiceReceiptReader? reader, EInvoiceIncoming file)
{
if (reader is null || !reader.IsReceipt(file.FileName, file.Content))
{
return null;
}
try
{
return reader.Read(file.FileName, file.Content);
}
catch (IncomingInvoiceException)
{
return null;
}
}
[LoggerMessage(EventId = 9111, Level = LogLevel.Information, Message = "Channel {Channel} of {Company}: {Messages} messages, {Invoices} invoices, {Receipts} notifications.")]
private static partial void LogPolled(ILogger logger, string channel, string company, int messages, int invoices, int receipts);
[LoggerMessage(EventId = 9112, Level = LogLevel.Warning, Message = "Channel {Channel} of {Company} could not be read.")]
private static partial void LogPollFailed(ILogger logger, Exception exception, string channel, string company);
[LoggerMessage(EventId = 9113, Level = LogLevel.Error, Message = "File {FileName} from channel {Channel} of {Company} was not kept; the message stays to read again.")]
private static partial void LogFileFailed(ILogger logger, Exception exception, string fileName, string channel, string company);
}
/// <summary>Reads the channels of the SDI of every company (job <c>einvoice.poll</c>, every 15 minutes).</summary>
/// <param name="companies">The companies.</param>
/// <param name="service">The reading of the channels.</param>
/// <param name="license">The licence.</param>
public sealed class EInvoicePollingJob(ICompanyRegistry companies, EInvoicePollingService service, ILicenseGate license) : IScheduledJob
{
/// <summary>The job type.</summary>
public const string JobType = "einvoice.poll";
/// <inheritdoc />
public string Type => JobType;
/// <inheritdoc />
public async Task<string?> RunAsync(JobContext context, CancellationToken cancellationToken)
{
if (!license.IsModuleActive(ModuleCodes.EInvoicing))
{
return "Modulo fatturazione elettronica non attivo.";
}
int done = 0, invoices = 0, receipts = 0, failed = 0;
foreach (var company in await companies.ListAsync(cancellationToken).ConfigureAwait(false))
{
if (company.Status is CompanyStatus.Disabled)
{
continue;
}
foreach (var outcome in await service.PollCompanyAsync(company.Code, cancellationToken).ConfigureAwait(false))
{
invoices += outcome.Invoices;
receipts += outcome.Receipts;
failed += outcome.Error is null ? 0 : 1;
}
done++;
}
return string.Create(CultureInfo.InvariantCulture, $"{done} aziende, {invoices} fatture ricevute, {receipts} notifiche, {failed} canali non letti.");
}
}
@@ -0,0 +1,761 @@
using System.Globalization;
using Khaemhat.Application.Documents;
using Khaemhat.Application.Files;
using Khaemhat.Application.Security;
using Khaemhat.Application.Tables;
using Khaemhat.Core.Documents;
using Khaemhat.Core.EInvoicing;
using Khaemhat.Core.Logging;
using Khaemhat.Core.Parties;
using Khaemhat.Core.Security;
using Khaemhat.Data;
using Khaemhat.Data.Querying;
using Khaemhat.Fiscal.Abstractions;
using Microsoft.Extensions.Logging;
namespace Khaemhat.Application.EInvoicing;
/// <summary>
/// The electronic invoices of the company (SPEC §11.9, mockup 058, ADR 0039, issues #74-#75): the dashboard, the file
/// of each issued document written and checked by the fiscal pack, sending through the channel the router chooses
/// (with its fallback), the notifications of the SDI that move the e-invoice and its document, the correction of a
/// rejected invoice and the courtesy copy.
/// </summary>
/// <remarks>
/// Permissions: <c>einvoice.document.read</c> to see, <c>einvoice.document.send</c> to generate, send and import
/// notifications. The state of the document follows the e-invoice in the same transaction (generated, sent, delivered,
/// rejected, not delivered); a rejected invoice can be changed and generated again with a new progressive.
/// </remarks>
public sealed partial class EInvoiceService
{
private readonly IUnitOfWorkFactory _factory;
private readonly PermissionService _permissions;
private readonly CompanyFiscalContext _packs;
private readonly DocumentEngine _engine;
private readonly ISecretProtector _secrets;
private readonly DocumentPdfGenerator _pdf;
private readonly TimeProvider _clock;
private readonly ILogger<EInvoiceService> _logger;
/// <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="secrets">Opens the secrets of the channels.</param>
/// <param name="pdf">The print of the documents (courtesy copy).</param>
/// <param name="clock">The clock.</param>
/// <param name="logger">The log (section SDI).</param>
public EInvoiceService(
IUnitOfWorkFactory factory, PermissionService permissions, CompanyFiscalContext packs, DocumentEngine engine, ISecretProtector secrets,
DocumentPdfGenerator pdf, TimeProvider clock, ILogger<EInvoiceService> logger)
{
ArgumentNullException.ThrowIfNull(factory);
ArgumentNullException.ThrowIfNull(permissions);
ArgumentNullException.ThrowIfNull(packs);
ArgumentNullException.ThrowIfNull(engine);
ArgumentNullException.ThrowIfNull(secrets);
ArgumentNullException.ThrowIfNull(pdf);
ArgumentNullException.ThrowIfNull(clock);
ArgumentNullException.ThrowIfNull(logger);
_factory = factory;
_permissions = permissions;
_packs = packs;
_engine = engine;
_secrets = secrets;
_pdf = pdf;
_clock = clock;
_logger = logger;
}
/// <summary>The dashboard: the e-invoices of the view, the documents to generate, the counters.</summary>
/// <param name="actor">Who looks: needs <c>einvoice.document.read</c>.</param>
/// <param name="companyCode">The company.</param>
/// <param name="filter">The filter.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The dashboard.</returns>
public async Task<EInvoiceDashboard> DashboardAsync(Actor actor, string companyCode, EInvoiceFilter filter, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(filter);
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, EInvoicePermissions.Read, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
var query = Query.For<EInvoice>().Where(e => !e.Superseded);
if (filter.From is { } from)
{
query = query.Where(e => e.DocumentDate >= from);
}
if (filter.To is { } to)
{
query = query.Where(e => e.DocumentDate <= to);
}
var all = (await uow.Repository<EInvoice, long>().ListAsync(query.OrderByDescending(e => e.DocumentDate), cancellationToken).ConfigureAwait(false)).Items
.Select(EInvoiceStore.Light)
.ToList();
var pending = await PendingAsync(uow, filter, cancellationToken).ConfigureAwait(false);
var received = await uow.Repository<EInvoiceInboxFile, long>().CountAsync(Query.For<EInvoiceInboxFile>().Where(f => f.Status == InboxFileStatus.New), cancellationToken)
.ConfigureAwait(false);
var counters = new EInvoiceCounters(
pending.Count(p => p.Status == DocumentStatus.Issued),
all.Count(e => e.Status == EInvoiceStatus.Generated),
all.Count(e => e.Status == EInvoiceStatus.Sent),
all.Count(e => EInvoiceStates.IsIssued(e.Status) && e.Status is not (EInvoiceStatus.Refused or EInvoiceStatus.NotDelivered or EInvoiceStatus.Undeliverable)),
all.Count(e => EInvoiceStates.NeedsAction(e.Status)),
all.Count(e => e.Status is EInvoiceStatus.NotDelivered or EInvoiceStatus.Undeliverable),
received);
IEnumerable<EInvoice> rows = filter.View switch
{
EInvoiceView.SelfInvoices => all.Where(e => e.Kind == DocumentKind.SelfInvoice),
EInvoiceView.ToDo => all.Where(e => e.Status == EInvoiceStatus.Generated || EInvoiceStates.NeedsAction(e.Status)),
_ => all.Where(e => e.Kind != DocumentKind.SelfInvoice),
};
if (filter.Status is { } status)
{
rows = rows.Where(e => e.Status == status);
}
var list = rows.ToList();
var parties = await PartiesAsync(uow, list.Select(e => e.PartyId).OfType<long>(), cancellationToken).ConfigureAwait(false);
var result = list.Select(e => new EInvoiceRow(e, parties.GetValueOrDefault(e.PartyId ?? 0)?.Code, parties.GetValueOrDefault(e.PartyId ?? 0)?.Name));
if (!string.IsNullOrWhiteSpace(filter.Search))
{
var text = filter.Search.Trim();
result = result.Where(r => Contains(r.Invoice.DocumentNumber, text) || Contains(r.Invoice.FileName, text) || Contains(r.Invoice.ExchangeId, text)
|| Contains(r.PartyName, text) || Contains(r.PartyCode, text));
}
var visiblePending = filter.View switch
{
EInvoiceView.SelfInvoices => pending.Where(p => p.Kind == DocumentKind.SelfInvoice),
EInvoiceView.ToDo => pending,
_ => pending.Where(p => p.Kind != DocumentKind.SelfInvoice),
};
return new EInvoiceDashboard([.. result], [.. visiblePending], counters);
}
/// <summary>The e-invoices of a document with their notifications, newest first (the page of the document).</summary>
/// <param name="actor">Who looks.</param>
/// <param name="companyCode">The company.</param>
/// <param name="family">The family.</param>
/// <param name="documentId">The document.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The files and their notifications.</returns>
public async Task<IReadOnlyList<(EInvoice Invoice, IReadOnlyList<EInvoiceNotification> Notifications)>> HistoryAsync(
Actor actor, string companyCode, DocumentFamily family, long documentId, CancellationToken cancellationToken = default)
{
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, EInvoicePermissions.Read, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
var invoices = (await uow.Repository<EInvoice, long>()
.ListAsync(Query.For<EInvoice>().Where(e => e.Family == family && e.DocumentId == documentId).OrderByDescending(e => e.Id), cancellationToken).ConfigureAwait(false)).Items;
var result = new List<(EInvoice, IReadOnlyList<EInvoiceNotification>)>();
foreach (var invoice in invoices)
{
var id = invoice.Id;
var notifications = (await uow.Repository<EInvoiceNotification, long>()
.ListAsync(Query.For<EInvoiceNotification>().Where(n => n.EInvoiceId == id).OrderBy(n => n.ReceivedAt), cancellationToken).ConfigureAwait(false)).Items;
result.Add((EInvoiceStore.Light(invoice), [.. notifications.Select(n => { n.Content = []; return n; })]));
}
return result;
}
/// <summary>The notifications received in a period, newest first (files not loaded).</summary>
/// <param name="actor">Who looks: needs <c>einvoice.document.read</c>.</param>
/// <param name="companyCode">The company.</param>
/// <param name="from">From this day.</param>
/// <param name="to">Up to this day.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The notifications.</returns>
public async Task<IReadOnlyList<EInvoiceNotification>> NotificationsAsync(Actor actor, string companyCode, DateOnly from, DateOnly to, CancellationToken cancellationToken = default)
{
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, EInvoicePermissions.Read, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
var start = from.ToDateTime(TimeOnly.MinValue, DateTimeKind.Utc);
var end = to.AddDays(1).ToDateTime(TimeOnly.MinValue, DateTimeKind.Utc);
var rows = (await uow.Repository<EInvoiceNotification, long>()
.ListAsync(Query.For<EInvoiceNotification>().Where(n => n.ReceivedAt >= start && n.ReceivedAt < end).OrderByDescending(n => n.ReceivedAt).Take(2000), cancellationToken)
.ConfigureAwait(false)).Items;
foreach (var row in rows)
{
row.Content = [];
}
return rows;
}
/// <summary>Checks the file a document would have, without writing it.</summary>
/// <param name="actor">Who checks: needs <c>einvoice.document.read</c>.</param>
/// <param name="companyCode">The company.</param>
/// <param name="family">The family.</param>
/// <param name="documentId">The document.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The problems, empty when the file can be sent.</returns>
public async Task<IReadOnlyList<EInvoiceProblem>> CheckAsync(Actor actor, string companyCode, DocumentFamily family, long documentId, CancellationToken cancellationToken = default)
{
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, EInvoicePermissions.Read, cancellationToken).ConfigureAwait(false);
var (writer, validator, _) = await FeaturesAsync(company, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
var record = await DocumentEngine.LoadAsync(uow, family, documentId, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(EInvoiceErrors.NotFound);
if (!EInvoiceBuilder.IsElectronic(record.Header.Kind))
{
return [Problem(EInvoiceErrors.NotElectronic)];
}
var (file, _, _) = await EInvoiceBuilder.BuildAsync(uow, record, cancellationToken).ConfigureAwait(false);
file = file with { FileName = writer.FileName(file.TransmitterCountry ?? "IT", file.TransmitterId ?? "0", 1), ProgressiveNumber = writer.Progressive(1) };
var problems = validator.Validate(file).ToList();
if (problems.All(p => p.Severity != EInvoiceProblemSeverity.Error))
{
problems.AddRange(validator.ValidateXml(writer.Write(file)));
}
return problems;
}
/// <summary>
/// Writes the file of an issued document (or of one rejected by the SDI): built from the document, checked against
/// the rules of the pack and its schema; the document goes to <i>XML generato</i>. A file generated and not sent is
/// written again with the same name; a rejected one is kept, superseded, and the new file has a new progressive.
/// </summary>
/// <param name="actor">Who generates: needs <c>einvoice.document.send</c>.</param>
/// <param name="companyCode">The company.</param>
/// <param name="family">The family.</param>
/// <param name="documentId">The document.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The e-invoice, or the errors.</returns>
public async Task<EInvoiceGeneration> GenerateAsync(Actor actor, string companyCode, DocumentFamily family, long documentId, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(actor);
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, EInvoicePermissions.Send, cancellationToken).ConfigureAwait(false);
var (writer, validator, _) = await FeaturesAsync(company, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
var result = await GenerateCoreAsync(uow, writer, validator, family, documentId, actor.UserName, cancellationToken).ConfigureAwait(false);
if (result.Success)
{
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
using (_logger.BeginScope(LogSections.Scope(LogSection.EInvoicing)))
{
LogGenerated(_logger, result.Invoice!.FileName, result.Invoice.DocumentNumber, company);
}
}
return result;
}
/// <summary>Generates the files of several documents and sends them (the button <i>Genera e invia</i>).</summary>
/// <param name="actor">Who sends.</param>
/// <param name="companyCode">The company.</param>
/// <param name="documents">The documents.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>For each document, the generation and the sending.</returns>
public async Task<IReadOnlyList<(PendingEInvoice? Document, EInvoiceGeneration Generation, EInvoiceSendOutcome? Sending)>> GenerateAndSendAsync(
Actor actor, string companyCode, IReadOnlyList<(DocumentFamily Family, long DocumentId)> documents, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(documents);
var result = new List<(PendingEInvoice?, EInvoiceGeneration, EInvoiceSendOutcome?)>();
foreach (var (family, id) in documents)
{
var generation = await GenerateAsync(actor, companyCode, family, id, cancellationToken).ConfigureAwait(false);
EInvoiceSendOutcome? sending = null;
if (generation.Invoice is { } invoice)
{
sending = (await SendAsync(actor, companyCode, [invoice.Id], cancellationToken).ConfigureAwait(false))[0];
}
result.Add((null, generation, sending));
}
return result;
}
/// <summary>
/// Sends generated files through the channel the router chooses; when the channel refuses the file the fallback of
/// the rule is tried. A file a channel took goes to <i>Inviato</i> with its document; one no channel took keeps its
/// state and the error.
/// </summary>
/// <param name="actor">Who sends: needs <c>einvoice.document.send</c>.</param>
/// <param name="companyCode">The company.</param>
/// <param name="ids">The e-invoices.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>What happened to each.</returns>
public async Task<IReadOnlyList<EInvoiceSendOutcome>> SendAsync(Actor actor, string companyCode, IReadOnlyList<long> ids, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(actor);
ArgumentNullException.ThrowIfNull(ids);
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, EInvoicePermissions.Send, cancellationToken).ConfigureAwait(false);
var pack = await _packs.PackOfAsync(company, cancellationToken).ConfigureAwait(false);
var channels = pack.GetFeature<IEInvoiceChannels>();
var result = new List<EInvoiceSendOutcome>();
foreach (var id in ids.Distinct())
{
result.Add(await SendOneAsync(company, channels, id, actor.UserName, cancellationToken).ConfigureAwait(false));
}
return result;
}
/// <summary>Records that a generated file was sent outside Khaemhat (portal of the AdE, another program).</summary>
/// <param name="actor">Who records it: needs <c>einvoice.document.send</c>.</param>
/// <param name="companyCode">The company.</param>
/// <param name="id">The e-invoice.</param>
/// <param name="exchangeId">The identifier of the SDI, when known.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The e-invoice.</returns>
public async Task<EInvoice> MarkSentAsync(Actor actor, string companyCode, long id, string? exchangeId, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(actor);
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, EInvoicePermissions.Send, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
var invoice = await uow.Repository<EInvoice, long>().GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(EInvoiceErrors.NotFound);
if (invoice.Superseded || invoice.Status != EInvoiceStatus.Generated)
{
throw new ValidationFailedException([":" + EInvoiceErrors.AlreadySent]);
}
await MarkSentCoreAsync(uow, invoice, EInvoiceStore.ManualChannel, EInvoiceStore.Trim(exchangeId, 40), null, actor.UserName, cancellationToken).ConfigureAwait(false);
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
return EInvoiceStore.Light(invoice);
}
/// <summary>Imports notifications downloaded from the portal of the AdE or from another program.</summary>
/// <param name="actor">Who imports: needs <c>einvoice.document.send</c>.</param>
/// <param name="companyCode">The company.</param>
/// <param name="files">The files.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>What happened to each.</returns>
public async Task<IReadOnlyList<ReceiptOutcome>> ImportReceiptsAsync(
Actor actor, string companyCode, IReadOnlyList<(string FileName, byte[] Content)> files, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(actor);
ArgumentNullException.ThrowIfNull(files);
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, EInvoicePermissions.Send, cancellationToken).ConfigureAwait(false);
var reader = (await _packs.PackOfAsync(company, cancellationToken).ConfigureAwait(false)).GetFeature<IEInvoiceReceiptReader>()
?? throw new ValidationFailedException([":" + EInvoiceErrors.NotSupported]);
var result = new List<ReceiptOutcome>();
foreach (var (name, content) in files)
{
EInvoiceReceipt receipt;
try
{
if (!reader.IsReceipt(name, content))
{
result.Add(new ReceiptOutcome(name, null, null, null, null, EInvoiceErrors.NotAReceipt));
continue;
}
receipt = reader.Read(name, content);
}
catch (IncomingInvoiceException)
{
result.Add(new ReceiptOutcome(name, null, null, null, null, EInvoiceErrors.NotAReceipt));
continue;
}
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
var outcome = await ApplyReceiptCoreAsync(uow, receipt, EInvoiceStore.ManualChannel, actor.UserName, false, cancellationToken).ConfigureAwait(false);
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
result.Add(outcome);
}
return result;
}
/// <summary>The file of an e-invoice, as sent.</summary>
/// <param name="actor">Who downloads: needs <c>einvoice.document.read</c>.</param>
/// <param name="companyCode">The company.</param>
/// <param name="id">The e-invoice.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>Name and content.</returns>
public async Task<(string FileName, byte[] Content)> FileAsync(Actor actor, string companyCode, long id, CancellationToken cancellationToken = default)
{
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, EInvoicePermissions.Read, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
var invoice = await uow.Repository<EInvoice, long>().GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(EInvoiceErrors.NotFound);
return (invoice.FileName, invoice.Content);
}
/// <summary>The file of a notification.</summary>
/// <param name="actor">Who downloads: needs <c>einvoice.document.read</c>.</param>
/// <param name="companyCode">The company.</param>
/// <param name="id">The notification.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>Name and content.</returns>
public async Task<(string FileName, byte[] Content)> NotificationFileAsync(Actor actor, string companyCode, long id, CancellationToken cancellationToken = default)
{
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, EInvoicePermissions.Read, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
var notification = await uow.Repository<EInvoiceNotification, long>().GetAsync(id, cancellationToken).ConfigureAwait(false)
?? throw new KeyNotFoundException(EInvoiceErrors.NotFound);
return (notification.FileName, notification.Content);
}
/// <summary>The courtesy copy: the print of the document with the XML of the e-invoice embedded.</summary>
/// <param name="actor">Who downloads: needs <c>einvoice.document.read</c> and to read the document.</param>
/// <param name="companyCode">The company.</param>
/// <param name="id">The e-invoice.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>Name and content of the PDF.</returns>
public async Task<(string FileName, byte[] Content)> CourtesyCopyAsync(Actor actor, string companyCode, long id, CancellationToken cancellationToken = default)
{
var (name, xml) = await FileAsync(actor, companyCode, id, cancellationToken).ConfigureAwait(false);
EInvoice invoice;
await using (var uow = await _factory.CreateAsync(DatabaseScope.Company(companyCode), cancellationToken).ConfigureAwait(false))
{
invoice = await uow.Repository<EInvoice, long>().GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(EInvoiceErrors.NotFound);
}
using var output = new MemoryStream();
var context = new FileGenerationContext(actor, companyCode, DocumentPrintService.EntityOf(invoice.Family), invoice.DocumentId, CultureInfo.GetCultureInfo("it-IT"), _clock.GetUtcNow().UtcDateTime);
await _pdf.CourtesyCopyAsync(context, name, xml, output, cancellationToken).ConfigureAwait(false);
return (EInvoiceStore.Stem(name) + ".pdf", output.ToArray());
}
/// <summary>The core of the generation, in the transaction of the caller (also the demo seed).</summary>
internal async Task<EInvoiceGeneration> GenerateCoreAsync(
IUnitOfWork uow, IEInvoiceWriter writer, IEInvoiceValidator validator, DocumentFamily family, long documentId, string userName, CancellationToken cancellationToken)
{
var record = await DocumentEngine.LoadAsync(uow, family, documentId, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(EInvoiceErrors.NotFound);
var header = record.Header;
if (!EInvoiceBuilder.IsElectronic(header.Kind))
{
return new(null, [Problem(EInvoiceErrors.NotElectronic)]);
}
if (header.Status is DocumentStatus.Draft or DocumentStatus.Cancelled)
{
return new(null, [Problem(EInvoiceErrors.NotIssued)]);
}
var repository = uow.Repository<EInvoice, long>();
var active = await repository.FindAsync(Query.For<EInvoice>().Where(e => e.Family == family && e.DocumentId == documentId && !e.Superseded), cancellationToken)
.ConfigureAwait(false);
if (header.Status is not (DocumentStatus.Issued or DocumentStatus.SdiGenerated or DocumentStatus.SdiRejected)
|| active is { Status: not (EInvoiceStatus.Generated or EInvoiceStatus.Rejected) })
{
return new(null, [Problem(EInvoiceErrors.AlreadySent)]);
}
var (file, party, _) = await EInvoiceBuilder.BuildAsync(uow, record, cancellationToken).ConfigureAwait(false);
var problems = validator.Validate(file).ToList();
if (problems.Any(p => p.Severity == EInvoiceProblemSeverity.Error))
{
return new(null, problems);
}
var reuse = active is { Status: EInvoiceStatus.Generated };
var progressive = reuse ? active!.Progressive : await NextProgressiveAsync(uow, cancellationToken).ConfigureAwait(false);
var fileName = reuse ? active!.FileName : writer.FileName(file.TransmitterCountry ?? "IT", file.TransmitterId ?? string.Empty, progressive);
file = file with { FileName = fileName, ProgressiveNumber = writer.Progressive(progressive) };
var xml = writer.Write(file);
var schema = validator.ValidateXml(xml);
if (schema.Any(p => p.Severity == EInvoiceProblemSeverity.Error))
{
return new(null, [.. problems, .. schema]);
}
var now = _clock.GetUtcNow().UtcDateTime;
var invoice = reuse ? active! : new EInvoice();
invoice.Family = family;
invoice.DocumentId = documentId;
invoice.Kind = header.Kind;
invoice.DocumentNumber = header.DocumentNumber;
invoice.DocumentDate = header.DocumentDate;
invoice.PartyId = party.Id;
invoice.DocumentType = file.Invoices[0].DocumentType;
invoice.FileName = fileName;
invoice.Progressive = progressive;
invoice.Format = file.TransmissionFormat ?? string.Empty;
invoice.RecipientCode = file.RecipientCode;
invoice.RecipientPec = file.RecipientPec;
invoice.TotalAmount = header.TotalAmount;
invoice.Status = EInvoiceStatus.Generated;
invoice.GeneratedAt = now;
invoice.LastMessage = null;
invoice.Content = xml;
invoice.IsDemo = header.IsDemo;
if (reuse)
{
await repository.UpdateAsync(invoice, cancellationToken).ConfigureAwait(false);
}
else
{
if (active is not null)
{
active.Superseded = true;
await repository.UpdateAsync(active, cancellationToken).ConfigureAwait(false);
}
invoice.Id = await repository.InsertAsync(invoice, cancellationToken).ConfigureAwait(false);
}
await _engine.AdvanceExchangeAsync(uow, family, documentId, s => EInvoiceStates.StepsTo(s, EInvoiceStatus.Generated), userName, cancellationToken).ConfigureAwait(false);
return new(invoice, problems);
}
/// <summary>A file taken by a channel: <i>Inviato</i>, with the document.</summary>
internal async Task MarkSentCoreAsync(IUnitOfWork uow, EInvoice invoice, string channel, string? exchangeId, string? messageId, string userName, CancellationToken cancellationToken)
{
invoice.Status = EInvoiceStatus.Sent;
invoice.SentAt = _clock.GetUtcNow().UtcDateTime;
invoice.ChannelCode = channel;
invoice.ExchangeId = exchangeId ?? invoice.ExchangeId;
invoice.MessageId = EInvoiceStore.Trim(messageId, 200);
invoice.LastMessage = null;
await uow.Repository<EInvoice, long>().UpdateAsync(invoice, cancellationToken).ConfigureAwait(false);
await _engine.AdvanceExchangeAsync(uow, invoice.Family, invoice.DocumentId, s => EInvoiceStates.StepsTo(s, EInvoiceStatus.Sent), userName, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Applies a notification in the transaction of the caller: kept as received (once: the file name is unique), the
/// e-invoice found by file name or identifier of the SDI gets the new state and its document follows.
/// </summary>
internal async Task<ReceiptOutcome> ApplyReceiptCoreAsync(
IUnitOfWork uow, EInvoiceReceipt receipt, string? channel, string userName, bool demo, CancellationToken cancellationToken)
{
var notifications = uow.Repository<EInvoiceNotification, long>();
var name = receipt.FileName;
if (await notifications.FindAsync(Query.For<EInvoiceNotification>().Where(n => n.FileName == name), cancellationToken).ConfigureAwait(false) is { } known)
{
return new ReceiptOutcome(name, receipt.Code, known.InvoiceFileName, known.EInvoiceId, null, EInvoiceErrors.ReceiptDuplicate);
}
var invoice = await FindInvoiceAsync(uow, receipt, cancellationToken).ConfigureAwait(false);
var errors = receipt.Errors.Count == 0 ? null : string.Join('\n', receipt.Errors.Select(e => e.Code + " - " + e.Description + (e.Hint is null ? string.Empty : " (" + e.Hint + ")")));
var receivedAt = (receipt.ReceivedAt ?? _clock.GetUtcNow()).UtcDateTime;
await notifications.InsertAsync(
new EInvoiceNotification
{
EInvoiceId = invoice?.Id,
Code = receipt.Code,
FileName = EInvoiceStore.Trim(name, 100)!,
InvoiceFileName = EInvoiceStore.Trim(receipt.InvoiceFileName ?? invoice?.FileName, 100),
ExchangeId = EInvoiceStore.Trim(receipt.ExchangeId, 40),
ReceivedAt = receivedAt,
Outcome = EInvoiceStore.Trim(receipt.Outcome, 10),
Description = EInvoiceStore.Trim(receipt.Description, 1000),
Errors = errors,
ChannelCode = channel,
Content = receipt.Content,
IsDemo = demo || invoice?.IsDemo == true,
},
cancellationToken).ConfigureAwait(false);
if (invoice is null)
{
return new ReceiptOutcome(name, receipt.Code, receipt.InvoiceFileName, null, null, receipt.Code is "MT" or "SE" ? null : EInvoiceErrors.ReceiptUnmatched);
}
var next = EInvoiceStates.After(receipt.Code, receipt.Outcome);
if (next is { } status)
{
if (invoice.Status == EInvoiceStatus.Generated)
{
invoice.SentAt ??= receivedAt;
invoice.ChannelCode ??= channel;
}
invoice.Status = status;
invoice.ExchangeId ??= EInvoiceStore.Trim(receipt.ExchangeId, 40);
invoice.LastNotificationAt = receivedAt;
invoice.LastMessage = EInvoiceStore.Trim(errors ?? receipt.Description, 1000);
await uow.Repository<EInvoice, long>().UpdateAsync(invoice, cancellationToken).ConfigureAwait(false);
await _engine.AdvanceExchangeAsync(uow, invoice.Family, invoice.DocumentId, s => EInvoiceStates.StepsTo(s, status), userName, cancellationToken).ConfigureAwait(false);
using (_logger.BeginScope(LogSections.Scope(LogSection.EInvoicing)))
{
LogReceipt(_logger, receipt.Code, invoice.FileName, status);
}
}
return new ReceiptOutcome(name, receipt.Code, invoice.FileName, invoice.Id, next, null);
}
private static async Task<EInvoice?> FindInvoiceAsync(IUnitOfWork uow, EInvoiceReceipt receipt, CancellationToken cancellationToken)
{
var repository = uow.Repository<EInvoice, long>();
var stem = receipt.InvoiceFileName is { } invoiceName ? EInvoiceStore.Stem(invoiceName) : EInvoiceStore.InvoiceStem(receipt.FileName);
if (stem is not null)
{
foreach (var candidate in new[] { stem + ".xml", stem + ".xml.p7m" })
{
if (await repository.FindAsync(Query.For<EInvoice>().Where(e => e.FileName == candidate), cancellationToken).ConfigureAwait(false) is { } byName)
{
return byName;
}
}
}
if (receipt.ExchangeId is { Length: > 0 } exchange)
{
return await repository.FindAsync(Query.For<EInvoice>().Where(e => e.ExchangeId == exchange).OrderByDescending(e => e.Id), cancellationToken).ConfigureAwait(false);
}
return null;
}
private async Task<EInvoiceSendOutcome> SendOneAsync(string company, IEInvoiceChannels? channels, long id, string userName, CancellationToken cancellationToken)
{
EInvoice invoice;
List<(string Code, EInvoiceChannelSettings Settings)> route;
await using (var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false))
{
invoice = await uow.Repository<EInvoice, long>().GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(EInvoiceErrors.NotFound);
if (invoice.Superseded || invoice.Status != EInvoiceStatus.Generated)
{
return new EInvoiceSendOutcome(id, invoice.FileName, invoice.DocumentNumber, false, invoice.ChannelCode, EInvoiceErrors.AlreadySent);
}
route = await RouteAsync(uow, channels, invoice, cancellationToken).ConfigureAwait(false);
}
if (route.Count == 0 || channels is null)
{
return new EInvoiceSendOutcome(id, invoice.FileName, invoice.DocumentNumber, false, null, EInvoiceErrors.NoChannel);
}
EInvoiceSendResult? result = null;
string? used = null;
var errors = new List<string>();
foreach (var (code, settings) in route)
{
var transport = channels.Find(code)!.Transport;
used = code;
result = await transport.SendAsync(settings, new EInvoiceOutgoing(invoice.FileName, invoice.Content, invoice.DocumentNumber), cancellationToken).ConfigureAwait(false);
if (result.Accepted)
{
break;
}
errors.Add(code + ": " + result.Error);
using (_logger.BeginScope(LogSections.Scope(LogSection.EInvoicing)))
{
LogSendFailed(_logger, invoice.FileName, code, result.Error);
}
}
await using (var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false))
{
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
var current = await uow.Repository<EInvoice, long>().GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(EInvoiceErrors.NotFound);
if (result is { Accepted: true })
{
await MarkSentCoreAsync(uow, current, used!, EInvoiceStore.Trim(result.ExchangeId, 40), result.MessageId, userName, cancellationToken).ConfigureAwait(false);
}
else
{
current.SendAttempts++;
current.LastMessage = EInvoiceStore.Trim(string.Join(" | ", errors), 1000);
await uow.Repository<EInvoice, long>().UpdateAsync(current, cancellationToken).ConfigureAwait(false);
}
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
}
if (result is { Accepted: true })
{
using (_logger.BeginScope(LogSections.Scope(LogSection.EInvoicing)))
{
LogSent(_logger, invoice.FileName, used!, company);
}
}
return new EInvoiceSendOutcome(id, invoice.FileName, invoice.DocumentNumber, result?.Accepted == true, used, result?.Accepted == true ? null : string.Join(" | ", errors));
}
// The channels to try, in order: the one of the router, then its fallback; each with its settings.
private async Task<List<(string Code, EInvoiceChannelSettings Settings)>> RouteAsync(IUnitOfWork uow, IEInvoiceChannels? channels, EInvoice invoice, CancellationToken cancellationToken)
{
if (channels is null)
{
return [];
}
var rows = (await uow.Repository<EInvoiceChannelSetting, long>().ListAsync(Query.For<EInvoiceChannelSetting>().Where(c => c.Enabled && !c.Paused), cancellationToken)
.ConfigureAwait(false)).Items.ToDictionary(c => c.Code, StringComparer.OrdinalIgnoreCase);
var usable = channels.All.Select(c => c.Code).Where(rows.ContainsKey).ToList();
var rules = (await uow.Repository<SdiRoutingRule, long>().ListAsync(Query.For<SdiRoutingRule>(), cancellationToken).ConfigureAwait(false)).Items;
var party = invoice.PartyId is { } partyId ? await uow.Repository<Party, long>().GetAsync(partyId, cancellationToken).ConfigureAwait(false) : null;
var today = _clock.GetUtcNow().UtcDateTime.Date;
var sentToday = await uow.Repository<EInvoice, long>().CountAsync(Query.For<EInvoice>().Where(e => e.SentAt >= today), cancellationToken).ConfigureAwait(false);
var choice = SdiRouter.Choose(new SdiRoutingInput(invoice.DocumentType, party?.Code, invoice.Format == "FPA12", sentToday), rules, usable);
if (choice is null)
{
return [];
}
return [.. new[] { choice.Channel, choice.Fallback }.OfType<string>().Distinct(StringComparer.OrdinalIgnoreCase)
.Select(code => (code, EInvoiceStore.Settings(rows[code], _secrets)))];
}
private async Task<(IEInvoiceWriter Writer, IEInvoiceValidator Validator, IFiscalPack Pack)> FeaturesAsync(string company, CancellationToken cancellationToken)
{
var pack = await _packs.PackOfAsync(company, cancellationToken).ConfigureAwait(false);
var writer = pack.GetFeature<IEInvoiceWriter>();
var validator = pack.GetFeature<IEInvoiceValidator>();
return writer is null || validator is null ? throw new ValidationFailedException([":" + EInvoiceErrors.NotSupported]) : (writer, validator, pack);
}
private static async Task<long> NextProgressiveAsync(IUnitOfWork uow, CancellationToken cancellationToken)
{
var last = await uow.Repository<EInvoice, long>().FindAsync(Query.For<EInvoice>().OrderByDescending(e => e.Progressive), cancellationToken).ConfigureAwait(false);
return (last?.Progressive ?? 0L) + 1L;
}
// Issued (or rejected) electronic documents without a file ready to send.
private static async Task<List<PendingEInvoice>> PendingAsync(IUnitOfWork uow, EInvoiceFilter filter, CancellationToken cancellationToken)
{
var query = Query.For<SaleDocument>().Where(d => d.Status == DocumentStatus.Issued || d.Status == DocumentStatus.SdiRejected);
if (filter.From is { } from)
{
query = query.Where(d => d.DocumentDate >= from);
}
if (filter.To is { } to)
{
query = query.Where(d => d.DocumentDate <= to);
}
var documents = (await uow.Repository<SaleDocument, long>().ListAsync(query.OrderBy(d => d.DocumentDate), cancellationToken).ConfigureAwait(false)).Items
.Where(d => EInvoiceBuilder.IsElectronic(d.Kind))
.ToList();
var parties = await PartiesAsync(uow, documents.Select(d => d.PartyId).OfType<long>(), cancellationToken).ConfigureAwait(false);
return [.. documents.Select(d => new PendingEInvoice(DocumentFamily.SaleDocument, d.Id, d.Kind, d.DocumentNumber, d.DocumentDate,
parties.GetValueOrDefault(d.PartyId ?? 0)?.Name, d.TotalAmount, d.Status))];
}
private static async Task<Dictionary<long, Party>> PartiesAsync(IUnitOfWork uow, IEnumerable<long> ids, CancellationToken cancellationToken)
{
var set = ids.Distinct().ToList();
var result = new Dictionary<long, Party>();
foreach (var chunk in set.Chunk(500))
{
var list = chunk.ToList();
foreach (var party in (await uow.Repository<Party, long>().ListAsync(Query.For<Party>().Where(p => list.Contains(p.Id)), cancellationToken).ConfigureAwait(false)).Items)
{
result[party.Id] = party;
}
}
return result;
}
private static bool Contains(string? value, string text) => value?.Contains(text, StringComparison.CurrentCultureIgnoreCase) == true;
private static EInvoiceProblem Problem(string code) => new(code, string.Empty, code, EInvoiceProblemSeverity.Error);
[LoggerMessage(EventId = 9101, Level = LogLevel.Information, Message = "E-invoice {FileName} generated for document {Number} in {Company}.")]
private static partial void LogGenerated(ILogger logger, string fileName, string? number, string company);
[LoggerMessage(EventId = 9102, Level = LogLevel.Information, Message = "E-invoice {FileName} sent through {Channel} in {Company}.")]
private static partial void LogSent(ILogger logger, string fileName, string channel, string company);
[LoggerMessage(EventId = 9103, Level = LogLevel.Warning, Message = "E-invoice {FileName} not taken by channel {Channel}: {Error}")]
private static partial void LogSendFailed(ILogger logger, string fileName, string channel, string? error);
[LoggerMessage(EventId = 9104, Level = LogLevel.Information, Message = "Notification {Code} for {FileName}: now {Status}.")]
private static partial void LogReceipt(ILogger logger, string code, string fileName, EInvoiceStatus status);
}
@@ -0,0 +1,284 @@
using System.Security.Cryptography;
using Khaemhat.Core.Documents;
using Khaemhat.Core.EInvoicing;
using Khaemhat.Core.Security;
using Khaemhat.Fiscal.Abstractions;
namespace Khaemhat.Application.EInvoicing;
/// <summary>The permissions of the electronic invoice (module EINV, <see cref="Modules.BuiltInModules"/>).</summary>
public static class EInvoicePermissions
{
/// <summary>See the e-invoices, their notifications and the conservation packages.</summary>
public const string Read = "einvoice.document.read";
/// <summary>Generate, send and send again; import notifications.</summary>
public const string Send = "einvoice.document.send";
/// <summary>See the invoices received.</summary>
public const string InboxRead = "einvoice.inbox.read";
/// <summary>Register, discard and upload the invoices received.</summary>
public const string InboxImport = "einvoice.inbox.import";
/// <summary>Configure the channels and the routing; read the channels now.</summary>
public const string ChannelManage = "einvoice.channel.manage";
}
/// <summary>The error codes of the electronic invoice (texts in <c>EInvoicing.json</c>).</summary>
public static class EInvoiceErrors
{
/// <summary>No e-invoice, notification or file with that identifier.</summary>
public const string NotFound = "einvoice.not-found";
/// <summary>The kind of document does not go to the exchange system.</summary>
public const string NotElectronic = "einvoice.not-electronic";
/// <summary>The document is not issued yet.</summary>
public const string NotIssued = "einvoice.not-issued";
/// <summary>The file was already sent: it can only receive notifications.</summary>
public const string AlreadySent = "einvoice.already-sent";
/// <summary>The profile of the company is missing.</summary>
public const string CompanyProfileMissing = "einvoice.profile-missing";
/// <summary>The fiscal pack of the company does not write e-invoices.</summary>
public const string NotSupported = "einvoice.not-supported";
/// <summary>No channel is enabled.</summary>
public const string NoChannel = "einvoice.no-channel";
/// <summary>The file is not a notification of the exchange system.</summary>
public const string NotAReceipt = "einvoice.not-a-receipt";
/// <summary>The notification is about a file Khaemhat did not send.</summary>
public const string ReceiptUnmatched = "einvoice.receipt-unmatched";
/// <summary>The notification was already imported.</summary>
public const string ReceiptDuplicate = "einvoice.receipt-duplicate";
/// <summary>The channel is not one of the pack.</summary>
public const string ChannelUnknown = "einvoice.channel-unknown";
/// <summary>A port out of range.</summary>
public const string PortInvalid = "einvoice.port-invalid";
/// <summary>The mailbox is not an e-mail address.</summary>
public const string MailboxInvalid = "einvoice.mailbox-invalid";
/// <summary>The address of the service is not an https address.</summary>
public const string EndpointInvalid = "einvoice.endpoint-invalid";
/// <summary>The value of a routing rule is missing or wrong.</summary>
public const string RuleValueInvalid = "einvoice.rule-value";
/// <summary>The received file is already in the inbox.</summary>
public const string InboxDuplicate = "einvoice.inbox-duplicate";
/// <summary>The received file is not in a state that allows the action.</summary>
public const string InboxState = "einvoice.inbox-state";
/// <summary>The period of the conservation package is wrong.</summary>
public const string PeriodInvalid = "einvoice.period-invalid";
}
/// <summary>An e-invoice in the lists, with its counterpart.</summary>
/// <param name="Invoice">The e-invoice (the file is not loaded for lists).</param>
/// <param name="PartyCode">The code of the customer or supplier.</param>
/// <param name="PartyName">The name.</param>
public sealed record EInvoiceRow(EInvoice Invoice, string? PartyCode, string? PartyName);
/// <summary>An issued document without its file yet, or whose file was rejected.</summary>
/// <param name="Family">The family.</param>
/// <param name="DocumentId">The document.</param>
/// <param name="Kind">The kind.</param>
/// <param name="Number">The number.</param>
/// <param name="Date">The date.</param>
/// <param name="PartyName">The customer, or the supplier of a self-invoice.</param>
/// <param name="Total">The total.</param>
/// <param name="Status">The state of the document.</param>
public sealed record PendingEInvoice(DocumentFamily Family, long DocumentId, DocumentKind Kind, string? Number, DateOnly Date, string? PartyName, decimal Total, DocumentStatus Status);
/// <summary>What the dashboard shows.</summary>
public enum EInvoiceView
{
/// <summary>Invoices, notes and fees sent to customers.</summary>
Issued = 0,
/// <summary>Self-invoices and integrations.</summary>
SelfInvoices = 1,
/// <summary>Everything that needs the user: to generate, to send, rejected, refused.</summary>
ToDo = 2,
}
/// <summary>The filter of the dashboard.</summary>
/// <param name="View">The view.</param>
/// <param name="Status">Only this state.</param>
/// <param name="From">From this date of the document.</param>
/// <param name="To">Up to this date.</param>
/// <param name="Search">Number, file name, identifier of the SDI or counterpart.</param>
public sealed record EInvoiceFilter(EInvoiceView View = EInvoiceView.Issued, EInvoiceStatus? Status = null, DateOnly? From = null, DateOnly? To = null, string? Search = null);
/// <summary>The counters of the dashboard (mockup 058).</summary>
/// <param name="ToGenerate">Issued documents without a file.</param>
/// <param name="ToSend">Files generated and not sent.</param>
/// <param name="Waiting">Sent, waiting for the receipt.</param>
/// <param name="Delivered">Delivered or accepted (RC, NE EC01, DT).</param>
/// <param name="Rejected">Rejected by the SDI or refused by a public administration.</param>
/// <param name="NotDelivered">Issued but not delivered: in the reserved area of the customer (MC, AT).</param>
/// <param name="Received">Invoices received to register.</param>
public sealed record EInvoiceCounters(int ToGenerate, int ToSend, int Waiting, int Delivered, int Rejected, int NotDelivered, int Received);
/// <summary>The dashboard.</summary>
/// <param name="Rows">The e-invoices of the view.</param>
/// <param name="Pending">The documents to generate (view <see cref="EInvoiceView.ToDo"/> and the counters).</param>
/// <param name="Counters">The counters.</param>
public sealed record EInvoiceDashboard(IReadOnlyList<EInvoiceRow> Rows, IReadOnlyList<PendingEInvoice> Pending, EInvoiceCounters Counters);
/// <summary>The outcome of a generation: the file, or why not.</summary>
/// <param name="Invoice">The e-invoice written.</param>
/// <param name="Problems">Errors (nothing written) and warnings.</param>
public sealed record EInvoiceGeneration(EInvoice? Invoice, IReadOnlyList<EInvoiceProblem> Problems)
{
/// <summary>Whether the file was written.</summary>
public bool Success => Invoice is not null;
}
/// <summary>The outcome of sending one file.</summary>
/// <param name="EInvoiceId">The e-invoice.</param>
/// <param name="FileName">The file.</param>
/// <param name="DocumentNumber">The document.</param>
/// <param name="Sent">Whether a channel took it.</param>
/// <param name="ChannelCode">The channel that took it, or the last one tried.</param>
/// <param name="Error">Why not (a message of the channel, or an error code).</param>
public sealed record EInvoiceSendOutcome(long EInvoiceId, string FileName, string? DocumentNumber, bool Sent, string? ChannelCode, string? Error);
/// <summary>The outcome of a notification imported or received.</summary>
/// <param name="FileName">The notification.</param>
/// <param name="Code">Its code (RC, NS …).</param>
/// <param name="InvoiceFileName">The file it is about.</param>
/// <param name="EInvoiceId">The e-invoice updated.</param>
/// <param name="Status">The state it reached.</param>
/// <param name="Error">Why it was not applied (error code).</param>
public sealed record ReceiptOutcome(string FileName, string? Code, string? InvoiceFileName, long? EInvoiceId, EInvoiceStatus? Status, string? Error);
/// <summary>What the services of the electronic invoice share.</summary>
internal static class EInvoiceStore
{
/// <summary>The channel of what the user uploads or sends from the portal of the AdE.</summary>
public const string ManualChannel = "MANUAL";
/// <summary>The purpose of the protection of the secrets of the channels.</summary>
public const string SecretPurpose = "einvoice.channel";
/// <summary>The SHA-256 of a file in lower-case hexadecimal.</summary>
public static string Hash(byte[] content) => Convert.ToHexStringLower(SHA256.HashData(content));
/// <summary>A text cut to a length.</summary>
public static string? Trim(string? text, int length) =>
string.IsNullOrWhiteSpace(text) ? null : text.Trim().Length <= length ? text.Trim() : text.Trim()[..length];
/// <summary>The settings of a channel for its transport, secrets unprotected.</summary>
public static EInvoiceChannelSettings Settings(EInvoiceChannelSetting row, ISecretProtector secrets)
{
string? Open(string? value) => string.IsNullOrEmpty(value) ? null : secrets.Unprotect(value, SecretPurpose);
var certificate = Open(row.ProtectedCertificate);
return new EInvoiceChannelSettings
{
Code = row.Code,
Mailbox = row.Mailbox,
SmtpHost = row.SmtpHost,
SmtpPort = row.SmtpPort,
ImapHost = row.ImapHost,
ImapPort = row.ImapPort,
Tls = row.Tls,
User = row.UserName,
Password = Open(row.ProtectedPassword),
ExchangeAddress = row.ExchangeAddress,
ArchiveFolder = row.ArchiveFolder,
Endpoint = row.Endpoint,
Certificate = certificate is null ? null : Convert.FromBase64String(certificate),
CertificatePassword = Open(row.ProtectedCertificatePassword),
ApiKey = Open(row.ProtectedApiKey),
TestEnvironment = row.TestEnvironment,
};
}
/// <summary>The name of the invoice file a notification is about, from the name of the notification.</summary>
/// <param name="receiptFileName">The notification (<c>IT01234567890_00001_RC_001.xml</c>).</param>
/// <returns>The stem of the invoice file (<c>IT01234567890_00001</c>), or <see langword="null"/>.</returns>
public static string? InvoiceStem(string receiptFileName)
{
var name = Path.GetFileName(receiptFileName);
var parts = name.Split('_');
return parts.Length >= 4 ? string.Join('_', parts[..^2]) : null;
}
/// <summary>The stem of a file name: without <c>.xml</c> and <c>.p7m</c>.</summary>
public static string Stem(string fileName)
{
var name = Path.GetFileName(fileName);
foreach (var extension in new[] { ".p7m", ".xml" })
{
if (name.EndsWith(extension, StringComparison.OrdinalIgnoreCase))
{
name = name[..^extension.Length];
}
}
return name;
}
/// <summary>A shallow copy of a row (public properties that can be written), for the history of a change.</summary>
public static T Clone<T>(T row)
where T : class, new()
{
var copy = new T();
foreach (var property in typeof(T).GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance))
{
if (property is { CanRead: true, CanWrite: true } && property.GetIndexParameters().Length == 0)
{
property.SetValue(copy, property.GetValue(row));
}
}
return copy;
}
/// <summary>A copy without the file, for lists and history.</summary>
public static EInvoice Light(EInvoice e) => new()
{
Id = e.Id,
Family = e.Family,
DocumentId = e.DocumentId,
Kind = e.Kind,
DocumentNumber = e.DocumentNumber,
DocumentDate = e.DocumentDate,
PartyId = e.PartyId,
DocumentType = e.DocumentType,
FileName = e.FileName,
Progressive = e.Progressive,
Format = e.Format,
RecipientCode = e.RecipientCode,
RecipientPec = e.RecipientPec,
TotalAmount = e.TotalAmount,
Status = e.Status,
ChannelCode = e.ChannelCode,
ExchangeId = e.ExchangeId,
MessageId = e.MessageId,
GeneratedAt = e.GeneratedAt,
SentAt = e.SentAt,
LastNotificationAt = e.LastNotificationAt,
LastMessage = e.LastMessage,
SendAttempts = e.SendAttempts,
Superseded = e.Superseded,
IsDemo = e.IsDemo,
CreatedAt = e.CreatedAt,
CreatedBy = e.CreatedBy,
UpdatedAt = e.UpdatedAt,
UpdatedBy = e.UpdatedBy,
RowVersion = e.RowVersion,
};
}
@@ -0,0 +1,351 @@
using Khaemhat.Application.Purchases;
using Khaemhat.Application.Security;
using Khaemhat.Application.Tables;
using Khaemhat.Core.EInvoicing;
using Khaemhat.Data;
using Khaemhat.Data.Querying;
using Khaemhat.Fiscal.Abstractions;
namespace Khaemhat.Application.EInvoicing;
/// <summary>The filter of the invoices received.</summary>
/// <param name="Status">Only this state.</param>
/// <param name="Search">Supplier, VAT number, number or file name.</param>
public sealed record InboxFilter(InboxFileStatus? Status = null, string? Search = null);
/// <summary>A received file stored, or why not.</summary>
/// <param name="FileName">The file.</param>
/// <param name="Id">The row of the inbox.</param>
/// <param name="Status">Its state.</param>
/// <param name="Error">Why it was not stored (error code).</param>
public sealed record InboxStored(string FileName, long? Id, InboxFileStatus? Status, string? Error);
/// <summary>A received invoice registered as a supplier document, or why not.</summary>
/// <param name="Id">The row of the inbox.</param>
/// <param name="FileName">The file.</param>
/// <param name="PurchaseDocumentId">The draft supplier document.</param>
/// <param name="Error">Why it was not registered (error code).</param>
/// <param name="Warnings">What to check on the draft (codes).</param>
public sealed record InboxRegistered(long Id, string FileName, long? PurchaseDocumentId, string? Error, IReadOnlyList<string> Warnings);
/// <summary>
/// The invoices received from the SDI (SPEC §11.9, issue #79): every file that arrives through a channel, or that the
/// user uploads, is kept as it was received with its metadata file (MT); the user registers it as a draft supplier
/// invoice (with the import of mockup 034), or discards it. A file is kept once, by its hash.
/// </summary>
/// <remarks>Permissions: <c>einvoice.inbox.read</c> to see, <c>einvoice.inbox.import</c> to upload, register and discard
/// (registering also needs <c>purchases.invoice.write</c>).</remarks>
public sealed class SdiInboxService
{
private readonly IUnitOfWorkFactory _factory;
private readonly PermissionService _permissions;
private readonly CompanyFiscalContext _packs;
private readonly PurchaseInvoiceImportService _import;
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="import">The import of supplier invoices.</param>
/// <param name="clock">The clock.</param>
public SdiInboxService(IUnitOfWorkFactory factory, PermissionService permissions, CompanyFiscalContext packs, PurchaseInvoiceImportService import, TimeProvider clock)
{
ArgumentNullException.ThrowIfNull(factory);
ArgumentNullException.ThrowIfNull(permissions);
ArgumentNullException.ThrowIfNull(packs);
ArgumentNullException.ThrowIfNull(import);
ArgumentNullException.ThrowIfNull(clock);
_factory = factory;
_permissions = permissions;
_packs = packs;
_import = import;
_clock = clock;
}
/// <summary>The invoices received, newest first (files not loaded).</summary>
/// <param name="actor">Who looks: needs <c>einvoice.inbox.read</c>.</param>
/// <param name="companyCode">The company.</param>
/// <param name="filter">The filter.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The rows.</returns>
public async Task<IReadOnlyList<EInvoiceInboxFile>> ListAsync(Actor actor, string companyCode, InboxFilter filter, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(filter);
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, EInvoicePermissions.InboxRead, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
var query = Query.For<EInvoiceInboxFile>();
if (filter.Status is { } status)
{
query = query.Where(f => f.Status == status);
}
var rows = (await uow.Repository<EInvoiceInboxFile, long>().ListAsync(query.OrderByDescending(f => f.ReceivedAt), cancellationToken).ConfigureAwait(false)).Items
.Select(Light);
if (!string.IsNullOrWhiteSpace(filter.Search))
{
var text = filter.Search.Trim();
rows = rows.Where(f => Has(f.SupplierName, text) || Has(f.SupplierVat, text) || Has(f.Number, text) || Has(f.FileName, text) || Has(f.ExchangeId, text));
}
return [.. rows];
}
/// <summary>The received file, as it arrived.</summary>
/// <param name="actor">Who downloads: needs <c>einvoice.inbox.read</c>.</param>
/// <param name="companyCode">The company.</param>
/// <param name="id">The row.</param>
/// <param name="metadata">The metadata file (MT) instead of the invoice.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>Name and content.</returns>
public async Task<(string FileName, byte[] Content)> FileAsync(Actor actor, string companyCode, long id, bool metadata = false, CancellationToken cancellationToken = default)
{
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, EInvoicePermissions.InboxRead, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
var row = await uow.Repository<EInvoiceInboxFile, long>().GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(EInvoiceErrors.NotFound);
return metadata
? (row.MetadataFileName ?? throw new KeyNotFoundException(EInvoiceErrors.NotFound), row.Metadata ?? [])
: (row.FileName, row.Content);
}
/// <summary>Stores files the user uploads (downloaded from the portal of the AdE or received elsewhere).</summary>
/// <param name="actor">Who uploads: needs <c>einvoice.inbox.import</c>.</param>
/// <param name="companyCode">The company.</param>
/// <param name="files">The files.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>What happened to each.</returns>
public async Task<IReadOnlyList<InboxStored>> UploadAsync(
Actor actor, string companyCode, IReadOnlyList<(string FileName, byte[] Content)> files, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(files);
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, EInvoicePermissions.InboxImport, cancellationToken).ConfigureAwait(false);
var pack = await _packs.PackOfAsync(company, cancellationToken).ConfigureAwait(false);
var reader = pack.GetFeature<IIncomingInvoiceReader>();
var receipts = pack.GetFeature<IEInvoiceReceiptReader>();
var result = new List<InboxStored>();
foreach (var (name, content) in files)
{
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
InboxStored stored;
if (receipts is not null && receipts.IsReceipt(name, content) && TryRead(receipts, name, content) is { Kind: EInvoiceReceiptKind.Metadata } meta)
{
var row = await AttachMetadataCoreAsync(uow, meta, cancellationToken).ConfigureAwait(false);
stored = new InboxStored(name, row?.Id, row?.Status, row is null ? EInvoiceErrors.ReceiptUnmatched : null);
}
else
{
stored = await StoreCoreAsync(uow, reader, name, content, _clock.GetUtcNow().UtcDateTime, EInvoiceStore.ManualChannel, null, false, cancellationToken)
.ConfigureAwait(false);
}
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
result.Add(stored);
}
return result;
}
/// <summary>
/// Registers received invoices as draft supplier documents, through the import of supplier invoices: the supplier is
/// found or added, the lines take their items and tax codes, the file is attached.
/// </summary>
/// <param name="actor">Who registers: needs <c>einvoice.inbox.import</c> and <c>purchases.invoice.write</c>.</param>
/// <param name="companyCode">The company.</param>
/// <param name="ids">The rows.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>What happened to each.</returns>
public async Task<IReadOnlyList<InboxRegistered>> RegisterAsync(Actor actor, string companyCode, IReadOnlyList<long> ids, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(actor);
ArgumentNullException.ThrowIfNull(ids);
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, EInvoicePermissions.InboxImport, cancellationToken).ConfigureAwait(false);
var result = new List<InboxRegistered>();
foreach (var id in ids.Distinct())
{
EInvoiceInboxFile row;
await using (var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false))
{
row = await uow.Repository<EInvoiceInboxFile, long>().GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(EInvoiceErrors.NotFound);
}
if (row.Status != InboxFileStatus.New)
{
result.Add(new InboxRegistered(id, row.FileName, row.PurchaseDocumentId, EInvoiceErrors.InboxState, []));
continue;
}
var reading = await _import.ReadAsync(actor, company, [(row.FileName, row.Content)], cancellationToken).ConfigureAwait(false);
if (reading.Rejected.Count > 0 || reading.Invoices.Count == 0)
{
result.Add(new InboxRegistered(id, row.FileName, null, (reading.Rejected.Count > 0 ? reading.Rejected[0].Error : PurchaseInvoiceImportService.EmptyArchive), []));
continue;
}
var blocked = reading.Invoices.FirstOrDefault(c => !c.CanImport);
if (blocked is not null)
{
result.Add(new InboxRegistered(id, row.FileName, null, (blocked.Problems.Count > 0 ? blocked.Problems[0] : PurchaseInvoiceImportService.UnsupportedType), blocked.Problems));
continue;
}
var imported = await _import.ImportAsync(actor, company, reading.Invoices, cancellationToken).ConfigureAwait(false);
var failed = imported.FirstOrDefault(i => i.Error is not null);
var first = imported.FirstOrDefault(i => i.Record is not null);
var documentId = first?.Record?.Header.Id;
await using (var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false))
{
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
var current = await uow.Repository<EInvoiceInboxFile, long>().GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(EInvoiceErrors.NotFound);
if (documentId is not null)
{
current.Status = InboxFileStatus.Registered;
current.PurchaseDocumentId = documentId;
current.PartyId = first!.Record!.Header.PartyId ?? current.PartyId;
}
current.Error = failed?.Error;
await uow.Repository<EInvoiceInboxFile, long>().UpdateAsync(current, cancellationToken).ConfigureAwait(false);
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
}
result.Add(new InboxRegistered(id, row.FileName, documentId, failed?.Error, [.. imported.SelectMany(i => i.Warnings).Distinct(StringComparer.Ordinal)]));
}
return result;
}
/// <summary>Discards a received invoice (a copy, a file not for the company), or takes it back.</summary>
/// <param name="actor">Who does it: needs <c>einvoice.inbox.import</c>.</param>
/// <param name="companyCode">The company.</param>
/// <param name="id">The row.</param>
/// <param name="discard">Discard, or take back.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
public async Task DiscardAsync(Actor actor, string companyCode, long id, bool discard, CancellationToken cancellationToken = default)
{
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, EInvoicePermissions.InboxImport, 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<EInvoiceInboxFile, long>();
var row = await repository.GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(EInvoiceErrors.NotFound);
var allowed = discard ? row.Status is InboxFileStatus.New or InboxFileStatus.Unreadable : row.Status == InboxFileStatus.Discarded;
if (!allowed)
{
throw new ValidationFailedException([":" + EInvoiceErrors.InboxState]);
}
row.Status = discard ? InboxFileStatus.Discarded : row.SupplierVat is null && row.Number is null ? InboxFileStatus.Unreadable : InboxFileStatus.New;
await repository.UpdateAsync(row, cancellationToken).ConfigureAwait(false);
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Stores a received file in the transaction of the caller: read by the pack for the list (supplier, number, date,
/// total); a file the pack cannot read is kept as unreadable, a file already kept is not stored again.
/// </summary>
internal static async Task<InboxStored> StoreCoreAsync(
IUnitOfWork uow, IIncomingInvoiceReader? reader, string fileName, byte[] content, DateTime receivedAt, string? channel, string? exchangeId, bool demo,
CancellationToken cancellationToken)
{
var repository = uow.Repository<EInvoiceInboxFile, long>();
var hash = EInvoiceStore.Hash(content);
if (await repository.FindAsync(Query.For<EInvoiceInboxFile>().Where(f => f.Hash == hash), cancellationToken).ConfigureAwait(false) is { } known)
{
return new InboxStored(fileName, known.Id, known.Status, EInvoiceErrors.InboxDuplicate);
}
var row = new EInvoiceInboxFile
{
FileName = EInvoiceStore.Trim(Path.GetFileName(fileName), 200) ?? "fattura.xml",
Hash = hash,
Content = content,
ReceivedAt = receivedAt,
ChannelCode = channel,
ExchangeId = EInvoiceStore.Trim(exchangeId, 40),
Status = InboxFileStatus.Unreadable,
IsDemo = demo,
};
try
{
if (reader is not null && reader.CanRead(fileName, content))
{
var file = reader.Read(fileName, content);
var invoice = file.Invoices[0];
row.SupplierVat = EInvoiceStore.Trim((file.Supplier.CountryCode ?? string.Empty) + (file.Supplier.VatNumber ?? file.Supplier.TaxCode), 30);
row.SupplierName = EInvoiceStore.Trim(file.Supplier.DisplayName, 200);
row.DocumentType = invoice.DocumentType;
row.Number = EInvoiceStore.Trim(invoice.Number, 40);
row.DocumentDate = invoice.Date;
row.TotalAmount = file.Invoices.Count == 1 ? invoice.Total ?? invoice.TaxSummary.Sum(t => t.Taxable + t.Tax) : null;
row.PartyId = await PurchaseInvoiceImportService.FindSupplierAsync(uow, file.Supplier, cancellationToken).ConfigureAwait(false);
row.Status = InboxFileStatus.New;
}
else
{
row.Error = IncomingInvoiceErrors.NotReadable;
}
}
catch (IncomingInvoiceException ex)
{
row.Error = ex.Code;
}
row.Id = await repository.InsertAsync(row, cancellationToken).ConfigureAwait(false);
return new InboxStored(fileName, row.Id, row.Status, null);
}
/// <summary>Keeps the metadata file (MT) with the invoice it describes, by the name of the invoice file.</summary>
internal static async Task<EInvoiceInboxFile?> AttachMetadataCoreAsync(IUnitOfWork uow, EInvoiceReceipt metadata, CancellationToken cancellationToken)
{
var repository = uow.Repository<EInvoiceInboxFile, long>();
var stem = metadata.InvoiceFileName is { } name ? EInvoiceStore.Stem(name) : EInvoiceStore.InvoiceStem(metadata.FileName);
if (stem is null)
{
return null;
}
EInvoiceInboxFile? row = null;
foreach (var candidate in new[] { stem + ".xml", stem + ".xml.p7m" })
{
row = await repository.FindAsync(Query.For<EInvoiceInboxFile>().Where(f => f.FileName == candidate).OrderByDescending(f => f.Id), cancellationToken).ConfigureAwait(false);
if (row is not null)
{
break;
}
}
if (row is null)
{
return null;
}
row.MetadataFileName = EInvoiceStore.Trim(metadata.FileName, 200);
row.Metadata = metadata.Content;
row.ExchangeId ??= EInvoiceStore.Trim(metadata.ExchangeId, 40);
await repository.UpdateAsync(row, cancellationToken).ConfigureAwait(false);
return row;
}
private static EInvoiceReceipt? TryRead(IEInvoiceReceiptReader reader, string name, byte[] content)
{
try
{
return reader.Read(name, content);
}
catch (IncomingInvoiceException)
{
return null;
}
}
private static EInvoiceInboxFile Light(EInvoiceInboxFile row)
{
var copy = EInvoiceStore.Clone(row);
copy.Content = [];
copy.Metadata = null;
return copy;
}
private static bool Has(string? value, string text) => value?.Contains(text, StringComparison.CurrentCultureIgnoreCase) == true;
}
@@ -0,0 +1,138 @@
using System.Security.Cryptography;
using System.Text;
using Khaemhat.Application.Licensing;
using Khaemhat.Application.Modules;
using Khaemhat.Application.Tables;
using Khaemhat.Core.EInvoicing;
using Khaemhat.Core.Instance;
using Khaemhat.Core.Logging;
using Khaemhat.Core.Security;
using Khaemhat.Data;
using Khaemhat.Data.Companies;
using Khaemhat.Data.Querying;
using Khaemhat.Fiscal.Abstractions;
using Microsoft.Extensions.Logging;
namespace Khaemhat.Application.EInvoicing;
/// <summary>The answer to a push of the exchange system.</summary>
/// <param name="StatusCode">The HTTP status.</param>
/// <param name="ContentType">The content type.</param>
/// <param name="Body">The body.</param>
public sealed record SdiPushAnswer(int StatusCode, string ContentType, string Body);
/// <summary>
/// Takes what the SDI pushes to the web service of a company (SdICoop, issue #76): invoices of suppliers and
/// notifications. The request carries the key stored in the channel (header <c>X-Khaemhat-SdiCoop-Key</c>); the mutual
/// TLS with the SDI is the job of the reverse proxy in front of Khaemhat. A disabled company, a channel that is not
/// enabled or a wrong key get nothing.
/// </summary>
public sealed partial class SdiPushService
{
/// <summary>The header with the key of the channel.</summary>
public const string KeyHeader = "X-Khaemhat-SdiCoop-Key";
private readonly ICompanyRegistry _companies;
private readonly ILicenseGate _license;
private readonly IUnitOfWorkFactory _factory;
private readonly CompanyFiscalContext _packs;
private readonly ISecretProtector _secrets;
private readonly EInvoicePollingService _polling;
private readonly TimeProvider _clock;
private readonly ILogger<SdiPushService> _logger;
/// <summary>Creates the service.</summary>
/// <param name="companies">The companies.</param>
/// <param name="license">The licence.</param>
/// <param name="factory">The units of work.</param>
/// <param name="packs">The fiscal pack of each company.</param>
/// <param name="secrets">Opens the key of the channel.</param>
/// <param name="polling">Sorts the files received.</param>
/// <param name="clock">The clock.</param>
/// <param name="logger">The log (section SDI).</param>
public SdiPushService(
ICompanyRegistry companies, ILicenseGate license, IUnitOfWorkFactory factory, CompanyFiscalContext packs, ISecretProtector secrets,
EInvoicePollingService polling, TimeProvider clock, ILogger<SdiPushService> logger)
{
ArgumentNullException.ThrowIfNull(companies);
ArgumentNullException.ThrowIfNull(license);
ArgumentNullException.ThrowIfNull(factory);
ArgumentNullException.ThrowIfNull(packs);
ArgumentNullException.ThrowIfNull(secrets);
ArgumentNullException.ThrowIfNull(polling);
ArgumentNullException.ThrowIfNull(clock);
ArgumentNullException.ThrowIfNull(logger);
_companies = companies;
_license = license;
_factory = factory;
_packs = packs;
_secrets = secrets;
_polling = polling;
_clock = clock;
_logger = logger;
}
/// <summary>Takes a push.</summary>
/// <param name="companyCode">The company in the address.</param>
/// <param name="key">The key in the header.</param>
/// <param name="contentType">The content type.</param>
/// <param name="body">The body.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The answer.</returns>
public async Task<SdiPushAnswer> ReceiveAsync(string companyCode, string? key, string? contentType, byte[] body, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(body);
using var scope = _logger.BeginScope(LogSections.Scope(LogSection.EInvoicing));
var notFound = new SdiPushAnswer(404, "text/plain", "Not found.");
if (!_license.IsModuleActive(ModuleCodes.EInvoicing)
|| await _companies.FindAsync(companyCode, cancellationToken).ConfigureAwait(false) is not { } company
|| company.Status is CompanyStatus.Disabled)
{
return notFound;
}
var pack = await _packs.PackOfAsync(company.Code, cancellationToken).ConfigureAwait(false);
if (pack.GetFeature<IEInvoicePushReader>() is not { } reader)
{
return notFound;
}
var channel = reader.Channel;
EInvoiceChannelSetting? row;
await using (var uow = await _factory.CreateAsync(DatabaseScope.Company(company.Code), cancellationToken).ConfigureAwait(false))
{
var rows = (await uow.Repository<EInvoiceChannelSetting, long>().ListAsync(Query.For<EInvoiceChannelSetting>().Where(c => c.Code == channel).Take(1), cancellationToken)
.ConfigureAwait(false)).Items;
row = rows.Count > 0 ? rows[0] : null;
}
var expected = row is { Enabled: true, ProtectedApiKey: { Length: > 0 } stored } ? _secrets.Unprotect(stored, EInvoiceStore.SecretPurpose) : null;
if (expected is null || key is null || !SameKey(expected, key))
{
LogRefused(_logger, company.Code, channel);
return new SdiPushAnswer(401, "text/plain", "Unauthorized.");
}
if (reader.Read(contentType, body) is not { } push)
{
var (type, refusal) = reader.Refusal();
return new SdiPushAnswer(400, type, refusal);
}
var now = _clock.GetUtcNow();
var messageKey = push.ExchangeId ?? EInvoiceStore.Hash(body);
var files = push.Files.Select(f => new EInvoiceIncoming(f.FileName, f.Content, now, messageKey, null)).ToList();
var outcome = await _polling.ReceivePushedAsync(company.Code, channel, files, cancellationToken).ConfigureAwait(false);
LogReceived(_logger, company.Code, channel, outcome.Invoices, outcome.Receipts);
return new SdiPushAnswer(200, push.AnswerContentType, push.Answer);
}
private static bool SameKey(string expected, string given) =>
CryptographicOperations.FixedTimeEquals(SHA256.HashData(Encoding.UTF8.GetBytes(expected)), SHA256.HashData(Encoding.UTF8.GetBytes(given)));
[LoggerMessage(Level = LogLevel.Warning, Message = "Push of channel {Channel} for company {Company} refused: wrong key or channel not enabled.")]
private static partial void LogRefused(ILogger logger, string company, string channel);
[LoggerMessage(Level = LogLevel.Information, Message = "Push of channel {Channel} for company {Company}: {Invoices} invoices, {Receipts} notifications.")]
private static partial void LogReceived(ILogger logger, string company, string channel, int invoices, int receipts);
}
@@ -268,6 +268,13 @@ public sealed class InventoryService
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);
return await ValuationAsync(uow, date, warehouseId, method, cancellationToken).ConfigureAwait(false);
}
/// <summary>The value of the stock at a date inside a unit of work (the closing values the inventory with it).</summary>
internal static async Task<IReadOnlyList<ValuationRow>> ValuationAsync(
IUnitOfWork uow, DateOnly date, long? warehouseId, StockValuationMethod method, CancellationToken cancellationToken)
{
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;
@@ -60,6 +60,8 @@ public sealed class JobScheduler
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),
new("finance.dunning", "Solleciti automatici", Treasury.DunningJob.JobType, "0 7 * * 1-5", 1800, UsesNetwork: true),
new("einvoice.poll", "Lettura dei canali SDI", EInvoicing.EInvoicePollingJob.JobType, "*/15 * * * *", 900, UsesNetwork: true),
];
private readonly IUnitOfWorkFactory _factory;
@@ -502,7 +502,10 @@ public sealed class JournalEntryService
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);
// Items the treasury touched stay: a new posting of the document takes them over (ADR 0038).
await uow.ExecuteAsync(
SqlFragment.Of($"DELETE FROM gl_open_items WHERE entry_id = {entry.Id} AND paid_amount = 0 AND remittance_id IS NULL AND unpaid_count = 0 AND NOT EXISTS (SELECT 1 FROM remittance_lines r WHERE r.open_item_id = gl_open_items.id) AND NOT EXISTS (SELECT 1 FROM payment_lines p WHERE p.open_item_id = gl_open_items.id)"),
cancellationToken).ConfigureAwait(false);
return reversal;
}
+62 -17
View File
@@ -108,7 +108,6 @@ public sealed class LedgerPoster
{
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))
@@ -150,6 +149,7 @@ public sealed class LedgerPoster
return;
}
await LedgerStore.EnsureUnpaidAsync(uow, existing.Id, cancellationToken).ConfigureAwait(false);
if (existing.Status == GlEntryStatus.Final)
{
await JournalEntryService.ReverseAsync(uow, existing, existing.EntryDate, null, cancellationToken).ConfigureAwait(false);
@@ -385,25 +385,70 @@ public sealed class LedgerPoster
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)];
// The items keep their identity by installment (ADR 0038): collections, payments and remittances point at them,
// so a new posting of the document changes them in place and never takes away what was already collected.
var repository = uow.Repository<OpenItem, long>();
foreach (var (number, due, amount, method) in rows)
var current = (await repository.ListAsync(
Query.For<OpenItem>().Where(o => o.SourceFamily == family && o.SourceDocumentId == header.Id), cancellationToken).ConfigureAwait(false)).Items
.Where(o => o.ParentId is null).ToList();
var direction = posting.Kind == PostingKind.Sale ? OpenItemDirection.Receivable : OpenItemDirection.Payable;
foreach (var (number, due, value, method) in rows)
{
await repository.InsertAsync(new OpenItem
var amount = sign * value;
var item = current.FirstOrDefault(o => o.Installment == number);
if (item is null)
{
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);
await repository.InsertAsync(new OpenItem
{
Direction = direction,
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 = amount,
PaymentMethodId = method,
IsDemo = header.IsDemo,
}, cancellationToken).ConfigureAwait(false);
continue;
}
current.Remove(item);
if (item.PaidAmount != 0m && (Math.Sign(amount) != Math.Sign(item.PaidAmount) || Math.Abs(amount) < Math.Abs(item.PaidAmount)))
{
throw new ValidationFailedException(["Amount:" + LedgerErrors.OpenItemPaid]);
}
item.Direction = direction;
item.PartyId = partyId;
item.AccountId = accountId;
item.EntryId = entry.Id;
item.DocumentNumber = entry.DocumentNumber;
item.DocumentDate = entry.DocumentDate ?? header.DocumentDate;
item.Amount = amount;
if (item.RemittanceId is null)
{
item.DueDate = due;
item.PaymentMethodId = method;
}
item.Status = Core.Treasury.OpenItemStates.Of(item);
item.Closed = item.Status == Core.Treasury.OpenItemStatus.Closed;
await repository.UpdateAsync(item, cancellationToken).ConfigureAwait(false);
}
foreach (var left in current)
{
if (left.PaidAmount != 0m || left.RemittanceId is not null || left.UnpaidCount > 0)
{
throw new ValidationFailedException(["Installments:" + LedgerErrors.OpenItemPaid]);
}
await repository.DeleteAsync(left.Id, cancellationToken).ConfigureAwait(false);
}
}
@@ -115,12 +115,25 @@ internal static class LedgerStore
/// <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 EnsureUnpaidAsync(uow, entryId, cancellationToken).ConfigureAwait(false);
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>Refuses when an open item of the entry was collected, paid or put in a remittance (ADR 0038).</summary>
public static async Task EnsureUnpaidAsync(IUnitOfWork uow, long entryId, CancellationToken cancellationToken)
{
var touched = await uow.QuerySingleAsync<long?>(
SqlFragment.Of($"SELECT COUNT(*) FROM gl_open_items o WHERE o.entry_id = {entryId} AND (o.paid_amount <> 0 OR o.remittance_id IS NOT NULL OR o.unpaid_count > 0 OR EXISTS (SELECT 1 FROM payment_lines p WHERE p.open_item_id = o.id) OR EXISTS (SELECT 1 FROM remittance_lines r WHERE r.open_item_id = o.id))"),
cancellationToken).ConfigureAwait(false) ?? 0L;
if (touched > 0)
{
throw new Security.ValidationFailedException(["Status:" + LedgerErrors.OpenItemPaid]);
}
}
/// <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)
+86 -70
View File
@@ -425,47 +425,7 @@ public sealed class TaxService
}
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 ApplyInvoicePaidAsync(uow, withholding, paidOn, settlementRules, withholdingRules, cancellationToken).ConfigureAwait(false);
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);
@@ -491,35 +451,7 @@ public sealed class TaxService
}
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 UndoInvoicePaidAsync(uow, withholding, Today(), actor.UserName, cancellationToken).ConfigureAwait(false);
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);
@@ -751,6 +683,90 @@ public sealed class TaxService
// 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.
/// <summary>Takes back the payment of the invoice of a withholding: its F24 share and its entry. The caller writes the withholding.</summary>
internal static async Task UndoInvoicePaidAsync(IUnitOfWork uow, Withholding withholding, DateOnly date, string? userName, CancellationToken cancellationToken)
{
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, date, 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;
}
/// <summary>
/// Makes a withholding due because its invoice was paid: the entry of the withholding and the F24 line of the month
/// (used also by the payments of the schedule, ADR 0038). The caller writes the withholding and the history.
/// </summary>
internal static async Task ApplyInvoicePaidAsync(
IUnitOfWork uow, Withholding withholding, DateOnly paidOn, IVatSettlementRules settlementRules, IWithholdingRules? withholdingRules, CancellationToken cancellationToken)
{
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;
}
}
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)
@@ -33,6 +33,8 @@ public static class BuiltInModules
("sales.invoice.delete", "Eliminare fatture in bozza"),
("sales.invoice.print", "Stampare fatture di vendita"),
("sales.invoice.export", "Esportare fatture di vendita"),
("sales.intent.read", "Vedere le dichiarazioni d'intento"),
("sales.intent.write", "Registrare le dichiarazioni d'intento"),
("purchases.order.read", "Vedere ordini fornitore"),
("purchases.order.write", "Creare e modificare ordini fornitore"),
("purchases.invoice.read", "Vedere fatture di acquisto"),
@@ -70,7 +72,8 @@ public static class BuiltInModules
("einvoice.document.read", "Vedere i documenti elettronici"),
("einvoice.document.send", "Inviare documenti allo SDI"),
("einvoice.inbox.read", "Vedere le fatture ricevute"),
("einvoice.inbox.import", "Importare le fatture ricevute")),
("einvoice.inbox.import", "Importare le fatture ricevute"),
("einvoice.channel.manage", "Configurare i canali verso lo SDI")),
Module(ModuleCodes.Intrastat, "Intrastat",
("intrastat.list.read", "Vedere gli elenchi Intrastat"),
("intrastat.list.write", "Compilare gli elenchi Intrastat"),
@@ -134,7 +137,7 @@ public static class PredefinedRoles
[
new(Administration, "Amministrazione", "Tutte le funzioni dell'azienda, compresi utenti e impostazioni.", ["*"]),
new("ACCOUNTING", "Contabilità", "Contabilità, IVA, cespiti, tesoreria, fatturazione elettronica e Intrastat.",
["ledger.*", "vat.*", "assets.*", "finance.*", "einvoice.*", "intrastat.*", "parties.party.read", "sales.invoice.read",
["ledger.*", "vat.*", "assets.*", "finance.*", "einvoice.*", "intrastat.*", "parties.party.read", "sales.invoice.read", "sales.intent.*",
"purchases.invoice.*", "reports.report.read", "attachments.read", "attachments.write"]),
new("SALES", "Vendite", "Preventivi, ordini, DDT e fatture di vendita; anagrafiche clienti.",
["sales.*", "parties.*", "items.item.read", "inventory.stock.read", "crm.lead.read", "crm.opportunity.read",
@@ -26,7 +26,7 @@ namespace Khaemhat.Application.Purchases;
/// <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,
string FileName, EInvoiceFile File, EInvoiceBody Invoice, string? DocumentTypeCode, long? SupplierId, bool Duplicate, decimal ComputedTotal,
IReadOnlyList<string> Problems)
{
/// <summary>Whether it can be registered.</summary>
@@ -141,7 +141,7 @@ public sealed class PurchaseInvoiceImportService
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 found = new List<(string Name, EInvoiceFile File)>();
var rejected = new List<IncomingRejected>();
foreach (var (name, content) in Expand(files, rejected))
{
@@ -330,16 +330,16 @@ public sealed class PurchaseInvoiceImportService
return result;
}
private static string KeyOf(IncomingParty party) =>
private static string KeyOf(EInvoiceParty 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) =>
private static string? VatOf(EInvoiceParty 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)
internal static async Task<long?> FindSupplierAsync(IUnitOfWork uow, EInvoiceParty party, CancellationToken cancellationToken)
{
var parties = uow.Repository<Party, long>();
if (VatOf(party) is { } vat)
@@ -365,7 +365,7 @@ public sealed class PurchaseInvoiceImportService
.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)
private static async Task<bool> IsDuplicateAsync(IUnitOfWork uow, long supplierId, EInvoiceBody invoice, CancellationToken cancellationToken)
{
var number = invoice.Number.Trim();
var from = new DateOnly(invoice.Date.Year, 1, 1);
@@ -377,7 +377,7 @@ public sealed class PurchaseInvoiceImportService
cancellationToken).ConfigureAwait(false) > 0;
}
private async Task<long> CreateSupplierAsync(Actor actor, string company, IncomingParty party, CancellationToken cancellationToken)
private async Task<long> CreateSupplierAsync(Actor actor, string company, EInvoiceParty party, CancellationToken cancellationToken)
{
var record = await _parties.NewAsync(actor, company, PartyKind.Supplier, cancellationToken).ConfigureAwait(false);
var p = record.Party;
@@ -493,7 +493,7 @@ public sealed class PurchaseInvoiceImportService
return (saved, warnings);
}
private static long? ItemOf(IncomingLine line, Dictionary<string, long> bySupplierCode, Dictionary<string, long> byBarcode, Dictionary<string, Item> byCode)
private static long? ItemOf(EInvoiceLine line, Dictionary<string, long> bySupplierCode, Dictionary<string, long> byBarcode, Dictionary<string, Item> byCode)
{
foreach (var code in line.Codes.Select(c => c.Value.Trim()))
{
@@ -0,0 +1,181 @@
using Khaemhat.Data;
using Khaemhat.Data.Migrations;
using Khaemhat.Data.Schema;
namespace Khaemhat.Application.Seeding;
/// <summary>What the removal of the demo data did.</summary>
/// <param name="Removed">Rows removed, by table.</param>
/// <param name="Blockers">Tables whose own rows (not demo) still refer to demo rows: nothing was removed.</param>
public sealed record DemoRemoval(IReadOnlyDictionary<string, int> Removed, IReadOnlyList<string> Blockers)
{
/// <summary>Whether the demo data were removed.</summary>
public bool Done => Blockers.Count == 0;
/// <summary>All the rows removed.</summary>
public int Total => Removed.Values.Sum();
}
/// <summary>
/// Removes the demo data of a company, and only them (SPEC §14, issue #80): the rows marked <c>is_demo</c> and the rows
/// of the tables without the mark that belong to them through a foreign key (the lines of a demo document, the balances
/// of a demo item). The tables and their keys come from the migrations, so a new module is covered without changes.
/// When a row the user entered refers to a demo row (an invoice to a demo customer) nothing is removed and the tables
/// are reported: the user decides what to do. Everything happens in one transaction.
/// </summary>
/// <param name="factory">The units of work.</param>
public sealed class DemoDataRemover(IUnitOfWorkFactory factory)
{
private const string DemoColumn = "is_demo";
/// <summary>Removes the demo data of a company.</summary>
/// <param name="companyCode">The company.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>What was removed, or what stopped it.</returns>
public async Task<DemoRemoval> RemoveAsync(string companyCode, CancellationToken cancellationToken = default)
{
var model = MigrationCatalog.ForCompany().BuildModel();
var tables = model.Tables.ToDictionary(t => t.Name, StringComparer.Ordinal);
var doomed = new Dictionary<string, SqlFragment?>(StringComparer.Ordinal);
foreach (var table in tables.Values)
{
Predicate(table, tables, doomed, []);
}
await using var uow = await factory.CreateAsync(DatabaseScope.Company(companyCode), cancellationToken).ConfigureAwait(false);
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
// Rows of the user that point to demo rows through a key that does not follow them.
var blockers = new List<string>();
foreach (var table in tables.Values.Where(t => t.Column(DemoColumn) is not null))
{
foreach (var key in table.ForeignKeys.Where(k => k.OnDelete != ReferentialAction.SetNull && k.ReferencedTable != table.Name && k.Columns.Count == 1))
{
if (doomed.GetValueOrDefault(key.ReferencedTable) is not { } parent)
{
continue;
}
var count = await uow.QuerySingleAsync<long>(
SqlFragment.Literal("SELECT COUNT(*) FROM ") + SqlFragment.Identifier(table.Name) + SqlFragment.Literal(" WHERE ")
+ SqlFragment.Identifier(DemoColumn) + SqlFragment.Literal(" = ") + SqlFragment.Parameter(false) + SqlFragment.Literal(" AND ")
+ SqlFragment.Identifier(key.Columns[0]) + SqlFragment.Literal(" IN (SELECT ") + SqlFragment.Identifier(key.ReferencedColumns[0]) + SqlFragment.Literal(" FROM ") + SqlFragment.Identifier(key.ReferencedTable)
+ SqlFragment.Literal(" WHERE ") + parent + SqlFragment.Literal(")"),
cancellationToken).ConfigureAwait(false);
if (count > 0 && !blockers.Contains(table.Name))
{
blockers.Add(table.Name);
}
}
}
if (blockers.Count > 0)
{
await uow.RollbackAsync(cancellationToken).ConfigureAwait(false);
return new DemoRemoval(new Dictionary<string, int>(), blockers);
}
var removed = new Dictionary<string, int>(StringComparer.Ordinal);
foreach (var table in DeleteOrder(tables.Values.Where(t => doomed.GetValueOrDefault(t.Name) is not null).ToList()))
{
var where = doomed[table.Name]!;
// A key to the same table (an item and its parent) is cleared first, so the rows can go in one statement.
foreach (var key in table.ForeignKeys.Where(k => k.ReferencedTable == table.Name && k.Columns.Count == 1))
{
if (table.Column(key.Columns[0]) is { IsNullable: true })
{
await uow.ExecuteAsync(
SqlFragment.Literal("UPDATE ") + SqlFragment.Identifier(table.Name) + SqlFragment.Literal(" SET ") + SqlFragment.Identifier(key.Columns[0])
+ SqlFragment.Literal(" = NULL WHERE ") + where,
cancellationToken).ConfigureAwait(false);
}
}
var rows = await uow.ExecuteAsync(SqlFragment.Literal("DELETE FROM ") + SqlFragment.Identifier(table.Name) + SqlFragment.Literal(" WHERE ") + where, cancellationToken)
.ConfigureAwait(false);
if (rows > 0)
{
removed[table.Name] = rows;
}
}
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
return new DemoRemoval(removed, []);
}
// The rows of a table that go: marked demo, or (for a table without the mark) belonging to a row that goes.
private static SqlFragment? Predicate(TableDefinition table, Dictionary<string, TableDefinition> tables, Dictionary<string, SqlFragment?> doomed, HashSet<string> visiting)
{
if (doomed.TryGetValue(table.Name, out var known))
{
return known;
}
if (table.Column(DemoColumn) is not null)
{
var own = SqlFragment.Identifier(DemoColumn) + SqlFragment.Literal(" = ") + SqlFragment.Parameter(true);
doomed[table.Name] = own;
return own;
}
if (table.ForeignKeys.Count == 0)
{
doomed[table.Name] = null;
return null;
}
if (!visiting.Add(table.Name))
{
return null;
}
var parts = new List<SqlFragment>();
foreach (var key in table.ForeignKeys.Where(k => k.OnDelete != ReferentialAction.SetNull && k.ReferencedTable != table.Name && k.Columns.Count == 1))
{
if (tables.TryGetValue(key.ReferencedTable, out var parentTable) && Predicate(parentTable, tables, doomed, visiting) is { } parent)
{
parts.Add(SqlFragment.Identifier(key.Columns[0]) + SqlFragment.Literal(" IN (SELECT ") + SqlFragment.Identifier(key.ReferencedColumns[0]) + SqlFragment.Literal(" FROM ") + SqlFragment.Identifier(key.ReferencedTable)
+ SqlFragment.Literal(" WHERE ") + parent + SqlFragment.Literal(")"));
}
}
visiting.Remove(table.Name);
var result = parts.Count == 0 ? null : SqlFragment.Join(" OR ", parts.Select(p => p.Parenthesize())).Parenthesize();
doomed[table.Name] = result;
return result;
}
// Children before their parents.
private static List<TableDefinition> DeleteOrder(List<TableDefinition> tables)
{
var names = tables.Select(t => t.Name).ToHashSet(StringComparer.Ordinal);
var result = new List<TableDefinition>();
var placed = new HashSet<string>(StringComparer.Ordinal);
while (result.Count < tables.Count)
{
var progress = false;
foreach (var table in tables.Where(t => !placed.Contains(t.Name)))
{
// A table goes once no table still to place refers to it.
var referenced = tables.Any(other => !placed.Contains(other.Name) && other.Name != table.Name
&& other.ForeignKeys.Any(k => k.ReferencedTable == table.Name && names.Contains(other.Name)));
if (!referenced)
{
result.Add(table);
placed.Add(table.Name);
progress = true;
}
}
if (!progress)
{
// A cycle between tables: the rest in any order (keys that set null resolve it).
result.AddRange(tables.Where(t => !placed.Contains(t.Name)));
break;
}
}
return result;
}
}
@@ -0,0 +1,289 @@
using System.Globalization;
using System.Text;
using Khaemhat.Application.Documents;
using Khaemhat.Application.EInvoicing;
using Khaemhat.Application.Instance;
using Khaemhat.Application.Licensing;
using Khaemhat.Application.Modules;
using Khaemhat.Application.Security;
using Khaemhat.Application.Tables;
using Khaemhat.Core.Documents;
using Khaemhat.Core.EInvoicing;
using Khaemhat.Core.Parties;
using Khaemhat.Core.Security;
using Khaemhat.Core.Tables;
using Khaemhat.Data;
using Khaemhat.Data.Querying;
using Khaemhat.Fiscal.Abstractions;
namespace Khaemhat.Application.Seeding;
/// <summary>
/// The demo electronic invoice (SPEC §14, issue #80): the PEC channel (paused, so the demo never writes to a real
/// mailbox) and the intermediary, the routing rules, the files of the demo invoices with the notifications the SDI
/// would have sent (delivered, one rejected to correct, one not delivered, the last ones still waiting), and three
/// supplier invoices received with their metadata. The notifications are written in the layout of the SDI and read by
/// the fiscal pack, as real ones. It runs after the demo treasury, only when the electronic invoice (EINV) is licensed
/// and only once: when the company has e-invoices it adds nothing.
/// </summary>
/// <param name="invoices">The e-invoices.</param>
/// <param name="packs">The fiscal pack of the company.</param>
/// <param name="secrets">Protects the demo password.</param>
/// <param name="factory">Reads and writes the company.</param>
/// <param name="licenses">Whether the electronic invoice is licensed.</param>
public sealed class DemoEInvoiceSeeder(
EInvoiceService invoices, CompanyFiscalContext packs, ISecretProtector secrets, IUnitOfWorkFactory factory, ILicenseGate licenses)
: ICompanySeeder
{
/// <summary>The demo certified mailbox.</summary>
public const string Mailbox = "fatture@pec.khaemhat-demo.it";
/// <summary>How many of the last invoices stay without a file (to generate).</summary>
public const int LeftToGenerate = 1;
/// <summary>How many files stay generated and not sent.</summary>
public const int LeftToSend = 1;
/// <summary>How many files sent stay waiting for the receipt.</summary>
public const int LeftWaiting = 2;
private const string Ns = "http://www.fatturapa.gov.it/sdi/messaggi/v1.0";
/// <inheritdoc />
public int Order => 60;
/// <inheritdoc />
public Task SeedAsync(string companyCode, CompanySeedContext context, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(context);
return context.Demo
? DemoMarker.RunAsync(factory, companyCode, () => SeedCoreAsync(companyCode, context, cancellationToken), cancellationToken)
: Task.CompletedTask;
}
private async Task SeedCoreAsync(string companyCode, CompanySeedContext context, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(context);
if (!context.Demo || !licenses.IsModuleActive(ModuleCodes.EInvoicing))
{
return;
}
var pack = await packs.PackOfAsync(companyCode, cancellationToken).ConfigureAwait(false);
if (pack.GetFeature<IEInvoiceWriter>() is not { } writer || pack.GetFeature<IEInvoiceValidator>() is not { } validator
|| pack.GetFeature<IEInvoiceReceiptReader>() is not { } receipts)
{
return;
}
List<SaleDocument> documents;
await using (var uow = await factory.CreateAsync(DatabaseScope.Company(companyCode), cancellationToken).ConfigureAwait(false))
{
if (await uow.Repository<EInvoice, long>().CountAsync(Query.For<EInvoice>(), cancellationToken).ConfigureAwait(false) > 0
|| await uow.Repository<EInvoiceInboxFile, long>().CountAsync(Query.For<EInvoiceInboxFile>(), cancellationToken).ConfigureAwait(false) > 0
|| await uow.Repository<CompanyProfile, long>().FindAsync(Query.For<CompanyProfile>(), cancellationToken).ConfigureAwait(false) is null)
{
return;
}
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
await ChannelsAsync(uow, cancellationToken).ConfigureAwait(false);
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
documents = [.. (await uow.Repository<SaleDocument, long>()
.ListAsync(Query.For<SaleDocument>().Where(d => d.IsDemo && d.Status == DocumentStatus.Issued).OrderBy(d => d.DocumentDate).OrderBy(d => d.Id), cancellationToken)
.ConfigureAwait(false)).Items.Where(d => EInvoiceBuilder.IsElectronic(d.Kind))];
}
var generated = new List<EInvoice>();
foreach (var document in documents.Take(Math.Max(0, documents.Count - LeftToGenerate)))
{
await using var uow = await factory.CreateAsync(DatabaseScope.Company(companyCode), cancellationToken).ConfigureAwait(false);
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
var result = await invoices.GenerateCoreAsync(uow, writer, validator, DocumentFamily.SaleDocument, document.Id, Actor.System.UserName, cancellationToken)
.ConfigureAwait(false);
if (result.Invoice is { } invoice)
{
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
generated.Add(invoice);
}
else
{
await uow.RollbackAsync(cancellationToken).ConfigureAwait(false);
}
}
var sent = generated.Take(Math.Max(0, generated.Count - LeftToSend)).ToList();
var answered = sent.Count - LeftWaiting;
for (var i = 0; i < sent.Count; i++)
{
var invoice = sent[i];
var exchangeId = (4_000_000_000L + invoice.Progressive).ToString(CultureInfo.InvariantCulture);
await using var uow = await factory.CreateAsync(DatabaseScope.Company(companyCode), cancellationToken).ConfigureAwait(false);
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
var current = await uow.Repository<EInvoice, long>().GetAsync(invoice.Id, cancellationToken).ConfigureAwait(false);
if (current is null)
{
continue;
}
await invoices.MarkSentCoreAsync(uow, current, "PEC", null, "<demo-" + exchangeId + "@pec.khaemhat-demo.it>", Actor.System.UserName, cancellationToken)
.ConfigureAwait(false);
// The file was written and sent the day after the document, not today.
var sentAt = new DateTimeOffset(current.DocumentDate.AddDays(1).ToDateTime(new TimeOnly(9, 40)), TimeSpan.FromHours(1)).UtcDateTime;
current.GeneratedAt = sentAt.AddMinutes(-5);
current.SentAt = sentAt;
await uow.Repository<EInvoice, long>().UpdateAsync(current, cancellationToken).ConfigureAwait(false);
if (i < answered)
{
var at = new DateTimeOffset(current.DocumentDate.AddDays(1).ToDateTime(new TimeOnly(10, 15)), TimeSpan.FromHours(1));
var stem = EInvoiceStore.Stem(current.FileName);
var (code, root, body) = (i % 9) switch
{
1 when answered >= 3 => ("NS", "NotificaScarto", Rejection(current.FileName, exchangeId, at)),
4 when answered >= 5 => ("MC", "NotificaMancataConsegna", Basic(current.FileName, exchangeId, at, "Casella del destinatario piena: fattura messa a disposizione nell'area riservata.")),
_ => ("RC", "RicevutaConsegna", Delivery(current.FileName, exchangeId, at)),
};
var name = stem + "_" + code + "_001.xml";
var receipt = receipts.Read(name, Notification(root, body));
await invoices.ApplyReceiptCoreAsync(uow, receipt, "PEC", Actor.System.UserName, true, cancellationToken).ConfigureAwait(false);
}
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
}
await InboxAsync(companyCode, pack, writer, documents.FirstOrDefault(), cancellationToken).ConfigureAwait(false);
}
/// <summary>A notification as the SDI writes it (<c>MessaggiTypes</c> v1.0).</summary>
/// <param name="root">The root element.</param>
/// <param name="body">The children.</param>
/// <returns>The file.</returns>
public static byte[] Notification(string root, string body) => Encoding.UTF8.GetBytes(
$"""<?xml version="1.0" encoding="UTF-8"?><types:{root} xmlns:types="{Ns}" versione="1.0">{body}</types:{root}>""");
private static string Stamp(DateTimeOffset at) => at.ToString("yyyy-MM-dd'T'HH:mm:ss.fffzzz", CultureInfo.InvariantCulture);
private static string Delivery(string file, string exchangeId, DateTimeOffset at) =>
$"<IdentificativoSdI>{exchangeId}</IdentificativoSdI><NomeFile>{file}</NomeFile><Hash>demo</Hash><DataOraRicezione>{Stamp(at.AddMinutes(-20))}</DataOraRicezione>"
+ $"<DataOraConsegna>{Stamp(at)}</DataOraConsegna><MessageId>{exchangeId}1</MessageId>";
private static string Basic(string file, string exchangeId, DateTimeOffset at, string note) =>
$"<IdentificativoSdI>{exchangeId}</IdentificativoSdI><NomeFile>{file}</NomeFile><Hash>demo</Hash><DataOraRicezione>{Stamp(at.AddMinutes(-20))}</DataOraRicezione>"
+ $"<Descrizione>{note}</Descrizione><MessageId>{exchangeId}2</MessageId><Note>{note}</Note>";
private static string Rejection(string file, string exchangeId, DateTimeOffset at) =>
$"<IdentificativoSdI>{exchangeId}</IdentificativoSdI><NomeFile>{file}</NomeFile><Hash>demo</Hash><DataOraRicezione>{Stamp(at.AddMinutes(-20))}</DataOraRicezione>"
+ "<ListaErrori><Errore><Codice>00305</Codice><Descrizione>1.4.1.1.2 IdCodice del cessionario/committente non valido</Descrizione>"
+ "<Suggerimento>Verificare la partita IVA del cliente in anagrafica</Suggerimento></Errore></ListaErrori>"
+ $"<MessageId>{exchangeId}3</MessageId>";
private async Task ChannelsAsync(IUnitOfWork uow, CancellationToken cancellationToken)
{
var channels = uow.Repository<EInvoiceChannelSetting, long>();
await channels.InsertAsync(
new EInvoiceChannelSetting
{
Code = "PEC",
Enabled = true,
Paused = true,
Mailbox = Mailbox,
SmtpHost = "smtps.pec.khaemhat-demo.it",
SmtpPort = 465,
ImapHost = "imaps.pec.khaemhat-demo.it",
ImapPort = 993,
Tls = true,
UserName = Mailbox,
ProtectedPassword = secrets.Protect("demo-non-valida", EInvoiceStore.SecretPurpose),
ExchangeAddress = "sdi27@pec.fatturapa.it",
ArchiveFolder = "SDI/Archiviati",
LastCheckMessage = "Canale dimostrativo in pausa: nessun messaggio viene inviato o letto.",
IsDemo = true,
},
cancellationToken).ConfigureAwait(false);
await channels.InsertAsync(
new EInvoiceChannelSetting
{
Code = "INTA",
Enabled = false,
Endpoint = "https://api.intermediario.khaemhat-demo.it/v1",
TestEnvironment = true,
IsDemo = true,
},
cancellationToken).ConfigureAwait(false);
var rules = uow.Repository<SdiRoutingRule, long>();
await rules.InsertAsync(new SdiRoutingRule { Position = 10, Condition = SdiRoutingCondition.PublicAdministration, ChannelCode = "PEC", IsDemo = true }, cancellationToken)
.ConfigureAwait(false);
await rules.InsertAsync(new SdiRoutingRule { Position = 20, Condition = SdiRoutingCondition.DailyVolume, Value = "200", ChannelCode = "INTA", FallbackChannelCode = "PEC", IsDemo = true },
cancellationToken).ConfigureAwait(false);
await rules.InsertAsync(new SdiRoutingRule { Position = 90, Condition = SdiRoutingCondition.Default, ChannelCode = "PEC", FallbackChannelCode = "INTA", IsDemo = true },
cancellationToken).ConfigureAwait(false);
}
// Three supplier invoices received through the SDI, with their metadata: made from a demo invoice, turned around.
private async Task InboxAsync(string companyCode, IFiscalPack pack, IEInvoiceWriter writer, SaleDocument? model, CancellationToken cancellationToken)
{
if (model is null || pack.GetFeature<IIncomingInvoiceReader>() is not { } reader)
{
return;
}
await using var uow = await factory.CreateAsync(DatabaseScope.Company(companyCode), cancellationToken).ConfigureAwait(false);
var profile = await uow.Repository<CompanyProfile, long>().FindAsync(Query.For<CompanyProfile>(), cancellationToken).ConfigureAwait(false);
var record = await DocumentEngine.LoadAsync(uow, DocumentFamily.SaleDocument, model.Id, cancellationToken).ConfigureAwait(false);
if (profile is null || record is null)
{
return;
}
var suppliers = (await uow.Repository<Party, long>().ListAsync(Query.For<Party>().Where(p => p.IsDemo && p.Kind == PartyKind.Supplier).OrderBy(p => p.Id).Take(3), cancellationToken)
.ConfigureAwait(false)).Items;
var (file, _, _) = await EInvoiceBuilder.BuildAsync(uow, record, cancellationToken).ConfigureAwait(false);
var customer = EInvoiceBuilder.CompanyParty(profile);
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
var n = 0;
foreach (var supplier in suppliers)
{
n++;
var supplierId = supplier.Id;
var fiscal = await uow.Repository<PartyFiscal, long>().FindAsync(Query.For<PartyFiscal>().Where(f => f.PartyId == supplierId), cancellationToken).ConfigureAwait(false);
var party = EInvoiceBuilder.PartyOf(supplier, fiscal, supplier: true);
var country = party.CountryCode ?? "IT";
var id = party.VatNumber ?? party.TaxCode ?? "00000000000";
var date = model.DocumentDate.AddDays(-3 * n);
var name = writer.FileName(country, id, 100 + n);
var number = string.Create(CultureInfo.InvariantCulture, $"{date.Year}/{(40 * n) + 7}");
var incoming = file with
{
FileName = name,
ProgressiveNumber = writer.Progressive(100 + n),
TransmitterCountry = country,
TransmitterId = id,
RecipientCode = profile.RecipientCode is { Length: 7 } code ? code : "0000000",
RecipientPec = profile.RecipientCode is { Length: 7 } ? null : Mailbox,
Supplier = party,
Customer = customer,
Invoices = [file.Invoices[0] with { Number = number, Date = date, DocumentType = "TD01" }],
IssuedBy = null,
};
var content = writer.Write(incoming);
var receivedAt = date.AddDays(1).ToDateTime(new TimeOnly(9, 30 + n), DateTimeKind.Utc);
var exchangeId = (5_000_000_000L + n).ToString(CultureInfo.InvariantCulture);
var stored = await SdiInboxService.StoreCoreAsync(uow, reader, name, content, receivedAt, "PEC", exchangeId, true, cancellationToken).ConfigureAwait(false);
if (stored.Id is { } rowId)
{
var row = await uow.Repository<EInvoiceInboxFile, long>().GetAsync(rowId, cancellationToken).ConfigureAwait(false);
if (row is not null)
{
row.MetadataFileName = EInvoiceStore.Stem(name) + "_MT_001.xml";
row.Metadata = Notification("FileMetadati",
$"<IdentificativoSdI>{exchangeId}</IdentificativoSdI><NomeFile>{name}</NomeFile><Hash>demo</Hash><CodiceDestinatario>{incoming.RecipientCode}</CodiceDestinatario>"
+ $"<Formato>FPR12</Formato><TentativiInvio>1</TentativiInvio><MessageId>{exchangeId}9</MessageId>");
await uow.Repository<EInvoiceInboxFile, long>().UpdateAsync(row, cancellationToken).ConfigureAwait(false);
}
}
}
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
}
}
@@ -41,7 +41,15 @@ public sealed class DemoLedgerSeeder(
public int Order => 40;
/// <inheritdoc />
public async Task SeedAsync(string companyCode, CompanySeedContext context, CancellationToken cancellationToken = default)
public Task SeedAsync(string companyCode, CompanySeedContext context, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(context);
return context.Demo
? DemoMarker.RunAsync(factory, companyCode, () => SeedCoreAsync(companyCode, context, cancellationToken), cancellationToken)
: Task.CompletedTask;
}
private async Task SeedCoreAsync(string companyCode, CompanySeedContext context, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(context);
if (!context.Demo)
@@ -0,0 +1,71 @@
using Khaemhat.Data;
using Khaemhat.Data.Migrations;
namespace Khaemhat.Application.Seeding;
/// <summary>
/// Marks as demo every row a demo seeder created, also those the services wrote for it (the entries of an issued
/// invoice, the open items, the payments): the last identifier of every table with <c>is_demo</c> is taken before the
/// seeder runs, and the rows after it are marked when it ends. So <see cref="DemoDataRemover"/> finds them all. A demo
/// seed is an administrative operation: rows the users would write meanwhile in the same company would be marked too.
/// </summary>
internal sealed class DemoMarker
{
private const string DemoColumn = "is_demo";
private static readonly Lazy<IReadOnlyList<string>> Tables = new(() =>
[.. MigrationCatalog.ForCompany().BuildModel().Tables.Where(t => t.Column(DemoColumn) is not null && t.PrimaryKey is ["id"]).Select(t => t.Name).Order(StringComparer.Ordinal)]);
private readonly IUnitOfWorkFactory _factory;
private readonly string _company;
private readonly Dictionary<string, long> _last;
private DemoMarker(IUnitOfWorkFactory factory, string company, Dictionary<string, long> last)
{
_factory = factory;
_company = company;
_last = last;
}
/// <summary>Runs a demo seeder and marks what it created.</summary>
/// <param name="factory">The units of work.</param>
/// <param name="company">The company.</param>
/// <param name="seed">The seeder.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
public static async Task RunAsync(IUnitOfWorkFactory factory, string company, Func<Task> seed, CancellationToken cancellationToken)
{
var marker = await TakeAsync(factory, company, cancellationToken).ConfigureAwait(false);
await seed().ConfigureAwait(false);
await marker.MarkAsync(cancellationToken).ConfigureAwait(false);
}
private static async Task<DemoMarker> TakeAsync(IUnitOfWorkFactory factory, string company, CancellationToken cancellationToken)
{
var last = new Dictionary<string, long>(StringComparer.Ordinal);
await using var uow = await factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
foreach (var table in Tables.Value)
{
last[table] = await uow.QuerySingleAsync<long?>(
SqlFragment.Literal("SELECT MAX(id) FROM ") + SqlFragment.Identifier(table), cancellationToken).ConfigureAwait(false) ?? 0L;
}
return new DemoMarker(factory, company, last);
}
private async Task MarkAsync(CancellationToken cancellationToken)
{
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(_company), cancellationToken).ConfigureAwait(false);
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
foreach (var (table, last) in _last)
{
await uow.ExecuteAsync(
SqlFragment.Literal("UPDATE ") + SqlFragment.Identifier(table) + SqlFragment.Literal(" SET ") + SqlFragment.Identifier(DemoColumn) + SqlFragment.Literal(" = ")
+ SqlFragment.Parameter(true) + SqlFragment.Literal(" WHERE id > ") + SqlFragment.Parameter(last) + SqlFragment.Literal(" AND ") + SqlFragment.Identifier(DemoColumn)
+ SqlFragment.Literal(" = ") + SqlFragment.Parameter(false),
cancellationToken).ConfigureAwait(false);
}
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
}
}
@@ -43,7 +43,15 @@ public sealed class DemoPurchasesSeeder(
public int Order => 30;
/// <inheritdoc />
public async Task SeedAsync(string companyCode, CompanySeedContext context, CancellationToken cancellationToken = default)
public Task SeedAsync(string companyCode, CompanySeedContext context, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(context);
return context.Demo
? DemoMarker.RunAsync(factory, companyCode, () => SeedCoreAsync(companyCode, context, cancellationToken), cancellationToken)
: Task.CompletedTask;
}
private async Task SeedCoreAsync(string companyCode, CompanySeedContext context, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(context);
if (!context.Demo)
@@ -43,7 +43,15 @@ public sealed class DemoSalesSeeder(
public int Order => 20;
/// <inheritdoc />
public async Task SeedAsync(string companyCode, CompanySeedContext context, CancellationToken cancellationToken = default)
public Task SeedAsync(string companyCode, CompanySeedContext context, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(context);
return context.Demo
? DemoMarker.RunAsync(factory, companyCode, () => SeedCoreAsync(companyCode, context, cancellationToken), cancellationToken)
: Task.CompletedTask;
}
private async Task SeedCoreAsync(string companyCode, CompanySeedContext context, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(context);
if (!context.Demo)
@@ -0,0 +1,382 @@
using System.Globalization;
using System.Numerics;
using System.Text;
using Khaemhat.Application.Instance;
using Khaemhat.Application.Ledger;
using Khaemhat.Application.Licensing;
using Khaemhat.Application.Modules;
using Khaemhat.Application.Security;
using Khaemhat.Application.Treasury;
using Khaemhat.Core.Accounting;
using Khaemhat.Core.Parties;
using Khaemhat.Core.Tables;
using Khaemhat.Core.Treasury;
using Khaemhat.Data;
using Khaemhat.Data.Querying;
namespace Khaemhat.Application.Seeding;
/// <summary>
/// The demo treasury (SPEC §14, issues #69-#72): the bank account of the company, the collections of the invoices
/// paid by transfer (one only in part), the payments to the suppliers, a RiBa remittance presented and credited with an
/// unpaid effect, a direct debit mandate, a bank statement still to reconcile with a saved rule for the fees, and the
/// first reminder already sent to a customer. It runs after the demo ledger, only when the treasury (FIN) is licensed and only once: when the company has
/// collections or remittances it adds nothing.
/// </summary>
/// <param name="payments">Collections and payments.</param>
/// <param name="remittances">The remittances.</param>
/// <param name="mandates">The mandates.</param>
/// <param name="reconciliation">The bank statements.</param>
/// <param name="factory">Reads and writes the company.</param>
/// <param name="licenses">Whether the treasury is licensed.</param>
/// <param name="clock">Today.</param>
public sealed class DemoTreasurySeeder(
PaymentService payments, RemittanceService remittances, MandateService mandates, BankReconciliationService reconciliation, IUnitOfWorkFactory factory,
ILicenseGate licenses, TimeProvider clock)
: ICompanySeeder
{
/// <summary>The code of the demo bank account.</summary>
public const string BankCode = "BPD";
/// <summary>The capital paid into the bank on the first day of the year.</summary>
public const decimal OpeningBalance = 25000m;
/// <summary>The account of the capital paid in by the shareholders.</summary>
public const string CapitalAccount = "10.01.004";
/// <summary>The fees of the unpaid effect.</summary>
public const decimal UnpaidFees = 6.50m;
/// <summary>The monthly fee of the bank account, matched by a saved rule.</summary>
public const decimal AccountFee = 12.50m;
private static readonly Actor Seed = Actor.System;
/// <inheritdoc />
public int Order => 50;
/// <summary>An Italian IBAN with its check digits computed from ABI, CAB and account.</summary>
/// <param name="cin">The CIN letter.</param>
/// <param name="abi">The ABI code.</param>
/// <param name="cab">The CAB code.</param>
/// <param name="account">The account number (12 characters).</param>
/// <returns>The IBAN.</returns>
public static string Iban(char cin, string abi, string cab, string account)
{
ArgumentNullException.ThrowIfNull(abi);
ArgumentNullException.ThrowIfNull(cab);
ArgumentNullException.ThrowIfNull(account);
var bban = cin + abi + cab + account;
var digits = new StringBuilder();
foreach (var c in bban + "IT00")
{
digits.Append(char.IsLetter(c) ? (c - 'A' + 10).ToString(CultureInfo.InvariantCulture) : c.ToString());
}
var check = 98 - (int)(BigInteger.Parse(digits.ToString(), CultureInfo.InvariantCulture) % 97);
return "IT" + check.ToString("00", CultureInfo.InvariantCulture) + bban;
}
/// <inheritdoc />
public Task SeedAsync(string companyCode, CompanySeedContext context, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(context);
return context.Demo
? DemoMarker.RunAsync(factory, companyCode, () => SeedCoreAsync(companyCode, context, cancellationToken), cancellationToken)
: Task.CompletedTask;
}
private async Task SeedCoreAsync(string companyCode, CompanySeedContext context, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(context);
if (!context.Demo || !licenses.IsModuleActive(ModuleCodes.Finance))
{
return;
}
var today = DateOnly.FromDateTime(TimeZoneInfo.ConvertTime(clock.GetUtcNow(), TimeZoneInfo.Local).DateTime);
long bankId;
await using (var uow = await factory.CreateAsync(DatabaseScope.Company(companyCode), cancellationToken).ConfigureAwait(false))
{
if (await uow.Repository<GlAccount, long>().CountAsync(Query.For<GlAccount>(), cancellationToken).ConfigureAwait(false) == 0
|| await uow.Repository<Payment, long>().CountAsync(Query.For<Payment>(), cancellationToken).ConfigureAwait(false) > 0
|| await uow.Repository<Remittance, long>().CountAsync(Query.For<Remittance>(), cancellationToken).ConfigureAwait(false) > 0)
{
return;
}
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
bankId = await BankAsync(uow, cancellationToken).ConfigureAwait(false);
await OpeningAsync(uow, new DateOnly(today.Year, 1, 1), cancellationToken).ConfigureAwait(false);
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
}
await CollectionsAsync(companyCode, bankId, today, cancellationToken).ConfigureAwait(false);
await RibaAsync(companyCode, bankId, today, cancellationToken).ConfigureAwait(false);
await MandateAsync(companyCode, today, cancellationToken).ConfigureAwait(false);
await StatementAsync(companyCode, bankId, today, cancellationToken).ConfigureAwait(false);
await RemindersAsync(companyCode, today, cancellationToken).ConfigureAwait(false);
}
private static async Task<long> BankAsync(IUnitOfWork uow, CancellationToken cancellationToken)
{
var banks = uow.Repository<BankAccount, long>();
var bank = await banks.FindAsync(Query.For<BankAccount>().Where(b => b.Code == BankCode), cancellationToken).ConfigureAwait(false);
if (bank is null)
{
bank = new BankAccount
{
Code = BankCode,
Description = "Conto corrente ordinario",
BankName = "Banca Popolare Dimostrativa",
Iban = Iban('X', "05034", "01000", "000000012345"),
Bic = "DEMOITM1XXX",
SiaCode = "A1B2C",
CucCode = "DEMO1234",
CreditorId = "IT66ZZZ00000000000000000",
AccountCode = DemoLedgerSeeder.BankAccount,
IsDefault = true,
IsDemo = true,
};
bank.Id = await banks.InsertAsync(bank, cancellationToken).ConfigureAwait(false);
}
var profile = await uow.Repository<CompanyProfile, long>().FindAsync(Query.For<CompanyProfile>(), cancellationToken).ConfigureAwait(false);
if (profile is not null && profile.DefaultBankAccountId is null)
{
profile.DefaultBankAccountId = bank.Id;
await uow.Repository<CompanyProfile, long>().UpdateAsync(profile, cancellationToken).ConfigureAwait(false);
}
await CustomerBanksAsync(uow, cancellationToken).ConfigureAwait(false);
return bank.Id;
}
// The shareholders paid the capital into the bank on the first day of the year, so the account starts in credit.
private static async Task OpeningAsync(IUnitOfWork uow, DateOnly day, CancellationToken cancellationToken)
{
var bank = await LedgerStore.AccountAsync(uow, DemoLedgerSeeder.BankAccount, cancellationToken).ConfigureAwait(false);
var capital = await LedgerStore.AccountAsync(uow, CapitalAccount, cancellationToken).ConfigureAwait(false);
if (bank is null || capital is null)
{
return;
}
await TreasuryStore.PostAsync(uow, "GIRO", day, "Versamento soci in conto capitale", null,
[new PaymentPostedLine(bank.Id, null, null, null, OpeningBalance, 0m), new PaymentPostedLine(capital.Id, null, null, null, 0m, OpeningBalance)], true, cancellationToken)
.ConfigureAwait(false);
}
// The customers who pay by RiBa or direct debit need the coordinates of their bank: the demo parties that have none
// get one, so the remittances are complete.
private static async Task CustomerBanksAsync(IUnitOfWork uow, CancellationToken cancellationToken)
{
var collected = (await uow.Repository<PaymentMethod, long>().ListAsync(Query.For<PaymentMethod>(), cancellationToken).ConfigureAwait(false)).Items
.Where(m => m.Code is "RIBA" or "SDD" or "SDDB").Select(m => (long?)m.Id).ToList();
var receivable = OpenItemDirection.Receivable;
var parties = (await uow.Repository<OpenItem, long>().ListAsync(
Query.For<OpenItem>().Where(o => o.Direction == receivable && !o.Closed && collected.Contains(o.PaymentMethodId)), cancellationToken).ConfigureAwait(false)).Items
.Select(o => o.PartyId).Distinct().Order().ToList();
(string Abi, string Cab, string Name)[] branches = [("03069", "01000", "Banca del Territorio"), ("02008", "30330", "Banca Subalpina"), ("05696", "11000", "Credito Cooperativo Demo")];
var n = 0;
foreach (var partyId in parties)
{
var accounts = uow.Repository<PartyBankAccount, long>();
if (await accounts.CountAsync(Query.For<PartyBankAccount>().Where(a => a.PartyId == partyId), cancellationToken).ConfigureAwait(false) > 0)
{
continue;
}
var branch = branches[n++ % branches.Length];
await accounts.InsertAsync(new PartyBankAccount
{
PartyId = partyId,
Iban = Iban('K', branch.Abi, branch.Cab, (100000 + partyId).ToString("000000000000", CultureInfo.InvariantCulture)),
BankName = branch.Name,
BankCode = branch.Abi,
BranchCode = branch.Cab,
IsDefault = true,
}, cancellationToken).ConfigureAwait(false);
}
}
// The invoices paid by transfer or on the spot are collected on their due date when it is more than three weeks
// ago; the oldest of one customer only in half, so the schedule shows a partial item. The suppliers, RiBa included,
// are paid on their due date when it is more than a week ago.
private async Task CollectionsAsync(string companyCode, long bankId, DateOnly today, CancellationToken cancellationToken)
{
List<OpenItem> items;
Dictionary<long, PaymentMethod> methods;
await using (var uow = await factory.CreateAsync(DatabaseScope.Company(companyCode), cancellationToken).ConfigureAwait(false))
{
var limit = today.AddDays(-7);
var customers = today.AddDays(-21);
items = [.. (await uow.Repository<OpenItem, long>().ListAsync(
Query.For<OpenItem>().Where(o => !o.Closed && o.DueDate <= limit).OrderBy(o => o.DueDate).OrderBy(o => o.Id), cancellationToken).ConfigureAwait(false)).Items
.Where(o => o.Direction == OpenItemDirection.Payable || o.DueDate <= customers)];
methods = (await uow.Repository<PaymentMethod, long>().ListAsync(Query.For<PaymentMethod>(), cancellationToken).ConfigureAwait(false)).Items.ToDictionary(m => m.Id);
}
var partialDone = false;
foreach (var item in items.Where(i => i.Residual > 0m))
{
var method = item.PaymentMethodId is { } m ? methods.GetValueOrDefault(m) : null;
var receivable = item.Direction == OpenItemDirection.Receivable;
if (receivable && method?.Code is "RIBA" or "SDD" or "SDDB")
{
continue;
}
var amount = item.Residual;
if (receivable && !partialDone && method?.Code == "BON")
{
// The first transfer collected only in half: the rest stays overdue for the reminders.
amount = Math.Round(item.Residual / 2m, 2, MidpointRounding.AwayFromZero);
partialDone = true;
}
await payments.RegisterAsync(Seed, companyCode, new PaymentInput(
receivable ? PaymentDirection.Receipt : PaymentDirection.Disbursement, item.PartyId, item.DueDate, item.PaymentMethodId, bankId,
receivable ? 0m : 1.50m, "CRO " + item.Id.ToString("000000", CultureInfo.InvariantCulture), null,
[new PaymentLineInput(item.Id, amount)]), cancellationToken).ConfigureAwait(false);
}
}
// The RiBa due before today in a remittance presented and credited, the effect of one customer back unpaid;
// those due in the next 45 days in a draft remittance ready for the file.
private async Task RibaAsync(string companyCode, long bankId, DateOnly today, CancellationToken cancellationToken)
{
var due = (await remittances.CandidatesAsync(Seed, companyCode, RemittanceKind.Riba, today.AddDays(-1), cancellationToken).ConfigureAwait(false))
.Where(c => c.Ready).ToList();
if (due.Count > 0)
{
var presentation = due.Min(c => c.Row.Item.DueDate).AddDays(-20);
var remittance = await remittances.CreateAsync(Seed, companyCode, new RemittanceInput(
RemittanceKind.Riba, bankId, presentation, today.AddDays(-1), false, "Distinta dimostrativa", [.. due.Select(c => c.Row.Item.Id)]), cancellationToken).ConfigureAwait(false);
await remittances.PresentAsync(Seed, companyCode, remittance.Id, cancellationToken).ConfigureAwait(false);
var latest = due.Max(c => c.Row.Item.DueDate);
await remittances.CreditAsync(Seed, companyCode, remittance.Id, latest, cancellationToken).ConfigureAwait(false);
var lines = (await remittances.GetAsync(Seed, companyCode, remittance.Id, cancellationToken).ConfigureAwait(false))!.Value.Lines;
var unpaid = lines.OrderByDescending(l => l.Line.DueDate).First();
var day = unpaid.Line.DueDate.AddDays(5);
await remittances.UnpaidAsync(Seed, companyCode, unpaid.Line.Id, day > today ? today : day, UnpaidFees, cancellationToken).ConfigureAwait(false);
}
var next = (await remittances.CandidatesAsync(Seed, companyCode, RemittanceKind.Riba, today.AddDays(45), cancellationToken).ConfigureAwait(false))
.Where(c => c.Ready && c.Row.Item.DueDate >= today && c.Row.Item.Status != OpenItemStatus.Unpaid).ToList();
if (next.Count > 0)
{
await remittances.CreateAsync(Seed, companyCode, new RemittanceInput(
RemittanceKind.Riba, bankId, today, today.AddDays(45), true, "Da presentare con anticipo s.b.f.", [.. next.Select(c => c.Row.Item.Id)]), cancellationToken).ConfigureAwait(false);
}
}
private async Task MandateAsync(string companyCode, DateOnly today, CancellationToken cancellationToken)
{
await using var uow = await factory.CreateAsync(DatabaseScope.Company(companyCode), cancellationToken).ConfigureAwait(false);
var party = await uow.Repository<Party, long>().FindAsync(Query.For<Party>().Where(p => p.Name == "Idrotermica Piemonte S.r.l."), cancellationToken).ConfigureAwait(false);
if (party is null)
{
return;
}
var account = await uow.Repository<PartyBankAccount, long>().FindAsync(Query.For<PartyBankAccount>().Where(a => a.PartyId == party.Id), cancellationToken).ConfigureAwait(false);
await mandates.SaveAsync(Seed, companyCode, new MandateInput(
null, party.Id, "KH-MND-" + party.Code, new DateOnly(today.Year, 1, 15), SddScheme.Core, account?.Iban ?? Iban('A', "06230", "10000", "000046012345"), null, false,
"Mandato firmato in sede"), cancellationToken).ConfigureAwait(false);
}
// A statement of the last days in CSV: a transfer received for an open invoice, a transfer to a supplier
// already recorded, the monthly fee of the account (matched by a saved rule) and a movement nobody knows yet.
private async Task StatementAsync(string companyCode, long bankId, DateOnly today, CancellationToken cancellationToken)
{
OpenItem? open;
Payment? paid;
string? openParty;
long? feeAccount;
await using (var uow = await factory.CreateAsync(DatabaseScope.Company(companyCode), cancellationToken).ConfigureAwait(false))
{
var receivable = OpenItemDirection.Receivable;
// The customer who paid half pays the rest: the movement matches the item, which names the invoice.
open = (await uow.Repository<OpenItem, long>().ListAsync(
Query.For<OpenItem>().Where(o => o.Direction == receivable && !o.Closed && (o.Status == OpenItemStatus.Partial || o.Status == OpenItemStatus.Open)).OrderBy(o => o.DueDate),
cancellationToken).ConfigureAwait(false)).Items
.Where(o => o.Residual > 0m && o.DocumentNumber is not null && o.DueDate <= today)
.OrderByDescending(o => o.Status == OpenItemStatus.Partial).FirstOrDefault();
openParty = open is null ? null : (await uow.Repository<Party, long>().GetAsync(open.PartyId, cancellationToken).ConfigureAwait(false))?.Name;
paid = await uow.Repository<Payment, long>().FindAsync(
Query.For<Payment>().Where(p => p.Direction == PaymentDirection.Disbursement).OrderByDescending(p => p.PaymentDate), cancellationToken).ConfigureAwait(false);
feeAccount = (await uow.Repository<GlAccount, long>().FindAsync(Query.For<GlAccount>().Where(a => a.Code == "21.03.011"), cancellationToken).ConfigureAwait(false))?.Id;
}
if (feeAccount is { } fees)
{
await reconciliation.SaveRuleAsync(Seed, companyCode, new BankRuleInput(null, "Canone e commissioni", "COMMISSIONI", BankRuleDirection.Out, fees, "Canone mensile conto corrente", false), cancellationToken)
.ConfigureAwait(false);
}
var culture = CultureInfo.GetCultureInfo("it-IT");
var csv = new StringBuilder("Data contabile;Data valuta;Descrizione;Importo\r\n");
void Row(DateOnly day, string text, decimal amount) =>
csv.Append(day.ToString("dd/MM/yyyy", culture)).Append(';').Append(day.ToString("dd/MM/yyyy", culture)).Append(';').Append(text).Append(';')
.Append(amount.ToString("0.00", culture)).Append("\r\n");
if (open is not null)
{
Row(today.AddDays(-4), "BONIFICO A VOSTRO FAVORE DA " + (openParty ?? string.Empty).ToUpperInvariant() + " SALDO FT " + open.DocumentNumber, open.Residual);
}
if (paid is not null)
{
Row(paid.PaymentDate, "BONIFICO SEPA " + paid.Reference, -(paid.Amount + paid.Fees));
}
Row(today.AddDays(-3), "COMMISSIONI E CANONE MENSILE CONTO", -AccountFee);
Row(today.AddDays(-2), "PAGAMENTO POS CARBURANTE", -64.20m);
await reconciliation.ImportAsync(Seed, companyCode, bankId, "estratto-demo.csv", Encoding.UTF8.GetBytes(csv.ToString()), cancellationToken).ConfigureAwait(false);
}
// The first reminder already sent ten days ago to the customer with the oldest overdue item.
private async Task RemindersAsync(string companyCode, DateOnly today, CancellationToken cancellationToken)
{
await using var uow = await factory.CreateAsync(DatabaseScope.Company(companyCode), cancellationToken).ConfigureAwait(false);
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
var receivable = OpenItemDirection.Receivable;
var limit = today.AddDays(-20);
var overdue = (await uow.Repository<OpenItem, long>().ListAsync(
Query.For<OpenItem>().Where(o => o.Direction == receivable && !o.Closed && o.DueDate <= limit && o.Status != OpenItemStatus.InRemittance).OrderBy(o => o.DueDate), cancellationToken)
.ConfigureAwait(false)).Items.Where(o => o.Residual > 0m).ToList();
var parties = await TreasuryStore.PartiesAsync(uow, overdue.Select(o => o.PartyId), cancellationToken).ConfigureAwait(false);
var first = overdue.FirstOrDefault(o => parties.TryGetValue(o.PartyId, out var p) && p.SubjectType != SubjectType.PublicAdministration);
if (first is null)
{
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
return;
}
var party = parties[first.PartyId];
var items = overdue.Where(o => o.PartyId == first.PartyId).ToList();
var sent = today.AddDays(-10);
await uow.Repository<DunningLetter, long>().InsertAsync(new DunningLetter
{
PartyId = party.Id,
Level = 1,
SentOn = sent,
Channel = DunningChannel.Email,
Recipients = party.Email,
Subject = "Promemoria scadenze",
ItemCount = items.Count,
OverdueAmount = items.Sum(i => i.Residual),
Status = DunningLetterStatus.Sent,
SentBy = "demo",
IsDemo = true,
}, cancellationToken).ConfigureAwait(false);
foreach (var item in items)
{
item.DunningLevel = 1;
item.LastDunningDate = sent;
await uow.Repository<OpenItem, long>().UpdateAsync(item, cancellationToken).ConfigureAwait(false);
}
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
}
}
@@ -0,0 +1,267 @@
using Khaemhat.Application.Documents;
using Khaemhat.Application.Instance;
using Khaemhat.Application.Inventory;
using Khaemhat.Application.Ledger;
using Khaemhat.Application.Licensing;
using Khaemhat.Application.Modules;
using Khaemhat.Application.Security;
using Khaemhat.Application.Tables;
using Khaemhat.Application.YearEnd;
using Khaemhat.Core.Accounting;
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;
using Khaemhat.Fiscal.Abstractions;
namespace Khaemhat.Application.Seeding;
/// <summary>
/// The demo data of the year end (SPEC §14, issue #87): the opening balances of the year (share capital, retained
/// earnings, bank, the opening stock and the fixed assets bought in the years before with their funds), the standard categories and four assets, one of them
/// bought this year; the declaration of intent of Idrotermica Piemonte taken into the register and an invoice under it
/// (NI8C); an intra-EU sale of goods to Bergwerk Bau (Austria) with nomenclature and mass for the Intrastat list; the
/// insurance premium paid in October with its prepaid share. With these the guided closing of the demo year runs from
/// the first step to the last. Runs after the demo e-invoices and only once: when the company has fixed assets or
/// accruals it adds nothing.
/// </summary>
/// <param name="engine">The document engine.</param>
/// <param name="editor">The document editor.</param>
/// <param name="ledger">Posts the new invoices.</param>
/// <param name="packs">The fiscal pack of the company.</param>
/// <param name="factory">Reads and writes the company.</param>
/// <param name="licenses">Which modules are licensed.</param>
/// <param name="clock">The clock.</param>
public sealed class DemoYearEndSeeder(
DocumentEngine engine, DocumentEditor editor, LedgerService ledger, CompanyFiscalContext packs, IUnitOfWorkFactory factory, ILicenseGate licenses, TimeProvider clock)
: ICompanySeeder
{
/// <summary>The share capital of the demo company.</summary>
public const decimal ShareCapital = 50_000m;
/// <summary>The bank balance on the first of January.</summary>
public const decimal OpeningBank = 25_000m;
/// <summary>The yearly insurance premium paid on the first of October.</summary>
public const decimal InsurancePremium = 1_800m;
private const string InsuranceAccount = "21.03.005";
private const string RetainedEarnings = "10.02.001";
private static readonly Actor Seed = Actor.System;
/// <inheritdoc />
public int Order => 70;
/// <inheritdoc />
public Task SeedAsync(string companyCode, CompanySeedContext context, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(context);
return context.Demo
? DemoMarker.RunAsync(factory, companyCode, () => SeedCoreAsync(companyCode, cancellationToken), cancellationToken)
: Task.CompletedTask;
}
private async Task SeedCoreAsync(string companyCode, CancellationToken cancellationToken)
{
if (!licenses.IsModuleActive(ModuleCodes.Accounting))
{
return;
}
var pack = await packs.PackOfAsync(companyCode, cancellationToken).ConfigureAwait(false);
var today = DateOnly.FromDateTime(TimeZoneInfo.ConvertTime(clock.GetUtcNow(), TimeZoneInfo.Local).DateTime);
var start = new DateOnly(today.Year, 1, 1);
await using (var uow = await factory.CreateAsync(DatabaseScope.Company(companyCode), cancellationToken).ConfigureAwait(false))
{
if (await uow.Repository<GlAccount, long>().CountAsync(Query.For<GlAccount>(), cancellationToken).ConfigureAwait(false) == 0
|| await uow.Repository<FixedAsset, long>().CountAsync(Query.For<FixedAsset>(), cancellationToken).ConfigureAwait(false) > 0
|| await uow.Repository<AccrualDeferral, long>().CountAsync(Query.For<AccrualDeferral>(), cancellationToken).ConfigureAwait(false) > 0
|| await uow.Repository<GlEntry, long>().CountAsync(Query.For<GlEntry>().Where(e => e.EntryDate == start && e.Source == GlEntrySource.Manual), cancellationToken)
.ConfigureAwait(false) > 0)
{
return;
}
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
await OpeningAsync(uow, pack, today, cancellationToken).ConfigureAwait(false);
await InsuranceAsync(uow, today, cancellationToken).ConfigureAwait(false);
if (pack.GetFeature<IIntentRules>() is { } intent)
{
await IntentDeclarationService.AdoptAsync(uow, intent, null, cancellationToken).ConfigureAwait(false);
}
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
}
await InvoicesAsync(companyCode, today, cancellationToken).ConfigureAwait(false);
await ledger.PostPendingAsync(Seed, companyCode, start, today, cancellationToken: cancellationToken).ConfigureAwait(false);
}
// The opening entry of the year and the fixed assets: three bought in the years before (cost and funds in the
// opening entry) and the computers bought in March and paid by bank transfer.
private async Task OpeningAsync(IUnitOfWork uow, IFiscalPack pack, DateOnly today, CancellationToken cancellationToken)
{
var accounts = await YearEndLedger.AccountsByCodeAsync(uow, cancellationToken).ConfigureAwait(false);
if (pack.GetFeature<IClosingRules>() is not { } closing
|| !accounts.TryGetValue(closing.Accounts.Capital, out var capital) || !accounts.TryGetValue(DemoLedgerSeeder.BankAccount, out var bank))
{
return;
}
var year = today.Year;
var start = new DateOnly(year, 1, 1);
var lines = new List<EntryLineDraft>();
var assets = new List<AssetInput>();
if (licenses.IsModuleActive(ModuleCodes.Assets) && pack.GetFeature<IFixedAssetRules>() is { } rules)
{
await FixedAssetService.CreateStandardCategoriesAsync(uow, rules.Coefficients, Seed.UserName, true, cancellationToken).ConfigureAwait(false);
var categories = (await FixedAssetService.CategoriesAsync(uow, cancellationToken).ConfigureAwait(false)).ToDictionary(c => c.Code, StringComparer.Ordinal);
void Add(string category, string description, int yearsBack, decimal cost, decimal fund, string? serial = null, string? location = null)
{
if (!categories.TryGetValue(category, out var c) || c.AssetAccountId is not { } asset || c.FundAccountId is not { } fundAccount)
{
return;
}
var bought = new DateOnly(year - yearsBack, 3, 15);
assets.Add(new AssetInput(null, null, description, c.Id, bought, bought, cost)
{
OpeningCivilFund = fund,
OpeningFiscalFund = fund,
LastDepreciationYear = yearsBack > 0 ? year - 1 : null,
SerialNumber = serial,
Location = location,
});
if (yearsBack > 0)
{
lines.Add(new EntryLineDraft(asset, null, description, cost, 0m));
lines.Add(new EntryLineDraft(fundAccount, null, description, 0m, fund));
}
}
// Funds: the civil quotas of the years before, half in the first year.
Add("AUC", "Furgone Fiat Ducato 2.3 Multijet", 3, 32_000m, 16_000m, "ZFA25000002K12345", "Sede");
Add("ATT", "Scaffalature metalliche magazzino", 2, 18_400m, 4_140m, null, "Magazzino");
Add("MOB", "Arredi ufficio commerciale", 4, 9_600m, 4_032m, null, "Uffici");
Add("EDP", "Server e personal computer", 0, 6_500m, 0m, "SRV-2026-001", "Sala server");
}
// The opening stock of the demo warehouse (the inventory entry of the first of January) at its cost.
var stock = (await InventoryService.ValuationAsync(uow, start, null, StockValuationMethod.WeightedAverage, cancellationToken).ConfigureAwait(false)).Sum(r => r.Value);
if (stock > 0m && accounts.TryGetValue(closing.Accounts.Inventory, out var inventory))
{
lines.Add(new EntryLineDraft(inventory.Id, null, "Rimanenze iniziali", Math.Round(stock, 2, MidpointRounding.AwayFromZero), 0m));
}
lines.Add(new EntryLineDraft(bank.Id, null, null, OpeningBank, 0m));
lines.Add(new EntryLineDraft(capital.Id, null, null, 0m, ShareCapital));
if (accounts.TryGetValue(RetainedEarnings, out var retained))
{
var balance = lines.Sum(l => l.Debit - l.Credit);
lines.Add(new EntryLineDraft(retained.Id, null, null, balance < 0m ? -balance : 0m, balance > 0m ? balance : 0m));
}
await YearEndLedger.PostAsync(uow, start, "Apertura conti (dati dimostrativi)", GlEntrySource.Manual, null, lines, true, cancellationToken).ConfigureAwait(false);
foreach (var input in assets)
{
await FixedAssetService.SaveAsync(uow, pack.Require<IFixedAssetRules>(), input, Seed.UserName, true, cancellationToken).ConfigureAwait(false);
if (input.LastDepreciationYear is null
&& (await FixedAssetService.CategoriesAsync(uow, cancellationToken).ConfigureAwait(false)).FirstOrDefault(c => c.Id == input.CategoryId) is { AssetAccountId: { } account })
{
// Bought this year: the purchase, paid by bank transfer (the invoice of the supplier is not part of the demo).
var bought = input.PurchaseDate;
await YearEndLedger.PostAsync(uow, bought <= today ? bought : today, "Acquisto " + input.Description.ToLowerInvariant(), GlEntrySource.Manual, null,
[new EntryLineDraft(account, null, null, input.Cost, 0m), new EntryLineDraft(bank.Id, null, null, 0m, input.Cost)], true, cancellationToken)
.ConfigureAwait(false);
}
}
}
// The insurance premium of the van, paid on the first of October for a year: three months fall in this year, nine
// in the next (prepaid expense).
private static async Task InsuranceAsync(IUnitOfWork uow, DateOnly today, CancellationToken cancellationToken)
{
var accounts = await YearEndLedger.AccountsByCodeAsync(uow, cancellationToken).ConfigureAwait(false);
var paid = new DateOnly(today.Year, 10, 1);
if (paid > today || !accounts.TryGetValue(InsuranceAccount, out var insurance) || !accounts.TryGetValue(DemoLedgerSeeder.BankAccount, out var bank))
{
return;
}
const string description = "Premio assicurazione furgone 01/10 - 30/09";
await YearEndLedger.PostAsync(uow, paid, description, GlEntrySource.Manual, null,
[new EntryLineDraft(insurance.Id, null, null, InsurancePremium, 0m), new EntryLineDraft(bank.Id, null, null, 0m, InsurancePremium)], true, cancellationToken)
.ConfigureAwait(false);
await AccrualService.SaveAsync(uow, new AccrualDeferral
{
Year = today.Year,
Kind = AccrualKind.PrepaidExpense,
Description = description,
AccountId = insurance.Id,
Amount = InsurancePremium,
PeriodStart = paid,
PeriodEnd = paid.AddYears(1).AddDays(-1),
DocumentNumber = "POL-4471",
}, Seed.UserName, true, cancellationToken).ConfigureAwait(false);
}
// An invoice under the declaration of intent of Idrotermica Piemonte (NI8C) and an intra-EU sale of goods to
// Bergwerk Bau (NI41), both of today so that the numbering stays in date order.
private async Task InvoicesAsync(string company, DateOnly today, CancellationToken cancellationToken)
{
Dictionary<string, long> parties;
List<Item> goods;
Dictionary<string, long> taxCodes;
await using (var uow = await factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false))
{
parties = (await uow.Repository<Party, long>().ListAsync(Query.For<Party>().Where(p => p.IsDemo), cancellationToken).ConfigureAwait(false)).Items
.GroupBy(p => p.Name, StringComparer.Ordinal).ToDictionary(g => g.Key, g => g.First().Id, StringComparer.Ordinal);
goods = [.. (await uow.Repository<Item, long>().ListAsync(Query.For<Item>().Where(i => i.IsDemo && i.Kind == ItemKind.Goods), cancellationToken).ConfigureAwait(false)).Items
.OrderBy(i => i.Id)];
taxCodes = (await uow.Repository<TaxCode, long>().ListAsync(Query.For<TaxCode>(), cancellationToken).ConfigureAwait(false)).Items
.GroupBy(t => t.Code, StringComparer.Ordinal).ToDictionary(g => g.Key, g => g.First().Id, StringComparer.Ordinal);
if (await uow.Repository<SaleDocument, long>().CountAsync(Query.For<SaleDocument>(), cancellationToken).ConfigureAwait(false) == 0)
{
return; // No demo sales: the documents would open the numbering.
}
}
var intrastat = goods.Where(i => !string.IsNullOrEmpty(i.CustomsCode) && i.NetWeight is > 0m).Take(2).ToList();
if (parties.TryGetValue("Idrotermica Piemonte S.r.l.", out var idrotermica) && taxCodes.TryGetValue("NI8C", out var ni8c) && goods.Count > 3)
{
await InvoiceAsync(company, idrotermica, today, [(goods[1], 40m), (goods[3], 25m)], ni8c, "Fornitura in sospensione d'imposta", cancellationToken).ConfigureAwait(false);
}
if (licenses.IsModuleActive(ModuleCodes.Intrastat) && parties.TryGetValue("Bergwerk Bau GmbH", out var bergwerk) && taxCodes.TryGetValue("NI41", out var ni41)
&& intrastat.Count > 0)
{
await InvoiceAsync(company, bergwerk, today, [.. intrastat.Select(i => (i, 30m))], ni41, "Consegna franco destino Innsbruck", cancellationToken).ConfigureAwait(false);
}
}
private async Task InvoiceAsync(
string company, long partyId, DateOnly date, IReadOnlyList<(Item Item, decimal Quantity)> lines, long taxCodeId, string notes, CancellationToken cancellationToken)
{
var record = await engine.NewAsync(Seed, company, "FI", cancellationToken).ConfigureAwait(false);
record.Header.IsDemo = true;
record.Header.DocumentDate = date;
record.Header.Notes = notes;
await editor.ApplyPartyAsync(Seed, company, record, partyId, cancellationToken).ConfigureAwait(false);
foreach (var (item, quantity) in lines)
{
var line = DocumentStores.Of(record.Family).NewLine();
line.Quantity = quantity;
await editor.FillLineAsync(Seed, company, record, line, item.Id, cancellationToken).ConfigureAwait(false);
line.TaxCodeId = taxCodeId;
record.Lines.Add(line);
}
record = await engine.SaveAsync(Seed, company, record, cancellationToken).ConfigureAwait(false);
await engine.ConfirmAsync(Seed, company, record.Family, record.Header.Id, cancellationToken).ConfigureAwait(false);
}
}
Loaded 100 of 241 files, more files were not shown because too many files have changed in this diff. Show more