Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
246d6f9357 | ||
|
|
b78260beb0 | ||
|
|
9d7cb9e71f | ||
|
|
fb12411404 | ||
|
|
709bb13532 | ||
|
|
0debd82983 | ||
|
|
f38b5894ce | ||
|
|
aef0a0d233 | ||
|
|
4014373797 | ||
|
|
5bbc2120a1 | ||
|
|
562bf98092 | ||
|
|
5fbbe4d3a4 | ||
|
|
b12dc79317 | ||
|
|
88a0c8ce9c | ||
|
|
cfca29d71c | ||
|
|
9e3ba92993 | ||
|
|
838362bfe1 | ||
|
|
7f8cb57a08 | ||
|
|
4b759ee96e | ||
|
|
cd4cb85562 | ||
|
|
ced689b297 | ||
|
|
eb301fa570 | ||
|
|
f8b72f4d17 | ||
|
|
eeabb12f96 | ||
|
|
20b2421eea | ||
|
|
9a40adecfe | ||
|
|
2c56c0dff0 |
No files matched your search
@@ -7,6 +7,218 @@ un'immagine `gitea.encke-hake.ts.net/balbosoft/khaemhat:X.Y.Z`.
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
## [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,
|
||||
con le righe IVA nel suo registro, le partite aperte e la ritenuta; la prima nota in partita doppia con registrazioni
|
||||
provvisorie, definitive e storni; registri IVA, liquidazione periodica con F24 e LIPE, ritenute, bollo virtuale,
|
||||
partitari, mastrini e bilancio di verifica.
|
||||
|
||||
### Added
|
||||
- Piano dei conti a tre livelli (#62, ADR 0036): mastro, conto e sottoconto (`MM.CC.SSS`), natura, tipo, voce CEE,
|
||||
partitario, rilevanza IVA; modello italiano *PMI standard* di 237 conti nel pacchetto fiscale
|
||||
(`ItalianLedgerTemplate`), albero con ricerca, scheda e mastrino con saldo progressivo e stampa.
|
||||
- Causali contabili con righe proposte, registro IVA, apertura delle partite e causale di storno (#62): `FV`, `NCV`,
|
||||
`FA`, `NCA`, `AFRC`, `CORR`, `INC`, `PAG`, `RIT`, `RITS`, `LIQ`, `F24`, `GIRO`, `SPB`, `STO` e altre.
|
||||
- Prima nota (#63): registrazioni in partita doppia con cliente o fornitore sui conti con partitario, centro di
|
||||
costo e righe IVA; bozza, registrata (numero per anno) e definitiva (numero del libro giornale) con *Rendi
|
||||
definitive*; storno; *Chiudi lo sbilancio*; filtri e paginazione.
|
||||
- Registrazioni ricorrenti (#63): copia di una registrazione modello mensile, trimestrale, semestrale o annuale fino
|
||||
a una data, job di sistema `ledger.recurring` ogni giorno alle 5:00 e *Genera ora*.
|
||||
- Contabilizzazione automatica dei documenti (#64, ADR 0037): fatture, note di debito, parcelle, note di credito,
|
||||
fatture e note fornitore, autofatture e integrazioni scrivono la registrazione alla conferma (`PostingEngine`,
|
||||
`LedgerPoster`), la riscrivono con lo stesso numero alla modifica e la tolgono o la stornano all'annullamento;
|
||||
scissione dei pagamenti, IVA indetraibile sul costo, rivalsa cassa e bollo; *Contabilizza documenti* per i
|
||||
documenti confermati prima.
|
||||
- Registri IVA vendite, acquisti, autofatture e corrispettivi (#65) con riepilogo per aliquota, stampa di prova e
|
||||
definitiva con numerazione delle pagine.
|
||||
- Liquidazione IVA mensile o trimestrale (#65): IVA a debito e a credito, pro rata, credito e debito riportati,
|
||||
interessi trimestrali, minimo di versamento, acconto di dicembre (storico, previsionale, effettivo); conferma con la
|
||||
registrazione `LIQ`, il blocco dei periodi e il versamento F24; riapertura; file della comunicazione LIPE
|
||||
(`IVP18`) e dati F24. Regole e codici tributo nel pacchetto italiano (`VatSettlementRulesIt`).
|
||||
- Ritenute d'acconto operate e subite (#66): da versare quando la fattura del professionista è pagata, registrazioni
|
||||
`RIT` e `RITS`, codice 1040 al 16 del mese dopo; dati della certificazione unica in CSV.
|
||||
- Bollo virtuale per trimestre (#66) con soglia dei 5.000 euro, codici 2521-2524 e scadenze.
|
||||
- Prospetto F24 per scadenza (#66) con export dei dati e registrazione del pagamento `F24` sulla banca
|
||||
dell'azienda.
|
||||
- Partitari clienti e fornitori con estratto conto e partite aperte, bilancio di verifica per mastri, conti e
|
||||
sottoconti con centro di costo e risultato del periodo, libro giornale di prova e definitivo in PDF (#67).
|
||||
- Menu *Contabilità*; testi in `Resources/it-IT/Ledger.json`; permessi `ledger.account.*`, `ledger.entry.*`,
|
||||
`vat.register.read`, `vat.settlement.*`.
|
||||
- Contabilità nei dati di esempio (#68): documenti contabilizzati, fattura del professionista pagata, noleggio
|
||||
mensile della stampante come ricorrente, liquidazioni dei mesi passati confermate e F24 scaduti pagati.
|
||||
- Tabelle `gl_accounts`, `gl_journal_templates`, `gl_journal_template_lines`, `gl_entries`, `gl_entry_lines`,
|
||||
`gl_entry_vat`, `gl_open_items`, `gl_recurring_entries`, `vat_registers`, `vat_register_prints`,
|
||||
`vat_settlements`, `vat_settlement_lines`, `tax_payments`, `withholdings` (migrazione `M20261113_002`).
|
||||
- ADR 0036 e 0037; pagine wiki *Contabilità*, *IVA* e *Fiscalità italiana* complete con le schermate.
|
||||
|
||||
### Changed
|
||||
- *Bollo virtuale* passa dal menu *Fatturazione elettronica* al menu *Contabilità*.
|
||||
- Il seed di base e *Aggiorna da tabelle base* aggiungono piano dei conti, causali e registri IVA alle aziende
|
||||
esistenti.
|
||||
|
||||
## [0.6.0] - 2026-11-12
|
||||
|
||||
M6 — Acquisti e Magazzino. Il ciclo passivo dall'ordine al fornitore alla fattura protocollata, le fatture
|
||||
elettroniche ricevute importate in bozza, le autofatture con la loro scadenza e un magazzino che si aggiorna da solo
|
||||
con i documenti: giacenze per deposito, costo medio, inventario, riordino e valorizzazione.
|
||||
|
||||
### Added
|
||||
- Movimenti di magazzino dai documenti (#59, ADR 0035): alla conferma DDT, fatture immediate e accompagnatorie, note,
|
||||
DDT e fatture fornitore, note di credito fornitore e movimenti `MM` scrivono i loro movimenti nella stessa
|
||||
transazione (`inventory_entries`, `inventory_entry_lines`); l'annullamento li toglie. La causale del tipo documento
|
||||
decide carico, scarico o trasferimento; la fattura di un DDT non muove di nuovo la merce, la nota di credito la
|
||||
muove all'inverso. Tabella `item_balances` con giacenza per deposito, impegnato (ordini clienti) e ordinato
|
||||
(ordini fornitore).
|
||||
- Costo medio ponderato per articolo ricalcolato dalla storia dei movimenti a ogni modifica, anche per documenti con
|
||||
data passata; ultimo costo e date di ultimo carico e scarico; il prezzo della fattura fornitore corregge il costo
|
||||
dei carichi che fattura.
|
||||
- Documenti del ciclo passivo nelle maschere dei documenti (#55, #56, #58): ordini fornitori, ricevimenti merce (DDT
|
||||
fornitore con il numero e la data del fornitore), fatture e note di credito fornitore con **protocollo** IVA alla
|
||||
conferma e rifiuto del doppio numero del fornitore nello stesso anno, autofatture e movimenti di magazzino con
|
||||
causale e depositi. Menu *Acquisti* e *Magazzino*.
|
||||
- Controllo dei prezzi: sulla fattura fornitore un avviso elenca le righe con un prezzo diverso dall'ordine o dal
|
||||
ricevimento e la differenza totale.
|
||||
- Autofatture e integrazioni: il pacchetto italiano (`SelfInvoiceRulesIt`) riconosce dalla fattura del fornitore
|
||||
l'integrazione dovuta (TD16, TD17, TD18, TD19, TD28) e la scadenza; la fattura lo mostra con **Crea autofattura**,
|
||||
che prepara la bozza con l'aliquota ordinaria; *Acquisti → Autofatture* elenca le integrazioni da emettere. Tipi
|
||||
`AF20`-`AF29` nelle tabelle di base.
|
||||
- Lettura delle fatture elettroniche ricevute (#57): `FatturaPaReader` (FPR12, FPA12, FSM10, lotti, allegati) e
|
||||
lettore CMS/CAdES dei file `.p7m` con verifica dell'impronta e della firma, scritti in casa.
|
||||
- Import delle fatture passive (#57): *Acquisti → Importa fatture* legge XML, P7M e ZIP, trova o crea il fornitore,
|
||||
segnala doppioni, tipi non d'acquisto, totali diversi e firme non verificate, e registra in bozza fatture (TD01,
|
||||
TD02, TD03, TD05, TD06, TD24-TD27) e note di credito (TD04, TD08) con articoli abbinati per codice del fornitore,
|
||||
EAN e codice, codice IVA per aliquota e natura, sconti di riga e file allegato. Le regole TD stanno nel pacchetto
|
||||
fiscale (`IncomingInvoiceRulesIt`).
|
||||
- Giacenze e disponibilità (#60): indicatori, filtri per deposito, categoria e stato (*Disponibile*, *Da riordinare*,
|
||||
*Sottoscorta*, *Esaurito*), movimenti di un articolo con saldo progressivo.
|
||||
- Inventario fisico (#60): apertura per deposito, data e categoria con la giacenza contabile congelata, conteggi
|
||||
scritti o importati dal file del lettore, rettifiche `INVP` e `INVN` alla data del conteggio; tabelle `stock_takes`
|
||||
e `stock_take_lines`.
|
||||
- Proposta di riordino (#60): articoli sotto il punto di riordino o la scorta minima, quantità dal lotto o dalla
|
||||
soglia con il minimo d'ordine del fornitore, fornitore preferito con prezzo e arrivo previsto, ordini fornitore in
|
||||
bozza uno per fornitore.
|
||||
- Valorizzazione a data con costo medio, ultimo costo o costo standard e classi ABC; ricostruzione del magazzino da
|
||||
interfaccia con avanzamento e come job di sistema `inventory.rebuild` ogni domenica alle 2:15.
|
||||
- Widget *Sottoscorta* della dashboard con i dati veri.
|
||||
- Dati di esempio di acquisti e magazzino (#61): esistenze iniziali, ordini ricevuti per intero e in parte, fatture
|
||||
con una differenza di prezzo e una integrazione AF18 da emettere, un inventario in conteggio.
|
||||
- ADR 0035; pagine wiki *Acquisti* e *Magazzino* complete con le schermate, guida all'uso aggiornata.
|
||||
|
||||
### Changed
|
||||
- Import *Giacenze iniziali*: non è più solo verifica, scrive e conferma un movimento `APE` per deposito.
|
||||
- I documenti confermati senza numero interno (DDT fornitore) si presentano come *Senza numero* invece di *Bozza*.
|
||||
- *Tipi documento*: fattura immediata, fattura e nota di credito fornitore ricevono la causale di magazzino (`SCA`,
|
||||
`CAR`, `RESF`); la migrazione la assegna anche nelle aziende esistenti dove manca. I tipi `AF20`-`AF29` mancanti si
|
||||
aggiungono con *Aggiorna da tabelle base* o `scripts/seed.sh --base`.
|
||||
|
||||
## [0.5.0] - 2026-11-12
|
||||
|
||||
M5 — Motore documenti e Vendite. Un solo motore per tutti i documenti, con numerazione, totali, scadenze e
|
||||
|
||||
@@ -206,28 +206,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
|
||||
|
||||
|
||||
@@ -2,19 +2,29 @@
|
||||
|
||||
> Punto di ripresa per ogni sessione. Aggiornare a fine sessione.
|
||||
|
||||
**Ultimo aggiornamento:** 2026-11-12
|
||||
**Milestone corrente:** M6 — Acquisti e Magazzino (issue #55-#61), **non ancora iniziata**: si parte quando il
|
||||
titolare lo dice. M5 chiusa: PR #124 in `main`, tag `v0.5.0`, immagine e release.
|
||||
**Prossimo passo:** M6 dall'issue #55. #35 (PNG ad alta risoluzione) resta aperta e non blocca; #45 resta aperta solo
|
||||
**Ultimo aggiornamento:** 2026-11-13
|
||||
**Milestone corrente:** M10 — Cespiti, Intrastat, chiusura e bilancio (issue #82-#87), da iniziare. M9 chiusa: PR in
|
||||
`main`, tag `v0.9.0`, immagine e release.
|
||||
**Prossimo passo:** M10 dall'issue #82. #35 (PNG ad alta risoluzione) resta aperta e non blocca; #45 resta aperta solo
|
||||
per le banche ABI/CAB (manca una fonte con licenza compatibile).
|
||||
Da recuperare: misure di riferimento su PostgreSQL in `docs/DATA-MODEL.md` §6.1; indicatore di robustezza della
|
||||
password (mockup 003); schede *Layout salvati* e *Notifiche* del profilo; rinomina e filtro predefinito nei radar;
|
||||
logo PNG nel PDF (oggi solo JPEG, ADR 0034); coda della posta persistente e modelli e-mail per azienda (M12).
|
||||
Da M6: schermata dell'import fatture con file caricati (serve un caricamento via CDP); nei movimenti di un articolo il
|
||||
numero del fornitore al posto di *DDT fornitore* senza numero; FIFO e LIFO a lotti (dopo la 1.0).
|
||||
Da M7: schermata del bollo virtuale (la demo non ha fatture esenti sopra 77,47 euro); import di causali e voci di
|
||||
bilancio dal file `khaemhat-coa.json`; scritture delle rimanenze e libro inventari (M10); 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, ADR 0040); conformità PDF/A-3 dichiarata della copia di cortesia;
|
||||
pulsanti *Carica* e *Rimuovi dati di esempio* nell'interfaccia (M12); dichiarazioni d'intento (M10).
|
||||
|
||||
## Fatto
|
||||
|
||||
- Specifica normativa in `docs/SPEC.md`; `CLAUDE.md` con emendamenti E1-E7.
|
||||
- ADR 0001-0034.
|
||||
- ADR 0001-0040.
|
||||
- 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`,
|
||||
@@ -66,6 +76,37 @@ logo PNG nel PDF (oggi solo JPEG, ADR 0034); coda della posta persistente e mode
|
||||
e-mail con SMTP e coda scritti in casa (#52, ADR 0034); log *Documenti*; profilo e un anno di vendite di esempio;
|
||||
wiki con la *Guida all'uso* e le schermate reali, README come guida per sviluppatori (#53). Test: 660 verdi in
|
||||
locale, 23 di PostgreSQL saltati (girano in CI).
|
||||
- **M6 (chiusa, `v0.6.0`, PR #125):** movimenti di magazzino dai documenti nella
|
||||
stessa transazione, costo medio ponderato ricalcolato dalla storia, impegnato e ordinato, correzione del costo dalla
|
||||
fattura fornitore (#59, ADR 0035); ordini fornitori, ricevimenti, fatture e note di credito fornitore con protocollo,
|
||||
doppioni rifiutati, controllo dei prezzi, autofatture TD16-TD29 consigliate dal pacchetto italiano con scadenza
|
||||
(#55, #56, #58); lettura FatturaPA e `.p7m` (CMS scritto in casa) e import delle fatture passive in bozza (#57);
|
||||
giacenze, movimenti di un articolo, inventario fisico, proposta di riordino, valorizzazione con classi ABC,
|
||||
ricostruzione anche come job settimanale, widget *Sottoscorta* (#60); giacenze iniziali da file con movimento `APE`;
|
||||
acquisti e magazzino nei dati di esempio, wiki *Acquisti* e *Magazzino* con le schermate, guida all'uso (#61).
|
||||
Test: 709 verdi in locale, 23 di PostgreSQL saltati (girano in CI).
|
||||
- **M7 (chiusa, `v0.7.0`):** piano dei conti a tre livelli con il modello *PMI standard* di 237 conti, causali con righe
|
||||
proposte (#62, ADR 0036); prima nota con bozze, registrazioni, definitive con numero del libro giornale e storni,
|
||||
ricorrenti con job giornaliero (#63); contabilizzazione automatica di fatture, note, parcelle e autofatture nella
|
||||
transazione del documento con righe IVA, partite e ritenute (#64, ADR 0037); registri IVA con stampa definitiva,
|
||||
liquidazione mensile o trimestrale con pro rata, interessi, minimo, acconto, F24 e LIPE (#65); ritenute operate e
|
||||
subite, dati CU, bollo virtuale con soglie, prospetto F24 con pagamento (#66); partitari, mastrini, bilancio di
|
||||
verifica, libro giornale (#67); contabilità nei dati di esempio con la liquidazione verificata a mano in un test,
|
||||
wiki *Contabilità*, *IVA* e *Fiscalità italiana* con le schermate (#68). Test: 754 verdi in locale, 23 di PostgreSQL saltati (girano in CI).
|
||||
- **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.
|
||||
- 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,
|
||||
@@ -112,12 +153,12 @@ Emersi durante la stesura della documentazione. Si decidono con un ADR quando si
|
||||
|
||||
### Contabilità, IVA, e-fattura, CRM (dalla stesura delle pagine funzionali)
|
||||
|
||||
12. Scadenza IVA di settembre: mockup 046 la mette al 16/10/2026, mockup 047 nell'F24 del 16/11/2026 (corretto: 16/10 per i mensili).
|
||||
12. Scadenza IVA di settembre: mockup 046 la mette al 16/10/2026, mockup 047 nell'F24 del 16/11/2026 (corretto: 16/10 per i mensili). **Deciso in M7: ADR 0037, il 16 del mese successivo.**
|
||||
13. Bollo sulle cessioni intracomunitarie: il mockup 060 lo addebita su N3.2, ma cessioni intra-UE ed esportazioni ne sono esenti; la regola del bollo va legata al codice IVA con esclusioni.
|
||||
14. Funzioni di fase 2 nelle schermate di M7: ventilazione dei corrispettivi (046) e IVA per cassa completa sono in M14 per §20.
|
||||
14. Funzioni di fase 2 nelle schermate di M7: ventilazione dei corrispettivi (046) e IVA per cassa completa sono in M14 per §20. **Confermato in M7: non implementate.**
|
||||
15. Moduli ambigui: bollo e dichiarazioni d'intento sotto ACCT e EINV (§8.1); export commercialista sotto ACCT e REPORT; Intrastat e LIPE nel menu e-fattura nei mockup; §10.2 senza voce Intrastat.
|
||||
16. Stato "Provvisorio" dell'esercizio nel mockup 052, non previsto da SPEC (aperto / in chiusura / chiuso).
|
||||
17. Codici conto incoerenti tra mockup (fornitori 05.02.001 in 040/043, 02.03.001 in 042).
|
||||
17. Codici conto incoerenti tra mockup (fornitori 05.02.001 in 040/043, 02.03.001 in 042). **Deciso in M7: ADR 0036, piano PMI standard (clienti 05.01.001, fornitori 14.01.001).**
|
||||
18. Regola R-005 del mockup 072 "riapre in bozza" una fattura scartata: contrasta con l'immutabilità della fattura emessa.
|
||||
19. Codice campagne `CMP-…` (068) non presente nelle maschere di §11.12.
|
||||
20. Codice di scarto 00327 citato in §18 senza descrizione.
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
# ADR 0035 - Magazzino e ciclo passivo
|
||||
|
||||
- **Stato:** accettata
|
||||
- **Data:** 2026-11-12
|
||||
- **Modifica:** SPEC §11.5, §11.6, §12.12; milestone M6, issue #55-#61
|
||||
|
||||
## Contesto
|
||||
|
||||
SPEC §11.6 chiede giacenze per deposito con impegnato, ordinato e disponibile aggiornati nella stessa transazione del
|
||||
documento, costo medio ponderato (FIFO e LIFO predisposti), inventario fisico, proposta di riordino, valorizzazione a
|
||||
data e una ricostruzione; §11.5 il ciclo passivo con protocollo IVA, import delle fatture elettroniche ricevute,
|
||||
controllo dei prezzi rispetto all'ordine e autofatture TD16-TD29. Il motore documenti di M5 (ADR 0032) sa già quali
|
||||
generi hanno effetto *Inventory*; restavano aperti: come si registra un movimento, come si calcola il costo quando i
|
||||
documenti arrivano fuori ordine di data, come non contare due volte la merce di una fattura nata da un DDT, come
|
||||
portare le novità nelle aziende create prima, dove stanno le regole italiane di autofatture e import.
|
||||
|
||||
## Decisione
|
||||
|
||||
1. **La causale decide, il genere filtra.** Ogni tipo documento ha una causale di magazzino (`inventory_reasons`:
|
||||
carico, scarico, nessun effetto; flag *trasferimento* e *muove il valore*). `StockEffectMatrix` (in `Khaemhat.Core`)
|
||||
dice quali generi la applicano (DDT, fatture immediate e accompagnatorie, note, DDT e fatture fornitore, note di
|
||||
credito fornitore, movimenti `MM`) e quali hanno costi d'acquisto che muovono la media (DDT fornitore, fattura
|
||||
fornitore, movimento con prezzo). Ordini clienti e fornitori non muovono la giacenza: il loro **residuo** è
|
||||
l'impegnato e l'ordinato. Le causali di base sono 12 (`CAR`, `SCA`, `RESC`, `RESF`, `TRA`, `INVP`, `INVN`, `CVU`,
|
||||
`CVR`, `OMA`, `AUTO`, `APE`).
|
||||
2. **Movimenti come righe derivate.** `InventoryPoster` gira dentro la transazione del motore documenti: alla conferma
|
||||
scrive un `inventory_entries` per documento con una riga per articolo e deposito (`inventory_entry_lines`, quantità
|
||||
nell'unità base, con segno); all'annullamento o alla modifica di un documento in vigore lo riscrive da capo. Le righe
|
||||
che vengono da un documento che ha già mosso la merce nello stesso verso (la fattura di un DDT) sono saltate;
|
||||
la nota di credito di una fattura la muove all'inverso.
|
||||
3. **Storia ricalcolata, non saldi incrementali.** Dopo ogni modifica la storia degli articoli toccati viene
|
||||
ripercorsa per data e ordine di registrazione (`StockCostCalculator`): giacenza per deposito, costo medio ponderato
|
||||
dell'articolo su tutti i depositi, ultimo costo, date di ultimo carico e scarico, e i risultati vanno in
|
||||
`item_balances` e nella scheda articolo. Così un documento con una data passata dà lo stesso risultato di uno
|
||||
inserito in ordine. Ogni carico con valore sposta la media; gli altri movimenti escono alla media del momento; con
|
||||
giacenza a zero o negativa il carico successivo fissa la media. La giacenza negativa non blocca la conferma (non
|
||||
si fermano le consegne), si vede nelle giacenze e nella dashboard.
|
||||
4. **La fattura corregge il costo del carico.** Il prezzo di una fattura fornitore confermata sostituisce, per la quota
|
||||
fatturata, il costo dei carichi dei DDT fornitore che fattura; la differenza di prezzo rispetto a ordine e ricevimento
|
||||
è anche mostrata come avviso sulla fattura (`PurchaseService.PriceDifferencesAsync`), senza bloccare.
|
||||
5. **Ricostruzione.** `InventoryService.RebuildAsync` cancella i movimenti e riposta tutti i documenti in vigore,
|
||||
dal più vecchio e, a parità di data, i DDT prima delle fatture, poi ricalcola ogni articolo; gira a mano (con
|
||||
avanzamento) e ogni domenica come job di sistema `inventory.rebuild`.
|
||||
6. **Inventario come documento a sé.** `stock_takes` e `stock_take_lines` fotografano la giacenza contabile alla
|
||||
data del conteggio; la registrazione crea due movimenti `MM` (`INVP` e `INVN`) alla stessa data. Gli articoli non
|
||||
contati non vengono toccati; non c'è blocco dei movimenti durante il conteggio, perché le rettifiche sono datate
|
||||
e la storia ricalcolata tiene conto dei movimenti successivi.
|
||||
7. **Valorizzazione.** Costo medio ponderato, ultimo costo e costo standard a qualsiasi data, con classi ABC (80% e
|
||||
95% del valore). FIFO e LIFO restano **predisposti**: il criterio è un parametro del calcolo
|
||||
(`StockValuationMethod`) e i movimenti conservano data, quantità e costo di ogni carico, ma i due metodi non sono
|
||||
ancora offerti perché richiedono i lotti di carico, rimandati a dopo la 1.0.
|
||||
8. **Tabelle di base nelle aziende esistenti.** La migrazione `M20261113_001_CreateInventory` crea le tabelle e
|
||||
assegna la causale ai tipi di base che non l'hanno (`FI` → `SCA`, `FF` → `CAR`, `NCF` → `RESF`), senza toccare una
|
||||
causale scelta dall'utente. I tipi nuovi (`AF20`-`AF29`) e le causali mancanti si aggiungono con *Aggiorna da
|
||||
tabelle base* o `scripts/seed.sh --base`, che aggiungono i codici mancanti senza modificare quelli esistenti
|
||||
(ADR 0026). Il tracciato
|
||||
*Giacenze iniziali* scrive un movimento `APE` per deposito.
|
||||
9. **Regole italiane nel pacchetto fiscale.** `ISelfInvoiceRules` (`SelfInvoiceRulesIt`) decide dall'anagrafica del
|
||||
fornitore (paese, UE), dal genere delle righe (beni o servizi) e dalle nature IVA quale autofattura serve (TD16,
|
||||
TD17, TD18, TD19, TD28) e la scadenza (15 del mese successivo; 90 giorni per TD20 e TD29).
|
||||
`IIncomingInvoiceRules` (`IncomingInvoiceRulesIt`) traduce il tipo FatturaPA nel tipo documento d'acquisto (TD01,
|
||||
TD02, TD03, TD05, TD06, TD24-TD27 in `FF`; TD04 e TD08 in `NCF`; gli altri sono rifiutati). L'applicazione non
|
||||
conosce i codici TD.
|
||||
10. **Import delle fatture ricevute.** `PurchaseInvoiceImportService` legge XML, P7M e ZIP con il lettore di #57, trova
|
||||
il fornitore per partita IVA o codice fiscale (o lo crea), rifiuta i doppioni (stesso fornitore, numero, anno),
|
||||
abbina le righe per codice del fornitore, EAN e codice articolo, il codice IVA per aliquota e natura, porta gli
|
||||
sconti percentuali nello sconto di riga e gli altri nel prezzo netto, e salva una bozza con il file allegato.
|
||||
Totale diverso, firma non verificata e sconti sul totale sono avvisi, non errori.
|
||||
|
||||
## Conseguenze
|
||||
|
||||
- Le quantità e i costi sono sempre ricostruibili dai documenti: i movimenti sono un dato derivato e la ricostruzione
|
||||
è anche la verifica di coerenza.
|
||||
- Ricalcolare la storia di un articolo costa più di un aggiornamento incrementale; con le dimensioni di una PMI
|
||||
(migliaia di movimenti per articolo all'anno) resta nell'ordine dei millisecondi, e i documenti toccano pochi
|
||||
articoli alla volta. Se servirà, un punto di partenza annuale (chiusura del magazzino) accorcia la storia.
|
||||
- I documenti fornitore senza numero interno (`DDTF`) si riconoscono dal numero del fornitore; l'interfaccia li mostra
|
||||
come *Senza numero*.
|
||||
- Rimandati: lotti, matricole e ubicazioni; FIFO e LIFO; libro inventari e scritture delle rimanenze (M7); XML delle
|
||||
autofatture e scarico dal canale SDI (M9); report di magazzino stampabili (M13).
|
||||
@@ -0,0 +1,65 @@
|
||||
# ADR 0036 - Contabilità generale
|
||||
|
||||
- **Stato:** accettata
|
||||
- **Data:** 2026-11-13
|
||||
- **Modifica:** SPEC §11.7, §12.11; milestone M7, issue #62, #63, #67, #68
|
||||
|
||||
## Contesto
|
||||
|
||||
SPEC §11.7 chiede un piano dei conti a tre livelli con un modello italiano, causali con righe proposte, prima nota
|
||||
in partita doppia con registrazioni provvisorie e definitive, registrazioni ricorrenti, partitari di clienti e
|
||||
fornitori, mastrini, bilancio di verifica e libro giornale. Restavano aperti: come si numerano le registrazioni,
|
||||
quando una registrazione non si può più toccare, come si correggono gli errori, dove sta il modello del piano dei
|
||||
conti, come si portano piano e causali nelle aziende create prima di M7.
|
||||
|
||||
## Decisione
|
||||
|
||||
1. **Piano dei conti a tre livelli.** `gl_accounts` con codice `MM.CC.SSS` (mastro, conto, sottoconto), padre,
|
||||
natura (attività, passività, costo, ricavo, ordine), tipo (generico, clienti, fornitori, banca, cassa, IVA,
|
||||
tributi), voce del bilancio CEE, flag *partitario*, *rilevante IVA* e *chiusura automatica*. Si registra solo sui
|
||||
sottoconti; i conti con partitario chiedono il cliente o il fornitore sulla riga. Un conto con movimenti o con
|
||||
sottoconti non si elimina (si disattiva). Le regole sui codici stanno in `AccountCodes` (`Khaemhat.Core`).
|
||||
2. **Il modello sta nel pacchetto fiscale.** `ILedgerTemplate` (`ItalianLedgerTemplate`) dà il piano *PMI standard*
|
||||
(237 conti, da `Data/piano-dei-conti.csv`), le causali, i registri IVA, il conto di ogni ruolo contabile
|
||||
(`PostingRole`: clienti, fornitori, IVA vendite e acquisti, erario, ritenute, bollo, arrotondamenti...) e quale
|
||||
causale usa ogni tipo documento. L'applicazione non conosce codici di conto italiani.
|
||||
3. **Causali con righe proposte.** `gl_journal_templates` e `gl_journal_template_lines`: area, registro IVA,
|
||||
*apre partite*, *causale di storno*, righe con ruolo o conto, segno e descrizione. La causale di storno non ha
|
||||
righe: copia quelle della registrazione stornata a segni invertiti. Una causale usata non si elimina.
|
||||
4. **Tre stati e due numeri.** Una registrazione (`gl_entries`, `gl_entry_lines`, `gl_entry_vat`) nasce *Bozza*
|
||||
(può non quadrare, non entra nei saldi se non lo si chiede), diventa *Registrata* quando quadra (numero di
|
||||
registrazione per anno, assegnato alla registrazione) e *Definitiva* con **Rendi definitive** fino a una data: le
|
||||
registrazioni ricevono il numero del libro giornale in ordine di data e non si modificano né si eliminano più. Il
|
||||
comando è rifiutato se prima di quella data restano bozze, e dopo non si registra più con una data anteriore
|
||||
all'ultima definitiva. Gli errori su una definitiva si correggono solo con lo
|
||||
**storno** (registrazione `STO` a segni invertiti, una sola per registrazione). `JournalEntryValidator`
|
||||
(`Khaemhat.Core`) controlla quadratura, sottoconti, partitari, righe IVA.
|
||||
5. **Partite aperte.** Le registrazioni con una causale che *apre partite* scrivono `gl_open_items` (una per rata,
|
||||
con scadenza, importo, pagato); il partitario mostra saldo, estratto conto e partite, con le scadute evidenziate.
|
||||
Incassi e pagamenti che chiudono le partite arrivano con la tesoreria (M8).
|
||||
6. **Ricorrenti come copia di un modello.** `gl_recurring_entries` punta a una registrazione modello e ne crea una
|
||||
copia a ogni data (mensile, trimestrale, semestrale, annuale, con la fine del mese mantenuta) fino alla data di
|
||||
fine; il job di sistema `ledger.recurring` gira ogni giorno alle 05:00 e il pulsante *Genera ora* lo anticipa. Le
|
||||
copie sono *Registrate* con origine *Ricorrente*.
|
||||
7. **Saldi calcolati dalle righe.** Mastrini, partitari e bilancio di verifica (`LedgerQueryService`) sommano le
|
||||
righe del periodo, con saldo di apertura dalle righe precedenti, senza tabelle di saldi: le registrazioni toccano
|
||||
poche righe e i totali restano coerenti per costruzione. Il bilancio di verifica raggruppa per mastro, conto e
|
||||
sottoconto, filtra per centro di costo e mostra il risultato del periodo (ricavi meno costi).
|
||||
8. **Stampe.** Libro giornale di prova o definitivo, mastrini, estratti conto e bilancio di verifica sono PDF di
|
||||
`LedgerReport` sul motore di stampa di M5 (ADR 0034).
|
||||
9. **Aziende esistenti.** La migrazione `M20261113_002_CreateLedger` crea le tabelle; i documenti hanno già la
|
||||
colonna *contabilizzato* da M5. Piano dei conti, causali e registri arrivano da `LedgerSeeder` (seed di base, *Aggiorna da tabelle
|
||||
base* o `scripts/seed.sh --base`), che aggiunge i codici mancanti senza toccare quelli esistenti (ADR 0026). La
|
||||
demo (`DemoLedgerSeeder`) contabilizza i documenti demo, paga la fattura del professionista, crea il noleggio
|
||||
mensile della stampante come ricorrente, conferma le liquidazioni dei mesi passati e paga gli F24 scaduti.
|
||||
10. **Permessi.** `ledger.account.read/write`, `ledger.entry.read/write/finalize`; tutto dietro il modulo `ACCT`.
|
||||
|
||||
## Conseguenze
|
||||
|
||||
- Un errore su una registrazione definitiva lascia sempre traccia (registrazione originale e storno), come chiede il
|
||||
libro giornale.
|
||||
- Sommare le righe a ogni richiesta costa più di un saldo memorizzato; con le dimensioni di una PMI (decine di
|
||||
migliaia di righe l'anno) resta sotto il secondo, e gli indici su conto e data coprono le query. La chiusura
|
||||
dell'esercizio (M10) porta i saldi di apertura e accorcia la storia.
|
||||
- Rimandati: chiusura e riapertura dell'esercizio, bilancio CEE riclassificato, cespiti (M10); incassi, pagamenti e
|
||||
riconciliazione bancaria (M8); budget per centro di costo.
|
||||
@@ -0,0 +1,72 @@
|
||||
# ADR 0037 - Contabilizzazione dei documenti, IVA e F24
|
||||
|
||||
- **Stato:** accettata
|
||||
- **Data:** 2026-11-13
|
||||
- **Modifica:** SPEC §11.7, §11.8, §12.11; milestone M7, issue #64, #65, #66
|
||||
|
||||
## Contesto
|
||||
|
||||
SPEC §11.7 e §11.8 chiedono che fatture, note e autofatture si contabilizzino da sole, con registri IVA,
|
||||
liquidazione periodica, acconto, comunicazione LIPE, ritenute d'acconto, certificazione unica, bollo virtuale e
|
||||
prospetto F24. Restavano aperti: quando si scrive la registrazione di un documento, come si corregge, come si
|
||||
calcola la liquidazione, cosa succede se la si riapre, dove stanno codici tributo e scadenze italiane.
|
||||
|
||||
## Decisione
|
||||
|
||||
1. **Contabilizzazione nella transazione del documento.** `LedgerPoster` gira nel motore documenti, come
|
||||
`InventoryPoster` (ADR 0035), e solo con il modulo `ACCT` attivo. Fatture (immediate, accompagnatorie,
|
||||
differite, di acconto), note di debito e parcelle sono *vendite*; la nota di credito è una vendita a segni
|
||||
invertiti; fattura e nota fornitore sono *acquisti*; autofatture e integrazioni vanno in entrambi i registri. La
|
||||
modifica di un documento in vigore riscrive la sua registrazione **con lo stesso numero**; l'annullamento la
|
||||
elimina o, se è definitiva, la storna. Una registrazione che viene da un documento non si modifica a mano: si
|
||||
corregge il documento. I documenti confermati prima della licenza si contabilizzano in blocco
|
||||
(`LedgerService.PostPendingAsync`, pulsante *Contabilizza documenti*).
|
||||
2. **Regole di registrazione in `PostingEngine`** (`Khaemhat.Core`, senza accesso ai dati): vendita = cliente Dare
|
||||
per il totale, ricavi Avere per conto dell'articolo o della riga, rivalsa cassa e bollo addebitato Avere, IVA
|
||||
vendite Avere; scissione dei pagamenti = l'IVA torna dal cliente al conto dell'erario; acquisto = fornitore Avere,
|
||||
costi Dare con l'IVA indetraibile sommata al costo, IVA acquisti Dare; autofattura = IVA acquisti Dare e IVA
|
||||
vendite Avere. Sconti di testata e arrotondamenti vanno sulla riga più grande, così la registrazione quadra sempre
|
||||
al centesimo. Un conto mancante blocca la conferma con un errore che dice quale ruolo configurare.
|
||||
3. **Righe IVA e partite dal documento.** Il castelletto del documento diventa `gl_entry_vat` nel registro della
|
||||
causale (`VEN1`, `VEN-RC`, `ACQ1`, `ACQ-RC`, `CORR`) con protocollo, data IVA, esigibilità e quota indetraibile;
|
||||
le rate diventano partite aperte; la ritenuta del documento diventa una riga di `withholdings`.
|
||||
4. **Registri e stampa definitiva.** I registri IVA si leggono per periodo con il riepilogo per aliquota; la stampa
|
||||
definitiva (`vat_register_prints`) parte dal giorno dopo l'ultima stampa definitiva e continua la numerazione delle
|
||||
pagine dell'anno. Il blocco del periodo viene dalla liquidazione (punto 5), non dalla stampa.
|
||||
5. **Liquidazione in `VatSettlementCalculator`** (`Khaemhat.Core`): IVA a debito delle vendite e dei corrispettivi
|
||||
esigibili (l'esigibilità differita resta fuori), IVA a credito degli acquisti al netto dell'indetraibile e del pro
|
||||
rata, credito o debito del periodo precedente, acconto di dicembre, interessi dell'1% sul trimestrale (anche sul
|
||||
quarto, versato a marzo con il codice 6099), minimo di versamento sotto il quale il debito passa al periodo dopo. Periodicità dal profilo
|
||||
azienda. La liquidazione si **calcola** quante volte si vuole e si **conferma** in ordine: la conferma scrive la
|
||||
registrazione `LIQ` (IVA vendite Dare, IVA acquisti Avere, interessi Dare, erario c/liquidazione Avere), segna i
|
||||
periodi fiscali come liquidati (da lì documenti e registrazioni con IVA in quelle date sono rifiutati, ADR 0026
|
||||
sui periodi) e crea il versamento F24 se c'è da pagare. La si può **riaprire** finché il suo F24
|
||||
non è pagato e nessuna liquidazione successiva è confermata.
|
||||
6. **Regole italiane nel pacchetto fiscale.** `IVatSettlementRules` (`VatSettlementRulesIt`) dà minimo (25,82),
|
||||
interessi trimestrali, acconto (88%, minimo 103,29, metodi storico, previsionale ed effettivo), codici tributo
|
||||
(6001-6012, 6031-6033, 6099 con rateazione 0101, 6013 e 6035 per l'acconto, 1040 per le ritenute, 2521-2524 per il
|
||||
bollo), scadenze (16 del mese, agosto al 20, acconto al 27 dicembre, giorno lavorativo successivo) e soglie del
|
||||
bollo virtuale (5.000 euro sul primo e secondo trimestre). `IPeriodicVatReturnWriter` (`LipeWriter`) scrive il
|
||||
file LIPE (fornitura `IVP18`); `ITaxPaymentFormExporter` esporta i dati F24 in CSV.
|
||||
7. **Tributi come versamenti.** `tax_payments` raccoglie ogni riga da versare (IVA, acconto, ritenute, bollo) con
|
||||
codice, periodo e scadenza; il prospetto F24 le raggruppa per scadenza. *Registra pagamento* scrive la
|
||||
registrazione `F24` (erario Dare per origine, banca Avere) e segna le righe come pagate; si annulla eliminando o
|
||||
stornando quella registrazione.
|
||||
8. **Ritenute.** Quelle *operate* nascono dalle fatture dei professionisti: in attesa finché la fattura non è
|
||||
pagata, poi da versare (registrazione `RIT`, riga F24 al 16 del mese dopo); quelle *subite* nascono dalle
|
||||
parcelle emesse (registrazione `RITS`, credito per ritenute). I dati della certificazione unica si esportano in
|
||||
CSV per anno e percipiente.
|
||||
9. **Nessun invio telematico.** Khaemhat prepara LIPE, dati F24 e dati CU; l'invio resta all'utente o
|
||||
all'intermediario con i servizi dell'Agenzia delle Entrate.
|
||||
10. **Permessi.** `vat.register.read`, `vat.settlement.read/confirm`, oltre a quelli di ADR 0036.
|
||||
|
||||
## Conseguenze
|
||||
|
||||
- Documenti e contabilità non divergono: la registrazione è un dato derivato, scritto nella stessa transazione, e
|
||||
una contabilizzazione in blocco la ricostruisce.
|
||||
- Correggere un documento di un periodo già liquidato è rifiutato dal blocco dei periodi: si corregge con una nota
|
||||
di variazione, come prevede la norma, oppure si riapre la liquidazione.
|
||||
- La verifica a mano della demo è un test (`DemoLedgerTests`): la prima liquidazione con IVA è ricalcolata dai
|
||||
registri e confrontata con quella confermata.
|
||||
- Rimandati: dichiarazione IVA annuale, Intrastat, F24 telematico, plafond e dichiarazioni d'intento, IVA per cassa
|
||||
con chiusura automatica delle partite (con gli incassi di M8).
|
||||
@@ -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).
|
||||
@@ -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,44 @@
|
||||
# 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.
|
||||
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).
|
||||
@@ -1,178 +1,180 @@
|
||||
# Acquisti
|
||||
|
||||
> **Stato:** bozza · **Ultima revisione:** 2026-11-10 · **Versione software:** non ancora rilasciata (milestone M6)
|
||||
> **Modulo di licenza:** CORE (XML delle autofatture e canale SDI con EINV, registrazione con ACCT) · **Permessi principali:** famiglia `purchases.*` (codici esatti definiti in sviluppo) · **Specifica:** SPEC §11.3, §11.5
|
||||
> **Stato:** completa per la versione 0.6 · **Ultima revisione:** 2026-11-12 · **Versione software:** 0.6.0 (M6)
|
||||
> **Modulo di licenza:** CORE (XML delle autofatture con EINV, registrazione contabile con ACCT) · **Permessi principali:** `purchases.order.*` (ordini fornitore), `inventory.entry.*` (DDT fornitore), `purchases.invoice.*` (fatture, note di credito, import, autofatture) · **Specifica:** SPEC §11.3, §11.5, ADR 0035
|
||||
|
||||
Il modulo **Acquisti** copre il ciclo passivo: **ordini ai fornitori** (anche generati dalla proposta di riordino),
|
||||
**DDT di carico** con controllo delle quantità ricevute, **fatture di acquisto** con protocollo IVA e conti per riga,
|
||||
**note di credito** dei fornitori, **import delle fatture passive** XML/P7M ricevute dallo SDI e le **autofatture e
|
||||
integrazioni** (TD16-TD29) per reverse charge e acquisti dall'estero.
|
||||
Il modulo **Acquisti** copre il ciclo passivo: **ordini ai fornitori** (anche dalla proposta di riordino),
|
||||
**ricevimento della merce** con il DDT del fornitore, **fatture e note di credito dei fornitori** con il protocollo
|
||||
IVA, **import delle fatture elettroniche** ricevute (XML, P7M, ZIP) e le **autofatture e integrazioni** (TD16-TD29)
|
||||
per inversione contabile e acquisti dall'estero.
|
||||
|
||||
> **In questa versione** ci sono ordini, ricevimenti, fatture e note di credito fornitore con protocollo, carico a
|
||||
> magazzino e costo medio, controllo dei prezzi rispetto a ordine e ricevimento, import delle fatture elettroniche e
|
||||
> autofatture in bozza con la loro scadenza. Dalla 0.7 le fatture e le note fornitore **si contabilizzano** da sole
|
||||
> con i registri IVA (vedi [Contabilità](Contabilita) e [IVA](IVA)). 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
|
||||
|
||||
Menu **Acquisti** → *Ordini fornitori*, *DDT di carico*, *Fatture di acquisto*, *Import XML SDI*, *Autofatture*.
|
||||
Menu **Acquisti** → *Ordini fornitori*, *Ricevimenti merce*, *Fatture passive*, *Importa fatture*, *Autofatture*.
|
||||
|
||||
Le maschere sono quelle comuni a tutti i documenti (toolbar, intestazione, schede, righe con castelletto e totali):
|
||||
vedi [Interfaccia e scorciatoie](Interfaccia-e-scorciatoie) e [Vendite](Vendite) per il motore documenti.
|
||||
Le maschere sono quelle comuni a tutti i documenti (toolbar, intestazione, schede, righe con castelletto e totali,
|
||||
trasformazioni, stampa, allegati): vedi [Vendite](Vendite) per il funzionamento del motore documenti e
|
||||
[Interfaccia e scorciatoie](Interfaccia-e-scorciatoie) per la tastiera.
|
||||
|
||||
```
|
||||
Proposta di riordino ──► Ordine fornitore ──ricevi merce──► DDT di carico ──registra fattura──► Fattura di acquisto
|
||||
▲
|
||||
Fattura passiva XML/P7M (SDI) ──import──┘ (abbinamento all'ordine o al DDT)
|
||||
Proposta di riordino ──► Ordine fornitore ──Crea DDT fornitore (carico)──► Ricevimento ──Crea Fattura fornitore──► Fattura
|
||||
▲
|
||||
Fattura elettronica XML / P7M / ZIP ──Importa fatture──► Fattura in bozza ─┘
|
||||
Fattura di un fornitore estero o in reverse charge ──Crea autofattura──► Autofattura / integrazione (TD16-TD29)
|
||||
```
|
||||
|
||||
## Ordini fornitori
|
||||
|
||||

|
||||
*Mockup 031 — ordine fornitore confermato, nato dalla proposta di riordino, con il pannello Origine del fabbisogno (anteprima ridotta).*
|
||||
Un **ordine fornitore** (`OF`) dice al fornitore che cosa ti serve; non muove il magazzino ma, una volta
|
||||
**confermato**, aumenta l'**ordinato** degli articoli finché non arriva la merce (vedi [Magazzino](Magazzino)).
|
||||
|
||||
Azioni: **Invia al fornitore** (e-mail con il PDF dell'ordine), **Ricevi merce (DDT carico)**, **Chiudi residuo**.
|
||||
- Scegliendo il fornitore si applicano le sue condizioni (pagamento, banca, porto, valuta).
|
||||
- Scegliendo un articolo, Khaemhat propone il **prezzo del fornitore** dalla scheda articolo (*Fornitori*).
|
||||
- Gli ordini nascono a mano, dalla **proposta di riordino** (un ordine in bozza per fornitore, vedi
|
||||
[Magazzino](Magazzino#proposta-di-riordino)) o copiando un altro documento.
|
||||
- Quando la merce arriva, **Crea DDT fornitore (carico)** porta le righe ancora da ricevere nel ricevimento: puoi scegliere
|
||||
righe e quantità, così un ordine può essere ricevuto in più volte. Lo stato diventa *Evaso in parte* ed *Evaso*;
|
||||
**Chiudi** chiude un residuo che non arriverà più.
|
||||
|
||||
- L'intestazione mostra la **data prevista** di consegna, calcolata come data dell'ordine + **lead time** del
|
||||
fornitore, e lo stato di ricevimento (*Ricevuto 0%*…).
|
||||
- Le righe riportano il **codice del fornitore** per l'articolo; il prezzo proposto è quello del fornitore.
|
||||
- Il pannello **Origine del fabbisogno** spiega perché si ordina: sottoscorta, impegni da ordini clienti, lotto di
|
||||
riordino.
|
||||
- Schede: *Righe*, *Testata*, *Totali*, *Ricevimenti*, *Note*, *Allegati*, *Collegamenti*.
|
||||
- Un ordine confermato aggiorna l'**ordinato** degli articoli (vedi [Magazzino](Magazzino)).
|
||||

|
||||
|
||||
Gli ordini nascono a mano, dalla **proposta di riordino** (un ordine in bozza per fornitore, vedi
|
||||
[Magazzino](Magazzino)) o dall'azione **Ordina a fornitore** di un ordine cliente.
|
||||
## Ricevimenti merce (DDT fornitore)
|
||||
|
||||
## DDT di carico
|
||||
Il **DDT fornitore (carico)** (`DDTF`) registra la merce arrivata. Non ha un numero interno: nella testata scrivi il
|
||||
**numero e la data del DDT del fornitore**, che lo identificano (nell'elenco compare come *Senza numero*).
|
||||
|
||||

|
||||
*Mockup 032 — ricevimento con confronto ordinato/ricevuto, riga con 20 pezzi mancanti e aggiornamento del costo medio (anteprima ridotta).*
|
||||
1. Dall'ordine premi **Crea DDT fornitore (carico)**, oppure crea un ricevimento e richiama l'ordine.
|
||||
2. Controlla le **quantità ricevute** riga per riga e il **deposito** di arrivo.
|
||||
3. **Conferma**: la merce viene **caricata a magazzino** con la causale `CAR` e aggiorna **costo medio** e **ultimo
|
||||
costo** degli articoli; l'ordine segna le quantità evase.
|
||||
|
||||
Il **DDT di carico** registra la merce ricevuta. Azioni: **Registra fattura da questo DDT**, **Stampa etichette**,
|
||||
**Riapri**.
|
||||
Un ricevimento confermato resta modificabile finché non è fatturato; dal ricevimento **Crea Fattura fornitore**
|
||||
prepara la fattura con le stesse righe.
|
||||
|
||||
1. Dall'ordine fornitore premi **Ricevi merce** oppure crea un DDT di carico e usa **Evadi da…** per richiamare
|
||||
l'ordine.
|
||||
2. Indica numero e data del **DDT del fornitore**.
|
||||
3. Conta la merce: per ogni riga inserisci la quantità **ricevuta**; si può **scansionare l'EAN o il codice
|
||||
fornitore** per contare. La colonna *Controllo* segnala le differenze (*OK*, *Mancanti 20*…).
|
||||
4. **Conferma**: la merce viene **caricata a magazzino** (causale *Carico da fornitore*, deposito indicato), si
|
||||
aggiornano **ultimo costo** e **costo medio ponderato** dell'articolo.
|
||||
## Fatture passive
|
||||
|
||||
Se arriva meno del previsto, il **residuo** resta aperto sull'ordine; se non arriverà più si chiude con **Chiudi
|
||||
residuo**. Un messaggio sotto le righe riassume differenze e variazioni del costo medio.
|
||||

|
||||
|
||||
## Fatture di acquisto
|
||||
|
||||

|
||||
*Mockup 033 — fattura di acquisto in bozza nata da XML, con protocollo, flag Verifica prezzi, righe con conto e centro di costo, castelletto con IVA detraibile (anteprima ridotta).*
|
||||
|
||||
Azioni: **Registra (protocolla)**, **Contabilizza**, **Confronta con ordine**, **Apri XML**.
|
||||
La **fattura fornitore** (`FF`) e la **nota di credito fornitore** (`NCF`) registrano i documenti del fornitore.
|
||||
|
||||
| Dato | Descrizione |
|
||||
|---|---|
|
||||
| **Data di registrazione** e **data/numero del documento** del fornitore | la registrazione determina il periodo IVA |
|
||||
| **Protocollo** | numero progressivo del registro IVA acquisti (es. `ACQ/2026/000613`), assegnato alla registrazione |
|
||||
| **Conto e centro di costo per riga** | ogni riga ha il proprio conto di costo e centro di costo (proposti da articolo, categoria o fornitore) |
|
||||
| **Indetraibilità** | codici IVA con indetraibilità parziale o totale (es. telefonia 50%): il castelletto mostra imponibile, imposta e quota **detraibile** |
|
||||
| **Ritenute e cassa** | per i professionisti: ritenuta d'acconto, cassa previdenza; il totale mostra il **netto a pagare** |
|
||||
| **Registrazione contabile** | scheda con l'anteprima della registrazione (con modulo Contabilità) |
|
||||
| **N. documento fornitore** e **data** | numero e data scritti dal fornitore (nella testata) |
|
||||
| **Data** | data di registrazione: decide il periodo IVA |
|
||||
| **Protocollo** | numero progressivo del registro IVA acquisti (numeratore `PRA`), assegnato alla **conferma**; nell'elenco compare nella colonna *Protocollo* |
|
||||
| **Righe** | articoli, righe descrittive e spese con il codice IVA di ogni riga; per i professionisti ritenuta d'acconto e cassa come nelle vendite |
|
||||
| **Scadenze** | calcolate dal pagamento del fornitore |
|
||||
|
||||
Schede: *Righe*, *Testata*, *Totali*, *Scadenze*, *Ritenute e cassa*, *Registrazione contabile*, *Note*,
|
||||
*Allegati*, *Collegamenti*.
|
||||
La fattura nasce dal ricevimento (**Crea Fattura fornitore**), dall'ordine (per servizi o merce senza DDT), dall'**import
|
||||
della fattura elettronica** (vedi sotto) o a mano. **Conferma** assegna il protocollo e la rende definitiva; una
|
||||
fattura confermata si corregge con una **nota di credito fornitore** (**Crea Nota di credito fornitore**).
|
||||
|
||||
**Registra (protocolla)** assegna il protocollo e rende la fattura definitiva; **Contabilizza** crea la registrazione
|
||||
(automatica alla conferma o in batch, secondo le preferenze). La fattura può nascere:
|
||||
**Magazzino.** Una fattura di merce senza DDT carica il magazzino alla conferma; una fattura nata da un ricevimento
|
||||
non carica di nuovo, ma il suo **prezzo corregge il costo** del carico. La nota di credito fornitore scarica la merce
|
||||
resa (causale `RESF`).
|
||||
|
||||
- dal **DDT di carico** (**Registra fattura da questo DDT**), che la collega ai carichi;
|
||||
- dall'**import XML** (vedi sotto);
|
||||
- a mano, ad esempio per fatture cartacee o estere.
|
||||
**Controllo dei prezzi.** Se una riga della fattura ha un prezzo diverso da quello dell'ordine o del ricevimento da
|
||||
cui viene, sopra le righe compare un avviso con la differenza totale e, riga per riga, il prezzo atteso e quello
|
||||
fatturato. È un avviso: decidi tu se registrare la fattura o chiedere una nota di credito.
|
||||
|
||||
Le **note di credito dei fornitori** si registrano allo stesso modo e chiudono le partite collegate.
|
||||
## Importare le fatture elettroniche
|
||||
|
||||
## Import delle fatture passive XML/P7M
|
||||

|
||||
|
||||

|
||||
*Mockup 034 — quattro file in import (pronto, con ritenuta e cassa, fornitore da creare, duplicato) e mappatura delle righe sull'ordine con differenza di prezzo (anteprima ridotta).*
|
||||
**Acquisti → Importa fatture** (o il link nell'elenco delle fatture passive) registra in bozza le fatture ricevute
|
||||
dallo SDI o dal tuo intermediario. Dalla 0.9 le fatture che arrivano dai canali SDI si registrano anche da
|
||||
**Fatturazione elettronica → Fatture ricevute**, con lo stesso import.
|
||||
|
||||
1. Carica i file con **Carica XML / P7M / ZIP**, oppure **Leggi inbox** (cartella di ingresso dell'istanza) o
|
||||
**Scarica dal canale SDI** (con il modulo Fatturazione elettronica).
|
||||
2. Per ogni file Khaemhat legge fornitore, numero, data, tipo documento (TD) e totale e mostra un **esito**:
|
||||
*Pronto*, *Fornitore da creare*, *Duplicato*, oppure avvisi (ad esempio *Ritenuta 20% · cassa 4%*).
|
||||
3. Il **fornitore** viene riconosciuto da **partita IVA o codice fiscale**; se non esiste si crea al volo dai dati
|
||||
dell'XML.
|
||||
4. **Mappatura righe**: ogni riga XML viene abbinata a un articolo cercando, in ordine, il **codice del fornitore**,
|
||||
l'**EAN** e la **descrizione** (ricerca approssimata). Le righe non abbinate diventano descrittive o si abbinano a
|
||||
mano.
|
||||
5. **Abbina a ordine**: confronta prezzi e quantità con l'ordine fornitore; le differenze sono evidenziate (es.
|
||||
*+3,4%*).
|
||||
6. **Salva bozza** o **Registra fattura di acquisto**. Se ci sono differenze la fattura nasce **in bozza** con il
|
||||
flag *Verifica prezzi*.
|
||||
1. **Caricamento**: scegli uno o più file: **XML FatturaPA**, file firmati **.p7m** o archivi **ZIP** che li
|
||||
contengono (fino a 50 MB per file). I file che non sono fatture elettroniche leggibili sono elencati a parte con il
|
||||
motivo.
|
||||
2. **Controllo**: per ogni fattura vedi fornitore (nuovo o già in anagrafica), numero, data, tipo, totale e un esito:
|
||||
*Pronta*, oppure *Già registrata* (stesso fornitore, stesso numero, stesso anno), *Non è un acquisto* (per esempio
|
||||
un'autofattura emessa dall'azienda stessa), *Totale diverso* (il totale del file non torna con le righe), *Firma non
|
||||
verificata*, *Sconto sul totale*. **Leggi** mostra righe, riepilogo IVA e pagamento del file.
|
||||
3. **Registrazione**: spunta le fatture e premi **Registra in bozza**. Per ognuna Khaemhat:
|
||||
- trova il **fornitore** dalla partita IVA o dal codice fiscale, o lo **crea** dai dati del file;
|
||||
- crea una **fattura fornitore** (tipi TD01, TD02, TD03, TD05, TD06, TD24-TD27) o una **nota di credito fornitore**
|
||||
(TD04, TD08) in bozza, con numero e data del fornitore e la causale nelle note;
|
||||
- abbina ogni riga a un **articolo** cercando il **codice del fornitore** (scheda articolo, *Fornitori*), poi l'**EAN**,
|
||||
poi il **codice articolo**; le righe non abbinate diventano righe libere con descrizione, prezzo e IVA;
|
||||
- riporta gli **sconti** percentuali come sconto di riga e gli altri nel prezzo netto;
|
||||
- sceglie il **codice IVA** dell'azienda con la stessa aliquota e natura;
|
||||
- **allega il file** originale alla fattura (scheda *Allegati*, tipo *Fattura elettronica*).
|
||||
|
||||
L'**XML originale** viene allegato alla fattura; per i file **P7M** la **firma CAdES** viene verificata. I file già
|
||||
importati sono riconosciuti come duplicati.
|
||||
Le fatture importate restano **in bozza**: controllale e confermale per protocollarle. Se un codice IVA manca (per
|
||||
esempio una natura non usata finora), aggiungilo in [Tabelle azienda](Tabelle-azienda) → *Codici IVA* e ripeti
|
||||
l'import.
|
||||
|
||||
## Autofatture e integrazioni (TD16-TD29)
|
||||
|
||||

|
||||
*Mockup 035 — integrazione TD17 per servizi da un fornitore estero: IVA integrata, effetto neutro, registri RC vendite e acquisti, scadenza di invio allo SDI (anteprima ridotta).*
|
||||

|
||||
|
||||
Quando l'IVA è dovuta dall'acquirente (inversione contabile) l'azienda deve **integrare** la fattura ricevuta o
|
||||
emettere un'**autofattura**, trasmettendola allo SDI. In Khaemhat questi documenti stanno in **Acquisti →
|
||||
Autofatture** e nascono dalla fattura di acquisto d'origine.
|
||||
Quando l'IVA è dovuta da chi compra (inversione contabile, acquisti dall'estero) l'azienda deve **integrare** la
|
||||
fattura ricevuta o emettere un'**autofattura** e trasmetterla allo SDI. Khaemhat lo riconosce da solo dalla fattura
|
||||
fornitore (paese del fornitore, beni o servizi, natura IVA delle righe) e mostra sopra le righe quale documento serve e **entro quando**:
|
||||
|
||||
| Codice | Documento | Quando si usa |
|
||||
| Tipo | Quando | Scadenza |
|
||||
|---|---|---|
|
||||
| **TD16** | Integrazione fattura reverse charge interno | acquisti nazionali in inversione contabile (art. 17 c.6 DPR 633/72, es. subappalto edile) |
|
||||
| **TD17** | Integrazione/autofattura per acquisto di servizi dall'estero | servizi da fornitori UE ed extra-UE |
|
||||
| **TD18** | Integrazione per acquisto di beni intracomunitari | beni da fornitori UE |
|
||||
| **TD19** | Integrazione/autofattura per acquisto di beni ex art. 17 c.2 DPR 633/72 | beni già in Italia acquistati da soggetti non residenti |
|
||||
| **TD20** | Autofattura per regolarizzazione e integrazione delle fatture | regolarizzazione nei casi previsti (definizione aggiornata dalle specifiche v1.9) |
|
||||
| **TD21** | Autofattura per splafonamento | acquisti oltre il plafond dell'esportatore abituale |
|
||||
| **TD22** | Estrazione beni da deposito IVA | |
|
||||
| **TD23** | Estrazione beni da deposito IVA con versamento dell'IVA | |
|
||||
| **TD28** | Acquisti da San Marino con IVA | fatture cartacee con IVA da operatori sammarinesi |
|
||||
| **TD29** | Comunicazione per omessa o irregolare fatturazione | introdotto con le specifiche v1.9 (dal 1° aprile 2025) |
|
||||
| **AF16** (TD16) | inversione contabile interna: righe con natura N6.x (subappalti, rottami, cellulari…) | 15 del mese dopo il ricevimento |
|
||||
| **AF17** (TD17) | servizi da un fornitore estero, UE o extra UE | 15 del mese dopo |
|
||||
| **AF18** (TD18) | beni da un fornitore di un altro Paese UE | 15 del mese dopo |
|
||||
| **AF19** (TD19) | beni già in Italia comprati da un soggetto non residente (art. 17 c.2) | 15 del mese dopo |
|
||||
| **AF28** (TD28) | acquisti da San Marino con IVA in fattura | 15 del mese dopo |
|
||||
| **AF20**, **AF29** | regolarizzazione di una fattura non ricevuta o irregolare | 90 giorni |
|
||||
| AF21, AF22, AF23 | splafonamento, estrazione da deposito IVA | a mano, quando servono |
|
||||
|
||||
Come funziona (esempio TD17, mockup 035):
|
||||

|
||||
|
||||
1. La fattura estera viene registrata negli acquisti.
|
||||
2. Si crea l'integrazione: le righe sono **riprese dalla fattura estera** con imponibile e aliquota; Khaemhat
|
||||
calcola l'**IVA integrata**.
|
||||
3. **Conferma e genera XML**: nell'XML il **fornitore estero** compare come cedente/prestatore e la **nostra azienda**
|
||||
come cessionario/committente.
|
||||
4. La registrazione va contemporaneamente nel **registro IVA vendite RC** e nel **registro IVA acquisti RC**: l'effetto
|
||||
è **neutro** (IVA a debito = IVA a credito, salvo indetraibilità). Il pannello *Effetto contabile* mostra le due
|
||||
righe.
|
||||
5. L'XML va inviato **entro il 15 del mese successivo**: Khaemhat mostra la scadenza nel documento e un promemoria
|
||||
nella dashboard.
|
||||
**Acquisti → Autofatture** elenca in alto le **integrazioni da emettere**, la scadenza più vicina per prima. **Crea
|
||||
autofattura** (qui o nella fattura fornitore) prepara il documento in bozza: le righe della fattura con il **codice IVA
|
||||
ordinario** al posto della natura, il numero e la data della fattura del fornitore come documento collegato, la data
|
||||
di oggi. Controllalo ed **emettilo**: prende il numero dal numeratore `AUT` delle autofatture.
|
||||
|
||||
Schede: *Righe*, *Testata*, *Registrazione IVA*, *XML SDI*, *Collegamenti*. Le definizioni ufficiali dei codici sono
|
||||
in [Fiscalità italiana](Fiscalita-italiana).
|
||||
Il **file XML** dell'autofattura (con il fornitore come cedente e l'azienda come cessionario) e l'invio allo SDI
|
||||
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).
|
||||
|
||||
## Fatture da fornitori forfettari
|
||||
|
||||
Le fatture dei fornitori in **regime forfettario** non hanno IVA (natura N2.2 nell'XML del fornitore) e riportano il
|
||||
**bollo** quando dovuto; non sono soggette a ritenuta d'acconto. Nella scheda del fornitore il flag *Regime
|
||||
forfettario* (gruppo *Ritenute e contributi*) indica questa situazione; i controlli automatici sulla fattura
|
||||
importata saranno definiti in sviluppo.
|
||||
Le fatture dei fornitori in **regime forfettario** non hanno IVA (natura N2.2) e riportano il **bollo** quando dovuto;
|
||||
non sono soggette a ritenuta. All'import la riga prende il codice IVA dell'azienda con natura N2.2; non serve
|
||||
nessuna autofattura.
|
||||
|
||||
## Stati
|
||||
|
||||
Ordini e DDT di carico seguono gli stati del motore documenti: *Bozza*, *Confermato*, *Ricevuto parzialmente* /
|
||||
*Ricevuto*, *Chiuso*, *Annullato*. Le fatture di acquisto sono *Bozza* finché non vengono **registrate
|
||||
(protocollate)**; i badge indicano anche *Da XML SDI*, *Verifica prezzi*, *Caricato a magazzino*, *Da fatturare*.
|
||||
| Documento | Stati |
|
||||
|---|---|
|
||||
| Ordine fornitore, ricevimento | *Bozza*, *Confermato*, *Evaso in parte*, *Evaso*, *Chiuso*, *Annullato* |
|
||||
| Fattura e nota di credito fornitore | *Bozza*, *Confermato* (protocollata), *Annullato* |
|
||||
| Autofattura | *Bozza*, *Emessa* e, con la fatturazione elettronica, gli stati dello SDI |
|
||||
|
||||
## Permessi e licenza
|
||||
|
||||
Ordini, carichi, fatture di acquisto e import da file sono nel modulo **CORE**. La generazione e l'invio dell'XML
|
||||
delle autofatture e lo scarico dal canale SDI richiedono **EINV**; la registrazione contabile e i registri IVA
|
||||
**ACCT**; i pagamenti **FIN**. Costi e margini sono visibili solo a chi ha il permesso `items.cost.read`.
|
||||
Ordini, ricevimenti, fatture, import e autofatture sono nel modulo **CORE**. Gli ordini richiedono
|
||||
`purchases.order.read`/`write`; i ricevimenti, che muovono il magazzino, `inventory.entry.read`/`write` (e
|
||||
`inventory.entry.post` per confermarli); fatture, note di credito, import e autofatture `purchases.invoice.read`/`write`.
|
||||
L'XML delle autofatture richiederà **EINV**, la registrazione contabile **ACCT**, i pagamenti **FIN**. Costi e margini
|
||||
sono visibili solo con `items.cost.read`.
|
||||
|
||||
## Domande frequenti
|
||||
|
||||
- **L'import segna "Duplicato".** La fattura risulta già importata: non va registrata una seconda volta (il
|
||||
criterio esatto di riconoscimento sarà definito in sviluppo).
|
||||
- **Una riga dell'XML non trova l'articolo.** Aggiungi il codice del fornitore nella scheda articolo (*Fornitori*):
|
||||
la volta successiva l'abbinamento sarà automatico.
|
||||
- **Ho ricevuto meno merce di quella ordinata.** Conferma il DDT con la quantità ricevuta: il residuo resta aperto
|
||||
sull'ordine.
|
||||
- **L'import dice "Già registrata".** Lo stesso fornitore ha già un documento con quel numero nello stesso anno: non
|
||||
va registrata due volte.
|
||||
- **Una riga dell'XML non trova l'articolo.** Aggiungi il codice che usa il fornitore nella scheda articolo
|
||||
(*Fornitori*, codice fornitore): dalla volta successiva l'abbinamento è automatico.
|
||||
- **Ho ricevuto meno merce di quella ordinata.** Conferma il ricevimento con la quantità arrivata: il residuo resta
|
||||
aperto sull'ordine e l'ordinato degli articoli lo tiene in conto.
|
||||
- **La fattura ha un prezzo diverso dall'ordine.** L'avviso sopra le righe lo segnala; se la fattura è giusta
|
||||
confermala e il costo medio si allinea al prezzo fatturato.
|
||||
- **Non vedo l'avviso dell'autofattura.** Compare sulle fatture di fornitori esteri o con righe in natura N6.x,
|
||||
finché non c'è un'autofattura collegata. L'elenco *Integrazioni da emettere* mostra solo le fatture **confermate**.
|
||||
|
||||
## Pagine correlate
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Articoli e listini
|
||||
|
||||
> **Stato:** completa · **Ultima revisione:** 2026-11-12 · **Versione software:** 0.4.0 (milestone M4; giacenze e costi dai movimenti con il magazzino, M6)
|
||||
> **Stato:** completa · **Ultima revisione:** 2026-11-12 · **Versione software:** 0.4.0 (milestone M4; giacenze e costi dai movimenti dalla 0.6.0, M6)
|
||||
> **Modulo di licenza:** CORE · **Permessi principali:** `items.item.read` (consultare), `items.item.write` (inserire, modificare, disattivare, prezzi), `items.item.delete` (eliminare), `items.cost.read` (vedere costi e margini) · **Specifica:** SPEC §11.2, §11.3 (prezzi), §14 · **Decisioni:** ADR 0030
|
||||
|
||||
L'**articolo** descrive ciò che l'azienda vende o compra: merci, servizi, spese, righe descrittive e cespiti. Nella
|
||||
@@ -75,18 +75,20 @@ salvataggio.
|
||||
### Costi
|
||||
|
||||
- **Costo standard**: valore scritto a mano.
|
||||
- **Ultimo costo** e **costo medio**: li aggiornano i carichi di magazzino (DDT di carico, fatture di acquisto) che
|
||||
arrivano con il magazzino (M6); fino ad allora sono valorizzati solo nei dati di esempio. Il costo medio è il
|
||||
criterio di valorizzazione del magazzino (vedi [Magazzino](Magazzino)).
|
||||
- **Ultimo costo** e **costo medio**: li calcolano i carichi di magazzino (DDT fornitore, fatture fornitore, esistenze
|
||||
iniziali, movimenti di carico) dalla versione 0.6.0. Il costo medio è il criterio di valorizzazione del magazzino
|
||||
(vedi [Magazzino](Magazzino#costo-medio-e-valorizzazione)).
|
||||
- Il **margine** è calcolato sul prezzo: (prezzo - costo) / prezzo.
|
||||
- Chi non ha il permesso `items.cost.read` non vede i costi (né nella scheda né nell'elenco né nei listini) e,
|
||||
quando salva, i costi in archivio restano quelli di prima.
|
||||
|
||||
### Giacenze e riordino
|
||||
|
||||
Con **Gestito a magazzino** l'articolo parteciperà a movimenti, giacenze per deposito (*Giacenza, Impegnato,
|
||||
Ordinato, Disponibile, Valore*) e **proposta di riordino**: questi arrivano con il magazzino (M6). Scorta minima,
|
||||
punto e lotto di riordino si possono già compilare.
|
||||
Con **Gestito a magazzino** l'articolo partecipa a movimenti, giacenze per deposito (*Giacenza, Impegnato,
|
||||
Ordinato, Disponibile, Valore*) e **proposta di riordino** (vedi [Magazzino](Magazzino)). **Scorta minima**, **punto
|
||||
di riordino** e **lotto di riordino** decidono lo stato dell'articolo nelle giacenze e la quantità proposta; il
|
||||
**fornitore preferito** della scheda *Fornitori*, con prezzo, minimo d'ordine e lead time, è quello a cui la
|
||||
proposta ordina.
|
||||
|
||||
### Controlli al salvataggio
|
||||
|
||||
|
||||
@@ -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 |
|
||||
@@ -137,13 +137,18 @@ il dettaglio dell'ultima. Le esecuzioni sono registrate nel database di sistema.
|
||||
|
||||
## Job di sistema
|
||||
|
||||
Nella versione 0.2.0 i job di sistema sono questi (orari nel fuso `Europe/Rome`):
|
||||
Nella versione 0.7.0 i job di sistema sono questi (orari nel fuso `Europe/Rome`):
|
||||
|
||||
| Codice | Cosa fa | Quando |
|
||||
|---|---|---|
|
||||
| `system.sessions-cleanup` | elimina le sessioni scadute o revocate da più di 30 giorni, nel database di sistema e in ogni azienda non disattivata | al minuto 15 di ogni ora |
|
||||
| `system.license-check` | ricalcola la licenza; avvisa gli amministratori a 30, 14, 7, 3 e 1 giorno dalla scadenza e quando è scaduta | ogni ora |
|
||||
| `system.log-retention` | elimina gli eventi di log più vecchi della retention del loro livello | ogni notte alle 03:30 |
|
||||
| `system.attachments-trash` | svuota il cestino degli allegati oltre i giorni di conservazione | ogni notte alle 03:45 |
|
||||
| `system.ecb-rates` | scarica i cambi di riferimento della BCE (richiede la rete) | nei giorni feriali alle 16:30 |
|
||||
| `inventory.rebuild` | ricostruisce il magazzino di ogni azienda attiva dai documenti in vigore (vedi [Magazzino](Magazzino#ricostruzione)) | la domenica alle 02:15 |
|
||||
| `ledger.recurring` | crea le registrazioni ricorrenti arrivate alla loro data in ogni azienda con la contabilità (vedi [Contabilità](Contabilita)) | ogni giorno alle 05:00 |
|
||||
| `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,
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Changelog
|
||||
|
||||
> **Stato:** completa per 0.5.0 · **Ultima revisione:** 2026-11-12
|
||||
> **Stato:** completa per 0.9.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,10 @@ Le novità di ogni versione sono nel file
|
||||
|
||||
| Versione | Data | Contenuto |
|
||||
|---|---|---|
|
||||
| 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. |
|
||||
| 0.4.0 | 2026-11-12 | M4 — Tabelle, anagrafiche, articoli: pacchetto fiscale italiano, profilo azienda, esercizi e cambi, 26 tabelle azienda con province, comuni e CAP, clienti, fornitori e contatti con controlli e VIES, articoli e listini con prezzi a validità, codici automatici, import/export guidato (anche del piano dei conti, per ora solo verifica) e dati di esempio. |
|
||||
| 0.3.0 | 2026-11-11 | M3 — Framework UI: la finestra di Khaemhat con menu, schede e barra di stato, la dashboard a widget, *Il mio profilo* con temi e colori, ricerca globale, aiuto in app, notifiche, componenti per maschere e liste, allegati e anteprima di stampa (provati su un documento di prova, le maschere gestionali arrivano da 0.4.0). |
|
||||
|
||||
@@ -1,272 +1,321 @@
|
||||
# Contabilità generale
|
||||
|
||||
> **Stato:** bozza · **Ultima revisione:** 2026-11-10 · **Versione software:** non ancora rilasciata (milestone M7; chiusura esercizio e bilancio CEE in M10)
|
||||
> **Modulo di licenza:** ACCT · **Permessi principali:** `ledger.entry.write`, `ledger.entry.finalize`, `ledger.entry.reopen`, `ledger.account.write`, `ledger.closing.run`, `ledger.export` · **Specifica:** SPEC §11.7, §11.1, §14
|
||||
> **Stato:** completa per la versione 0.7 · **Ultima revisione:** 2026-11-13 · **Versione software:** 0.7.0 (M7)
|
||||
> **Modulo di licenza:** ACCT · **Permessi principali:** `ledger.account.read`/`write` (piano dei conti e causali), `ledger.entry.read`/`write` (prima nota, partitari, bilancio), `ledger.entry.finalize` (registrazioni definitive) · **Specifica:** SPEC §11.7, §14, ADR 0036, ADR 0037
|
||||
|
||||
## A cosa serve
|
||||
Il modulo **Contabilità** tiene la **contabilità generale in partita doppia** dell'azienda: piano dei conti, causali,
|
||||
prima nota, registrazioni ricorrenti, partitari di clienti e fornitori, mastrini, bilancio di verifica e libro
|
||||
giornale. È collegato al resto del gestionale: ogni fattura, nota di credito o autofattura confermata scrive da sola
|
||||
la sua registrazione, con le righe IVA e le partite.
|
||||
|
||||
Il modulo Contabilità tiene la **contabilità generale in partita doppia** dell'azienda: piano dei conti, causali,
|
||||
prima nota, partitari e mastrini, esercizi e periodi, chiusura dell'esercizio e bilancio. È collegato al resto del
|
||||
gestionale: ogni documento confermato (fattura di vendita o di acquisto, nota di credito, incasso, pagamento,
|
||||
ammortamento…) genera da solo la propria registrazione partendo dalla **causale contabile** del tipo di documento.
|
||||
La parte fiscale (registri IVA, liquidazione, acconto, F24, LIPE, ritenute d'acconto, bollo virtuale) è descritta
|
||||
nella pagina [IVA](IVA); le regole italiane usate (piano dei conti modello, codici tributo, scadenze) in
|
||||
[Fiscalità italiana](Fiscalita-italiana).
|
||||
|
||||
La parte IVA (registri, liquidazione, F24, LIPE, ritenute, bollo, dichiarazioni d'intento) è descritta nella pagina
|
||||
[IVA](IVA); i cespiti nella pagina [Cespiti](Cespiti); partite, incassi e banche nello [Scadenzario](Scadenzario).
|
||||
> **In questa versione** ci sono il piano dei conti modello *PMI standard* con voci CEE, le causali contabili, la
|
||||
> prima nota manuale con castelletto IVA, la **contabilizzazione automatica** di fatture, note e autofatture, le
|
||||
> registrazioni ricorrenti, lo storno, le registrazioni definitive con il numero di libro giornale, i partitari con
|
||||
> estratto conto e partite, i mastrini, il bilancio di verifica e le stampe del bilancio e del libro giornale.
|
||||
> Dalla 0.8 incassi, pagamenti, distinte e riconciliazione bancaria scrivono le loro registrazioni dallo
|
||||
> [Scadenzario](Scadenzario). Arrivano più avanti: **chiusura
|
||||
> dell'esercizio**, ratei e risconti, **bilancio CEE** riclassificato e **cespiti** (M10). Non ci sono ancora
|
||||
> l'import del piano dei conti da file e l'export per il commercialista.
|
||||
|
||||
## Dove si trova
|
||||
|
||||
Menu laterale **Contabilità**, con le voci **Prima nota**, **Piano dei conti**, **Causali contabili**, **Registri IVA**,
|
||||
**Liquidazione IVA**, **Ritenute**, **Chiusura esercizio**, **Bilancio**. Esercizi e periodi si gestiscono da
|
||||
**Tabelle azienda → Esercizi** (mockup 052). Le voci compaiono solo se il modulo ACCT è licenziato e l'utente ha i
|
||||
permessi (vedi [Licenze e moduli](Licenze-e-moduli) e [Utenti e permessi](Utenti-e-permessi)).
|
||||
Menu **Contabilità** → *Prima nota*, *Piano dei conti*, *Causali*, *Partitari*, *Registri IVA*, *Liquidazione IVA*,
|
||||
*Ritenute e F24*, *Bollo virtuale*, *Bilancio*. Le ultime quattro voci fiscali sono spiegate in [IVA](IVA).
|
||||
|
||||
## Schermate
|
||||
Il menu compare solo se la licenza dell'azienda comprende il modulo **ACCT** e l'utente ha i permessi (vedi
|
||||
[Licenze e moduli](Licenze-e-moduli) e [Utenti e permessi](Utenti-e-permessi)). Esercizi e periodi si gestiscono da
|
||||
**Tabelle azienda → Esercizi** (vedi [Tabelle azienda](Tabelle-azienda)); periodicità IVA e pro rata sono nel
|
||||
**profilo azienda**.
|
||||
|
||||

|
||||
*Mockup 040 — registrazione di prima nota generata da una fattura di acquisto: intestazione con causale FA, stato *Provvisoria* e *Quadrata*, righe in partita doppia con centro di costo e partita, riquadro delle righe IVA (anteprima ridotta)*
|
||||
|
||||

|
||||
*Mockup 041 — giroconto manuale in bozza con sbilancio di € 300,00 evidenziato e suggerimento "Ctrl+D quadra sull'ultima riga" (anteprima ridotta)*
|
||||
|
||||

|
||||
*Mockup 042 — albero dei conti con saldi, dettaglio del sottoconto (natura, tipo, conto padre, voce CEE, riclassificato, flag) e mastrino sotto (anteprima ridotta)*
|
||||
|
||||

|
||||
*Mockup 043 — elenco delle causali con area, registro IVA e "genera partita"; sotto, il modello righe della causale FA con ruoli, segno e base d'importo (anteprima ridotta)*
|
||||
|
||||

|
||||
*Mockup 044 — partitario di un cliente con saldo iniziale, dare/avere del periodo, saldo e scaduto; movimenti con saldo progressivo e stato della partita (anteprima ridotta)*
|
||||
|
||||

|
||||
*Mockup 050 — procedura guidata di chiusura in nove passi raggruppati in cinque fasi (Controlli, Assestamento, Chiusura, Apertura, Stampe), con esito e autore di ogni passo*
|
||||
|
||||

|
||||
*Mockup 051 — bilancio CEE con stato patrimoniale espandibile e conto economico a confronto con l'esercizio precedente (Δ %); viste Verifica, CEE, Riclassificato, Indici*
|
||||
|
||||

|
||||
*Mockup 052 — elenco degli esercizi con stato, registrazioni e ultimo periodo IVA liquidato; sotto, i periodi mensili con stato (Aperto, Liquidato, Bloccato) e interruttore di blocco*
|
||||
|
||||
## Piano dei conti
|
||||
|
||||
Il piano dei conti ha tre livelli con codice **`MM.CC.SSS`** (mastro, conto, sottoconto; per esempio `01.04.001`
|
||||
*Clienti Italia*). Alla creazione dell'azienda viene **precaricato un piano standard per PMI** con le voci di bilancio
|
||||
CEE già associate (nel mockup 042 l'intestazione mostra la versione del modello caricato).
|
||||
|
||||
| Campo | Significato |
|
||||
|---|---|
|
||||
| **Codice** | `MM.CC.SSS`, gerarchico; il conto padre è il livello superiore |
|
||||
| **Descrizione** | obbligatoria |
|
||||
| **Natura** | patrimoniale (attività/passività), economica (costi/ricavi), d'ordine |
|
||||
| **Tipo** | mastro, conto, sottoconto |
|
||||
| **Voce CEE** | voce dello schema di stato patrimoniale (art. 2424 c.c.) o conto economico (art. 2425 c.c.) |
|
||||
| **Riclassificato** | voce del riclassificato finanziario/gestionale (es. *Crediti commerciali*) |
|
||||
| **Partitario clienti/fornitori** | il conto si articola per controparte (vedi sotto) |
|
||||
| **Rilevante IVA** | il conto entra nei controlli IVA |
|
||||
| **Chiusura automatica** | il conto viene chiuso dalla procedura di fine esercizio |
|
||||
| **Movimentabile** | si possono registrare movimenti (di norma solo i sottoconti) |
|
||||
| **Attivo** | i conti disattivati restano nello storico ma non si propongono |
|
||||
|
||||
Selezionando un conto nell'albero si vedono a destra i suoi dati e sotto il **mastrino** (data, registrazione,
|
||||
descrizione, dare, avere, saldo); il pulsante **Mastrino completo** apre la vista intera con i filtri.
|
||||
|
||||
### Importare un piano dei conti
|
||||
|
||||
Non esiste in Italia un formato standard per scambiare il piano dei conti, quindi Khaemhat accetta tre formati:
|
||||
|
||||
| Formato | Uso | Contenuto |
|
||||
|---|---|---|
|
||||
| **CSV** (separatore `;`) | import da altri gestionali o da foglio di calcolo | colonne `codice;descrizione;livello;padre;natura;tipo;voce_cee;riclassifica;flag` |
|
||||
| **XLSX** | come il CSV | stesso tracciato, una riga per conto |
|
||||
| **JSON** (`khaemhat-coa.json`) | export/import completo fra installazioni Khaemhat | conti, voci di bilancio, causali e mappature |
|
||||
|
||||
1. Apri **Contabilità → Piano dei conti** e premi **Importa piano dei conti** (oppure usa la procedura guidata di
|
||||
[Import-Export](Import-Export)).
|
||||
2. Scegli il file e verifica la **mappatura delle colonne**.
|
||||
3. Controlla l'**anteprima**: Khaemhat verifica la coerenza gerarchica (ogni conto ha un padre esistente, il livello
|
||||
corrisponde al codice, le voci CEE esistono) e segnala le righe errate.
|
||||
4. Conferma. Il risultato e gli eventuali errori restano nel report dell'importazione.
|
||||
|
||||
I valori ammessi nelle colonne `natura`, `tipo` e `flag` saranno fissati in sviluppo e riportati qui.
|
||||
|
||||
## Causali contabili e ruoli
|
||||
|
||||
Una **causale contabile** è il modello di una registrazione. Ogni causale ha **righe modello** che non indicano un
|
||||
conto fisso ma un **ruolo**; il ruolo viene risolto nel conto reale al momento della registrazione (il conto del
|
||||
cliente, il conto di ricavo dell'articolo o della sua categoria, il conto IVA del codice IVA…).
|
||||
|
||||
| Ruolo | Esempio di conto risolto |
|
||||
|---|---|
|
||||
| cliente / fornitore | sottoconto del partitario della controparte |
|
||||
| ricavo / costo | conto della riga, dell'articolo o della categoria |
|
||||
| IVA vendite / IVA acquisti | conti IVA del codice IVA |
|
||||
| banca / cassa | conto collegato al conto bancario o alla cassa |
|
||||
| Erario ritenute, cassa previdenza, bollo | conti configurati per azienda |
|
||||
| abbuoni, contropartita | conti configurati o indicati a mano |
|
||||
|
||||
Per ogni riga si indicano anche **dare/avere**, la base dell'importo (totale documento, imponibile riga, IVA
|
||||
detraibile, IVA indetraibile, ritenuta, cassa…), il **registro IVA** e se la riga **genera una partita** nello
|
||||
scadenzario. Il pulsante **Prova su documento** mostra la registrazione che la causale produrrebbe su un documento
|
||||
esistente, senza salvarla.
|
||||
|
||||
Causali di base precaricate: **FV** fattura di vendita, **NCV** nota di credito a cliente, **FA** fattura di
|
||||
acquisto, **NCA** nota di credito da fornitore, **AFRC** integrazione reverse charge (autofatture TD16-TD19),
|
||||
**CORR** corrispettivi, **INC** incasso, **PAG** pagamento, **INS** insoluto, **GIRO** giroconto, **AMM**
|
||||
ammortamenti, **RAT** ratei e risconti, **RIM** rimanenze, chiusura e apertura, **F24**, ritenute versate, stipendi
|
||||
(da import), interessi e commissioni.
|
||||
```
|
||||
Fattura / nota / autofattura ──Conferma──► Registrazione "Da documento" (righe, castelletto IVA, partite)
|
||||
Registrazione manuale ──Registra──► Registrata ──Rendi definitive──► Definitiva (n. libro giornale) ──Storna──► Storno
|
||||
Ricorrente ──ogni notte alle 5:00──► Registrazione "Ricorrente" alla data prevista
|
||||
```
|
||||
|
||||
## Prima nota
|
||||
|
||||
Ogni registrazione ha un numero per esercizio (es. `2026/001205`), data di registrazione, data di competenza,
|
||||
causale, descrizione, documento d'origine, registro IVA e protocollo, stato, periodo e fonte.
|
||||

|
||||
*La prima nota dell'azienda demo: fatture di vendita (FV) e di acquisto (FA), nota di credito (NCV), liquidazioni IVA
|
||||
(LIQ), versamenti F24, ritenuta (RIT) e il noleggio mensile ricorrente, tutte nello stato* Registrata.
|
||||
|
||||
### Registrare a mano
|
||||
**Contabilità → Prima nota** elenca le registrazioni dell'esercizio, la più recente per prima, con numero, data,
|
||||
causale, descrizione, documento, cliente o fornitore, importo e stato. In alto la ricerca (descrizione, numero o
|
||||
documento) e i filtri **Dal**, **Al** e **Stato**; in fondo la paginazione. Un clic sul numero apre la registrazione.
|
||||
|
||||
1. **Contabilità → Prima nota**, premi **+** (Ctrl+N) e scegli la causale.
|
||||
2. Nella scheda **Righe contabili** inserisci conto (F4 apre il piano dei conti), descrizione, controparte, dare o
|
||||
avere, centro di costo, commessa e partita. Ctrl+↓ aggiunge una riga.
|
||||
3. Se la registrazione ha IVA, compila la scheda **Righe IVA** (codice IVA, imponibile, aliquota, imposta, % di
|
||||
indetraibilità, detraibile, natura).
|
||||
4. Controlla la **quadratura** nell'intestazione: Dare, Avere e **Sbilancio**. Se c'è uno sbilancio, **Ctrl+D**
|
||||
lo assegna all'ultima riga.
|
||||
5. **Salva** (Ctrl+S). La registrazione resta *provvisoria*; quando è corretta premi **Rendi definitiva**.
|
||||
La scheda **Registrazioni** contiene l'elenco; la scheda **Ricorrenti** le registrazioni che si ripetono (vedi
|
||||
[sotto](#registrazioni-ricorrenti)). I pulsanti della barra:
|
||||
|
||||
Una registrazione che non quadra si può salvare **solo come bozza** (mockup 041: badge rosso con lo sbilancio) e non
|
||||
può mai diventare definitiva.
|
||||
|
||||
### Stati e regole
|
||||
|
||||
| Stato | Cosa significa | Cosa si può fare |
|
||||
| Pulsante | Cosa fa | Permesso |
|
||||
|---|---|---|
|
||||
| **Bozza / Provvisoria** | in lavorazione, entra nei saldi ma non sul libro giornale definitivo | modificare, eliminare, rendere definitiva (solo se quadra) |
|
||||
| **Definitiva** | numerata in modo continuo sul libro giornale | **immutabile**: si corregge solo con uno **storno** collegato |
|
||||
| **Nuova registrazione** | apre una registrazione vuota | `ledger.entry.write` |
|
||||
| **Contabilizza documenti** | registra in prima nota i documenti di vendita e acquisto confermati di un periodo che non sono ancora contabilizzati | `ledger.entry.write` |
|
||||
| **Rendi definitive** | rende definitive tutte le registrazioni fino a un giorno | `ledger.entry.finalize` |
|
||||
|
||||
- Le registrazioni **generate da un documento** si modificano solo stornando o correggendo il documento d'origine
|
||||
(pulsante **Documento origine** per aprirlo).
|
||||
- Le date sono ammesse solo in **periodi aperti**: un periodo liquidato o bloccato e un esercizio chiuso rifiutano
|
||||
nuove registrazioni con data interna.
|
||||
- **Storna** crea la registrazione inversa collegata all'originale (campo *storno di*).
|
||||
- **Registrazioni ricorrenti**: da una registrazione manuale **Salva modello ricorrente** crea un modello riusabile
|
||||
(affitti, canoni, stipendi…).
|
||||
- **Valuta**: le righe possono essere in valuta estera con il cambio; le differenze cambio si rilevano alla chiusura
|
||||
della partita (vedi [Scadenzario](Scadenzario)).
|
||||
### Gli stati di una registrazione
|
||||
|
||||
| Stato | Significato | Cosa si può fare |
|
||||
|---|---|---|
|
||||
| **Bozza** | in lavorazione, senza numero; può non quadrare; non entra nei saldi | modificare, registrare, eliminare |
|
||||
| **Registrata** | numerata (per esempio `2026/00011`), quadrata, entra nei saldi e nei registri IVA | modificare ed eliminare (se manuale), stornare, rendere definitiva |
|
||||
| **Definitiva** | ha il numero di **libro giornale** | solo **stornare**: non si modifica né si elimina |
|
||||
|
||||
Ogni registrazione indica anche la sua **origine**: *Manuale*, *Da documento*, *Liquidazione IVA*, *Versamento F24*,
|
||||
*Ricorrente*, *Storno*, *Ritenuta*.
|
||||
|
||||
## Registrare a mano
|
||||
|
||||

|
||||
*La registrazione di una fattura di acquisto intracomunitaria: causale FA, registro ACQ1, fornitore in Avere e merci
|
||||
in Dare; nel castelletto IVA il codice NI41 (natura N3.2). La striscia in alto riassume Dare, Avere, Sbilancio e
|
||||
righe.*
|
||||
|
||||
1. **Contabilità → Prima nota → Nuova registrazione**.
|
||||
2. Nella **Testata** scegli la **data** e la **causale**: la causale propone le righe con conti e segni e il
|
||||
**registro IVA**. Scrivi la **descrizione** e, se serve, **numero** e **data del documento**.
|
||||
3. Nelle **Righe** completa per ogni riga il **conto** (si registra solo sui **sottoconti**), il **cliente o
|
||||
fornitore** (obbligatorio sui conti con partitario, come *Clienti Italia* e *Fornitori Italia*), la descrizione,
|
||||
il **centro di costo** e l'importo in **Dare** oppure in **Avere**. **Aggiungi riga** e il cestino aggiungono e
|
||||
tolgono righe.
|
||||
4. Se la registrazione ha IVA, compila il **Castelletto IVA** con **Aggiungi aliquota**: codice IVA, imponibile,
|
||||
imposta e parte indetraibile. Con righe IVA serve un registro IVA.
|
||||
5. Controlla la striscia in alto: **Dare**, **Avere**, **Sbilancio** e numero di **righe**. **Chiudi lo
|
||||
sbilancio** mette la differenza sull'ultima riga senza importo (o su una nuova riga, a cui dai il conto).
|
||||
6. **Salva bozza** conserva il lavoro anche se non quadra; **Registra** salva la registrazione, che deve quadrare, e
|
||||
le assegna il numero.
|
||||
|
||||
Una registrazione con righe IVA non si può datare in un periodo già **liquidato** (vedi [IVA](IVA#liquidazione-iva));
|
||||
nessuna registrazione si può datare in un periodo **bloccato**, in un esercizio chiuso o **prima dell'ultima
|
||||
registrazione definitiva**.
|
||||
|
||||
### Registrazioni che vengono dai documenti
|
||||
|
||||
Le registrazioni *Da documento* non si modificano né si eliminano dalla prima nota: si corregge il **documento** e
|
||||
Khaemhat riscrive la registrazione con lo stesso numero. Se il documento viene annullato, la registrazione sparisce
|
||||
oppure, se era già definitiva, viene stornata.
|
||||
|
||||
### Stornare ed eliminare
|
||||
|
||||
- **Storna** chiede la **data dello storno** e crea una nuova registrazione con Dare e Avere invertiti, collegata
|
||||
all'originale (che diventa *Stornata*). Si stornano solo le registrazioni registrate o definitive, una volta sola.
|
||||
- **Elimina** toglie una registrazione manuale non definitiva. Una registrazione usata come modello di una ricorrente
|
||||
si elimina solo dopo aver tolto la ricorrente.
|
||||
|
||||
### Rendere definitive le registrazioni
|
||||
|
||||
**Rendi definitive** chiede un giorno e rende definitive tutte le registrazioni registrate fino a quel giorno: ognuna
|
||||
riceve il **numero di libro giornale**, in ordine di data, e da quel momento si corregge solo con uno storno.
|
||||
L'operazione non si annulla ed è rifiutata se nel periodo ci sono ancora **bozze** (registrale o eliminale prima).
|
||||
Dopo, nessuna nuova registrazione può avere una data anteriore all'ultima definitiva.
|
||||
|
||||
## Contabilizzazione automatica dei documenti
|
||||
|
||||
Alla conferma di un documento (o in un secondo momento con la procedura **Contabilizzazione documenti**, vedi
|
||||
[Automazioni](Automazioni)) Khaemhat applica la causale contabile del **tipo documento** e genera la registrazione
|
||||
con le righe IVA e le partite di scadenzario, nella stessa transazione del documento. Il documento mostra il flag
|
||||
*contabilizzato* e il collegamento alla registrazione; la registrazione mostra il documento d'origine.
|
||||
Con il modulo ACCT attivo, quando **confermi** (o emetti) uno di questi documenti Khaemhat scrive la sua registrazione
|
||||
**nella stessa operazione**, con le righe IVA nel suo registro, le **partite** dalle rate di scadenza e l'eventuale
|
||||
**ritenuta d'acconto**:
|
||||
|
||||
## Partitari, mastrini ed estratti conto
|
||||
|
||||
Il **partitario** (mockup 044) mostra per un cliente o fornitore: saldo iniziale, dare e avere del periodo, saldo,
|
||||
di cui scaduto e l'elenco dei movimenti con saldo progressivo e stato della partita. Filtri per periodo, conto,
|
||||
stato e "solo definitive". Da qui:
|
||||
|
||||
- **Estratto conto**: genera il PDF da inviare al cliente (resta come allegato, vedi [Allegati e file](Allegati-e-file));
|
||||
- **Sollecito**: apre i solleciti dello [Scadenzario](Scadenzario).
|
||||
|
||||
Il **drill-down** è completo: dal bilancio al conto, dal conto al mastrino, dal mastrino alla registrazione, dalla
|
||||
registrazione al documento.
|
||||
|
||||
## Esercizi e periodi
|
||||
|
||||
In **Tabelle azienda → Esercizi** (mockup 052) ogni esercizio ha inizio, fine, stato, numero di registrazioni,
|
||||
ultimo periodo IVA liquidato, data di blocco, prima pagina del libro giornale e ultima registrazione definitiva.
|
||||
|
||||
| Esercizio | Periodo (mese o trimestre) |
|
||||
|---|---|
|
||||
| **Aperto** — si registra normalmente | **Aperto** — accetta registrazioni |
|
||||
| **In chiusura** — è in corso la procedura di chiusura | **Liquidato** — la liquidazione IVA è stata confermata |
|
||||
| **Chiuso** — sola lettura | **Bloccato** — rifiuta ogni registrazione con data interna |
|
||||
|
||||
**Nuovo esercizio** crea l'esercizio successivo; di norma lo crea la chiusura stessa, in stato provvisorio, per
|
||||
permettere di registrare nel nuovo anno prima di aver chiuso il vecchio. I periodi si bloccano e sbloccano con
|
||||
l'interruttore **Blocco** (permesso di riapertura richiesto).
|
||||
|
||||
## Chiusura dell'esercizio guidata
|
||||
|
||||
**Contabilità → Chiusura esercizio** (mockup 050) guida la chiusura in nove passi. Ogni passo è **ripetibile e
|
||||
annullabile**; le registrazioni generate sono marcate con la fonte `closing/<passo>` e restano provvisorie fino alle
|
||||
stampe definitive.
|
||||
|
||||
| # | Passo | Cosa fa |
|
||||
| Documento | Causale | Registro IVA |
|
||||
|---|---|---|
|
||||
| 1 | Controlli preliminari | nessuna registrazione provvisoria, partite quadrate, IVA liquidata, numerazioni continue |
|
||||
| 2 | Ammortamenti | quote civilistiche e fiscali dei [Cespiti](Cespiti) |
|
||||
| 3 | Ratei e risconti | da competenze dei documenti e inserimenti manuali (**Verifica ratei/risconti**) |
|
||||
| 4 | Rimanenze finali | valorizzazione del [Magazzino](Magazzino) al 31/12 e storno delle iniziali |
|
||||
| 5 | Accantonamenti | svalutazione crediti, TFR (da import) |
|
||||
| 6 | Chiusura conti economici | giroconto a Conto economico e rilevazione del risultato |
|
||||
| 7 | Chiusura conti patrimoniali | giroconto a Stato patrimoniale finale |
|
||||
| 8 | Apertura nuovo esercizio | riporto dei saldi e delle partite aperte |
|
||||
| 9 | Stampe definitive | libro giornale, libro inventari, registri IVA, registro cespiti |
|
||||
| Fattura immediata, accompagnatoria, differita, di acconto; nota di debito; parcella | `FV` | `VEN1` |
|
||||
| Nota di credito a cliente | `NCV` | `VEN1` |
|
||||
| Fattura fornitore | `FA` | `ACQ1` |
|
||||
| Nota di credito fornitore | `NCA` | `ACQ1` |
|
||||
| Autofatture e integrazioni (AF16-AF29) | `AFRC` | `VEN-RC` e `ACQ-RC` |
|
||||
|
||||
1. Apri la procedura e premi **Esegui passo N**: il passo mostra il numero di registrazioni prodotte e l'esito
|
||||
(*Superato*, *Eseguito*, *Da verificare*, *In attesa*).
|
||||
2. Controlla i risultati con l'icona di anteprima e, se serve, torna indietro di un passo.
|
||||
3. Dopo le stampe definitive premi **Blocca esercizio**: l'esercizio diventa **chiuso**, in sola lettura, e le date
|
||||
precedenti al nuovo esercizio vengono rifiutate.
|
||||
Come si formano le righe:
|
||||
|
||||
La chiusura è anche nel catalogo delle procedure ([Automazioni](Automazioni)).
|
||||
- **Vendita**: il **cliente** in Dare per il totale; i **ricavi** in Avere, raggruppati per conto; la **rivalsa
|
||||
della cassa previdenziale** e il **bollo addebitato** al cliente in Avere; l'**IVA vendite** in Avere. Con lo
|
||||
**split payment** l'IVA viene subito tolta al cliente (il cliente paga solo l'imponibile).
|
||||
- **Acquisto**: il **fornitore** in Avere; i **costi** in Dare, con l'**IVA indetraibile** aggiunta al costo;
|
||||
l'**IVA acquisti** in Dare.
|
||||
- **Autofattura e integrazione**: **IVA acquisti** in Dare e **IVA vendite** in Avere, senza cliente né fornitore;
|
||||
il documento compare in entrambi i registri RC, con effetto neutro sulla liquidazione.
|
||||
- **Note di credito**: le stesse righe con i segni invertiti.
|
||||
- Lo **sconto in calce** e gli **arrotondamenti** si ripartiscono sulle righe; i centesimi di differenza vanno sulla
|
||||
riga più grande.
|
||||
|
||||
## Bilancio
|
||||
**Quale conto.** Per ogni riga Khaemhat usa il **Conto ricavi** o **Conto costi** dell'articolo (scheda articolo),
|
||||
per gli acquisti il **Conto di costo** del fornitore, poi il conto del codice IVA e, se manca, quello della causale
|
||||
(`30.01.001` *Ricavi per vendita di merci*, `20.01.001` *Merci c/acquisti*). Il cliente e il fornitore usano il
|
||||
**Conto cliente** o **Conto fornitore** della loro scheda, altrimenti `05.01.001` *Clienti Italia* e `14.01.001`
|
||||
*Fornitori Italia*. Se manca un conto la conferma del documento si ferma con un messaggio che lo dice.
|
||||
|
||||
**Contabilità → Bilancio** (mockup 051) offre quattro viste:
|
||||
**Contabilizza documenti.** I documenti confermati quando ACCT non era attivo (o prima della versione 0.7) si
|
||||
registrano in blocco: **Prima nota → Contabilizza documenti**, scegli **Dal** e **Al** e premi **Contabilizza**. La
|
||||
casella *Ricontabilizza anche i documenti già registrati* riscrive anche le registrazioni esistenti, purché non
|
||||
siano definitive.
|
||||
|
||||
| Vista | Contenuto |
|
||||
## Registrazioni ricorrenti
|
||||
|
||||

|
||||
*Il noleggio mensile della stampante dei dati demo: frequenza mensile, prossima data, registrazione modello e stato.*
|
||||
|
||||
Affitti, canoni, noleggi: una registrazione **ricorrente** copia una **registrazione modello** alle date previste.
|
||||
|
||||
1. Registra una volta la scrittura da ripetere (per esempio *Noleggi* in Dare e *Banca c/c* in Avere).
|
||||
2. **Prima nota → Ricorrenti → Nuova ricorrente**: descrizione, **numero della registrazione modello** (il numero di
|
||||
prima nota, per esempio `2026/00018`), **frequenza** (*Mensile*, *Trimestrale*, *Semestrale*, *Annuale*),
|
||||
**prossima data**, data **Fino al** facoltativa, casella **Sospesa**.
|
||||
3. Ogni notte alle **5:00** l'attività di sistema *Registrazioni ricorrenti* (vedi
|
||||
[Attività programmate](Attivita-programmate)) scrive le registrazioni arrivate a scadenza, con origine
|
||||
*Ricorrente*, e sposta in avanti la prossima data. **Genera ora** fa lo stesso subito.
|
||||
|
||||
Una data di fine mese resta di fine mese (31/01, poi 28/02, poi 31/03). **Apri il modello** apre la registrazione da
|
||||
copiare; eliminando una ricorrente le registrazioni già generate restano.
|
||||
|
||||
## Piano dei conti
|
||||
|
||||

|
||||
*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: 240 conti con le voci di
|
||||
bilancio CEE già associate (vedi [Fiscalità italiana](Fiscalita-italiana#piano-dei-conti-modello)).
|
||||
|
||||
| Campo | Significato |
|
||||
|---|---|
|
||||
| **Verifica** | bilancio di verifica per conto (dare, avere, saldo); bilancini per centro di costo e commessa |
|
||||
| **CEE** | schema civilistico **ordinario**, **abbreviato** o **micro**, con confronto con l'esercizio precedente e Δ % |
|
||||
| **Riclassificato** | riclassificato finanziario e gestionale |
|
||||
| **Indici** | indici di bilancio |
|
||||
| **Codice** | mastro, conto e sottoconto separati da punti; il conto padre deve esistere |
|
||||
| **Descrizione** | obbligatoria |
|
||||
| **Natura** | *Attività*, *Passività*, *Costo*, *Ricavo*, *Conto d'ordine* |
|
||||
| **Tipo** | *Generico*, *Clienti*, *Fornitori*, *Banca*, *Cassa*, *IVA*, *Tributi*: dice alle registrazioni automatiche che cosa cercare |
|
||||
| **Voce di bilancio CEE** | voce dello schema civilistico (art. 2424 e 2425 c.c.), per esempio `C.II.1` |
|
||||
| **Riclassificazione** | voce del riclassificato, facoltativa |
|
||||
| **Partitario** | le righe indicano il cliente o il fornitore |
|
||||
| **Rilevante IVA** | il conto entra nelle registrazioni con IVA |
|
||||
| **Chiuso in automatico a fine esercizio** | il conto sarà chiuso dalla procedura di fine esercizio (M10) |
|
||||
| **Disattivato** | il conto resta nello storico ma non si usa più |
|
||||
|
||||
L'intestazione indica la data di situazione (anche **infrannuale**) e se include le registrazioni provvisorie.
|
||||
Doppio clic su una voce apre i conti, poi il mastrino, la registrazione e il documento. Il bilancio si stampa e si
|
||||
esporta in XLSX e PDF; la **nota integrativa** è prodotta in bozza. Il formato XBRL è previsto in fase 2
|
||||
([Roadmap](Roadmap)).
|
||||
A sinistra l'**albero** con la ricerca per codice o descrizione; a destra i dati del conto scelto e, per i
|
||||
sottoconti, il **mastrino**: i movimenti del periodo (**Dal**, **Al**) con saldo iniziale, Dare, Avere, **saldo
|
||||
progressivo**, totali e paginazione. **Stampa** scarica il mastrino in PDF; il numero della registrazione la apre.
|
||||
|
||||
## Export per il commercialista
|
||||
**Nuovo conto**, **Modifica** ed **Elimina** richiedono `ledger.account.write`. Un conto con **movimenti** non si
|
||||
elimina (disattivalo); un conto con **sottoconti** si elimina solo dopo di loro.
|
||||
|
||||
Pacchetto **ZIP mensile** con libro giornale, registri IVA, partitari e bilancio in XLSX, CSV e PDF. Si genera a mano
|
||||
o in automatico con la procedura **Export per il commercialista** pianificata ogni mese (vedi [Automazioni](Automazioni)
|
||||
e [Attività programmate](Attivita-programmate)).
|
||||
## Causali contabili
|
||||
|
||||
## Report del modulo
|
||||

|
||||
*Le causali di base con il loro registro IVA; a destra la causale FA Fattura di acquisto: area Acquisti, registro
|
||||
ACQ1, apre partite, e le righe proposte con ruolo, segno e conto.*
|
||||
|
||||
Libro giornale, mastrini, bilancini per centro di costo e commessa, registri IVA, liquidazioni, scadenzario IVA,
|
||||
elenco clienti e fornitori per fatturato, riepilogo per natura IVA, dati dei quadri VE/VF, estratti conto, export per
|
||||
il commercialista. Vedi [Report](Report).
|
||||
Una **causale** è il modello di una registrazione: propone conti, segni e registro IVA. Ogni causale ha:
|
||||
|
||||
## Scorciatoie
|
||||
|
||||
| Tasto | Azione |
|
||||
| Campo | Significato |
|
||||
|---|---|
|
||||
| Ctrl+N / Ctrl+S | nuova registrazione / salva |
|
||||
| Ctrl+D | quadra la registrazione sull'ultima riga |
|
||||
| F4 | ricerca nel piano dei conti dalla cella *Conto* |
|
||||
| Ctrl+↓ | nuova riga |
|
||||
| Ctrl+↑ / Ctrl+↓ (fuori dalla griglia) | registrazione precedente / successiva |
|
||||
| Alt+1…9 | cambia scheda |
|
||||
| **Codice**, **Descrizione** | per esempio `FA` *Fattura di acquisto* |
|
||||
| **Area** | *Generale*, *Vendite*, *Acquisti*, *Tesoreria*, *Imposte*, *Chiusura esercizio* |
|
||||
| **Registro IVA** | il registro delle registrazioni con IVA |
|
||||
| **Apre partite** | le registrazioni aprono partite di clienti o fornitori |
|
||||
| **Causale di storno** | note di credito: i segni del documento si invertono |
|
||||
| **Disattivato** | la causale non si propone più |
|
||||
| **Righe proposte** | per ogni riga **ruolo** (*Cliente*, *Fornitore*, *Ricavo*, *Costo*, *IVA vendite*, *IVA acquisti*, *Banca*, *Cassa*, *Ritenute da versare*, *Ritenute subite*, *Contributo cassa*, *Bollo*, *Arrotondamenti*, *Erario c/IVA*, *IVA split payment* o *Conto indicato*), **segno** Dare o Avere, **conto** e descrizione |
|
||||
|
||||
Elenco completo in [Interfaccia e scorciatoie](Interfaccia-e-scorciatoie).
|
||||
Causali di base: **FV** fattura di vendita, **NCV** nota di credito a cliente, **FA** fattura di acquisto, **NCA**
|
||||
nota di credito da fornitore, **AFRC** autofattura e integrazione reverse charge, **CORR** corrispettivi giornalieri,
|
||||
**INC** incasso da cliente, **PAG** pagamento a fornitore, **RIT** ritenuta d'acconto operata, **RITS** ritenuta
|
||||
d'acconto subita, **LIQ** liquidazione IVA periodica, **F24** versamento con modello F24, **GIRO** giroconto, **SPB**
|
||||
spese e commissioni bancarie, **STO** storno di scrittura.
|
||||
|
||||
Le causali dei documenti, della liquidazione, delle ritenute e dell'F24 sono usate dalle registrazioni automatiche:
|
||||
cambiarne i conti cambia le registrazioni future. Una causale usata da registrazioni non si elimina: disattivala.
|
||||
Per un'azienda creata con una versione precedente, conti, causali e registri mancanti si aggiungono con
|
||||
`scripts/seed.sh --base` (vedi [Dati di base e di esempio](Dati-di-base-e-esempio)).
|
||||
|
||||
## Partitari ed estratto conto
|
||||
|
||||

|
||||
*Il partitario clienti con Dare, Avere, saldo e partite aperte; a destra l'estratto conto di Edilizia Moderna S.p.A. e
|
||||
le sue partite, con le scadenze passate in rosso.*
|
||||
|
||||
**Contabilità → Partitari** ha due schede, **Clienti** e **Fornitori**. L'elenco mostra per ogni soggetto con
|
||||
movimenti Dare, Avere, **Saldo** e numero di partite **aperte**, con ricerca per nome o codice e il **saldo
|
||||
complessivo**.
|
||||
|
||||
Scegliendo un soggetto si vedono:
|
||||
|
||||
- l'**estratto conto** del periodo (**Dal**, **Al**): saldo iniziale, movimenti con documento e saldo progressivo,
|
||||
totali; **Stampa** lo scarica in PDF;
|
||||
- le **partite**: una per rata di ogni documento, con data documento, numero della rata, **scadenza**, importo,
|
||||
pagato e **residuo**; le scadenze superate sono in rosso. *Mostra anche le partite chiuse* aggiunge quelle saldate.
|
||||
|
||||
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
|
||||
|
||||

|
||||
*Il bilancio di verifica dell'azienda demo al livello dei sottoconti, con i totali di conti e mastri; la striscia
|
||||
riassume Dare, Avere, quadratura e risultato del periodo.*
|
||||
|
||||
**Contabilità → Bilancio** mostra i saldi di tutti i conti in un periodo:
|
||||
|
||||
- filtri **Dal** e **Al**, **Centro di costo** (tutti o uno), **Dettaglio** (*Mastri*, *Conti*, *Sottoconti*) e
|
||||
**Comprendi le bozze**;
|
||||
- per ogni conto **saldo iniziale**, **Dare**, **Avere**, **Saldo Dare** o **Saldo Avere**, con i totali di conti e
|
||||
mastri;
|
||||
- la striscia con i totali **Dare** e **Avere**, la **Quadratura** (*Dare e Avere quadrano* o no) e il **Risultato
|
||||
del periodo** (ricavi meno costi: *Utile* o *Perdita*).
|
||||
|
||||
Le stampe sono file PDF da scaricare:
|
||||
|
||||
| Pulsante | Contenuto |
|
||||
|---|---|
|
||||
| **Stampa bilancio** | il bilancio di verifica del periodo e del centro di costo scelti |
|
||||
| **Libro giornale di prova** | registrazioni registrate e definitive del periodo, in ordine di data, con le righe |
|
||||
| **Libro giornale definitivo** | solo le registrazioni definitive, con il numero di libro giornale e le pagine numerate dall'inizio dell'anno |
|
||||
|
||||
Il bilancio CEE (stato patrimoniale e conto economico civilistici), il riclassificato e gli indici arrivano con la
|
||||
chiusura dell'esercizio (M10).
|
||||
|
||||
## Dati demo
|
||||
|
||||
Con i dati di esempio (`scripts/seed.sh --demo`) la contabilità parte già popolata: i documenti demo sono
|
||||
contabilizzati, la fattura del professionista *Studio Rag. Neri Paola* è pagata e la sua ritenuta è da versare, il
|
||||
noleggio mensile della stampante (45 euro, conto `22.01.003` *Noleggi* contro la banca) è una registrazione
|
||||
ricorrente, le liquidazioni IVA dei mesi già finiti sono confermate e gli F24 già scaduti sono pagati. Vedi
|
||||
[Dati di base e di esempio](Dati-di-base-e-esempio).
|
||||
|
||||
## Permessi e licenza
|
||||
|
||||
Serve il modulo **ACCT**. Il permesso `ledger.entry.finalize` è necessario per rendere definitiva una registrazione;
|
||||
gli altri codici indicati in testa seguono la convenzione `modulo.entità.azione` (SPEC §7.2) e saranno fissati in
|
||||
sviluppo. Il ruolo predefinito **Contabilità** li comprende. Senza licenza ACCT le voci del menu non compaiono, ma i
|
||||
dati restano conservati.
|
||||
Serve il modulo **ACCT**: senza, il menu Contabilità non compare, i documenti non vengono contabilizzati (si
|
||||
recuperano dopo con **Contabilizza documenti**) e i dati già registrati restano conservati.
|
||||
|
||||
## Attenzione
|
||||
| Permesso | Cosa consente |
|
||||
|---|---|
|
||||
| `ledger.account.read` | vedere piano dei conti e causali |
|
||||
| `ledger.account.write` | creare, modificare ed eliminare conti e causali |
|
||||
| `ledger.entry.read` | prima nota, mastrini, partitari, bilancio e stampe del libro giornale |
|
||||
| `ledger.entry.write` | registrazioni manuali, storni, ricorrenti, contabilizzazione dei documenti |
|
||||
| `ledger.entry.finalize` | rendere definitive le registrazioni |
|
||||
|
||||
- Una registrazione **definitiva** non si modifica: va stornata. Usa lo stato provvisorio finché non hai controllato.
|
||||
- Confermare una liquidazione IVA blocca il periodo: correzioni successive richiedono la riapertura (permesso
|
||||
dedicato) e vanno ricalcolate.
|
||||
- I numeri del libro giornale definitivo sono continui; la procedura di chiusura verifica che non ci siano buchi.
|
||||
I permessi della parte IVA (`vat.register.read`, `vat.settlement.read`, `vat.settlement.confirm`) sono in [IVA](IVA).
|
||||
|
||||
## Domande frequenti
|
||||
|
||||
- **Il pulsante Registra è spento.** Dare e Avere non quadrano: guarda lo *Sbilancio* nella striscia, correggi gli
|
||||
importi o usa **Chiudi lo sbilancio**. Intanto puoi usare **Salva bozza**.
|
||||
- **"Si registra solo sui sottoconti".** Hai scelto un mastro o un conto: scegli un sottoconto (codice a tre parti).
|
||||
- **"Le righe su clienti e fornitori indicano il soggetto".** Il conto ha il partitario: indica il cliente o il
|
||||
fornitore nella riga.
|
||||
- **Non riesco a modificare la registrazione di una fattura.** Viene dal documento: correggi la fattura e la
|
||||
registrazione si aggiorna. Se è già definitiva, la correzione del documento la storna e la riscrive.
|
||||
- **"Manca un conto per contabilizzare il documento".** Una causale o il piano dei conti non hanno il conto che
|
||||
serve (per esempio dopo aver cancellato un sottoconto): controlla la causale del documento e il conto dell'articolo.
|
||||
- **La data è rifiutata.** Il periodo è liquidato (solo per registrazioni con IVA), bloccato, l'esercizio è chiuso o
|
||||
c'è già una registrazione definitiva successiva.
|
||||
- **La ricorrente non ha generato nulla.** È sospesa, la data *Fino al* è passata o la prossima data è nel futuro;
|
||||
**Genera ora** mostra l'eventuale problema.
|
||||
|
||||
## Pagine correlate
|
||||
|
||||
[IVA](IVA) · [Cespiti](Cespiti) · [Scadenzario](Scadenzario) · [Vendite](Vendite) · [Acquisti](Acquisti) ·
|
||||
[Magazzino](Magazzino) · [Tabelle azienda](Tabelle-azienda) · [Report](Report) · [Automazioni](Automazioni) ·
|
||||
[Import-Export](Import-Export) · [Fiscalità italiana](Fiscalita-italiana) · [Glossario](Glossario)
|
||||
[IVA](IVA) · [Fiscalità italiana](Fiscalita-italiana) · [Vendite](Vendite) · [Acquisti](Acquisti) ·
|
||||
[Scadenzario](Scadenzario) · [Cespiti](Cespiti) · [Tabelle azienda](Tabelle-azienda) ·
|
||||
[Attività programmate](Attivita-programmate) · [Dati di base e di esempio](Dati-di-base-e-esempio) ·
|
||||
[Glossario](Glossario)
|
||||
@@ -56,7 +56,7 @@ magazzino* M6, *CRM* M11), senza numeri finti.
|
||||
| **Attività CRM** | le attività del giorno (chiamate, riunioni, visite) | richiede il modulo CRM |
|
||||
| **Promemoria personali** | note libere, visibili solo a te | |
|
||||
| **Scorciatoie** | pulsanti configurabili verso maschere e azioni frequenti | |
|
||||
| **Sottoscorta** | articoli sotto la scorta minima | |
|
||||
| **Sottoscorta** | gli articoli più urgenti da riordinare (esauriti, sottoscorta, sotto il punto di riordino) con disponibile e scorta; un clic apre i movimenti dell'articolo, **Riordina** la proposta di riordino | dalla 0.6.0 |
|
||||
| **Pipeline CRM** | valore delle opportunità per fase | richiede il modulo CRM |
|
||||
| **Ultimi documenti** | ultimi documenti aperti o creati | |
|
||||
| **Stato del sistema** | versione, database, cache, licenza, aziende aperte, attività programmate di oggi, ognuno con un pallino verde, giallo o rosso | solo account di istanza |
|
||||
@@ -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
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Dati di base e di esempio
|
||||
|
||||
> **Stato:** completa per M5 · **Ultima revisione:** 2026-11-12 · **Versione software:** 0.5.0 (dati di esempio di acquisti, magazzino e contabilità con i moduli, completi in M9)
|
||||
> **Stato:** completa per la versione 0.9 · **Ultima revisione:** 2026-11-13 · **Versione software:** 0.9.0 (M9)
|
||||
> **Modulo di licenza:** CORE · **Livello richiesto:** amministratore (rimozione dati di esempio: super utente) · **Specifica:** SPEC §6, §12.11, §14
|
||||
|
||||
## A cosa serve
|
||||
@@ -115,7 +115,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 |
|
||||
@@ -148,7 +148,46 @@ pagina delle stampe) e **un anno di vendite** costruite con il motore dei docume
|
||||
|
||||
Le fatture e la nota condividono il numeratore (`1/2026` … `7/2026`), senza buchi e in ordine di data. Tutti i
|
||||
documenti sono marcati come dimostrativi e la stampa lo scrive in evidenza. Il caricamento non si ripete se
|
||||
l'azienda ha già documenti di vendita. Il resto della tabella arriva con le milestone dei rispettivi moduli.
|
||||
l'azienda ha già documenti di vendita.
|
||||
|
||||
**Da M6** ci sono anche **acquisti e magazzino**, costruiti allo stesso modo:
|
||||
|
||||
| Documenti | Che cosa mostrano |
|
||||
|---|---|
|
||||
| 1 movimento di esistenze iniziali al 1° gennaio (`APE`) | la giacenza di partenza di ogni articolo; un articolo su cinque parte con poca merce, così le vendite lo portano sotto scorta e la [proposta di riordino](Magazzino#proposta-di-riordino) ha qualcosa da proporre |
|
||||
| 2 ordini fornitori | uno ricevuto per intero, uno ricevuto in parte (il resto è nell'*ordinato*) |
|
||||
| 2 ricevimenti merce | i carichi dei due ordini |
|
||||
| 3 fatture fornitore | una dal ricevimento con un prezzo più alto dell'ordine (vedi l'avviso sulle differenze), la parcella del commercialista, la fattura di un fornitore tedesco che aspetta la sua **integrazione AF18** |
|
||||
| 1 inventario aperto | 12 articoli già contati, due con una differenza |
|
||||
|
||||
Il caricamento non si ripete se l'azienda ha già documenti di acquisto o di magazzino.
|
||||
|
||||
**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 |
|
||||
|
||||
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.
|
||||
|
||||
@@ -163,8 +202,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)).
|
||||
@@ -191,6 +235,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]`.
|
||||
@@ -200,8 +245,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
|
||||
|
||||
@@ -1,200 +1,323 @@
|
||||
# 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.9 · **Ultima revisione:** 2026-11-13 · **Versione software:** 0.9.0 (M9)
|
||||
> **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. Arrivano più avanti: le **dichiarazioni
|
||||
> d'intento** e la **LIPE** ([IVA](IVA), M10), **Intrastat** ([Intrastat](Intrastat), M10) e 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.
|
||||
|
||||

|
||||
*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:
|
||||
|
||||

|
||||
*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 — 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 — 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 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 — esito della trasmissione di due file.*
|
||||
|
||||

|
||||
*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 — 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: 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 — 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`.
|
||||
|
||||
**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 — 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
|
||||
|
||||
|
||||
@@ -1,21 +1,30 @@
|
||||
# Fiscalità italiana
|
||||
|
||||
> **Stato:** bozza · **Ultima revisione:** 2026-11-11 · **Versione software:** 0.4.0 (codici e regole di base; il resto con M5-M10)
|
||||
> **Modulo di licenza:** CORE, ACCT, EINV, INTRA · **Specifica:** SPEC §11.1, §11.3-§11.9, §14
|
||||
> **Stato:** completa per la versione 0.9 · **Ultima revisione:** 2026-11-13 · **Versione software:** 0.9.0 (M9)
|
||||
> **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, codici tributo F24 e scadenze. Serve come
|
||||
riferimento rapido mentre si compilano anagrafiche, codici IVA e documenti.
|
||||
SDI, nature IVA, modalità e condizioni di pagamento, regimi fiscali, il **piano dei conti modello**, i **codici
|
||||
tributo F24** con le scadenze, la **LIPE**, le **ritenute d'acconto** e il **bollo virtuale**. Serve come riferimento
|
||||
rapido mentre si compilano anagrafiche, codici IVA e documenti e mentre si liquida l'IVA.
|
||||
|
||||
Tutte queste tabelle sono **caricate dai dati di base** (pacchetto dati, per esempio `IT 2026.3`) e si aggiornano da
|
||||
**Amministrazione → Dati di base e di esempio** con **Aggiorna tabelle di base**. Le descrizioni ufficiali complete
|
||||
sono quelle delle *specifiche tecniche della fattura elettronica* dell'Agenzia delle Entrate, caricate nel seed: in
|
||||
caso di dubbio fa fede il testo mostrato dal programma, non questa pagina.
|
||||
Tutto ciò che è italiano sta nel **pacchetto fiscale Italia** del programma: le tabelle sono **caricate dai dati di
|
||||
base** (pacchetto dati, per esempio `IT 2026.3`) e si aggiornano da **Amministrazione → Dati di base e di esempio**
|
||||
con **Aggiorna tabelle di base** (o con `scripts/seed.sh --base`). Le descrizioni ufficiali complete sono quelle
|
||||
delle *specifiche tecniche della fattura elettronica* dell'Agenzia delle Entrate, caricate nel seed: in caso di dubbio
|
||||
fa fede il testo mostrato dal programma, non questa pagina.
|
||||
|
||||
> **Attenzione.** Khaemhat calcola e prepara i dati (F24, LIPE, Intrastat, bollo) ma **non sostituisce il
|
||||
> commercialista** né invia F24 e LIPE: l'invio telematico avviene tramite intermediario o home banking, come
|
||||
> indicato nella maschera della liquidazione. Le norme cambiano: la versione delle specifiche SDI supportata è
|
||||
> indicata nel programma ed è verificata a ogni rilascio.
|
||||
> **In questa versione** sono in uso i codici dei documenti, delle nature, dei pagamenti e dei regimi (dalla 0.4),
|
||||
> e con la 0.7 il piano dei conti *PMI standard*, i registri IVA, le regole della liquidazione e dell'acconto, i
|
||||
> codici tributo e le scadenze dell'F24, il tracciato LIPE, le ritenute d'acconto e il bollo virtuale. Con la 0.9 il
|
||||
> file FatturaPA e le notifiche SDI sono in uso nella [Fatturazione elettronica](Fatturazione-elettronica). Le parti
|
||||
> su dichiarazioni d'intento, Intrastat e cespiti descrivono regole che il programma userà con [IVA](IVA),
|
||||
> [Cespiti](Cespiti) e [Intrastat](Intrastat) (M10).
|
||||
|
||||
> **Attenzione.** Khaemhat calcola e prepara i dati (F24, LIPE, Certificazione Unica, bollo) ma **non sostituisce il
|
||||
> commercialista** né invia F24, LIPE e CU: l'invio telematico avviene con i servizi dell'Agenzia delle Entrate,
|
||||
> l'home banking o l'intermediario, come ricordato nelle maschere. Le norme cambiano: la versione delle specifiche SDI
|
||||
> supportata (oggi la 1.9.1) è scritta nel pacchetto fiscale ed è verificata a ogni rilascio.
|
||||
|
||||
## Dove si trovano questi codici nel programma
|
||||
|
||||
@@ -25,10 +34,12 @@ caso di dubbio fa fede il testo mostrato dal programma, non questa pagina.
|
||||
| Nature IVA (N…) | **Tabelle azienda → Codici IVA** | [Tabelle-azienda](Tabelle-azienda), [IVA](IVA) |
|
||||
| Modalità di pagamento (MP) | **Tabelle azienda → Metodi di pagamento** | [Tabelle-azienda](Tabelle-azienda) |
|
||||
| Regime fiscale (RF) | **Tabelle azienda → Profilo azienda**, scheda fornitore | [Tabelle-azienda](Tabelle-azienda), [Anagrafiche](Anagrafiche) |
|
||||
| Codici tributo F24 | liquidazione IVA, ritenute, bollo virtuale | [IVA](IVA), [Contabilita](Contabilita) |
|
||||
| Piano dei conti, causali, registri IVA | **Contabilità → Piano dei conti**, *Causali*, *Registri IVA* | [Contabilita](Contabilita), [IVA](IVA) |
|
||||
| Codici tributo F24 | liquidazione IVA, acconto, ritenute, bollo virtuale | [IVA](IVA) |
|
||||
| Tipi di ritenuta (RT) e casse (TC) | scheda fiscale del fornitore e del cliente, parcelle, fatture dei professionisti | [Anagrafiche](Anagrafiche), [IVA](IVA#ritenute-dacconto) |
|
||||
|
||||

|
||||
*Mockup 076 — tabella dei codici IVA con aliquota, natura SDI, riferimento normativo ed esigibilità; sotto, il dettaglio del codice selezionato (anteprima ridotta).*
|
||||

|
||||
*La tabella dei codici IVA dell'azienda in Tabelle azienda: ogni codice porta aliquota o natura SDI.*
|
||||
|
||||
## Tipi documento SDI (TD)
|
||||
|
||||
@@ -168,72 +179,170 @@ 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).
|
||||
|
||||
|
||||
## Piano dei conti modello
|
||||
|
||||
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)).
|
||||
|
||||
| Mastri | Natura | Contenuto |
|
||||
|---|---|---|
|
||||
| `01`-`09` | Attività | immobilizzazioni immateriali, materiali e finanziarie, rimanenze, crediti verso clienti, altri crediti (IVA, tributi), disponibilità liquide, ratei e risconti attivi, fondi di ammortamento |
|
||||
| `10`-`17` | Passività | patrimonio netto, fondi rischi, TFR, debiti verso banche, fornitori, debiti tributari e previdenziali, altri debiti, ratei e risconti passivi |
|
||||
| `20`-`29` | Costi | acquisti, servizi, godimento di beni di terzi, personale, ammortamenti, variazioni delle rimanenze, accantonamenti, oneri diversi, oneri finanziari, imposte sul reddito |
|
||||
| `30`-`32` | Ricavi | vendite e prestazioni, altri ricavi e proventi, proventi finanziari |
|
||||
| `90` | Conti d'ordine | conti di apertura e chiusura |
|
||||
|
||||
I conti usati dalle registrazioni automatiche:
|
||||
|
||||
| Conto | Uso |
|
||||
|---|---|
|
||||
| `05.01.001` Clienti Italia | cliente delle fatture di vendita (se la scheda cliente non indica un altro conto) |
|
||||
| `14.01.001` Fornitori Italia | fornitore delle fatture di acquisto |
|
||||
| `30.01.001` Ricavi per vendita di merci, `30.02.001` Resi e sconti su vendite | ricavi delle fatture e delle note di credito senza conto sull'articolo |
|
||||
| `20.01.001` Merci c/acquisti, `20.02.001` Resi e sconti su acquisti | costi delle fatture e note di credito fornitore senza conto sull'articolo o sul fornitore |
|
||||
| `06.02.001` IVA su acquisti, `15.01.001` IVA su vendite | IVA dei registri acquisti e vendite |
|
||||
| `15.01.002` Erario c/liquidazione IVA | saldo della liquidazione periodica e suo versamento |
|
||||
| `15.02.001` Erario c/ritenute lavoro autonomo, `06.03.001` Erario c/ritenute subite | ritenute operate e subite |
|
||||
| `31.01.002` Rimborso spese di bollo, `27.01.002` Imposta di bollo | bollo addebitato al cliente (ricavo) e bollo a carico dell'azienda (costo) |
|
||||
| `31.01.003` Rivalsa contributi previdenziali | rivalsa della cassa previdenziale sulle parcelle |
|
||||
| `27.01.003` IVA indetraibile | IVA indetraibile delle autofatture e del pro rata |
|
||||
| `28.01.003` Interessi sulla liquidazione IVA trimestrale | interessi dei contribuenti IVA trimestrali |
|
||||
| `07.01.001` Banca c/c, `07.02.001` Cassa contanti | banca predefinita per i versamenti F24, cassa dei corrispettivi |
|
||||
|
||||
**Registri IVA di base:** `VEN1` fatture emesse, `ACQ1` fatture acquisti, `CORR` corrispettivi, `VEN-RC` e `ACQ-RC`
|
||||
per autofatture e integrazioni. **Causali di base:** FV, NCV, FA, NCA, AFRC, CORR, INC, PAG, RIT, RITS, LIQ, F24,
|
||||
GIRO, SPB, STO (vedi [Contabilità](Contabilita#causali-contabili)). Fatture, note di debito e parcelle si registrano
|
||||
con FV su VEN1, le note di credito con NCV, le fatture fornitore con FA su ACQ1, le note di credito fornitore con NCA,
|
||||
le autofatture AF16-AF29 con AFRC su VEN-RC e ACQ-RC.
|
||||
|
||||
## Codici tributo F24
|
||||
|
||||
Khaemhat propone il codice tributo e prepara i **dati F24** da passare a intermediario o home banking.
|
||||
Khaemhat propone il codice tributo e prepara i **dati F24** da passare all'home banking o all'intermediario (vedi
|
||||
[IVA](IVA#prospetto-f24-e-pagamento)).
|
||||
|
||||
| Codice | Uso | Maschera |
|
||||
| Codice | Uso | Dove nasce |
|
||||
|---|---|---|
|
||||
| 6001 … 6012 | IVA mensile, da gennaio (6001) a dicembre (6012) | Liquidazione IVA (046) |
|
||||
| 6031 … 6034 | IVA trimestrale, dal 1° (6031) al 4° trimestre (6034, contribuenti trimestrali "speciali") | Liquidazione IVA |
|
||||
| 6013 | Acconto IVA mensili | Liquidazione IVA (acconto di dicembre) |
|
||||
| 6035 | Acconto IVA trimestrali | Liquidazione IVA (acconto di dicembre) |
|
||||
| 6099 | IVA dovuta in base alla dichiarazione annuale | Liquidazione IVA |
|
||||
| 1040 | Ritenute su redditi di lavoro autonomo | Ritenute (047) |
|
||||
| 1038 | Ritenute su provvigioni | Ritenute (047) |
|
||||
| 2521 … 2524 | Imposta di bollo sulle fatture elettroniche, dal 1° (2521) al 4° trimestre (2524) | Bollo virtuale (060) |
|
||||
| 6001 … 6012 | IVA mensile, da gennaio (6001) a dicembre (6012) | Liquidazione IVA |
|
||||
| 6031, 6032, 6033 | IVA trimestrale del 1°, 2° e 3° trimestre | Liquidazione IVA |
|
||||
| 6099, rateazione `0101` | saldo IVA del 4° trimestre dei trimestrali, versato con la dichiarazione annuale | Liquidazione IVA |
|
||||
| 6013 | Acconto IVA mensili | Acconto IVA |
|
||||
| 6035 | Acconto IVA trimestrali | Acconto IVA |
|
||||
| 1040 | Ritenute su redditi di lavoro autonomo | Ritenute |
|
||||
| 1038 | Ritenute su provvigioni | Ritenute |
|
||||
| 1019 | Ritenute del 4% operate dal condominio | tabella dei codici |
|
||||
| 1001 | Ritenute su retribuzioni e pensioni | tabella dei codici |
|
||||
| 2521 … 2524 | Imposta di bollo sulle fatture elettroniche, dal 1° (2521) al 4° trimestre (2524) | Bollo virtuale |
|
||||
|
||||

|
||||
*Mockup 046 — liquidazione periodica: registri del periodo con controlli, calcolo dell'IVA da versare, riquadro Versamento con codice tributo, scadenza e termine della LIPE.*
|
||||
Il codice 6034 (4° trimestre dei trimestrali "speciali") non è usato: per i trimestrali ordinari il saldo del 4°
|
||||
trimestre si versa con il 6099. Il file **Dati F24** è un CSV con separatore `;`: una riga di intestazione (scadenza,
|
||||
codice fiscale e denominazione dell'azienda), poi una riga per codice della sezione Erario con rateazione o mese,
|
||||
anno di riferimento, importo a debito, importo a credito e descrizione, e in fondo il saldo. Il tracciato telematico
|
||||
degli intermediari non viene prodotto.
|
||||
|
||||

|
||||
*Mockup 047 — ritenute operate su parcelle e provvigioni con cassa previdenziale ed ENASARCO; in basso il prospetto F24 con i codici 1040, 1038 e IVA.*
|
||||
## Liquidazione e acconto IVA
|
||||
|
||||
| Regola | Valore in Khaemhat | Riferimento |
|
||||
|---|---|---|
|
||||
| Periodicità | mensile o trimestrale, dal profilo azienda | |
|
||||
| Versamento minimo | se il dovuto (con gli interessi) è sotto **25,82 euro** non si versa e passa al periodo dopo | art. 1 c. 4 DPR 100/1998 |
|
||||
| Interessi dei trimestrali | **1%** sul saldo a debito di ogni trimestre | |
|
||||
| Pro rata | percentuale di detraibilità del profilo azienda, applicata all'IVA detraibile degli acquisti | art. 19-bis DPR 633/72 |
|
||||
| Esigibilità differita e split payment | l'IVA resta fuori dal debito del periodo | |
|
||||
| Acconto di dicembre | **88%** della base con i metodi storico e previsionale, tutto l'importo con il metodo effettivo (operazioni fino al 20 dicembre); non dovuto sotto **103,29 euro**; versamento entro il **27 dicembre** | L. 405/1990 |
|
||||
|
||||
## Comunicazione LIPE
|
||||
|
||||
La **comunicazione delle liquidazioni periodiche IVA** (art. 21-bis DL 78/2010) si prepara come file XML nel
|
||||
tracciato **IVP18** dell'Agenzia delle Entrate: un file per trimestre, con un modulo per ogni mese (o uno per il
|
||||
trimestre). Ogni modulo riporta totale delle operazioni attive e passive, IVA esigibile e detratta, IVA dovuta o a
|
||||
credito, debito e credito del periodo precedente, interessi, acconto e importo da versare o a credito. Gli importi
|
||||
hanno la virgola e due decimali. Il file si chiama `IT<codice fiscale>_LI_<anno>_T<trimestre>.xml`; va firmato e
|
||||
inviato con i servizi dell'Agenzia o dall'intermediario.
|
||||
|
||||
| Trimestre | Scadenza della LIPE |
|
||||
|---|---|
|
||||
| 1° | 31 maggio |
|
||||
| 2° | 16 settembre |
|
||||
| 3° | 30 novembre |
|
||||
| 4° | fine febbraio dell'anno dopo |
|
||||
|
||||
## Ritenute d'acconto e casse previdenziali
|
||||
|
||||
| Tipo | Aliquota | Su | Codice F24 | Tipo e causale nell'XML |
|
||||
|---|---|---|---|---|
|
||||
| Lavoro autonomo professionale | 20% | tutto il compenso | 1040 | RT01, causale A |
|
||||
| Lavoro autonomo occasionale | 20% | tutto il compenso | 1040 | RT01, causale M |
|
||||
| Provvigioni ad agenti e rappresentanti | 23% | 50% della provvigione | 1038 | RT01, causale R |
|
||||
| Provvigioni ad agenti con dipendenti o terzi | 23% | 20% della provvigione | 1038 | RT01, causale R |
|
||||
|
||||
I tipi di ritenuta della fattura elettronica sono **RT01** (persone fisiche), **RT02** (persone giuridiche),
|
||||
**RT03**-**RT06** (contributi INPS, ENASARCO, ENPAM, altri); le casse previdenziali vanno da **TC01** (avvocati) a
|
||||
**TC22** (per esempio **TC04** ingegneri e architetti). La ritenuta operata diventa dovuta quando si **paga** la
|
||||
fattura del professionista (criterio di cassa) e si versa entro il **16 del mese successivo** al pagamento. I dati
|
||||
della **Certificazione Unica** (compenso lordo, somme non soggette, imponibile, ritenute per percipiente e causale)
|
||||
si esportano in CSV; la CU si invia con i servizi dell'Agenzia o dall'intermediario.
|
||||
|
||||
## Imposta di bollo
|
||||
|
||||
| Regola | Valore |
|
||||
|---|---|
|
||||
| Quando | fatture senza IVA (esenti, non imponibili, fuori campo) sopra **77,47 euro** |
|
||||
| Importo | **2,00 euro** per fattura |
|
||||
| Nature che contano | N1, N2.1, N2.2, N3.5, N3.6, N4, N5; non contano esportazioni (N3.1), cessioni intracomunitarie (N3.2), San Marino (N3.3), operazioni assimilate (N3.4), inversione contabile (N6.x) e N7 |
|
||||
| Versamento | per trimestre: 1° entro il **31 maggio** (2521), 2° entro il **30 settembre** (2522), 3° entro il **30 novembre** (2523), 4° entro **fine febbraio** dell'anno dopo (2524) |
|
||||
| Importi bassi | se il bollo del 1° trimestre non supera **5.000 euro** si versa con il 2°; se 1° e 2° insieme non superano 5.000 euro, con il 3° (DM 4/12/2023) |
|
||||
|
||||
## Scadenze e regole principali
|
||||
|
||||
| Adempimento | Regola | Note in Khaemhat |
|
||||
|---|---|---|
|
||||
| Liquidazione IVA mensile | versamento entro il **16 del mese successivo** | la conferma della liquidazione **blocca il periodo** |
|
||||
| Liquidazione IVA trimestrale | versamento entro il 16 del secondo mese successivo al trimestre (per il secondo trimestre vale la proroga estiva di agosto), con **interessi dell'1%**; il quarto trimestre si versa con il saldo annuale entro il 16 marzo | interessi calcolati in automatico |
|
||||
| Liquidazione IVA mensile | versamento entro il **16 del mese successivo** | la conferma della liquidazione segna il periodo come **liquidato** |
|
||||
| Liquidazione IVA trimestrale | 1°-3° trimestre entro il 16 del secondo mese successivo al trimestre, con **interessi dell'1%**; il 4° trimestre entro il **16 marzo** con il codice 6099 | interessi calcolati in automatico |
|
||||
| Scadenze in agosto e nei festivi | i versamenti fra il 1° e il 20 agosto slittano al **20 agosto**; una scadenza di sabato, domenica o festivo slitta al primo giorno lavorativo | festivi nazionali, Pasquetta e, dal 2026, il 4 ottobre |
|
||||
| Versamento minimo | importo fino a **€ 25,82** non versato e riportato al periodo successivo | valore della specifica; da verificare in sviluppo rispetto alla norma vigente |
|
||||
| Acconto IVA | entro il **27 dicembre**; metodo **storico**, **previsionale** o **analitico** | scelta del metodo nella liquidazione di dicembre |
|
||||
| LIPE | 1° trimestre entro 31 maggio, 2° entro 16 settembre, 3° entro 30 novembre, 4° entro fine febbraio (o nella dichiarazione annuale) | XML LIPE generato dalla liquidazione |
|
||||
| Ritenute d'acconto operate | versamento entro il **16 del mese successivo** al pagamento della parcella (1040/1038) | la ritenuta nasce al pagamento della fattura |
|
||||
| Imposta di bollo | **€ 2,00** se le operazioni esenti, non imponibili o fuori campo superano **€ 77,47** | contano le nature N1, N2.1, N2.2, N3.5, N3.6, N4, N5; non contano esportazioni (N3.1), cessioni intracomunitarie (N3.2), San Marino (N3.3), operazioni assimilate (N3.4), inversione contabile (N6.x) e N7 |
|
||||
| Bollo virtuale | versamento trimestrale: 1° trimestre entro 31 maggio, 2° entro 30 settembre, 3° entro 30 novembre, 4° entro fine febbraio; con importi bassi i primi trimestri possono slittare (soglia di € 5.000) | elenco da confrontare con quello proposto dall'Agenzia |
|
||||
| Autofatture e integrazioni (TD16-TD19) | XML da trasmettere **entro il 15 del mese successivo** | promemoria nella dashboard |
|
||||
| Versamento minimo IVA | importo sotto **25,82 euro** non versato e riportato al periodo successivo | *debito sotto la soglia* nella liquidazione |
|
||||
| Acconto IVA | entro il **27 dicembre**; metodo **storico**, **previsionale** o **effettivo**; non dovuto sotto 103,29 euro | riquadro *Acconto IVA* della liquidazione |
|
||||
| LIPE | 1° trimestre entro 31 maggio, 2° entro 16 settembre, 3° entro 30 novembre, 4° entro fine febbraio | file XML dalla liquidazione |
|
||||
| Ritenute d'acconto operate | versamento entro il **16 del mese successivo** al pagamento della fattura (1040/1038) | la ritenuta diventa dovuta con **Fattura pagata** |
|
||||
| Bollo virtuale | versamento trimestrale (vedi sopra), con la soglia dei 5.000 euro | elenco da confrontare con quello proposto dall'Agenzia |
|
||||
| Autofatture e integrazioni (TD16-TD19) | XML da trasmettere **entro il 15 del mese successivo** | promemoria nelle autofatture |
|
||||
| Fattura differita (TD24) | emissione entro il 15 del mese successivo a quello delle consegne documentate da DDT | procedura **Fatturazione differita** |
|
||||
| Interessi di mora | D.Lgs. 231/2002 per i ritardi nelle transazioni commerciali | calcolati nei solleciti |
|
||||
|
||||

|
||||
*Mockup 060 — imposta di bollo del trimestre: fatture con bollo, importo, codice tributo 2524 e scadenza; in fondo la regola dei € 77,47.*
|
||||
| Interessi di mora | D.Lgs. 231/2002 per i ritardi nelle transazioni commerciali: 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
|
||||
|
||||
| Tema | Regola | Pagina |
|
||||
|---|---|---|
|
||||
| Split payment | IVA versata dalla PA cessionaria (esigibilità **S**) | [Vendite](Vendite) |
|
||||
| Split payment | IVA versata dalla PA cessionaria (esigibilità **S**): in contabilità l'IVA viene tolta subito al cliente | [Vendite](Vendite), [Contabilita](Contabilita) |
|
||||
| Reverse charge interno | IVA a carico del cessionario, registri RC vendite e acquisti (IVA neutra) | [Acquisti](Acquisti), [IVA](IVA) |
|
||||
| Dichiarazione d'intento | operazioni non imponibili N3.5 con controllo di plafond, utilizzato e residuo | [Fatturazione-elettronica](Fatturazione-elettronica) |
|
||||
| Ritenuta e cassa previdenza | parcelle TD06: cassa (ad esempio 4%) e ritenuta d'acconto; ENASARCO per gli agenti | [Contabilita](Contabilita) |
|
||||
| Cespiti | coefficienti del DM 31/12/1988, primo anno al 50%, limiti per le autovetture, beni sotto € 516,46 | [Cespiti](Cespiti) |
|
||||
| Intrastat | elenchi INTRA cessioni e acquisti, periodicità da soglie, nomenclatura NC8 | [Intrastat](Intrastat) |
|
||||
| Bilancio | schemi CEE art. 2424 (stato patrimoniale) e 2425 (conto economico), ordinario/abbreviato/micro | [Contabilita](Contabilita) |
|
||||
| Dichiarazione d'intento | operazioni non imponibili N3.5 con controllo di plafond, utilizzato e residuo (M10) | [Fatturazione-elettronica](Fatturazione-elettronica) |
|
||||
| Ritenuta e cassa previdenza | parcelle TD06: cassa (ad esempio 4%) e ritenuta d'acconto | [IVA](IVA#ritenute-dacconto) |
|
||||
| Cespiti | coefficienti del DM 31/12/1988, primo anno al 50%, limiti per le autovetture, beni sotto € 516,46 (M10) | [Cespiti](Cespiti) |
|
||||
| Intrastat | elenchi INTRA cessioni e acquisti, periodicità da soglie, nomenclatura NC8 (M10) | [Intrastat](Intrastat) |
|
||||
| Bilancio | schemi CEE art. 2424 (stato patrimoniale) e 2425 (conto economico): le voci sono già sui conti, gli schemi arrivano con M10 | [Contabilita](Contabilita) |
|
||||
|
||||
## Domande frequenti
|
||||
|
||||
**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.
|
||||
|
||||
**Khaemhat invia l'F24?** No: prepara i dati e la stampa; l'invio passa da intermediario o home banking.
|
||||
**Posso usare un mio piano dei conti?** Sì: il modello *PMI standard* si modifica, si ampliano i sottoconti e si
|
||||
disattivano quelli che non servono. L'import di un piano dei conti da file non c'è ancora.
|
||||
|
||||
**Khaemhat invia l'F24?** No: prepara i dati e il file; l'invio passa da home banking o intermediario.
|
||||
|
||||
## Pagine correlate
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Guida all'uso
|
||||
|
||||
> **Stato:** completa per la versione 0.5 · **Ultima revisione:** 2026-11-12 · **Versione software:** 0.5.0 (M5)
|
||||
> **Stato:** completa per la versione 0.9 · **Ultima revisione:** 2026-11-13 · **Versione software:** 0.9.0 (M9)
|
||||
|
||||
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,18 +9,21 @@ volta, con le schermate della versione attuale. Ogni passo rimanda alla pagina c
|
||||
|
||||
## Che cosa c'è in questa versione
|
||||
|
||||
| Area | In 0.5.0 | Arriva con |
|
||||
| Area | In 0.9.0 | Arriva con |
|
||||
|---|---|---|
|
||||
| Accesso e sicurezza | password, verifica in due passaggi, codici di recupero, blocco dopo i tentativi sbagliati | — |
|
||||
| Interfaccia | menu, schede, ricerca globale, notifiche, aiuto F1, dashboard a widget, temi e colori | — |
|
||||
| Tabelle azienda | profilo azienda, esercizi, cambi, codici IVA, pagamenti, banche, depositi, tipi documento, numeratori e le altre tabelle di base | — |
|
||||
| Anagrafiche | clienti, fornitori, contatti, controlli di partita IVA e codice fiscale, VIES | CRM (lead, opportunità): M11 |
|
||||
| Articoli | articoli, categorie, listini con prezzi a validità, prezzi netti per cliente | giacenze: M6 |
|
||||
| Vendite | preventivi, ordini, DDT, fatture, note, pro forma, fatturazione differita, stampa PDF, invio per e-mail | magazzino M6, contabilità M7, partite M8, XML SDI M9 |
|
||||
| Acquisti e magazzino | — | M6 |
|
||||
| Contabilità, IVA, scadenzario | — | M7, M8 |
|
||||
| Fatturazione elettronica | — | M9 |
|
||||
| Import ed export | clienti, fornitori, articoli e prezzi da CSV, Excel e JSON; esportazione dai radar | giacenze iniziali M6, piano dei conti M7 |
|
||||
| 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 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 | 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 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 | dichiarazioni d'intento M10, 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 |
|
||||
|
||||
Le voci di menu delle aree non ancora pronte aprono una pagina che dice che cosa conterranno.
|
||||
@@ -121,22 +124,79 @@ La **stampante** della toolbar (`Ctrl+P`) apre l'anteprima: **Stampa** con la st
|
||||
Dal menu **⋯** del documento, **Invia per e-mail** propone destinatario, oggetto e testo; il PDF parte in allegato e
|
||||
l'esito finisce nel log. Vedi [Vendite](Vendite#invio-per-e-mail).
|
||||
|
||||
## 8. Allegati
|
||||
## 8. Comprare
|
||||
|
||||

|
||||
|
||||
Il ciclo passivo usa le stesse maschere delle vendite. In **Acquisti → Ordini fornitori** prepari l'ordine (il prezzo
|
||||
è quello del fornitore nella scheda articolo); quando arriva la merce **Crea DDT fornitore (carico)** registra il
|
||||
ricevimento, anche in più volte, e alla conferma carica il magazzino. **Crea Fattura fornitore** prepara la fattura:
|
||||
alla conferma prende il **protocollo** IVA. Se il prezzo fatturato è diverso da quello dell'ordine o del ricevimento,
|
||||
un avviso sopra le righe lo segnala.
|
||||
|
||||

|
||||
|
||||
Le fatture elettroniche ricevute si caricano da **Acquisti → Importa fatture**: XML, P7M o ZIP, anche molti file
|
||||
insieme. Khaemhat trova o crea il fornitore, abbina gli articoli, scarta i doppioni e registra le fatture in bozza con
|
||||
il file allegato. Per le fatture di fornitori esteri o in inversione contabile indica quale **autofattura** serve ed
|
||||
entro quando; **Acquisti → Autofatture** le elenca tutte. Vedi [Acquisti](Acquisti).
|
||||
|
||||
## 9. Il magazzino
|
||||
|
||||

|
||||
|
||||
**Magazzino → Giacenze** mostra per ogni articolo giacenza, impegnato, ordinato, disponibile, costo medio e valore,
|
||||
con lo stato rispetto a scorta minima e punto di riordino; apri una riga per vedere i movimenti. I documenti
|
||||
confermati muovono il magazzino da soli: non serve registrare a parte carichi e scarichi.
|
||||
|
||||

|
||||
|
||||
**Proposte di riordino** calcola che cosa ordinare e a quale fornitore e crea gli ordini in bozza, uno per fornitore.
|
||||
**Inventario** guida il conteggio fisico (anche dal file del lettore di codici a barre) e registra le rettifiche;
|
||||
**Valorizzazione** calcola il valore del magazzino a una data con le classi ABC. Vedi [Magazzino](Magazzino).
|
||||
|
||||
## 10. La contabilità
|
||||
|
||||

|
||||
|
||||
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. Vedi [Contabilità](Contabilita) e
|
||||
[IVA](IVA).
|
||||
|
||||
## 11. Incassare, pagare e la banca
|
||||
|
||||

|
||||
|
||||
**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**.
|
||||
|
||||

|
||||
|
||||
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
|
||||
|
||||

|
||||
|
||||
Ogni anagrafica e ogni documento ha la scheda **Allegati**: carichi file dal computer, li vedi in anteprima, scarichi tutto in un archivio ZIP. I PDF che Khaemhat genera sono **versionati**: ogni stampa salvata o
|
||||
e-mail inviata aggiunge una versione e le precedenti restano. Vedi [Allegati e file](Allegati-e-file).
|
||||
|
||||
## 9. Importare ed esportare
|
||||
## 13. Importare ed esportare
|
||||
|
||||

|
||||
|
||||
**Amministrazione → Import/Export** porta in Khaemhat clienti, fornitori, articoli e prezzi di listino da un file
|
||||
**Amministrazione → Import/Export** porta in Khaemhat clienti, fornitori, articoli, prezzi di listino e giacenze iniziali da un file
|
||||
CSV, Excel o JSON: scegli il file, abbini le colonne, guarda l'anteprima con gli errori riga per riga e conferma. Ogni radar
|
||||
esporta le righe visibili. Vedi [Import/Export](Import-Export).
|
||||
|
||||
## 10. Personalizzare
|
||||
## 14. Personalizzare
|
||||
|
||||

|
||||
|
||||
@@ -157,4 +217,5 @@ prezzi) sono in **Tabelle azienda → Preferenze**. Vedi [Preferenze utente](Pre
|
||||
|
||||
[Primi passi](Primi-passi) · [Interfaccia e scorciatoie](Interfaccia-e-scorciatoie) · [Anagrafiche](Anagrafiche) ·
|
||||
[Articoli e listini](Articoli-e-listini) · [Tabelle azienda](Tabelle-azienda) · [Vendite](Vendite) ·
|
||||
[Acquisti](Acquisti) · [Magazzino](Magazzino) · [Contabilità](Contabilita) · [IVA](IVA) ·
|
||||
[Allegati e file](Allegati-e-file) · [Import/Export](Import-Export) · [Preferenze utente](Preferenze-utente)
|
||||
@@ -1,6 +1,6 @@
|
||||
# Khaemhat
|
||||
|
||||
> **Stato:** completa per 0.5.0 · **Ultima revisione:** 2026-11-12 · **Versione software:** 0.5.0 (M5; sviluppo in corso)
|
||||
> **Stato:** completa per 0.9.0 · **Ultima revisione:** 2026-11-13 · **Versione software:** 0.9.0 (M9; sviluppo in corso)
|
||||
|
||||

|
||||
|
||||
|
||||
@@ -1,199 +1,288 @@
|
||||
# IVA
|
||||
|
||||
> **Stato:** bozza · **Ultima revisione:** 2026-11-10 · **Versione software:** non ancora rilasciata (milestone M7; dichiarazioni d'intento in M10)
|
||||
> **Modulo di licenza:** ACCT (bollo virtuale e dichiarazioni d'intento anche con EINV) · **Permessi principali:** `vat.settlement.confirm`, `vat.register.print`, `vat.withholding.write`, `vat.intent.write` · **Specifica:** SPEC §11.7, §11.9, §11.3, §14
|
||||
> **Stato:** completa per la versione 0.7 · **Ultima revisione:** 2026-11-13 · **Versione software:** 0.7.0 (M7)
|
||||
> **Modulo di licenza:** ACCT · **Permessi principali:** `vat.register.read` (registri IVA), `vat.settlement.read` (liquidazione, ritenute, bollo, F24), `vat.settlement.confirm` (conferme, versamenti, stampe definitive) · **Specifica:** SPEC §11.7, §11.9, §14, ADR 0037
|
||||
|
||||
## A cosa serve
|
||||
Questa pagina descrive l'IVA e i versamenti collegati, tutti nel menu **Contabilità**:
|
||||
|
||||
Questa pagina descrive tutto ciò che riguarda l'IVA e i versamenti collegati:
|
||||
- **registri IVA** con protocollo, stampa di prova e stampa definitiva;
|
||||
- **liquidazione periodica** mensile o trimestrale, con credito e debito riportati, pro rata, interessi trimestrali e
|
||||
minimo di versamento; **acconto di dicembre**; file della **comunicazione LIPE** e dati del modello **F24**;
|
||||
- **ritenute d'acconto** operate e subite, **prospetto F24** con il suo pagamento e dati per la **Certificazione
|
||||
Unica**;
|
||||
- **imposta di bollo virtuale** sulle fatture elettroniche, per trimestre.
|
||||
|
||||
- **registri IVA** con protocollo e stampe definitive;
|
||||
- **liquidazione periodica** con esigibilità differita, IVA per cassa, pro-rata, acconto di dicembre, interessi,
|
||||
minimo di versamento, **dati F24** e **LIPE**;
|
||||
- **ritenute d'acconto** e **casse previdenziali**, con prospetto F24 e dati per la **CU**;
|
||||
- **imposta di bollo virtuale** sulle fatture elettroniche;
|
||||
- **dichiarazioni d'intento** ricevute ed emesse, con plafond.
|
||||
> **Khaemhat non trasmette nulla.** Prepara i file della LIPE, i dati dell'F24 e i dati della Certificazione Unica;
|
||||
> l'invio telematico si fa con i servizi dell'Agenzia delle Entrate, con l'home banking o tramite l'intermediario.
|
||||
|
||||
Khaemhat **non trasmette** F24, LIPE e CU: prepara i dati, i file e le stampe; l'invio telematico avviene tramite
|
||||
intermediario o home banking (avviso presente nel mockup 046).
|
||||
> **In questa versione** ci sono i cinque registri IVA con stampe di prova e definitive, la liquidazione con la sua
|
||||
> registrazione e il versamento F24, l'acconto IVA, il file LIPE, le ritenute con il prospetto F24 e il pagamento, i
|
||||
> dati della CU e il bollo virtuale. Dalla 0.8 il pagamento di una parcella dallo
|
||||
> [Scadenzario](Scadenzario) rende dovuta la ritenuta da solo. Arrivano più avanti: le **dichiarazioni d'intento** e il plafond e l'**Intrastat** (M10),
|
||||
> l'**IVA per cassa** completa (fase 2). Non ci sono ancora la **dichiarazione IVA annuale** e l'**invio
|
||||
> telematico** di F24, LIPE e CU.
|
||||
|
||||
## Dove si trova
|
||||
|
||||
- **Contabilità → Registri IVA**, **Contabilità → Liquidazione IVA**, **Contabilità → Ritenute**.
|
||||
- **Fatturazione elettronica → Bollo virtuale**, **→ Dichiarazioni d'intento**, **→ LIPE**.
|
||||
Menu **Contabilità** → *Registri IVA*, *Liquidazione IVA*, *Ritenute e F24*, *Bollo virtuale*. La **periodicità**
|
||||
IVA (mensile o trimestrale) e la **percentuale di pro rata** si impostano nel **profilo azienda** (vedi
|
||||
[Tabelle azienda](Tabelle-azienda)). Le registrazioni che queste pagine scrivono sono in **Prima nota** (vedi
|
||||
[Contabilità](Contabilita)).
|
||||
|
||||
## Schermate
|
||||
|
||||

|
||||
*Mockup 045 — registro Vendite 1 del mese con protocolli, imponibile, aliquota o natura, imposta ed esigibilità; in alto l'ultima stampa definitiva (anteprima ridotta)*
|
||||
|
||||

|
||||
*Mockup 046 — liquidazione mensile provvisoria: parametri, registri del periodo con i controlli superati, calcolo dell'IVA da versare e riquadro del versamento (codice tributo, scadenza, export F24, scadenza LIPE)*
|
||||
|
||||

|
||||
*Mockup 047 — ritenute operate e subite con cassa previdenziale, periodo e stato del versamento; sotto, il prospetto F24 del 16 del mese con i tributi 1040, 1038 e 6009*
|
||||
|
||||

|
||||
*Mockup 060 — fatture del trimestre soggette a bollo con natura, importo esente e addebito; riquadri con importo, codice tributo, scadenza e trimestre precedente*
|
||||
|
||||

|
||||
*Mockup 061 — dichiarazioni d'intento ricevute con protocollo AdE, plafond, utilizzato, residuo e stato (attiva, avviso al 97 %, esaurita)*
|
||||
```
|
||||
Documenti confermati ──► Registri IVA ──Calcola──► Liquidazione ──Conferma──► registrazione LIQ + riga F24
|
||||
Fattura del professionista ──Fattura pagata──► Ritenuta da versare ──► riga F24 (1040)
|
||||
Fatture con bollo del trimestre ──Metti in F24──► riga F24 (2521-2524)
|
||||
Righe F24 della scadenza ──► Prospetto F24 ──Registra pagamento──► registrazione F24
|
||||
```
|
||||
|
||||
## Registri IVA
|
||||
|
||||
Registri previsti: **vendite**, **acquisti**, **corrispettivi**, **vendite reverse charge**, **acquisti reverse
|
||||
charge** e i **sezionali** che servono (es. `VEN1`, `ACQ1`, `VEN-RC`, `ACQ-RC`, `ACQ-SP` per lo split payment,
|
||||
`CORR`). Ogni documento registrato riceve un **protocollo** progressivo nel suo registro.
|
||||

|
||||
*Il registro VEN1 di ottobre: una scheda per registro, la striscia con tipo, imponibile, imposta, ultima stampa
|
||||
definitiva e ultima pagina, le righe con protocollo e il riepilogo per aliquota.*
|
||||
|
||||
La griglia mostra protocollo, data di registrazione, documento, data del documento, controparte, P.IVA o codice
|
||||
fiscale, imponibile, aliquota o natura, imposta, totale ed **esigibilità** (`I` immediata, `D` differita, `S`
|
||||
scissione dei pagamenti).
|
||||
**Contabilità → Registri IVA** ha una scheda per registro:
|
||||
|
||||
**Stampe**
|
||||
|
||||
| Stampa | Effetto |
|
||||
| Registro | Contenuto |
|
||||
|---|---|
|
||||
| **Provvisoria** | in qualunque momento, senza effetti |
|
||||
| **Stampa definitiva** del periodo | pagine numerate, totali per aliquota e natura; aggiorna "ultima stampa definitiva" |
|
||||
| **Riepilogo aliquote** | totali del periodo per codice IVA e natura |
|
||||
| **VEN1** Registro fatture emesse | fatture, note di debito, parcelle e note di credito di vendita |
|
||||
| **VEN-RC** Registro fatture emesse - autofatture e integrazioni | il lato *vendite* delle autofatture e integrazioni (TD16-TD29) |
|
||||
| **ACQ1** Registro fatture acquisti | fatture e note di credito dei fornitori |
|
||||
| **ACQ-RC** Registro fatture acquisti - autofatture e integrazioni | il lato *acquisti* delle stesse autofatture |
|
||||
| **CORR** Registro dei corrispettivi | le registrazioni dei corrispettivi (causale `CORR`) |
|
||||
|
||||
Le autofatture reverse charge (TD16-TD19) sono annotate sia nel registro vendite RC sia nel registro acquisti RC,
|
||||
Scegli il periodo con **Dal** e **Al**. Ogni riga mostra **protocollo** (il link apre la registrazione), **data di
|
||||
registrazione IVA**, documento e data, cliente o fornitore, **aliquota** o natura, **imponibile**, **imposta**,
|
||||
**indetraibile** ed **esigibilità** (*Immediata*, *Differita*, *Scissione dei pagamenti*). Sotto, il **riepilogo per
|
||||
aliquota** e il totale del registro.
|
||||
|
||||
Le autofatture e integrazioni compaiono in **VEN-RC** e in **ACQ-RC** con la stessa imposta: a debito e a credito,
|
||||
con effetto neutro sulla liquidazione.
|
||||
|
||||
## Liquidazione IVA periodica
|
||||
### Stampe
|
||||
|
||||
| Stampa | Effetto | Permesso |
|
||||
|---|---|---|
|
||||
| **Stampa di prova** | PDF del registro nel periodo scelto, in qualunque momento, senza effetti | `vat.register.read` |
|
||||
| **Stampa definitiva** | PDF dal giorno dopo l'ultima stampa definitiva fino al giorno scelto, con le pagine numerate di seguito all'ultima pagina dell'anno | `vat.settlement.confirm` |
|
||||
|
||||
La stampa definitiva non si annulla: la striscia mostra la data dell'**ultima stampa definitiva** e l'**ultima
|
||||
pagina**, e la stampa successiva riparte da lì (la prima dell'anno parte dal 1° gennaio e dalla pagina 1). La stampa
|
||||
definitiva **non blocca** le registrazioni: a bloccare il periodo è la conferma della liquidazione (vedi sotto).
|
||||
|
||||
## Liquidazione IVA
|
||||
|
||||

|
||||
*La liquidazione mensile di ottobre 2026 confermata: registri del periodo, calcolo con il credito di settembre,
|
||||
riquadro del versamento (codice 6010, scadenza 16/11/2026, trimestre LIPE) e l'elenco delle liquidazioni dell'anno.*
|
||||
|
||||
### Come si fa
|
||||
|
||||
1. **Contabilità → Liquidazione IVA**. Controlla i parametri: **Periodicità** (mensile o trimestrale, dal profilo
|
||||
azienda), **Periodo**, **Data liquidazione**, **Credito precedente**, **Pro-rata**.
|
||||
2. Premi **Calcola**. Khaemhat esegue i **controlli preliminari** (mostrati con il segno di spunta sopra i registri):
|
||||
numerazione continua, nessuna bozza, date coerenti, periodo precedente confermato.
|
||||
3. Controlla la tabella **Registri del periodo** (documenti, imponibile, IVA, indetraibile, note come *neutra* per il
|
||||
reverse charge) e il riquadro **Calcolo**.
|
||||
4. Premi **Conferma**: la liquidazione diventa definitiva e il **periodo viene bloccato** (vedi
|
||||
[Contabilità](Contabilita), esercizi e periodi). Serve il permesso `vat.settlement.confirm`.
|
||||
5. Premi **Dati F24** per esportare i dati del versamento e **LIPE XML** per il file della comunicazione.
|
||||
1. **Contabilità → Liquidazione IVA**. La **periodicità** viene dal profilo azienda; scegli **Anno** e **Periodo**
|
||||
(mese o trimestre).
|
||||
2. Premi **Calcola** (serve `vat.settlement.read`). Khaemhat legge i registri del periodo e mostra la tabella
|
||||
**Registri del periodo** (documenti, imponibile, imposta, indetraibile, esigibilità differita), il riquadro
|
||||
**Calcolo** e il riquadro **Versamento** con codice tributo, anno, importo, scadenza e trimestre LIPE. Puoi
|
||||
ricalcolare quante volte vuoi finché la liquidazione non è confermata.
|
||||
3. Premi **Conferma liquidazione** (serve `vat.settlement.confirm`). Le liquidazioni si confermano in ordine: se un
|
||||
periodo precedente è calcolato ma non confermato, va confermato prima. Alla conferma Khaemhat:
|
||||
- scrive in prima nota la registrazione **LIQ**: *IVA su vendite* in Dare, *IVA su acquisti* in Avere, gli
|
||||
interessi trimestrali in Dare, l'eventuale IVA resa indetraibile dal pro rata a costo, e la differenza su
|
||||
*Erario c/liquidazione IVA*;
|
||||
- segna i periodi dell'esercizio come **liquidati**;
|
||||
- se c'è da versare, aggiunge la riga del modello **F24** con codice tributo e scadenza (vedi
|
||||
[Prospetto F24](#prospetto-f24-e-pagamento)).
|
||||
4. **Dati F24** scarica i dati del modello F24 della scadenza; **Comunicazione LIPE** scarica il file del trimestre
|
||||
(vedi [sotto](#comunicazione-lipe)).
|
||||
|
||||
**Riapri** annulla la conferma: la registrazione LIQ viene eliminata (o stornata, se è già definitiva), la riga F24
|
||||
viene tolta e i periodi tornano aperti. Non si riapre se l'F24 della liquidazione è già **pagato** (annulla prima il
|
||||
pagamento) né se una liquidazione **successiva** è confermata (riapri prima quella).
|
||||
|
||||
**Periodi liquidati.** Dopo la conferma, documenti e registrazioni **con IVA** datati nei periodi liquidati sono
|
||||
rifiutati: per correggere bisogna riaprire la liquidazione. Le registrazioni senza IVA restano libere.
|
||||
|
||||
### Le voci del calcolo
|
||||
|
||||
| Voce | Regola |
|
||||
| Voce | Regola in Khaemhat |
|
||||
|---|---|
|
||||
| IVA a debito | dai registri vendite e corrispettivi del periodo (esigibilità immediata) |
|
||||
| IVA a credito | dai registri acquisti, al netto dell'**indetraibile** e del **pro-rata** |
|
||||
| Esigibilità differita | l'IVA delle fatture a esigibilità differita entra quando si incassa (o alla scadenza di legge) |
|
||||
| IVA per cassa | con il regime dell'IVA per cassa attivo nel profilo azienda, debito e credito seguono incassi e pagamenti; il regime completo è previsto in fase 2 ([Roadmap](Roadmap)) |
|
||||
| Credito del periodo precedente | riportato automaticamente |
|
||||
| Acconto versato | sottratto nella liquidazione di dicembre (o del 4° trimestre) |
|
||||
| Interessi 1 % | maggiorazione dell'1 % per i contribuenti **trimestrali** |
|
||||
| Minimo di versamento | se l'IVA dovuta non supera **€ 25,82** non si versa e si **riporta** al periodo successivo |
|
||||
| **IVA a debito sulle vendite** | imposta dei registri vendite e corrispettivi del periodo, tolta quella a esigibilità differita e in scissione dei pagamenti |
|
||||
| **IVA a credito sugli acquisti** | imposta dei registri acquisti, tolta la parte **indetraibile** dei codici IVA, poi ridotta dal **pro rata** del profilo azienda |
|
||||
| **IVA indetraibile** | indetraibile per codice IVA più la parte tolta dal pro rata |
|
||||
| **IVA a esigibilità differita** | mostrata a parte: non entra nel debito del periodo |
|
||||
| **Credito / debito periodo precedente** | riportati dalla liquidazione confermata precedente |
|
||||
| **Acconto versato** | l'acconto di dicembre registrato, tolto nell'ultima liquidazione dell'anno (dicembre o 4° trimestre) |
|
||||
| **Interessi trimestrali 1%** | per i contribuenti trimestrali, sul saldo a debito |
|
||||
| **Da versare** | se il totale (con gli interessi) è sotto **25,82 euro** non si versa: diventa *debito sotto la soglia* e passa al periodo dopo; se il saldo è a credito diventa *credito da riportare* |
|
||||
|
||||
### Acconto di dicembre
|
||||
### Codici tributo e scadenze
|
||||
|
||||
L'acconto si calcola con uno dei tre metodi: **storico**, **previsionale**, **analitico**. Khaemhat propone gli
|
||||
importi di tutti e tre e l'utente sceglie. Percentuali e scadenza seguono le regole in vigore (al momento della
|
||||
stesura: 88 % per storico e previsionale, liquidazione al 20 dicembre per l'analitico, versamento entro il 27
|
||||
dicembre) e sono aggiornate con il pacchetto fiscale. Codici tributo: **6013** (mensili) e **6035** (trimestrali).
|
||||
| Periodo | Codice | Scadenza |
|
||||
|---|---|---|
|
||||
| Mese (gennaio-dicembre) | **6001**-**6012** | 16 del mese dopo |
|
||||
| 1°, 2°, 3° trimestre | **6031**, **6032**, **6033** | 16 del secondo mese dopo il trimestre (16/5, 20/8, 16/11) |
|
||||
| 4° trimestre | **6099**, rateazione **0101** | 16 marzo dell'anno dopo, con il saldo annuale |
|
||||
|
||||
### Codici tributo F24
|
||||
Le scadenze di sabato, domenica o festivo passano al primo giorno lavorativo; i versamenti dal 1° al 20 agosto
|
||||
passano al **20 agosto**. Codici e calendario sono in [Fiscalità italiana](Fiscalita-italiana#codici-tributo-f24).
|
||||
|
||||
| Codice | Versamento |
|
||||
### Acconto IVA di dicembre
|
||||
|
||||
Il riquadro **Acconto IVA** (sotto l'elenco delle liquidazioni, con `vat.settlement.confirm`) calcola l'acconto da
|
||||
versare entro il **27 dicembre** (primo giorno lavorativo successivo se festivo) con il codice **6013** (mensili) o
|
||||
**6035** (trimestrali).
|
||||
|
||||
| Metodo | Base di calcolo | Acconto |
|
||||
|---|---|---|
|
||||
| **Storico** | l'IVA dell'ultimo periodo dell'anno prima (dicembre o 4° trimestre), al lordo dell'acconto di allora e senza interessi | 88% della base |
|
||||
| **Previsionale** | l'IVA che prevedi per l'ultimo periodo dell'anno: la scrivi tu | 88% della base |
|
||||
| **Effettivo** | l'IVA dall'inizio dell'ultimo periodo al **20 dicembre** | tutta la base |
|
||||
|
||||
1. Scegli il **metodo**: la **base di calcolo** si compila con il valore che Khaemhat conosce (il riquadro *Basi di
|
||||
calcolo* mostra storico ed effettivo; **Ricalcola le basi** le rilegge). Per il previsionale scrivila tu.
|
||||
2. **Registra acconto** aggiunge la riga F24 dell'acconto. Sotto **103,29 euro** l'acconto non è dovuto e non viene
|
||||
registrato. Finché non è pagato puoi registrarlo di nuovo con un altro metodo: la riga si aggiorna.
|
||||
|
||||
L'acconto registrato viene tolto nella liquidazione di dicembre o del 4° trimestre.
|
||||
|
||||
### Comunicazione LIPE
|
||||
|
||||
**Comunicazione LIPE** scarica il file XML della **comunicazione delle liquidazioni periodiche IVA** di un trimestre,
|
||||
nel tracciato **IVP18** dell'Agenzia delle Entrate: un modulo per ogni mese (o per il trimestre), con operazioni
|
||||
attive e passive, IVA esigibile e detratta, debiti e crediti riportati, interessi, acconto e importo da versare o a
|
||||
credito. Il pulsante si accende quando è confermata la liquidazione dell'ultimo mese del trimestre (o del trimestre).
|
||||
Il file si chiama `IT<codice fiscale>_LI_<anno>_T<trimestre>.xml` e va firmato e inviato con i servizi dell'Agenzia
|
||||
o dall'intermediario. Le scadenze sono in [Fiscalità italiana](Fiscalita-italiana#comunicazione-lipe).
|
||||
|
||||
## Ritenute d'acconto
|
||||
|
||||

|
||||
*La ritenuta operata sulla fattura dello Studio Rag. Neri Paola (RT01, causale A, cassa TC04, 20% di 450 euro) già
|
||||
pagata e da versare; sotto, il prospetto F24 della scadenza del 16/11/2026 con l'IVA di ottobre.*
|
||||
|
||||
**Contabilità → Ritenute e F24** elenca le ritenute dei documenti di un **anno**, nelle schede **Operate**, **Subite**
|
||||
e **Tutte**:
|
||||
|
||||
- **operate**: quelle che l'azienda trattiene sulle **fatture dei professionisti** e degli agenti (fatture fornitore
|
||||
con ritenuta);
|
||||
- **subite**: quelle che i clienti trattengono sulle **parcelle** e fatture emesse dall'azienda con ritenuta.
|
||||
|
||||
Le ritenute nascono da sole quando il documento viene contabilizzato. Per ognuna: documento (il link apre la
|
||||
registrazione), data, cliente o fornitore, **tipo** e causale di pagamento (per esempio `RT01 · A`), imponibile,
|
||||
**cassa** previdenziale e contributo, **aliquota** (con la quota dell'imponibile, per esempio *20% su 50%* per gli
|
||||
agenti), importo, data di pagamento della fattura e **stato**:
|
||||
|
||||
| Stato | Significato |
|
||||
|---|---|
|
||||
| 6001 … 6012 | IVA mensile, da gennaio (6001) a dicembre (6012) |
|
||||
| 6031 … 6034 | IVA trimestrale, dal 1° (6031) al 4° trimestre (6034); il 6034 riguarda i trimestrali "speciali", per gli altri il saldo del 4° trimestre si versa con la dichiarazione annuale (6099) |
|
||||
| 6013 / 6035 | acconto IVA mensili / trimestrali |
|
||||
| 6099 | IVA da dichiarazione annuale |
|
||||
| 1040 | ritenute su redditi di lavoro autonomo |
|
||||
| 1038 | ritenute su provvigioni (agenti e rappresentanti) |
|
||||
| *In attesa del pagamento* | ritenuta operata su una fattura non ancora pagata |
|
||||
| *Da versare* | la fattura è pagata: la ritenuta va versata con l'F24 |
|
||||
| *Versata* | l'F24 che la contiene è pagato |
|
||||
| *Subita* | ritenuta trattenuta dal cliente su una fattura dell'azienda |
|
||||
|
||||
I codici sono caricati con i dati di base ([Dati di base e di esempio](Dati-di-base-e-esempio)) e riepilogati in
|
||||
[Fiscalità italiana](Fiscalita-italiana).
|
||||
### Registrare il pagamento della fattura
|
||||
|
||||
### LIPE
|
||||
La ritenuta operata diventa dovuta **quando paghi la fattura** del professionista (criterio di cassa). 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:
|
||||
|
||||
La **Comunicazione delle liquidazioni periodiche IVA** si genera come file XML nel tracciato dell'Agenzia delle
|
||||
Entrate dalle liquidazioni confermate del trimestre (voce di menu **Fatturazione elettronica → LIPE** o pulsante
|
||||
**LIPE XML**). Il riquadro **Versamento** mostra il trimestre di riferimento e la scadenza.
|
||||
1. Sulla riga della ritenuta premi **Fattura pagata** e indica la data di pagamento.
|
||||
2. Khaemhat scrive la registrazione **RIT** (*fornitore* in Dare, *Erario c/ritenute lavoro autonomo* in Avere) e
|
||||
aggiunge la ritenuta alla riga F24 del suo codice tributo (**1040** lavoro autonomo, **1038** provvigioni) e del
|
||||
mese di pagamento, con scadenza il **16 del mese dopo**. Le ritenute dello stesso codice e mese si sommano.
|
||||
3. Per una ritenuta **subita**, **Fattura pagata** chiede la data in cui il cliente ha pagato e scrive la registrazione
|
||||
**RITS** (*Erario c/ritenute subite* in Dare, *cliente* in Avere): è un credito d'imposta.
|
||||
|
||||
## Ritenute d'acconto e casse previdenziali
|
||||
Il pulsante con la freccia annulla il pagamento della fattura (e la sua registrazione) finché l'F24 non è pagato.
|
||||
|
||||
**Contabilità → Ritenute** (mockup 047) elenca le ritenute **operate** (sulle parcelle e provvigioni che paghiamo) e
|
||||
quelle **subite** (sulle nostre fatture, ad esempio verso la PA), con i filtri **Operate / Subite / Tutte**.
|
||||
### Dati per la Certificazione Unica
|
||||
|
||||
| Colonna | Significato |
|
||||
|---|---|
|
||||
| Tipo | professionista TD06, agente ENASARCO, ritenuta subita… |
|
||||
| Imponibile, Cassa, Importo cassa | contributo previdenziale (es. 4 % INPS di rivalsa, 4 % cassa professionale) |
|
||||
| Ritenuta | aliquota (es. 20 %; per gli agenti l'aliquota si applica a una quota della provvigione) |
|
||||
| Periodo → F24 | mese di pagamento della fattura e data del modello F24 in cui confluisce |
|
||||
| Stato | *Da versare*, *In F24*, *Versata*, *Subita* |
|
||||
**Dati Certificazione Unica** scarica un file CSV con i **percipienti** dell'anno: una riga per professionista e
|
||||
causale con codice fiscale, denominazione, causale, anno, compenso lordo, somme non soggette, imponibile, ritenute,
|
||||
codice tributo e documenti. Contiene le ritenute operate sulle fatture pagate nell'anno. La CU si compila e si invia
|
||||
con i servizi dell'Agenzia delle Entrate o dall'intermediario.
|
||||
|
||||
Regole:
|
||||
## Prospetto F24 e pagamento
|
||||
|
||||
- La ritenuta nasce come **debito verso l'Erario al pagamento** della fattura (criterio di cassa) e confluisce nel
|
||||
prospetto F24 del mese successivo (tributi **1040** e **1038**).
|
||||
- Sulle **parcelle (TD06)** cassa previdenziale, ritenuta e netto a pagare sono calcolati in automatico; **ENASARCO**
|
||||
si applica agli agenti con i relativi massimali.
|
||||
- **Registra versamento** registra il pagamento del modello F24 e chiude le ritenute versate.
|
||||
- **CU export** produce i dati della Certificazione Unica da consegnare all'intermediario.
|
||||
Il riquadro **Prospetto F24** (nella pagina *Ritenute e F24*) raccoglie tutto ciò che va versato con l'F24: IVA della
|
||||
liquidazione, acconto IVA, ritenute operate, bollo virtuale.
|
||||
|
||||
Il **Prospetto F24** del giorno di scadenza riepiloga tributi, periodi e importi (ritenute e IVA) con il totale.
|
||||
1. Scegli la **scadenza** nell'elenco (si apre sulla prima non pagata).
|
||||
2. Il prospetto mostra una riga per **codice tributo** e periodo con descrizione, periodo di riferimento, importo a
|
||||
debito e a credito, e il **saldo** dell'F24.
|
||||
3. **Dati F24** scarica un file CSV (separatore `;`, sezione Erario) con intestazione, una riga per codice tributo e il
|
||||
saldo, da passare all'home banking o all'intermediario.
|
||||
4. Pagato l'F24, **Registra pagamento** chiede la data: Khaemhat scrive la registrazione **F24** (*Erario
|
||||
c/liquidazione IVA*, *Erario c/ritenute* e *imposta di bollo* in Dare secondo le righe, la **banca** in Avere) e
|
||||
segna versate le righe e le ritenute. La banca è quella predefinita dell'azienda (il suo *conto contabile*), o
|
||||
`07.01.001` *Banca c/c*.
|
||||
|
||||
**Annulla pagamento** toglie la registrazione del pagamento (o la storna, se è definitiva) e riporta le righe da
|
||||
versare.
|
||||
|
||||
## Imposta di bollo virtuale
|
||||
|
||||
Sulle fatture con operazioni **esenti, non imponibili o fuori campo IVA** di importo **superiore a € 77,47** si
|
||||
applica il bollo di **€ 2,00**, calcolato in automatico sul documento e indicato nell'XML (`DatiBollo`).
|
||||
Sulle fatture elettroniche **senza IVA** (operazioni esenti, non imponibili o fuori campo) di importo **superiore a
|
||||
77,47 euro** si applica il bollo di **2 euro**. Khaemhat lo calcola già sul documento di vendita (vedi
|
||||
[Vendite](Vendite)), che dice anche se è **addebitato al cliente** o **a carico dell'azienda**.
|
||||
|
||||
**Fatturazione elettronica → Bollo virtuale** (mockup 060) mostra le fatture del trimestre con il bollo, la natura
|
||||
IVA, l'importo esente e l'**addebito** (*addebitato al cliente*, *a carico azienda*; per le fatture ricevute *a
|
||||
carico fornitore*). I riquadri riportano numero di fatture, importo, codice tributo del trimestre (**2521-2524**),
|
||||
scadenza e stato del trimestre precedente.
|
||||
**Contabilità → Bollo virtuale** riepiloga il bollo per **anno** e **trimestre**:
|
||||
|
||||
1. A fine trimestre controlla l'elenco e confrontalo con quello messo a disposizione dall'Agenzia delle Entrate.
|
||||
2. **Esporta per F24** produce i dati del versamento.
|
||||
3. A pagamento avvenuto premi **Segna versato**.
|
||||
- la striscia del trimestre: numero di **fatture**, **importo**, **codice tributo**, **scadenza** e lo stato del
|
||||
**trimestre precedente**;
|
||||
- l'elenco delle fatture del trimestre con il bollo: documento (il link lo apre), data, cliente, imponibile, bollo e
|
||||
**addebito**;
|
||||
- il riepilogo dei quattro trimestri dell'anno con fatture, importo, scadenza e stato (*Da mettere in F24*, *In F24*,
|
||||
*pagato il*).
|
||||
|
||||
> **Attenzione:** alcune operazioni non imponibili sono escluse dal bollo per legge (per esempio le cessioni
|
||||
> intracomunitarie e le esportazioni). L'esclusione sarà gestita sul codice IVA; la regola precisa sarà verificata in
|
||||
> sviluppo con la normativa vigente.
|
||||
| Trimestre | Codice | Scadenza |
|
||||
|---|---|---|
|
||||
| 1° | **2521** | 31 maggio |
|
||||
| 2° | **2522** | 30 settembre |
|
||||
| 3° | **2523** | 30 novembre |
|
||||
| 4° | **2524** | fine febbraio dell'anno dopo |
|
||||
|
||||
## Dichiarazioni d'intento e plafond
|
||||
Se il bollo del **1° trimestre** non supera **5.000 euro** si versa con il 2° (30 settembre); se quello del 1° e del
|
||||
2° insieme non supera 5.000 euro si versa con il 3° (30 novembre). Le scadenze festive passano al primo giorno
|
||||
lavorativo.
|
||||
|
||||
**Fatturazione elettronica → Dichiarazioni d'intento** (mockup 061) gestisce:
|
||||
|
||||
- **Ricevute**: dichiarazioni degli esportatori abituali nostri clienti (numero, data, cliente, **protocollo AdE**,
|
||||
plafond, utilizzato, residuo, anno, stato);
|
||||
- **Emesse (plafond nostro)**: dichiarazioni che l'azienda presenta ai propri fornitori.
|
||||
|
||||
Regole:
|
||||
|
||||
- Il plafond si aggiorna a ogni fattura con codice IVA **N3.5** (non imponibile a seguito di dichiarazione d'intento).
|
||||
- Al **90 %** di utilizzo compare un avviso (e la regola di automazione predefinita *Avviso plafond* avvisa
|
||||
l'amministrazione, vedi [Automazioni](Automazioni)); al **100 %** la fattura è bloccata.
|
||||
- Il protocollo della dichiarazione è riportato nell'XML della fattura (blocco `AltriDatiGestionali`).
|
||||
- **Registro cronologico** stampa il registro delle dichiarazioni.
|
||||
|
||||
La dichiarazione è collegata alla scheda fiscale del cliente ([Anagrafiche](Anagrafiche)).
|
||||
1. Scegli il trimestre e confronta l'elenco con quello che l'Agenzia delle Entrate mette a disposizione nell'area
|
||||
riservata.
|
||||
2. **Metti in F24** (serve `vat.settlement.confirm`) aggiunge la riga del bollo al prospetto F24 della scadenza. Se
|
||||
il bollo del trimestre cambia (una fattura in più), premilo di nuovo: finché non è pagata la riga si aggiorna.
|
||||
3. **Dati F24** scarica i dati dell'F24 di quella scadenza; il pagamento si registra dal
|
||||
[Prospetto F24](#prospetto-f24-e-pagamento).
|
||||
|
||||
## Permessi e licenza
|
||||
|
||||
- Registri, liquidazione, F24, LIPE, ritenute: modulo **ACCT**.
|
||||
- Bollo virtuale e dichiarazioni d'intento: compaiono nel menu Fatturazione elettronica e la specifica li elenca sia
|
||||
in ACCT sia in EINV; l'abbinamento definitivo sarà fissato in sviluppo.
|
||||
- `vat.settlement.confirm` è richiesto per confermare la liquidazione; gli altri codici in testa sono indicativi
|
||||
(convenzione `modulo.entità.azione`, SPEC §7.2).
|
||||
Tutto è nel modulo **ACCT**.
|
||||
|
||||
| Permesso | Cosa consente |
|
||||
|---|---|
|
||||
| `vat.register.read` | vedere i registri IVA e farne la stampa di prova |
|
||||
| `vat.settlement.read` | calcolare e vedere le liquidazioni, ritenute, bollo, prospetto F24; scaricare LIPE, dati F24 e CU |
|
||||
| `vat.settlement.confirm` | confermare e riaprire le liquidazioni, registrare acconto, pagamenti delle fatture, pagamenti F24, bollo in F24, stampa definitiva dei registri |
|
||||
|
||||
## Domande frequenti
|
||||
|
||||
**Ho trovato un errore in un periodo già liquidato.** Il periodo è bloccato: un utente con il permesso di
|
||||
riapertura sblocca il periodo, si corregge, si ricalcola e si conferma di nuovo. Se l'F24 è già stato versato, la
|
||||
differenza va gestita nella liquidazione successiva o con ravvedimento (fuori da Khaemhat).
|
||||
|
||||
**Khaemhat invia l'F24?** No. Prepara dati e stampe; l'invio è dell'intermediario o dell'home banking.
|
||||
|
||||
**Dove imposto la periodicità IVA e il pro-rata?** Nel profilo azienda ([Tabelle azienda](Tabelle-azienda)).
|
||||
- **"Conferma prima la liquidazione del periodo precedente".** Un mese (o trimestre) precedente è calcolato ma non
|
||||
confermato: confermalo prima. Il credito e il debito si riportano solo da una liquidazione confermata.
|
||||
- **Ho trovato un errore in un periodo già liquidato.** Riapri la liquidazione (e prima quelle successive, se
|
||||
confermate), correggi il documento, ricalcola e conferma di nuovo. Se l'F24 è già pagato, annulla prima il
|
||||
pagamento; se l'hai davvero versato, la differenza va gestita nella liquidazione successiva o con il ravvedimento,
|
||||
fuori da Khaemhat.
|
||||
- **Il pulsante Comunicazione LIPE è spento.** Il trimestre non è finito o la liquidazione del suo ultimo mese non è
|
||||
confermata.
|
||||
- **La ritenuta non compare nel prospetto F24.** È *In attesa del pagamento*: registra **Fattura pagata**. La ritenuta
|
||||
va nella scadenza del 16 del mese dopo il pagamento.
|
||||
- **La stampa definitiva del registro è rifiutata.** Deve partire dal giorno dopo l'ultima stampa definitiva: la
|
||||
striscia del registro mostra quale.
|
||||
- **Khaemhat invia F24, LIPE o CU?** No: prepara i dati e i file; l'invio è dell'home banking, dei servizi
|
||||
dell'Agenzia delle Entrate o dell'intermediario.
|
||||
- **Dove imposto periodicità e pro rata?** Nel profilo azienda, in [Tabelle azienda](Tabelle-azienda).
|
||||
|
||||
## Pagine correlate
|
||||
|
||||
[Contabilità](Contabilita) · [Fatturazione elettronica](Fatturazione-elettronica) · [Vendite](Vendite) ·
|
||||
[Acquisti](Acquisti) · [Intrastat](Intrastat) · [Scadenzario](Scadenzario) · [Fiscalità italiana](Fiscalita-italiana) ·
|
||||
[Automazioni](Automazioni) · [Report](Report)
|
||||
[Contabilità](Contabilita) · [Fiscalità italiana](Fiscalita-italiana) · [Vendite](Vendite) · [Acquisti](Acquisti) ·
|
||||
[Scadenzario](Scadenzario) · [Fatturazione elettronica](Fatturazione-elettronica) · [Tabelle azienda](Tabelle-azienda) ·
|
||||
[Glossario](Glossario)
|
||||
@@ -1,6 +1,6 @@
|
||||
# Import/Export
|
||||
|
||||
> **Stato:** completa per M4 · **Ultima revisione:** 2026-11-12 · **Versione software:** 0.4.0 (scrittura di giacenze iniziali in M6, piano dei conti in M7; saldi e partite di apertura in M7 e M9)
|
||||
> **Stato:** completa per M4 · **Ultima revisione:** 2026-11-12 · **Versione software:** 0.4.0 (giacenze iniziali dalla 0.6.0, piano dei conti dalla 0.7.0; saldi e partite di apertura più avanti)
|
||||
> **Modulo di licenza:** CORE (piano dei conti: ACCT) · **Livello richiesto:** amministratore, oppure permesso di scrittura o di export dell'entità · **Specifica:** SPEC §11.7, §12.12 · **Decisione:** ADR 0031
|
||||
|
||||
## A cosa serve
|
||||
@@ -94,13 +94,16 @@ obbligatoria. Unità alternative, codici alternativi, fornitori e sostitutivi re
|
||||
netto), non entrambi. Stesso articolo, listino o cliente e data: il prezzo si sostituisce; una data nuova aggiunge
|
||||
un prezzo che vale da quel giorno, come nella griglia dei listini. Le righe senza errori si scrivono tutte insieme.
|
||||
|
||||
### Giacenze iniziali (solo verifica fino a M6)
|
||||
### Giacenze iniziali
|
||||
|
||||
`articolo`\*, `deposito` (vuoto: il deposito dell'articolo), `quantita`\* (maggiore di zero), `costo_unitario`.
|
||||
L'articolo deve essere merce gestita a magazzino. Il controllo serve a preparare il file: la scrittura del movimento
|
||||
di apertura arriva con il [Magazzino](Magazzino).
|
||||
`articolo`\*, `deposito` (vuoto: il deposito dell'articolo, poi quello predefinito), `quantita`\* (maggiore di zero),
|
||||
`costo_unitario` (vuoto: costo medio, standard o ultimo costo dell'articolo). L'articolo deve essere merce gestita a
|
||||
magazzino e non può comparire due volte nello stesso deposito. Dalla 0.6.0 l'import scrive **un movimento di
|
||||
magazzino per deposito** con la causale `APE` (esistenza iniziale) alla data dell'import e lo conferma: giacenze e
|
||||
costo medio partono da lì (vedi [Magazzino](Magazzino#esistenze-iniziali)). Se la causale `APE` manca, le righe sono
|
||||
saltate con un messaggio: aggiungila con *Aggiorna da tabelle base*.
|
||||
|
||||
### Piano dei conti (solo verifica fino a M7)
|
||||
### Piano dei conti
|
||||
|
||||
Vedi il tracciato più sotto.
|
||||
|
||||
@@ -113,7 +116,7 @@ Vedi il tracciato più sotto.
|
||||
|
||||
| Opzione | Valori | Entità |
|
||||
|---|---|---|
|
||||
| **Se il codice esiste** | *Aggiorna* (le celle piene cambiano il record, le vuote lasciano ciò che c'è) oppure *Salta la riga* (avviso) | clienti, fornitori, articoli, prezzi |
|
||||
| **Se il codice esiste** | *Aggiorna* (le celle piene cambiano il record, le vuote lasciano ciò che c'è) oppure *Salta la riga* (avviso) | clienti, fornitori, articoli, prezzi, piano dei conti |
|
||||
| **Codice mancante** | *Genera automatico* con le regole dei codici automatici (vedi [Tabelle azienda](Tabelle-azienda)) oppure *Errore sulla riga* | clienti, fornitori, articoli |
|
||||
| **Verifica P.IVA su VIES (UE)** | controlla su VIES le partite IVA dei soggetti UE durante l'import (più lento) | clienti, fornitori |
|
||||
| **Completa comune da CAP** | completa comune e provincia da un CAP con un solo comune, o il CAP da un comune con un solo CAP (avviso) | clienti, fornitori |
|
||||
@@ -158,8 +161,10 @@ farla sull'azienda reale.
|
||||
## Tracciato del piano dei conti
|
||||
|
||||
In Italia non esiste uno standard per lo scambio del piano dei conti, perciò Khaemhat definisce il proprio
|
||||
tracciato. Il piano standard per PMI sarà **precaricato** con la contabilità (M7); l'importazione serve a chi vuole
|
||||
usare il piano del proprio commercialista o del gestionale precedente. Fino a M7 il file si **verifica** soltanto.
|
||||
tracciato. Il piano standard per PMI è **precaricato** con la contabilità (dalla 0.7, vedi [Contabilità](Contabilita));
|
||||
l'importazione serve a chi vuole usare il piano del proprio commercialista o del gestionale precedente. I conti nuovi
|
||||
si aggiungono; quelli che esistono si aggiornano se l'opzione **Se il codice esiste** è *Aggiorna*, altrimenti si
|
||||
saltano. Lo stesso tracciato si usa per esportare il piano dell'azienda.
|
||||
|
||||
### CSV e XLSX
|
||||
|
||||
@@ -210,7 +215,8 @@ Per lo scambio **completo** fra installazioni Khaemhat:
|
||||
```
|
||||
|
||||
`accounts` ha le stesse colonne del CSV. Voci di bilancio (`statementLines`), causali (`journalTemplates`) e
|
||||
mappature (`mappings`) si contano già nella mappatura e si importano con la contabilità (M7).
|
||||
mappature (`mappings`) si contano nella mappatura ma non si importano ancora: le causali si gestiscono in
|
||||
*Contabilità → Causali*.
|
||||
|
||||
### Controlli
|
||||
|
||||
@@ -231,8 +237,8 @@ Il riquadro **Esporta e modelli** usa l'entità scelta in alto:
|
||||
(nome `clienti-2026-11-12.csv`). I codici delle tabelle sono esportati come codici.
|
||||
|
||||
L'export richiede il flag utente **Può esportare dati** e il permesso di export dell'entità (per le anagrafiche
|
||||
*Esportare anagrafiche*) (vedi [Utenti e permessi](Utenti-e-permessi)). Giacenze e piano dei conti hanno per ora solo
|
||||
il modello. Le griglie esportano anche dal proprio menu (CSV/XLSX).
|
||||
*Esportare anagrafiche*) (vedi [Utenti e permessi](Utenti-e-permessi)). Le giacenze hanno per ora solo il
|
||||
modello; il piano dei conti si esporta per intero. Le griglie esportano anche dal proprio menu (CSV/XLSX).
|
||||
|
||||
## Domande frequenti
|
||||
|
||||
|
||||
@@ -1,148 +1,194 @@
|
||||
# Magazzino
|
||||
|
||||
> **Stato:** bozza · **Ultima revisione:** 2026-11-10 · **Versione software:** non ancora rilasciata (milestone M6)
|
||||
> **Modulo di licenza:** CORE · **Permessi principali:** `inventory.entry.post`, `items.cost.read`, famiglia `inventory.*` · **Specifica:** SPEC §11.6, §22
|
||||
> **Stato:** completa per la versione 0.6 · **Ultima revisione:** 2026-11-12 · **Versione software:** 0.6.0 (M6)
|
||||
> **Modulo di licenza:** CORE · **Permessi principali:** `inventory.stock.read` (giacenze), `inventory.entry.*` (movimenti, inventario), `inventory.entry.post` (conferma, rettifiche, ricostruzione), `items.cost.read` (costi e valori) · **Specifica:** SPEC §11.6, ADR 0035
|
||||
|
||||
Il **magazzino** tiene la quantità e il valore di ogni articolo in ogni **deposito**. Le giacenze si aggiornano da
|
||||
sole con i documenti (DDT, fatture accompagnatorie, carichi, resi) e con i movimenti manuali; da qui si fanno
|
||||
trasferimenti tra depositi, inventari fisici, la proposta di riordino e la valorizzazione.
|
||||
sole quando confermi un documento che muove la merce (DDT, fatture accompagnatorie, carichi dai fornitori, resi,
|
||||
movimenti manuali); da qui consulti giacenze e movimenti, fai l'**inventario fisico**, generi la **proposta di
|
||||
riordino** e calcoli la **valorizzazione** a una data.
|
||||
|
||||
> **In questa versione** ci sono giacenze per deposito, impegnato e ordinato, costo medio ponderato, movimenti per
|
||||
> articolo, movimenti manuali e trasferimenti, inventario fisico con import dei conteggi, proposta di riordino,
|
||||
> valorizzazione con analisi ABC e ricostruzione. Arrivano più avanti: le **scritture contabili** delle rimanenze e il
|
||||
> **libro inventari** con la chiusura dell'esercizio (M10), i report di magazzino stampabili (M13), FIFO e LIFO a lotti (dopo la 1.0).
|
||||
|
||||
## Dove si trova
|
||||
|
||||
Menu **Magazzino** → *Giacenze*, *Movimenti*, *Inventario fisico*, *Sottoscorta* (proposta di riordino),
|
||||
*Trasferimenti*. I depositi e le causali di magazzino sono in [Tabelle azienda](Tabelle-azienda).
|
||||
Menu **Magazzino** → *Giacenze*, *Movimenti*, *Inventario*, *Proposte di riordino*. I **depositi** e le **causali
|
||||
di magazzino** sono in [Tabelle azienda](Tabelle-azienda); scorta minima, punto e lotto di riordino e fornitori
|
||||
abituali sono nella scheda dell'articolo (vedi [Articoli e listini](Articoli-e-listini)).
|
||||
|
||||
## Le quattro quantità
|
||||
## Le quantità
|
||||
|
||||
| Quantità | Significato | Da dove nasce |
|
||||
|---|---|---|
|
||||
| **Giacenza** | merce fisicamente presente nel deposito | carichi e scarichi confermati |
|
||||
| **Impegnato** | merce riservata a ordini clienti confermati e non ancora evasi | ordini clienti, trasferimenti in bozza |
|
||||
| **Ordinato** | merce in arrivo dai fornitori | ordini fornitore confermati e non ancora ricevuti |
|
||||
| **Disponibile** | **giacenza - impegnato** | calcolata |
|
||||
| **Giacenza** | merce presente nel deposito | movimenti dei documenti confermati |
|
||||
| **Impegnato** | merce riservata a ordini clienti confermati e non ancora evasi | residuo degli ordini clienti |
|
||||
| **Ordinato** | merce in arrivo dai fornitori | residuo degli ordini fornitore confermati |
|
||||
| **Disponibile** | giacenza meno impegnato | calcolata |
|
||||
|
||||
Il sistema registra anche la merce **in transito** e il **valore medio** per articolo e deposito. Tutte queste
|
||||
quantità sono aggiornate **nella stessa transazione** del documento che le muove: non c'è mai un momento in cui il
|
||||
documento è confermato e la giacenza no.
|
||||
Tutte si aggiornano **nella stessa operazione** che conferma il documento: non c'è mai un momento in cui il documento
|
||||
è confermato e la giacenza no. Se annulli il documento, i suoi movimenti spariscono e le quantità tornano come prima.
|
||||
|
||||
## Quali documenti muovono il magazzino
|
||||
|
||||
Ogni tipo documento ha una **causale di magazzino** (in *Tabelle azienda → Tipi documento*) che decide se carica,
|
||||
scarica o trasferisce. Con i tipi di base:
|
||||
|
||||
| Documento | Causale | Effetto |
|
||||
|---|---|---|
|
||||
| DDT, fattura immediata, fattura accompagnatoria | `SCA` scarico per vendita | scarica al costo medio |
|
||||
| DDT fornitore (carico), fattura fornitore | `CAR` carico da acquisto | carica e aggiorna il costo medio |
|
||||
| Nota di credito fornitore | `RESF` reso a fornitore | scarica |
|
||||
| Movimento di magazzino (`MM`) | quella scelta nel movimento | carico, scarico o trasferimento |
|
||||
| Ordini clienti e fornitori, preventivi, fatture differite | nessuna | solo impegnato e ordinato |
|
||||
|
||||
Una fattura nata da un DDT **non muove di nuovo** la merce: le sue righe trovano il carico o lo scarico già fatto
|
||||
dal DDT. Il prezzo della fattura fornitore però **corregge il costo** del carico: se il fornitore fattura a un prezzo
|
||||
diverso da quello del DDT, il costo medio viene ricalcolato con il prezzo fatturato.
|
||||
|
||||
Le causali di base sono: `CAR` carico da acquisto, `SCA` scarico per vendita, `RESC` reso da cliente, `RESF` reso a
|
||||
fornitore, `TRA` trasferimento tra depositi, `INVP` e `INVN` rettifiche inventariali, `CVU` e `CVR` uscita e rientro
|
||||
in conto visione (solo quantità), `OMA` omaggio, `AUTO` autoconsumo, `APE` esistenza iniziale. Per un'azienda creata
|
||||
con una versione precedente le causali e i tipi documento mancanti si aggiungono con **Aggiorna da tabelle base** nel
|
||||
menu `…` della tabella (vedi [Tabelle azienda](Tabelle-azienda)) o, per tutte le tabelle, con `scripts/seed.sh --base`.
|
||||
|
||||
## Giacenze e disponibilità
|
||||
|
||||

|
||||
*Mockup 036 — striscia di indicatori (valore magazzino, articoli gestiti, sottoscorta, sotto riordino, in arrivo) e griglia giacenze con stato (anteprima ridotta).*
|
||||

|
||||
|
||||
In alto una **striscia di indicatori**: valore del magazzino, articoli gestiti, articoli **sottoscorta**, articoli
|
||||
**sotto il punto di riordino**, valore **in arrivo** (ordinato).
|
||||
In alto la striscia degli indicatori: **articoli in giacenza**, **sottoscorta**, **esauriti**, **articoli in
|
||||
arrivo** (con ordini fornitore aperti) e **valore di magazzino** (visibile solo con `items.cost.read`).
|
||||
|
||||
La griglia mostra per ogni articolo: categoria, UM, **giacenza**, **impegnato**, **ordinato**, **disponibile**,
|
||||
**scorta minima**, **punto di riordino**, **costo medio**, **valore** e uno **stato**:
|
||||
Sotto, il filtro **Deposito** (tutti o uno solo) e la casella **Anche gli articoli senza giacenza**; poi il radar
|
||||
con ricerca per codice o descrizione e i filtri rapidi **Categoria** e **Stato**. Per ogni articolo: categoria, unità,
|
||||
giacenza, impegnato, ordinato, disponibile, scorta minima, costo medio, valore e uno **stato**:
|
||||
|
||||
| Stato | Quando |
|
||||
|---|---|
|
||||
| *OK* | disponibilità sopra il punto di riordino |
|
||||
| *Sotto riordino* | disponibilità sotto il punto di riordino |
|
||||
| *Sottoscorta* | disponibilità sotto la scorta minima (riga evidenziata) |
|
||||
| *Esaurito · in arrivo* | giacenza a zero con ordini fornitore aperti |
|
||||
| *Disponibile* | il disponibile più l'ordinato supera il punto di riordino |
|
||||
| *Da riordinare* | disponibile più ordinato pari o sotto il punto di riordino |
|
||||
| *Sottoscorta* | disponibile sotto la scorta minima |
|
||||
| *Esaurito* | disponibile sotto zero, o a zero per un articolo con scorta minima o punto di riordino |
|
||||
|
||||
Filtri: ricerca (articolo, EAN, descrizione), **Deposito**, **Categoria**, **Mostra** (*Solo gestiti a magazzino*),
|
||||
chip *Evidenzia sottoscorta*. Azioni: **Proposta di riordino**, **Inventario**. Il dettaglio per deposito di un
|
||||
singolo articolo è anche nella scheda articolo (vedi [Articoli e listini](Articoli-e-listini)).
|
||||
Le colonne *Ultimo carico* e *Ultimo scarico* si aggiungono dal selettore delle colonne del radar. I pulsanti
|
||||
portano alla **proposta di riordino** e all'**inventario**, aprono la **valorizzazione** e la **ricostruzione**.
|
||||
|
||||
## Movimenti e trasferimenti
|
||||
## Movimenti di un articolo
|
||||
|
||||

|
||||
*Mockup 037 — trasferimento in bozza dal deposito SEDE al deposito furgone, con disponibilità all'origine e valore (anteprima ridotta).*
|
||||

|
||||
|
||||
I **movimenti manuali** servono per tutto ciò che non passa da un documento di vendita o acquisto: carichi e scarichi
|
||||
rettificativi, omaggi interni, consumi, **trasferimenti** tra depositi. Ogni movimento ha una **causale di
|
||||
magazzino** che ne stabilisce l'effetto (carico, scarico, trasferimento).
|
||||
Apri una riga delle giacenze (doppio clic o **Invio**) per vedere i movimenti dell'articolo in ordine di data: il
|
||||
documento che li ha generati (il link lo apre), la causale, il cliente o fornitore, il deposito, la quantità, il
|
||||
costo unitario e il **saldo progressivo**. **Apri l'articolo** porta alla scheda. Il widget *Sottoscorta* della
|
||||
[Dashboard](Dashboard) apre direttamente questa finestra sull'articolo scelto.
|
||||
|
||||
Per un trasferimento:
|
||||
## Movimenti manuali e trasferimenti
|
||||
|
||||
1. **Magazzino → Trasferimenti** (o *Movimenti*), **Nuovo**.
|
||||
2. Scegli la causale di trasferimento, il **deposito di origine** e quello di **destinazione**.
|
||||
3. Inserisci le righe: la colonna *Disp. origine* mostra quanto è disponibile nel deposito di partenza.
|
||||
4. Se serve, **Stampa lista prelievo** per chi prepara la merce.
|
||||
5. **Conferma**.
|
||||
Per tutto ciò che non passa da un documento di vendita o acquisto (rettifiche, omaggi, autoconsumi, conto visione,
|
||||
trasferimenti) usa **Magazzino → Movimenti** e crea un **Movimento di magazzino**: è un documento come gli altri
|
||||
(vedi [Vendite](Vendite) per la maschera), con in più la **causale** e il **deposito**.
|
||||
|
||||
Un trasferimento genera **due movimenti collegati** (scarico dall'origine e carico nella destinazione) nella stessa
|
||||
transazione. Finché il movimento è in bozza la merce dell'origine risulta **impegnata**.
|
||||
1. Scegli la **causale**: decide se il movimento carica, scarica o trasferisce.
|
||||
2. Indica il **deposito**; per un trasferimento anche il **deposito di destinazione**, diverso dall'origine.
|
||||
3. Inserisci le righe con articolo e quantità; nei carichi il prezzo è il costo unitario.
|
||||
4. **Conferma**: il magazzino si aggiorna. Un trasferimento scarica l'origine e carica la destinazione al costo medio,
|
||||
senza cambiare il valore complessivo.
|
||||
|
||||
Un movimento confermato si può annullare: i suoi movimenti vengono tolti e le giacenze ricalcolate.
|
||||
|
||||
## Inventario fisico
|
||||
|
||||

|
||||
*Mockup 038 — inventario guidato in cinque passi, griglia con giacenza teorica, contato, differenza, valore e rettifica (anteprima ridotta).*
|
||||

|
||||
|
||||
L'inventario è una procedura guidata:
|
||||
L'inventario confronta la merce contata con la **giacenza contabile** e trasforma le differenze in rettifiche.
|
||||
|
||||
1. **Preparazione**: scegli il **deposito**, la **data** e il criterio di **valorizzazione** (es. costo medio);
|
||||
l'opzione **Blocca movimenti durante il conteggio** congela le giacenze del deposito.
|
||||
2. **Conteggio**: **Stampa liste di conteggio** (anche per ubicazione e squadra) e inserisci i quantitativi contati
|
||||
nella griglia oppure **Importa conteggi CSV**.
|
||||
3. **Verifica differenze**: la griglia confronta **giacenza teorica** e **contato** e mostra differenza e valore;
|
||||
il filtro *Solo differenze e da contare* aiuta a chiudere il lavoro.
|
||||
4. **Rettifiche**: **Genera rettifiche** crea i movimenti di carico o scarico per allineare la giacenza al contato.
|
||||
5. **Chiusura**: sblocca il deposito.
|
||||
1. **Apertura**: in **Magazzino → Inventario** scegli il **deposito**, la **data del conteggio**, se vuoi una
|
||||
**categoria** e una descrizione, poi **Apri inventario**. Khaemhat fotografa la giacenza contabile di ogni articolo
|
||||
gestito a magazzino a quella data.
|
||||
2. **Conteggio**: scrivi le quantità contate nella colonna *Contato* e premi **Salva conteggi**, oppure **Importa
|
||||
conteggi** da un file CSV o di testo del lettore di codici a barre: una riga per articolo con *codice articolo* e
|
||||
*quantità*, separati da punto e virgola, tabulazione o virgola (con la virgola la quantità usa il punto decimale).
|
||||
Una riga di intestazione viene saltata; i codici non in lista sono segnalati.
|
||||
3. **Verifica differenze**: il filtro **Mostra** (*Tutti*, *Da contare*, *Con differenze*) aiuta a chiudere il
|
||||
lavoro; le righe con differenza sono evidenziate e la striscia in alto riassume articoli contati, differenze e
|
||||
valore delle differenze.
|
||||
4. **Registrazione**: **Registra rettifiche** crea alla data del conteggio un movimento `INVP` per le eccedenze e uno
|
||||
`INVN` per gli ammanchi, e chiude l'inventario. Gli articoli **non contati restano come sono**.
|
||||
|
||||
**Annulla inventario** lo chiude senza muovere il magazzino; i conteggi restano consultabili. I movimenti successivi
|
||||
alla data del conteggio non disturbano: le rettifiche sono alla data del conteggio e la giacenza di oggi tiene conto
|
||||
di entrambi.
|
||||
|
||||
## Proposta di riordino
|
||||
|
||||

|
||||
*Mockup 039 — proposta di riordino: indicatori, criterio di calcolo, quantità proposta modificabile e fornitore per riga (anteprima ridotta).*
|
||||

|
||||
|
||||
La proposta elenca gli articoli sotto il punto di riordino con giacenza, impegnato, ordinato, disponibile, scorta
|
||||
minima, punto e **lotto** di riordino, **quantità proposta** (modificabile), **fornitore** abituale, lead time,
|
||||
prezzo e valore. In alto gli indicatori: articoli sotto riordino, proposte, valore, fornitori coinvolti, articoli
|
||||
già coperti da ordini.
|
||||
La proposta elenca gli articoli il cui **disponibile più ordinato** non copre più il **punto di riordino** (o, se manca,
|
||||
la **scorta minima**). Per ogni articolo propone:
|
||||
|
||||
1. Scegli **deposito**, **fornitore** (o tutti) e il **criterio di calcolo** (es. *disponibile + ordinato < punto
|
||||
di riordino*, con o senza l'impegnato).
|
||||
2. **Ricalcola**, controlla e correggi le quantità proposte, togli la spunta alle righe da non ordinare.
|
||||
3. **Genera ordini fornitore**: Khaemhat crea **un ordine in bozza per fornitore** (vedi [Acquisti](Acquisti)).
|
||||
- la **quantità**: il **lotto di riordino** dell'articolo se c'è, altrimenti quanto riporta al punto di riordino (o
|
||||
alla scorta minima); mai meno del **minimo d'ordine** del fornitore;
|
||||
- il **fornitore abituale** (il preferito nella scheda articolo, *Fornitori*) con il suo prezzo e la **data di arrivo
|
||||
prevista** dal lead time.
|
||||
|
||||
Il mockup indica come fabbisogno il maggiore tra il lotto e la differenza fra punto di riordino e disponibile più
|
||||
ordinato; la formula definitiva (compresi gli arrotondamenti al lotto) sarà fissata in sviluppo. La proposta può
|
||||
anche essere eseguita da una procedura pianificata o alimentata da una regola di automazione (evento *articolo sotto
|
||||
il punto di riordino*, vedi [Automazioni](Automazioni)).
|
||||
Correggi le quantità, cambia il fornitore di una riga o togli la spunta alle righe da non ordinare; **Ricalcola**
|
||||
rilegge le giacenze. **Genera ordini fornitore** crea **un ordine in bozza per fornitore** con prezzi e condizioni del
|
||||
fornitore: controllali e confermali da **Acquisti → Ordini fornitori** (vedi [Acquisti](Acquisti)). Le righe senza
|
||||
fornitore non vengono ordinate.
|
||||
|
||||
## Costo medio e valorizzazione
|
||||
|
||||
- Il criterio di valorizzazione è il **costo medio ponderato**: a ogni carico il nuovo costo medio è
|
||||
(valore della giacenza esistente + valore del carico) / (giacenza esistente + quantità caricata). FIFO e LIFO sono
|
||||
predisposti ma non attivi.
|
||||
- Il **valore** di una giacenza è quantità x costo medio.
|
||||
- La **valorizzazione a data** ricostruisce quantità e valore a una data passata (ad esempio al 31 dicembre).
|
||||
- Le **rimanenze finali** valorizzate alimentano la chiusura dell'esercizio e il **libro inventari** (vedi
|
||||
[Contabilità](Contabilita)); sono disponibili le **scritture ausiliarie di magazzino** e l'**analisi ABC**.
|
||||

|
||||
|
||||
- Il criterio è il **costo medio ponderato** per articolo, su tutti i depositi: a ogni carico con valore il nuovo
|
||||
costo medio è (valore della giacenza + valore del carico) / (giacenza + quantità caricata). Scarichi, trasferimenti
|
||||
e conto visione escono al costo medio del momento e non lo cambiano.
|
||||
- La scheda articolo mostra **costo medio** e **ultimo costo** calcolati dai movimenti.
|
||||
- La **valorizzazione** (pulsante nelle giacenze) calcola quantità e valore **a una data** qualsiasi, anche passata,
|
||||
con il criterio scelto: *costo medio ponderato*, *ultimo costo* o *costo standard*. Divide gli articoli in **classi
|
||||
ABC**: A gli articoli che fanno l'80% del valore, B fino al 95%, C il resto.
|
||||
- FIFO e LIFO sono previsti con la gestione a lotti; le rimanenze alimenteranno la chiusura dell'esercizio e il libro
|
||||
inventari con la chiusura dell'esercizio (M10).
|
||||
|
||||
## Ricostruzione
|
||||
|
||||
Se le giacenze risultassero non allineate (ad esempio dopo un ripristino o un import), la **ricostruzione** ricalcola
|
||||
giacenze, impegnato, ordinato e costi medi ripercorrendo tutti i movimenti. È una procedura eseguibile a mano o da
|
||||
attività programmata e non modifica i documenti. Vedi [Automazioni](Automazioni) e
|
||||
[Attività programmate](Attivita-programmate).
|
||||
Se le giacenze sembrano non tornare (dopo un ripristino, un import diretto nel database, un cambio di causale su un
|
||||
tipo documento), **Ricostruisci** nelle giacenze riscrive tutti i movimenti dai documenti in vigore, dal più vecchio,
|
||||
e ricalcola giacenze, impegnato, ordinato e costi. I documenti non cambiano e i dati restano consultabili durante il
|
||||
lavoro, che mostra l'avanzamento. Richiede `inventory.entry.post`.
|
||||
|
||||
## Stati dei movimenti
|
||||
La stessa ricostruzione gira ogni **domenica alle 2:15** come attività di sistema *Ricostruzione del magazzino* (vedi
|
||||
[Attività programmate](Attivita-programmate)), su tutte le aziende attive.
|
||||
|
||||
| Stato | Effetto |
|
||||
|---|---|
|
||||
| **Bozza** | nessun effetto sulla giacenza (nei trasferimenti l'origine è impegnata) |
|
||||
| **Confermato** | giacenze aggiornate; righe non più modificabili |
|
||||
| **Annullato** | movimenti stornati |
|
||||
## Esistenze iniziali
|
||||
|
||||
Per partire con le giacenze di un altro gestionale importa il tracciato **Giacenze iniziali** da
|
||||
[Import ed export](Import-Export): articolo, deposito, quantità e costo unitario. Khaemhat crea e conferma un
|
||||
movimento con causale `APE` per deposito, alla data dell'import.
|
||||
|
||||
## Permessi e licenza
|
||||
|
||||
Il magazzino è nel modulo **CORE**. Confermare un movimento richiede `inventory.entry.post`; vedere costi e valori
|
||||
richiede `items.cost.read`.
|
||||
Il magazzino è nel modulo **CORE**. Vedere giacenze e movimenti richiede `inventory.stock.read`; scrivere movimenti
|
||||
e conteggi `inventory.entry.write`; confermare i movimenti, registrare le rettifiche e ricostruire
|
||||
`inventory.entry.post`. Costi, valori e valorizzazione sono visibili solo con `items.cost.read`.
|
||||
|
||||
## Domande frequenti
|
||||
|
||||
- **Il disponibile è negativo.** Gli ordini clienti confermati impegnano più merce di quella in giacenza: ordina al
|
||||
fornitore o rivedi le consegne.
|
||||
- **Il costo medio è cambiato dopo un carico.** È il comportamento previsto del costo medio ponderato; il messaggio
|
||||
sul DDT di carico indica il vecchio e il nuovo valore.
|
||||
- **Durante l'inventario non riesco a scaricare merce dal deposito.** È attivo il blocco dei movimenti: termina la
|
||||
procedura o disattiva il blocco.
|
||||
- **La giacenza è negativa.** È stato confermato uno scarico senza merce a sufficienza (Khaemhat non lo blocca, per
|
||||
non fermare le consegne): registra il carico mancante o fai un inventario.
|
||||
- **Il costo medio è cambiato dopo una fattura fornitore.** Il prezzo fatturato era diverso da quello del DDT di
|
||||
carico: il costo del carico viene corretto con il prezzo della fattura.
|
||||
- **Un articolo non compare nelle giacenze.** Non ha movimenti: spunta *Anche gli articoli senza giacenza*. Se non
|
||||
compare comunque, nella scheda non è *gestito a magazzino* o non è un bene.
|
||||
- **L'articolo non è nella proposta di riordino.** Non ha punto di riordino né scorta minima, oppure l'ordinato già
|
||||
lo copre.
|
||||
|
||||
## Pagine correlate
|
||||
|
||||
[Articoli e listini](Articoli-e-listini) · [Acquisti](Acquisti) · [Vendite](Vendite) ·
|
||||
[Tabelle azienda](Tabelle-azienda) · [Report](Report) · [Contabilità](Contabilita) · [Automazioni](Automazioni)
|
||||
[Tabelle azienda](Tabelle-azienda) · [Import ed export](Import-Export) · [Dashboard](Dashboard) ·
|
||||
[Attività programmate](Attivita-programmate)
|
||||
@@ -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) |
|
||||
|
||||
@@ -289,7 +289,7 @@ Con l'azienda configurata puoi emettere la prima fattura:
|
||||
|
||||

|
||||
|
||||
La guida completa è in [Vendite](Vendite). La contabilizzazione arriva con M7 e l'XML FatturaPA per lo SDI con M9
|
||||
La guida completa è in [Vendite](Vendite). Dalla 0.7 la fattura confermata è già in [Contabilità](Contabilita); l'XML FatturaPA per lo SDI con M9
|
||||
(modulo EINV, vedi [Fatturazione elettronica](Fatturazione-elettronica)).
|
||||
|
||||
## Domande frequenti
|
||||
|
||||
@@ -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). **Prossima:** M6.
|
||||
**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). **Prossima:** M10.
|
||||
|
||||
| # | Milestone | Contenuto principale | Versione |
|
||||
|---|---|---|---|
|
||||
|
||||
@@ -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.
|
||||
|
||||

|
||||
*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:
|
||||
|
||||

|
||||
*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)).
|
||||
|
||||

|
||||
*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
|
||||
|
||||

|
||||
*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 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).*
|
||||
|
||||

|
||||
*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 — 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 — 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 — Incassi del periodo con documento saldato, riferimento CRO, banca e registrazione contabile.*
|
||||
|
||||

|
||||
*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: 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 — 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 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 — 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 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 — 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 — 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)
|
||||
@@ -81,7 +81,7 @@ liquidazione IVA (*provvisoria*, *confermata*), registrazioni, interruttore **Bl
|
||||
|
||||
Indirizzo: `/tabelle/esercizi`. **Nuovo esercizio** crea l'anno successivo all'ultimo con i suoi dodici mesi. Il
|
||||
pulsante **Blocca** di un mese impedisce nuove registrazioni con date in quel mese; **Sblocca** chiede conferma. Un
|
||||
mese *liquidato* si sblocca solo annullando la liquidazione IVA (M7).
|
||||
mese *liquidato* si sblocca solo riaprendo la liquidazione IVA (vedi [IVA](IVA)).
|
||||
|
||||
Regola fondamentale: **si possono registrare documenti e movimenti contabili solo con data in un periodo aperto**. Un
|
||||
periodo bloccato rifiuta ogni registrazione con data al suo interno; la conferma della liquidazione IVA blocca il
|
||||
@@ -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… |
|
||||
|
||||
@@ -9,9 +9,11 @@ accompagnatorie, differite, di acconto, parcelle), **note di credito e di debito
|
||||
e si inviano per e-mail.
|
||||
|
||||
> **In questa versione** i documenti hanno numeri, totali, castelletto IVA, bollo, ritenute, scadenze, collegamenti
|
||||
> riga per riga, stampa ed e-mail. Arrivano più avanti: lo **scarico di magazzino** e l'impegno (M6, con il
|
||||
> magazzino), la **registrazione contabile** (M7), le **partite** e il controllo del fido (M8), il **file XML** per lo
|
||||
> SDI (M9) e il collegamento alle opportunità del **CRM** (M11). I pulsanti di queste funzioni compaiono quando la
|
||||
> 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)). 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
|
||||
@@ -148,8 +150,8 @@ e CUP, riportati nella stampa.
|
||||
|
||||
Il DDT accompagna la merce: si compila la scheda *Trasporto* e si stampa con gli spazi per le firme. Un DDT confermato
|
||||
non ancora fatturato compare nella **fatturazione differita**; un DDT fatturato risulta *Evaso*. Finché non è
|
||||
fatturato le righe si possono ancora correggere; **Annulla documento** lo annulla con un motivo. Lo scarico del
|
||||
magazzino arriva con M6.
|
||||
fatturato le righe si possono ancora correggere; **Annulla documento** lo annulla con un motivo. Alla conferma il DDT
|
||||
**scarica il magazzino** (causale `SCA`); la fattura differita che lo fattura non scarica di nuovo.
|
||||
|
||||
## Fatture
|
||||
|
||||
@@ -275,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:
|
||||
|
||||
|
||||
|
After Width: | Height: | Size: 74 KiB |
|
After Width: | Height: | Size: 113 KiB |
|
After Width: | Height: | Size: 121 KiB |
|
After Width: | Height: | Size: 69 KiB |
|
After Width: | Height: | Size: 119 KiB |
|
After Width: | Height: | Size: 165 KiB |
|
After Width: | Height: | Size: 118 KiB |
|
After Width: | Height: | Size: 174 KiB |
|
After Width: | Height: | Size: 115 KiB |
|
After Width: | Height: | Size: 149 KiB |
|
After Width: | Height: | Size: 190 KiB |
|
After Width: | Height: | Size: 100 KiB |
|
After Width: | Height: | Size: 97 KiB |
|
After Width: | Height: | Size: 73 KiB |
|
After Width: | Height: | Size: 97 KiB |
|
After Width: | Height: | Size: 133 KiB |
|
After Width: | Height: | Size: 65 KiB |
|
After Width: | Height: | Size: 130 KiB |
|
After Width: | Height: | Size: 172 KiB |
|
After Width: | Height: | Size: 130 KiB |
|
After Width: | Height: | Size: 136 KiB |
|
After Width: | Height: | Size: 75 KiB |
|
After Width: | Height: | Size: 93 KiB |
|
After Width: | Height: | Size: 178 KiB |
|
After Width: | Height: | Size: 177 KiB |
|
After Width: | Height: | Size: 178 KiB |
|
After Width: | Height: | Size: 199 KiB |
|
After Width: | Height: | Size: 166 KiB |
|
After Width: | Height: | Size: 220 KiB |
|
After Width: | Height: | Size: 100 KiB |
|
After Width: | Height: | Size: 117 KiB |
|
After Width: | Height: | Size: 168 KiB |
|
After Width: | Height: | Size: 98 KiB |
|
After Width: | Height: | Size: 62 KiB |
|
After Width: | Height: | Size: 147 KiB |
|
After Width: | Height: | Size: 66 KiB |
|
After Width: | Height: | Size: 69 KiB |
|
After Width: | Height: | Size: 142 KiB |
|
After Width: | Height: | Size: 113 KiB |
|
After Width: | Height: | Size: 108 KiB |
|
After Width: | Height: | Size: 119 KiB |
@@ -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>
|
||||
|
||||
@@ -105,7 +105,7 @@ public static class WidgetCatalog
|
||||
new(WidgetIds.CrmActivities, "Dashboard.Widgets.CrmActivities.Title", "target", 6, ModuleCodes.Crm, "crm.lead.read", Milestone: "M11"),
|
||||
new(WidgetIds.Notes, "Dashboard.Widgets.Notes.Title", "edit", 4, ModuleCodes.Core),
|
||||
new(WidgetIds.Shortcuts, "Dashboard.Widgets.Shortcuts.Title", "zap", 4, ModuleCodes.Core),
|
||||
new(WidgetIds.Understock, "Dashboard.Widgets.Understock.Title", "box", 6, ModuleCodes.Core, "inventory.stock.read", Milestone: "M6"),
|
||||
new(WidgetIds.Understock, "Dashboard.Widgets.Understock.Title", "box", 6, ModuleCodes.Core, "inventory.stock.read"),
|
||||
new(WidgetIds.Pipeline, "Dashboard.Widgets.Pipeline.Title", "target", 6, ModuleCodes.Crm, "crm.lead.read", Milestone: "M11"),
|
||||
new(WidgetIds.RecentDocuments, "Dashboard.Widgets.RecentDocuments.Title", "file", 6, ModuleCodes.Core, "sales.invoice.read", Milestone: "M5"),
|
||||
new(WidgetIds.SystemStatus, "Dashboard.Widgets.System.Title", "shield", 4, ModuleCodes.Core, InstanceOnly: true),
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
using Khaemhat.Application.Audit;
|
||||
using Khaemhat.Application.Inventory;
|
||||
using Khaemhat.Application.Security;
|
||||
using Khaemhat.Application.Tables;
|
||||
using Khaemhat.Core.Documents;
|
||||
@@ -89,6 +90,15 @@ public static class DocumentErrors
|
||||
|
||||
/// <summary>Error: a line of an invoice without its VAT code.</summary>
|
||||
public const string LineTaxRequired = "document.line.tax-required";
|
||||
|
||||
/// <summary>A supplier invoice needs the number and date the supplier gave it.</summary>
|
||||
public const string SupplierNumberRequired = "document.purchase.number-required";
|
||||
|
||||
/// <summary>The same supplier already has a document of the kind with that number in that year.</summary>
|
||||
public const string SupplierDuplicate = "document.purchase.duplicate";
|
||||
|
||||
/// <summary>The VAT date comes before the date of the supplier document.</summary>
|
||||
public const string VatDateBefore = "document.purchase.vat-date-before";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -105,6 +115,7 @@ public sealed partial class DocumentEngine
|
||||
private readonly CompanyFiscalContext _packs;
|
||||
private readonly TimeProvider _clock;
|
||||
private readonly ILogger<DocumentEngine> _logger;
|
||||
private readonly Ledger.LedgerPoster _ledger;
|
||||
|
||||
/// <summary>Creates the engine.</summary>
|
||||
/// <param name="factory">The units of work.</param>
|
||||
@@ -114,10 +125,13 @@ public sealed partial class DocumentEngine
|
||||
/// <param name="packs">The fiscal pack of each company (tax rounding, stamp duty).</param>
|
||||
/// <param name="clock">The clock.</param>
|
||||
/// <param name="logger">The log (section Documenti): confirmations, changes of state, deletions.</param>
|
||||
/// <param name="ledger">Posts the documents to the ledger (module ACCT).</param>
|
||||
public DocumentEngine(
|
||||
IUnitOfWorkFactory factory, PermissionService permissions, AuditTrail audit, FiscalYearService fiscal, CompanyFiscalContext packs, TimeProvider clock,
|
||||
ILogger<DocumentEngine> logger)
|
||||
ILogger<DocumentEngine> logger, Ledger.LedgerPoster ledger)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(ledger);
|
||||
_ledger = ledger;
|
||||
ArgumentNullException.ThrowIfNull(logger);
|
||||
_logger = logger;
|
||||
ArgumentNullException.ThrowIfNull(packs);
|
||||
@@ -240,6 +254,7 @@ public sealed partial class DocumentEngine
|
||||
}
|
||||
|
||||
var errors = Check(definition, record, before);
|
||||
await CheckSupplierDocumentAsync(uow, record, confirming: false, errors, cancellationToken).ConfigureAwait(false);
|
||||
if (errors.Count > 0)
|
||||
{
|
||||
throw new ValidationFailedException(errors);
|
||||
@@ -257,6 +272,8 @@ public sealed partial class DocumentEngine
|
||||
if (before is not null && DocumentStateMachine.IsInForce(header.Status))
|
||||
{
|
||||
await RefreshFulfillmentAsync(uow, record.Family, id, actor.UserName, cancellationToken).ConfigureAwait(false);
|
||||
await InventoryPoster.SyncAsync(uow, record.Family, id, cancellationToken).ConfigureAwait(false);
|
||||
await _ledger.SyncAsync(uow, record.Family, id, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
|
||||
@@ -300,6 +317,8 @@ public sealed partial class DocumentEngine
|
||||
errors.Add("Lines:" + DocumentErrors.LinesRequired);
|
||||
}
|
||||
|
||||
await CheckSupplierDocumentAsync(uow, record, confirming: true, errors, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
if (definition.Behavior.Has(DocumentEffects.Ledger))
|
||||
{
|
||||
// A document that goes to the VAT registers needs the VAT of every line with an amount.
|
||||
@@ -329,12 +348,21 @@ public sealed partial class DocumentEngine
|
||||
}
|
||||
|
||||
header.Year = header.DocumentDate.Year;
|
||||
if (IsRegistered(header.Kind))
|
||||
{
|
||||
// A supplier invoice takes its protocol from the numbering of the purchase register (§11.5).
|
||||
header.VatProtocol = header.Number;
|
||||
header.VatDate ??= header.DocumentDate;
|
||||
}
|
||||
|
||||
header.Status = next;
|
||||
header.ConfirmedAt = _clock.GetUtcNow().UtcDateTime;
|
||||
header.ConfirmedBy = actor.UserName;
|
||||
await store.UpdateAsync(uow, header, cancellationToken).ConfigureAwait(false);
|
||||
await store.RecordAsync(_audit, uow, AuditAction.Update, id, before, header, actor.UserName, cancellationToken).ConfigureAwait(false);
|
||||
await LinkAsync(uow, definition, record, actor.UserName, cancellationToken).ConfigureAwait(false);
|
||||
await InventoryPoster.SyncAsync(uow, family, id, cancellationToken).ConfigureAwait(false);
|
||||
await _ledger.SyncAsync(uow, family, id, cancellationToken).ConfigureAwait(false);
|
||||
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
|
||||
LogConfirmed(_logger, header.Kind, header.DocumentNumber ?? id.ToString(System.Globalization.CultureInfo.InvariantCulture), header.Status, company, actor.UserName);
|
||||
}
|
||||
@@ -423,6 +451,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>
|
||||
@@ -679,6 +749,9 @@ public sealed partial class DocumentEngine
|
||||
await after(uow, record, actor.UserName, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
// A cancelled delivery note gives its stock back; a closed or reopened order its open quantities.
|
||||
await InventoryPoster.SyncAsync(uow, family, id, cancellationToken).ConfigureAwait(false);
|
||||
await _ledger.SyncAsync(uow, family, id, cancellationToken).ConfigureAwait(false);
|
||||
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
|
||||
LogChanged(_logger, record.Header.Kind, record.Header.DocumentNumber ?? id.ToString(System.Globalization.CultureInfo.InvariantCulture), action, next, company, actor.UserName);
|
||||
}
|
||||
@@ -834,6 +907,52 @@ public sealed partial class DocumentEngine
|
||||
header.Revision = 0;
|
||||
}
|
||||
|
||||
// Supplier invoices and credit notes go to the purchase register with a protocol and a VAT date.
|
||||
private static bool IsRegistered(DocumentKind kind) => kind is DocumentKind.PurchaseInvoice or DocumentKind.PurchaseCreditNote;
|
||||
|
||||
// The rules of a supplier document (§11.5): its own number and date, the VAT date not before it, no duplicate of
|
||||
// the same supplier, kind, number and year among the documents in force or in draft.
|
||||
private static async Task CheckSupplierDocumentAsync(IUnitOfWork uow, DocumentRecord record, bool confirming, List<string> errors, CancellationToken cancellationToken)
|
||||
{
|
||||
var header = record.Header;
|
||||
if (!IsRegistered(header.Kind))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var number = header.ExternalReference?.Trim();
|
||||
if (confirming && string.IsNullOrEmpty(number))
|
||||
{
|
||||
errors.Add(nameof(DocumentHeader.ExternalReference) + ":" + DocumentErrors.SupplierNumberRequired);
|
||||
}
|
||||
|
||||
if (confirming && header.ExternalDate is null)
|
||||
{
|
||||
errors.Add(nameof(DocumentHeader.ExternalDate) + ":" + DocumentErrors.SupplierNumberRequired);
|
||||
}
|
||||
|
||||
if (header.VatDate is { } vatDate && header.ExternalDate is { } supplierDate && vatDate < supplierDate)
|
||||
{
|
||||
errors.Add(nameof(DocumentHeader.VatDate) + ":" + DocumentErrors.VatDateBefore);
|
||||
}
|
||||
|
||||
if (string.IsNullOrEmpty(number) || header.PartyId is not { } party)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var year = (header.ExternalDate ?? header.DocumentDate).Year;
|
||||
var kind = header.Kind;
|
||||
var id = header.Id;
|
||||
var others = (await uow.Repository<PurchaseDocument, long>().ListAsync(
|
||||
Query.For<PurchaseDocument>().Where(d => d.PartyId == party && d.Kind == kind && d.ExternalReference == number && d.Id != id && d.Status != DocumentStatus.Cancelled),
|
||||
cancellationToken).ConfigureAwait(false)).Items;
|
||||
if (others.Any(d => (d.ExternalDate ?? d.DocumentDate).Year == year))
|
||||
{
|
||||
errors.Add(nameof(DocumentHeader.ExternalReference) + ":" + DocumentErrors.SupplierDuplicate);
|
||||
}
|
||||
}
|
||||
|
||||
private static string Company(Actor actor, string companyCode)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(actor);
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
|
||||
@@ -40,6 +40,12 @@ internal interface IDocumentStore
|
||||
/// <returns>The lines.</returns>
|
||||
Task<List<DocumentLine>> LinesAsync(IUnitOfWork uow, long documentId, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>Reads the headers of the documents in force (neither drafts nor cancelled).</summary>
|
||||
/// <param name="uow">The unit of work.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The headers.</returns>
|
||||
Task<IReadOnlyList<DocumentHeader>> InForceAsync(IUnitOfWork uow, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>Reads a line.</summary>
|
||||
/// <param name="uow">The unit of work.</param>
|
||||
/// <param name="id">The line.</param>
|
||||
@@ -136,6 +142,11 @@ internal sealed class DocumentStore<THeader, TLine>(DocumentFamily family, strin
|
||||
public async Task<DocumentHeader?> GetAsync(IUnitOfWork uow, long id, CancellationToken cancellationToken) =>
|
||||
await uow.Repository<THeader, long>().GetAsync(id, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<IReadOnlyList<DocumentHeader>> InForceAsync(IUnitOfWork uow, CancellationToken cancellationToken) =>
|
||||
[.. (await uow.Repository<THeader, long>().ListAsync(
|
||||
Query.For<THeader>().Where(h => h.Status != DocumentStatus.Draft && h.Status != DocumentStatus.Cancelled), cancellationToken).ConfigureAwait(false)).Items];
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<List<DocumentLine>> LinesAsync(IUnitOfWork uow, long documentId, CancellationToken cancellationToken)
|
||||
{
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
@@ -2,10 +2,7 @@ using Khaemhat.Application.Modules;
|
||||
using Khaemhat.Application.Security;
|
||||
using Khaemhat.Application.Tables;
|
||||
using Khaemhat.Core.Accounting;
|
||||
using Khaemhat.Core.Items;
|
||||
using Khaemhat.Core.Tables;
|
||||
using Khaemhat.Data;
|
||||
using Khaemhat.Data.Querying;
|
||||
|
||||
namespace Khaemhat.Application.ImportExport;
|
||||
|
||||
@@ -21,9 +18,11 @@ namespace Khaemhat.Application.ImportExport;
|
||||
/// <param name="SubLedger">With a sub-ledger of customers or suppliers.</param>
|
||||
/// <param name="ClosesAutomatically">Closed by the year end.</param>
|
||||
/// <param name="Disabled">Not used any more.</param>
|
||||
/// <param name="StatementLine">The line of the legal statements (voce CEE).</param>
|
||||
/// <param name="Reclassification">The line of the reclassified statements.</param>
|
||||
public sealed record ImportedAccount(
|
||||
string Code, string Description, int Level, string? ParentCode, AccountNature Nature, AccountType Type, bool Postable, bool VatRelevant, bool SubLedger,
|
||||
bool ClosesAutomatically, bool Disabled);
|
||||
bool ClosesAutomatically, bool Disabled, string? StatementLine = null, string? Reclassification = null);
|
||||
|
||||
/// <summary>
|
||||
/// The checks of a chart of accounts from a file (SPEC §12.12, ADR 0031): codes of one to three parts separated by
|
||||
@@ -149,7 +148,7 @@ public static class ChartOfAccountsImportValidator
|
||||
if (messages.All(m => m.IsWarning) && nature is { } valid)
|
||||
{
|
||||
accounts.Add(new(code, row["descrizione"] ?? string.Empty, level, parent, valid, type, postable, flags.Contains('I'), flags.Contains('P'), flags.Contains('C'),
|
||||
flags.Contains('X')));
|
||||
flags.Contains('X'), row["voce_cee"], row["riclassifica"]));
|
||||
}
|
||||
|
||||
results.Add(new(row.Line, code, messages.Any(m => !m.IsWarning) ? ImportAction.Skip : ImportAction.Create, messages));
|
||||
@@ -186,15 +185,26 @@ public static class ChartOfAccountsImportValidator
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The chart of accounts (<c>piano-dei-conti</c>): CSV, XLSX or <c>khaemhat-coa.json</c>. Until the ledger exists (M7)
|
||||
/// the file is only checked; M7 writes the accounts this check accepts.
|
||||
/// The chart of accounts (<c>piano-dei-conti</c>): CSV, XLSX or <c>khaemhat-coa.json</c>. The accounts the check
|
||||
/// accepts are added; those that exist are updated when the options say so (M7, issue #62).
|
||||
/// </summary>
|
||||
/// <param name="permissions">Checks the permission.</param>
|
||||
public sealed class ChartOfAccountsImportTarget(PermissionService permissions) : IImportTarget
|
||||
public sealed class ChartOfAccountsImportTarget : IImportTarget
|
||||
{
|
||||
/// <summary>The permission to change the chart of accounts.</summary>
|
||||
public const string WritePermission = "ledger.account.write";
|
||||
|
||||
private readonly PermissionService _permissions;
|
||||
private readonly IUnitOfWorkFactory? _factory;
|
||||
|
||||
/// <summary>Creates the target.</summary>
|
||||
/// <param name="permissions">Checks the permission.</param>
|
||||
/// <param name="factory">The units of work, to write the accounts.</param>
|
||||
public ChartOfAccountsImportTarget(PermissionService permissions, IUnitOfWorkFactory? factory = null)
|
||||
{
|
||||
_permissions = permissions;
|
||||
_factory = factory;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public string Key => "piano-dei-conti";
|
||||
|
||||
@@ -208,10 +218,10 @@ public sealed class ChartOfAccountsImportTarget(PermissionService permissions) :
|
||||
public string ExportPermission => "ledger.account.read";
|
||||
|
||||
/// <inheritdoc />
|
||||
public bool CanApply => false;
|
||||
public bool CanApply => _factory is not null;
|
||||
|
||||
/// <inheritdoc />
|
||||
public bool CanExport => false;
|
||||
public bool CanExport => _factory is not null;
|
||||
|
||||
/// <inheritdoc />
|
||||
public IReadOnlyList<ImportField> Fields => ChartOfAccountsImportValidator.Fields;
|
||||
@@ -220,113 +230,46 @@ public sealed class ChartOfAccountsImportTarget(PermissionService permissions) :
|
||||
public async Task<IReadOnlyList<ImportRowResult>> CheckAsync(ImportContext context, IReadOnlyList<ImportRow> rows, CancellationToken cancellationToken)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(context);
|
||||
await CompanyGuard.DemandAsync(permissions, context.Actor, context.CompanyCode, Permission, cancellationToken).ConfigureAwait(false);
|
||||
await CompanyGuard.DemandAsync(_permissions, context.Actor, context.CompanyCode, Permission, cancellationToken).ConfigureAwait(false);
|
||||
return ChartOfAccountsImportValidator.Check(rows).Results;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public Task<IReadOnlyList<ImportRowResult>> ApplyAsync(ImportContext context, IReadOnlyList<ImportRow> rows, CancellationToken cancellationToken) =>
|
||||
throw new InvalidOperationException(ImportErrors.CheckOnly);
|
||||
|
||||
/// <inheritdoc />
|
||||
public Task<IReadOnlyList<IReadOnlyList<object?>>> ExportAsync(ImportContext context, CancellationToken cancellationToken) =>
|
||||
Task.FromResult<IReadOnlyList<IReadOnlyList<object?>>>([]);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The opening stock (<c>giacenze-iniziali</c>): item, warehouse, quantity and unit cost. Until the stock entries exist
|
||||
/// (M6) the file is only checked; M6 writes the opening entry from the rows this check accepts.
|
||||
/// </summary>
|
||||
/// <param name="factory">Opens the company databases.</param>
|
||||
/// <param name="permissions">Checks the permission.</param>
|
||||
public sealed class OpeningStockImportTarget(IUnitOfWorkFactory factory, PermissionService permissions) : IImportTarget
|
||||
{
|
||||
private static readonly ImportField[] StockFields =
|
||||
[
|
||||
new("articolo", ImportFieldKind.Code, Required: true, Aliases: ["codice_articolo", "codice", "cod_articolo", "sku"]),
|
||||
new("deposito", ImportFieldKind.Code, Aliases: ["magazzino", "codice_magazzino"]),
|
||||
new("quantita", ImportFieldKind.Number, Required: true, Aliases: ["qta", "qty", "giacenza", "esistenza"]),
|
||||
new("costo_unitario", ImportFieldKind.Number, Aliases: ["costo", "valore_unitario", "prezzo_acquisto"]),
|
||||
];
|
||||
|
||||
/// <inheritdoc />
|
||||
public string Key => "giacenze-iniziali";
|
||||
|
||||
/// <inheritdoc />
|
||||
public string ModuleCode => ModuleCodes.Core;
|
||||
|
||||
/// <inheritdoc />
|
||||
public string Permission => "inventory.entry.write";
|
||||
|
||||
/// <inheritdoc />
|
||||
public string ExportPermission => "inventory.stock.read";
|
||||
|
||||
/// <inheritdoc />
|
||||
public bool CanApply => false;
|
||||
|
||||
/// <inheritdoc />
|
||||
public bool CanExport => false;
|
||||
|
||||
/// <inheritdoc />
|
||||
public IReadOnlyList<ImportField> Fields => StockFields;
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<IReadOnlyList<ImportRowResult>> CheckAsync(ImportContext context, IReadOnlyList<ImportRow> rows, CancellationToken cancellationToken)
|
||||
public async Task<IReadOnlyList<ImportRowResult>> ApplyAsync(ImportContext context, IReadOnlyList<ImportRow> rows, CancellationToken cancellationToken)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(context);
|
||||
ArgumentNullException.ThrowIfNull(rows);
|
||||
var company = await CompanyGuard.DemandAsync(permissions, context.Actor, context.CompanyCode, Permission, cancellationToken).ConfigureAwait(false);
|
||||
await using var uow = await factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
||||
var items = (await uow.Repository<Item, long>().ListAsync(Query.For<Item>(), cancellationToken).ConfigureAwait(false)).Items;
|
||||
var codes = new CodeIndex(items.Select(i => (i.Code, i.Id)));
|
||||
var byId = items.ToDictionary(i => i.Id);
|
||||
var warehouses = await CodeIndex.LoadAsync<Warehouse>(uow, cancellationToken).ConfigureAwait(false);
|
||||
var seen = new HashSet<(long, long)>();
|
||||
var results = new List<ImportRowResult>(rows.Count);
|
||||
foreach (var row in rows)
|
||||
var factory = _factory ?? throw new InvalidOperationException(ImportErrors.CheckOnly);
|
||||
var company = await CompanyGuard.DemandAsync(_permissions, context.Actor, context.CompanyCode, Permission, cancellationToken).ConfigureAwait(false);
|
||||
var (results, accounts) = ChartOfAccountsImportValidator.Check(rows);
|
||||
var update = context.Options.Existing == ExistingCodeAction.Update;
|
||||
Dictionary<string, bool> written;
|
||||
await using (var uow = await factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
var messages = new List<ImportMessage>();
|
||||
var cells = new CellReader(row, messages);
|
||||
messages.AddRange(StockFields.Where(f => f.Required && !cells.Has(f.Key)).Select(f => new ImportMessage(f.Key, ImportErrors.Required)));
|
||||
var item = cells.Code("articolo", codes) is { } id ? byId[id] : null;
|
||||
var warehouse = cells.Code("deposito", warehouses) ?? (cells.Has("deposito") ? null : item?.WarehouseId);
|
||||
if (item is not null && (item.Kind != ItemKind.Goods || !item.Stocked))
|
||||
{
|
||||
messages.Add(new("articolo", ImportErrors.NotStocked, Value: item.Code));
|
||||
}
|
||||
|
||||
if (item is not null && warehouse is null && !cells.Has("deposito"))
|
||||
{
|
||||
messages.Add(new("deposito", ImportErrors.Required));
|
||||
}
|
||||
|
||||
if (cells.Number("quantita") is <= 0)
|
||||
{
|
||||
messages.Add(new("quantita", ImportErrors.Positive));
|
||||
}
|
||||
|
||||
if (cells.Number("costo_unitario") is < 0)
|
||||
{
|
||||
messages.Add(new("costo_unitario", Items.ItemService.NotNegative));
|
||||
}
|
||||
|
||||
var label = row["articolo"] ?? string.Empty;
|
||||
if (item is not null && warehouse is { } w && !seen.Add((item.Id, w)))
|
||||
{
|
||||
messages.Add(new("articolo", ImportErrors.CodeRepeated, Value: label));
|
||||
}
|
||||
|
||||
results.Add(new(row.Line, label, messages.Any(m => !m.IsWarning) ? ImportAction.Skip : ImportAction.Create, messages));
|
||||
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
|
||||
written = await Ledger.LedgerService.ImportAsync(uow, accounts, update, cancellationToken).ConfigureAwait(false);
|
||||
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
return results;
|
||||
return [.. results.Select(r => r.Action == ImportAction.Skip
|
||||
? r
|
||||
: r with { Action = written.TryGetValue(r.Key, out var created) ? (created ? ImportAction.Create : ImportAction.Update) : ImportAction.Skip })];
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public Task<IReadOnlyList<ImportRowResult>> ApplyAsync(ImportContext context, IReadOnlyList<ImportRow> rows, CancellationToken cancellationToken) =>
|
||||
throw new InvalidOperationException(ImportErrors.CheckOnly);
|
||||
|
||||
/// <inheritdoc />
|
||||
public Task<IReadOnlyList<IReadOnlyList<object?>>> ExportAsync(ImportContext context, CancellationToken cancellationToken) =>
|
||||
Task.FromResult<IReadOnlyList<IReadOnlyList<object?>>>([]);
|
||||
public async Task<IReadOnlyList<IReadOnlyList<object?>>> ExportAsync(ImportContext context, CancellationToken cancellationToken)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(context);
|
||||
var factory = _factory ?? throw new InvalidOperationException(ImportErrors.CheckOnly);
|
||||
var company = await CompanyGuard.DemandAsync(_permissions, context.Actor, context.CompanyCode, ExportPermission, cancellationToken).ConfigureAwait(false);
|
||||
await using var uow = await factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
||||
var accounts = (await uow.Repository<GlAccount, long>().ListAsync(Data.Querying.Query.For<GlAccount>(), cancellationToken).ConfigureAwait(false)).Items
|
||||
.OrderBy(a => a.Code, StringComparer.Ordinal);
|
||||
return [.. accounts.Select(a => (IReadOnlyList<object?>)
|
||||
[
|
||||
a.Code, a.Description, a.Level, ChartOfAccountsImportValidator.ParentOf(a.Code), ChartOfAccountsImportValidator.NatureWords[(int)a.Nature],
|
||||
ChartOfAccountsImportValidator.TypeWords[(int)a.Type], a.StatementLine, a.Reclassification,
|
||||
(a.Postable ? "M" : string.Empty) + (a.VatRelevant ? "I" : string.Empty) + (a.SubLedger ? "P" : string.Empty)
|
||||
+ (a.ClosesAutomatically ? "C" : string.Empty) + (a.Disabled ? "X" : string.Empty),
|
||||
])];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,191 @@
|
||||
using Khaemhat.Application.Documents;
|
||||
using Khaemhat.Application.Modules;
|
||||
using Khaemhat.Application.Security;
|
||||
using Khaemhat.Application.Tables;
|
||||
using Khaemhat.Core.Documents;
|
||||
using Khaemhat.Core.Items;
|
||||
using Khaemhat.Core.Tables;
|
||||
using Khaemhat.Data;
|
||||
using Khaemhat.Data.Querying;
|
||||
|
||||
namespace Khaemhat.Application.ImportExport;
|
||||
|
||||
/// <summary>
|
||||
/// The opening stock (<c>giacenze-iniziali</c>, SPEC §12.12): item, warehouse, quantity and unit cost. The rows accepted
|
||||
/// become one warehouse movement per warehouse with the reason <c>APE</c> (opening stock), confirmed at the day of the
|
||||
/// import: the stock and the average cost start from there.
|
||||
/// </summary>
|
||||
/// <param name="factory">Opens the company databases.</param>
|
||||
/// <param name="permissions">Checks the permission.</param>
|
||||
/// <param name="engine">Writes the movements.</param>
|
||||
/// <param name="clock">The day of the movements.</param>
|
||||
public sealed class OpeningStockImportTarget(IUnitOfWorkFactory factory, PermissionService permissions, DocumentEngine engine, TimeProvider clock) : IImportTarget
|
||||
{
|
||||
/// <summary>The reason of the opening stock.</summary>
|
||||
public const string OpeningReason = "APE";
|
||||
|
||||
/// <summary>Error: the reason APE is missing.</summary>
|
||||
public const string ReasonMissing = "import.stock.reason-missing";
|
||||
|
||||
private static readonly ImportField[] StockFields =
|
||||
[
|
||||
new("articolo", ImportFieldKind.Code, Required: true, Aliases: ["codice_articolo", "codice", "cod_articolo", "sku"]),
|
||||
new("deposito", ImportFieldKind.Code, Aliases: ["magazzino", "codice_magazzino"]),
|
||||
new("quantita", ImportFieldKind.Number, Required: true, Aliases: ["qta", "qty", "giacenza", "esistenza"]),
|
||||
new("costo_unitario", ImportFieldKind.Number, Aliases: ["costo", "valore_unitario", "prezzo_acquisto"]),
|
||||
];
|
||||
|
||||
/// <inheritdoc />
|
||||
public string Key => "giacenze-iniziali";
|
||||
|
||||
/// <inheritdoc />
|
||||
public string ModuleCode => ModuleCodes.Core;
|
||||
|
||||
/// <inheritdoc />
|
||||
public string Permission => "inventory.entry.write";
|
||||
|
||||
/// <inheritdoc />
|
||||
public string ExportPermission => "inventory.stock.read";
|
||||
|
||||
/// <inheritdoc />
|
||||
public bool CanApply => true;
|
||||
|
||||
/// <inheritdoc />
|
||||
public bool CanExport => false;
|
||||
|
||||
/// <inheritdoc />
|
||||
public IReadOnlyList<ImportField> Fields => StockFields;
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<IReadOnlyList<ImportRowResult>> CheckAsync(ImportContext context, IReadOnlyList<ImportRow> rows, CancellationToken cancellationToken) =>
|
||||
[.. (await ReadAsync(context, rows, cancellationToken).ConfigureAwait(false)).Select(r => r.Result)];
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<IReadOnlyList<ImportRowResult>> ApplyAsync(ImportContext context, IReadOnlyList<ImportRow> rows, CancellationToken cancellationToken)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(context);
|
||||
var read = await ReadAsync(context, rows, cancellationToken).ConfigureAwait(false);
|
||||
var company = await CompanyGuard.DemandAsync(permissions, context.Actor, context.CompanyCode, Permission, cancellationToken).ConfigureAwait(false);
|
||||
long? reason;
|
||||
await using (var uow = await factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
reason = (await uow.Repository<InventoryReason, long>().FindAsync(Query.For<InventoryReason>().Where(r => r.Code == OpeningReason), cancellationToken)
|
||||
.ConfigureAwait(false))?.Id;
|
||||
}
|
||||
|
||||
var results = read.Select(r => r.Result).ToArray();
|
||||
var good = read.Select((r, i) => (Row: r, Index: i)).Where(x => x.Row.Result.Action == ImportAction.Create && x.Row.Stock is not null).ToList();
|
||||
if (reason is null)
|
||||
{
|
||||
foreach (var (_, index) in good)
|
||||
{
|
||||
results[index] = results[index] with { Action = ImportAction.Skip, Messages = [.. results[index].Messages, new ImportMessage("articolo", ReasonMissing)] };
|
||||
}
|
||||
|
||||
return results;
|
||||
}
|
||||
|
||||
var today = DateOnly.FromDateTime(clock.GetLocalNow().DateTime);
|
||||
foreach (var group in good.GroupBy(x => x.Row.Stock!.Value.WarehouseId))
|
||||
{
|
||||
var movement = await engine.NewAsync(context.Actor, company, "MM", cancellationToken).ConfigureAwait(false);
|
||||
movement.Header.DocumentDate = today;
|
||||
movement.Header.WarehouseId = group.Key;
|
||||
movement.Header.InventoryReasonId = reason;
|
||||
foreach (var (row, _) in group)
|
||||
{
|
||||
var stock = row.Stock!.Value;
|
||||
movement.Lines.Add(new InventoryDocumentLine
|
||||
{
|
||||
Kind = DocumentLineKind.Item,
|
||||
ItemId = stock.Item.Id,
|
||||
Description = stock.Item.Description,
|
||||
UnitOfMeasureId = stock.Item.UnitOfMeasureId,
|
||||
Quantity = stock.Quantity,
|
||||
Price = stock.Cost,
|
||||
WarehouseId = group.Key,
|
||||
});
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
var saved = await engine.SaveAsync(context.Actor, company, movement, cancellationToken).ConfigureAwait(false);
|
||||
await engine.ConfirmAsync(context.Actor, company, saved.Family, saved.Header.Id, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
catch (ValidationFailedException ex)
|
||||
{
|
||||
var message = new ImportMessage("articolo", ex.Errors.Count > 0 ? ex.Errors[0].Split(':', 2)[^1] : ImportErrors.Required);
|
||||
foreach (var (_, index) in group)
|
||||
{
|
||||
results[index] = results[index] with { Action = ImportAction.Skip, Messages = [.. results[index].Messages, message] };
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return results;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public Task<IReadOnlyList<IReadOnlyList<object?>>> ExportAsync(ImportContext context, CancellationToken cancellationToken) =>
|
||||
Task.FromResult<IReadOnlyList<IReadOnlyList<object?>>>([]);
|
||||
|
||||
private async Task<List<(ImportRowResult Result, (Item Item, long WarehouseId, decimal Quantity, decimal Cost)? Stock)>> ReadAsync(
|
||||
ImportContext context, IReadOnlyList<ImportRow> rows, CancellationToken cancellationToken)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(context);
|
||||
ArgumentNullException.ThrowIfNull(rows);
|
||||
var company = await CompanyGuard.DemandAsync(permissions, context.Actor, context.CompanyCode, Permission, cancellationToken).ConfigureAwait(false);
|
||||
await using var uow = await factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
||||
var items = (await uow.Repository<Item, long>().ListAsync(Query.For<Item>(), cancellationToken).ConfigureAwait(false)).Items;
|
||||
var codes = new CodeIndex(items.Select(i => (i.Code, i.Id)));
|
||||
var byId = items.ToDictionary(i => i.Id);
|
||||
var warehouses = await CodeIndex.LoadAsync<Warehouse>(uow, cancellationToken).ConfigureAwait(false);
|
||||
var fallback = (await uow.Repository<Warehouse, long>().ListAsync(Query.For<Warehouse>().Where(w => !w.Disabled), cancellationToken).ConfigureAwait(false)).Items
|
||||
.OrderByDescending(w => w.IsDefault).ThenBy(w => w.Code, StringComparer.Ordinal).FirstOrDefault()?.Id;
|
||||
var seen = new HashSet<(long, long)>();
|
||||
var results = new List<(ImportRowResult, (Item, long, decimal, decimal)?)>(rows.Count);
|
||||
foreach (var row in rows)
|
||||
{
|
||||
var messages = new List<ImportMessage>();
|
||||
var cells = new CellReader(row, messages);
|
||||
messages.AddRange(StockFields.Where(f => f.Required && !cells.Has(f.Key)).Select(f => new ImportMessage(f.Key, ImportErrors.Required)));
|
||||
var item = cells.Code("articolo", codes) is { } id ? byId[id] : null;
|
||||
var warehouse = cells.Code("deposito", warehouses) ?? (cells.Has("deposito") ? null : item?.WarehouseId ?? fallback);
|
||||
if (item is not null && (item.Kind != ItemKind.Goods || !item.Stocked))
|
||||
{
|
||||
messages.Add(new("articolo", ImportErrors.NotStocked, Value: item.Code));
|
||||
}
|
||||
|
||||
if (item is not null && warehouse is null && !cells.Has("deposito"))
|
||||
{
|
||||
messages.Add(new("deposito", ImportErrors.Required));
|
||||
}
|
||||
|
||||
var quantity = cells.Number("quantita");
|
||||
if (quantity is <= 0)
|
||||
{
|
||||
messages.Add(new("quantita", ImportErrors.Positive));
|
||||
}
|
||||
|
||||
var cost = cells.Number("costo_unitario");
|
||||
if (cost is < 0)
|
||||
{
|
||||
messages.Add(new("costo_unitario", Items.ItemService.NotNegative));
|
||||
}
|
||||
|
||||
var label = row["articolo"] ?? string.Empty;
|
||||
if (item is not null && warehouse is { } w && !seen.Add((item.Id, w)))
|
||||
{
|
||||
messages.Add(new("articolo", ImportErrors.CodeRepeated, Value: label));
|
||||
}
|
||||
|
||||
var failed = messages.Any(m => !m.IsWarning);
|
||||
(Item, long, decimal, decimal)? stock = !failed && item is not null && warehouse is { } where && quantity is { } q
|
||||
? (item, where, q, cost ?? item.AverageCost ?? item.StandardCost ?? item.LastCost ?? 0m)
|
||||
: null;
|
||||
results.Add((new ImportRowResult(row.Line, label, failed ? ImportAction.Skip : ImportAction.Create, messages), stock));
|
||||
}
|
||||
|
||||
return results;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,553 @@
|
||||
using Khaemhat.Application.Security;
|
||||
using Khaemhat.Core.Documents;
|
||||
using Khaemhat.Core.Inventory;
|
||||
using Khaemhat.Core.Items;
|
||||
using Khaemhat.Core.Tables;
|
||||
using Khaemhat.Data;
|
||||
using Khaemhat.Data.Querying;
|
||||
|
||||
namespace Khaemhat.Application.Inventory;
|
||||
|
||||
/// <summary>
|
||||
/// Posts the documents to the warehouse (SPEC §11.6, ADR 0035) inside the transaction of the document engine: a
|
||||
/// confirmed document that moves the stock writes one movement per stocked line; a cancelled one loses it. After every
|
||||
/// change the history of the items touched runs again through the weighted average and gives the balances of each
|
||||
/// warehouse, the committed and ordered quantities of the open orders and the costs on the item card.
|
||||
/// </summary>
|
||||
public static class InventoryPoster
|
||||
{
|
||||
/// <summary>A transfer needs a destination different from the origin.</summary>
|
||||
public const string TransferDestination = "document.transfer.destination";
|
||||
|
||||
/// <summary>Writes again the movements of a document from its current state and refreshes its items.</summary>
|
||||
/// <param name="uow">The unit of work of the company, in a transaction.</param>
|
||||
/// <param name="family">The family of the document.</param>
|
||||
/// <param name="documentId">The document.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>A task.</returns>
|
||||
public static async Task SyncAsync(IUnitOfWork uow, DocumentFamily family, long documentId, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(uow);
|
||||
var items = new HashSet<long>();
|
||||
await RemoveAsync(uow, family, documentId, items, cancellationToken).ConfigureAwait(false);
|
||||
var header = await HeaderAsync(uow, family, documentId, cancellationToken).ConfigureAwait(false);
|
||||
if (header is null)
|
||||
{
|
||||
await RecomputeAsync(uow, items, cancellationToken).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
|
||||
var lines = await LinesAsync(uow, family, documentId, cancellationToken).ConfigureAwait(false);
|
||||
foreach (var line in lines.Where(l => l.ItemId is not null))
|
||||
{
|
||||
// Orders hold committed and ordered quantities; every state change of theirs moves the balances.
|
||||
items.Add(line.ItemId!.Value);
|
||||
}
|
||||
|
||||
if (DocumentStateMachine.IsInForce(header.Status) && StockEffectMatrix.MovesStock(header.Kind))
|
||||
{
|
||||
await PostAsync(uow, family, header, lines, items, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
await RecomputeAsync(uow, items, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Rebuilds the warehouse from the documents (SPEC §11.6, <i>ricostruzione</i>): removes every movement, posts
|
||||
/// again every document in force that moves the stock, oldest first and the delivery notes before the invoices of
|
||||
/// the same day, then runs the history of every item.
|
||||
/// </summary>
|
||||
/// <param name="uow">The unit of work of the company, in a transaction.</param>
|
||||
/// <param name="progress">Receives the documents posted and the total, then the items and their total.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The documents posted and the items computed.</returns>
|
||||
public static async Task<(int Documents, int Items)> RebuildAsync(IUnitOfWork uow, IProgress<RebuildProgress>? progress = null, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(uow);
|
||||
await uow.ExecuteAsync(SqlFragment.Of($"DELETE FROM inventory_entry_lines"), cancellationToken).ConfigureAwait(false);
|
||||
await uow.ExecuteAsync(SqlFragment.Of($"DELETE FROM inventory_entries"), cancellationToken).ConfigureAwait(false);
|
||||
var documents = new List<(DocumentFamily Family, DocumentHeader Header)>();
|
||||
foreach (var family in new[] { DocumentFamily.SaleDocument, DocumentFamily.PurchaseDocument, DocumentFamily.InventoryDocument })
|
||||
{
|
||||
foreach (var header in await Documents.DocumentStores.Of(family).InForceAsync(uow, cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
if (StockEffectMatrix.MovesStock(header.Kind))
|
||||
{
|
||||
documents.Add((family, header));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Delivery notes and receipts first: their invoices then find the goods already moved.
|
||||
var ordered = documents
|
||||
.OrderBy(d => d.Header.DocumentDate)
|
||||
.ThenBy(d => d.Header.Kind is DocumentKind.DeliveryNote or DocumentKind.PurchaseDeliveryNote or DocumentKind.InventoryEntry ? 0 : 1)
|
||||
.ThenBy(d => d.Header.ConfirmedAt)
|
||||
.ThenBy(d => d.Header.Id)
|
||||
.ToList();
|
||||
var items = new HashSet<long>();
|
||||
for (var i = 0; i < ordered.Count; i++)
|
||||
{
|
||||
var (family, header) = ordered[i];
|
||||
var lines = await LinesAsync(uow, family, header.Id, cancellationToken).ConfigureAwait(false);
|
||||
await PostAsync(uow, family, header, lines, items, cancellationToken).ConfigureAwait(false);
|
||||
progress?.Report(new RebuildProgress(RebuildPhase.Documents, i + 1, ordered.Count));
|
||||
}
|
||||
|
||||
// Every stocked item, also those with only orders or with no movement left.
|
||||
var all = (await uow.Repository<Item, long>().ListAsync(Query.For<Item>().Where(i => i.Stocked), cancellationToken).ConfigureAwait(false)).Items.Select(i => i.Id);
|
||||
var balanced = (await uow.Repository<ItemBalance, long>().ListAsync(Query.For<ItemBalance>(), cancellationToken).ConfigureAwait(false)).Items.Select(b => b.ItemId);
|
||||
var ids = items.Concat(all).Concat(balanced).Distinct().ToList();
|
||||
for (var i = 0; i < ids.Count; i += 50)
|
||||
{
|
||||
await RecomputeAsync(uow, ids.Skip(i).Take(50), cancellationToken).ConfigureAwait(false);
|
||||
progress?.Report(new RebuildProgress(RebuildPhase.Items, Math.Min(i + 50, ids.Count), ids.Count));
|
||||
}
|
||||
|
||||
return (ordered.Count, ids.Count);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Runs again the history of items: the cost of every movement, the balances of each warehouse, the committed and
|
||||
/// ordered quantities, the average and last cost on the item card.
|
||||
/// </summary>
|
||||
/// <param name="uow">The unit of work of the company, in a transaction.</param>
|
||||
/// <param name="itemIds">The items.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>A task.</returns>
|
||||
public static async Task RecomputeAsync(IUnitOfWork uow, IEnumerable<long> itemIds, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(uow);
|
||||
ArgumentNullException.ThrowIfNull(itemIds);
|
||||
var ids = itemIds.Distinct().ToList();
|
||||
if (ids.Count == 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var committed = await OpenQuantitiesAsync<SaleOrder, SaleOrderLine>(uow, ids, cancellationToken).ConfigureAwait(false);
|
||||
var ordered = await OpenQuantitiesAsync<PurchaseOrder, PurchaseOrderLine>(uow, ids, cancellationToken).ConfigureAwait(false);
|
||||
var defaultWarehouse = await DefaultWarehouseAsync(uow, cancellationToken).ConfigureAwait(false);
|
||||
foreach (var itemId in ids)
|
||||
{
|
||||
await RecomputeItemAsync(uow, itemId, committed, ordered, defaultWarehouse, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The default warehouse of the company: the one marked as such, or the first.</summary>
|
||||
/// <param name="uow">The unit of work.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The warehouse, if any.</returns>
|
||||
public static async Task<long?> DefaultWarehouseAsync(IUnitOfWork uow, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(uow);
|
||||
var warehouses = uow.Repository<Warehouse, long>();
|
||||
var marked = await warehouses.FindAsync(Query.For<Warehouse>().Where(w => w.IsDefault && !w.Disabled), cancellationToken).ConfigureAwait(false);
|
||||
return marked?.Id ?? (await warehouses.FindAsync(Query.For<Warehouse>().Where(w => !w.Disabled).OrderBy(w => w.Code), cancellationToken).ConfigureAwait(false))?.Id;
|
||||
}
|
||||
|
||||
/// <summary>The quantity of a line in the base unit of its item.</summary>
|
||||
/// <param name="quantity">The quantity on the line.</param>
|
||||
/// <param name="lineUnit">The unit of the line.</param>
|
||||
/// <param name="item">The item.</param>
|
||||
/// <param name="units">The alternative units of the item.</param>
|
||||
/// <returns>The quantity in the base unit.</returns>
|
||||
public static decimal ToBase(decimal quantity, long? lineUnit, Item item, IEnumerable<ItemUnit> units)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(item);
|
||||
ArgumentNullException.ThrowIfNull(units);
|
||||
if (lineUnit is null || lineUnit == item.UnitOfMeasureId)
|
||||
{
|
||||
return quantity;
|
||||
}
|
||||
|
||||
var unit = units.FirstOrDefault(u => u.ItemId == item.Id && u.UnitOfMeasureId == lineUnit);
|
||||
return unit is null || unit.Factor <= 0m ? quantity : quantity * unit.Factor;
|
||||
}
|
||||
|
||||
private static async Task RemoveAsync(IUnitOfWork uow, DocumentFamily family, long documentId, HashSet<long> items, CancellationToken cancellationToken)
|
||||
{
|
||||
var entries = uow.Repository<InventoryEntry, long>();
|
||||
var lines = uow.Repository<InventoryEntryLine, long>();
|
||||
foreach (var entry in (await entries.ListAsync(Query.For<InventoryEntry>().Where(e => e.SourceFamily == family && e.SourceDocumentId == documentId), cancellationToken)
|
||||
.ConfigureAwait(false)).Items)
|
||||
{
|
||||
foreach (var line in (await lines.ListAsync(Query.For<InventoryEntryLine>().Where(l => l.EntryId == entry.Id), cancellationToken).ConfigureAwait(false)).Items)
|
||||
{
|
||||
items.Add(line.ItemId);
|
||||
await lines.DeleteAsync(line.Id, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
await entries.DeleteAsync(entry.Id, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
private static async Task PostAsync(
|
||||
IUnitOfWork uow, DocumentFamily family, DocumentHeader header, IReadOnlyList<DocumentLine> lines, HashSet<long> items, CancellationToken cancellationToken)
|
||||
{
|
||||
if (header.InventoryReasonId is not { } reasonId
|
||||
|| await uow.Repository<InventoryReason, long>().GetAsync(reasonId, cancellationToken).ConfigureAwait(false) is not { } reason)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// A line that comes from a document that already moved its goods the same way (the invoice of a delivery note)
|
||||
// does not move them again; a credit note of an invoice moves them back.
|
||||
var sign = reason.IsTransfer ? 0 : reason.Effect switch { StockEffect.Load => 1, StockEffect.Unload => -1, _ => 0 };
|
||||
var stockLines = await StockLinesAsync(uow, header, lines, sign, cancellationToken).ConfigureAwait(false);
|
||||
IReadOnlyList<StockMovement> movements;
|
||||
try
|
||||
{
|
||||
movements = StockEffectMatrix.Movements(header.Kind, StockReason.Of(reason), header.ToWarehouseId, stockLines);
|
||||
}
|
||||
catch (InvalidOperationException)
|
||||
{
|
||||
throw new ValidationFailedException([nameof(DocumentHeader.ToWarehouseId) + ":" + TransferDestination]);
|
||||
}
|
||||
if (movements.Count == 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var entry = new InventoryEntry
|
||||
{
|
||||
EntryDate = header.DocumentDate,
|
||||
SourceFamily = family,
|
||||
SourceDocumentId = header.Id,
|
||||
SourceKind = header.Kind,
|
||||
SourceNumber = header.DocumentNumber,
|
||||
InventoryReasonId = reason.Id,
|
||||
PartyId = header.PartyId,
|
||||
IsDemo = header.IsDemo,
|
||||
};
|
||||
await uow.Repository<InventoryEntry, long>().InsertAsync(entry, cancellationToken).ConfigureAwait(false);
|
||||
var repository = uow.Repository<InventoryEntryLine, long>();
|
||||
var order = 0;
|
||||
foreach (var m in movements)
|
||||
{
|
||||
items.Add(m.ItemId);
|
||||
await repository.InsertAsync(
|
||||
new InventoryEntryLine
|
||||
{
|
||||
EntryId = entry.Id,
|
||||
EntryDate = entry.EntryDate,
|
||||
ItemId = m.ItemId,
|
||||
WarehouseId = m.WarehouseId,
|
||||
Quantity = m.Quantity,
|
||||
Valued = m.Valued,
|
||||
UnitCost = m.UnitCost,
|
||||
Value = StockCostCalculator.Value(m.Quantity, m.UnitCost),
|
||||
SourceLineId = m.SourceLineId,
|
||||
SortOrder = ++order,
|
||||
},
|
||||
cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
// The stocked lines of a document in the base unit, with their warehouse and cost; the lines that come from a
|
||||
// document that already moved the stock (the invoice of a delivery note) are left out.
|
||||
private static async Task<List<StockLineInput>> StockLinesAsync(
|
||||
IUnitOfWork uow, DocumentHeader header, IReadOnlyList<DocumentLine> lines, int sign, CancellationToken cancellationToken)
|
||||
{
|
||||
var result = new List<StockLineInput>();
|
||||
var itemIds = lines.Where(l => l.Kind == DocumentLineKind.Item && l.ItemId is not null).Select(l => l.ItemId).Distinct().ToList();
|
||||
if (itemIds.Count == 0)
|
||||
{
|
||||
return result;
|
||||
}
|
||||
|
||||
var catalog = (await uow.Repository<Item, long>().ListAsync(Query.For<Item>().Where(i => itemIds.Contains(i.Id)), cancellationToken).ConfigureAwait(false)).Items
|
||||
.ToDictionary(i => i.Id);
|
||||
var ids = catalog.Keys.ToList();
|
||||
var units = (await uow.Repository<ItemUnit, long>().ListAsync(Query.For<ItemUnit>().Where(u => ids.Contains(u.ItemId)), cancellationToken).ConfigureAwait(false)).Items;
|
||||
var fallback = await DefaultWarehouseAsync(uow, cancellationToken).ConfigureAwait(false);
|
||||
var moved = new Dictionary<(DocumentFamily, long), Dictionary<long, int>>();
|
||||
foreach (var line in lines.Where(l => l.Kind == DocumentLineKind.Item && l.ItemId is not null && l.Quantity != 0m))
|
||||
{
|
||||
if (!catalog.TryGetValue(line.ItemId!.Value, out var item) || !item.Stocked || item.Kind != ItemKind.Goods)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
if (sign != 0 && line.SourceFamily is { } sourceFamily && line.SourceLineId is { } sourceLineId
|
||||
&& await MovedSignAsync(uow, sourceFamily, sourceLineId, moved, cancellationToken).ConfigureAwait(false) == sign)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var warehouse = line.WarehouseId ?? header.WarehouseId ?? item.WarehouseId ?? fallback;
|
||||
if (warehouse is null)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var quantity = ToBase(Math.Abs(line.Quantity), line.UnitOfMeasureId, item, units);
|
||||
result.Add(new StockLineInput(line.Id, item.Id, quantity, warehouse.Value, UnitCost(header, line, quantity)));
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
// The cost per base unit in euro of a line: its taxable amount over the quantity, at the exchange rate of the document.
|
||||
private static decimal? UnitCost(DocumentHeader header, DocumentLine line, decimal baseQuantity)
|
||||
{
|
||||
if (baseQuantity == 0m || line.TaxableAmount == 0m)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var amount = Math.Abs(line.TaxableAmount);
|
||||
if (!string.Equals(header.CurrencyCode, "EUR", StringComparison.Ordinal) && header.ExchangeRate > 0m)
|
||||
{
|
||||
amount /= header.ExchangeRate;
|
||||
}
|
||||
|
||||
return Math.Round(amount / baseQuantity, StockCostCalculator.CostDecimals, MidpointRounding.AwayFromZero);
|
||||
}
|
||||
|
||||
// How a line of another document moved the stock: 1 loaded, -1 unloaded, 0 not at all.
|
||||
private static async Task<int> MovedSignAsync(
|
||||
IUnitOfWork uow, DocumentFamily sourceFamily, long sourceLineId, Dictionary<(DocumentFamily, long), Dictionary<long, int>> moved, CancellationToken cancellationToken)
|
||||
{
|
||||
var source = await StoreLineAsync(uow, sourceFamily, sourceLineId, cancellationToken).ConfigureAwait(false);
|
||||
if (source is null)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
var key = (sourceFamily, source.DocumentId);
|
||||
if (!moved.TryGetValue(key, out var lines))
|
||||
{
|
||||
lines = [];
|
||||
var entries = (await uow.Repository<InventoryEntry, long>()
|
||||
.ListAsync(Query.For<InventoryEntry>().Where(e => e.SourceFamily == sourceFamily && e.SourceDocumentId == source.DocumentId), cancellationToken).ConfigureAwait(false)).Items;
|
||||
foreach (var entry in entries)
|
||||
{
|
||||
foreach (var line in (await uow.Repository<InventoryEntryLine, long>()
|
||||
.ListAsync(Query.For<InventoryEntryLine>().Where(l => l.EntryId == entry.Id), cancellationToken).ConfigureAwait(false)).Items)
|
||||
{
|
||||
if (line.SourceLineId is { } id)
|
||||
{
|
||||
lines[id] = Math.Sign(line.Quantity);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
moved[key] = lines;
|
||||
}
|
||||
|
||||
return lines.GetValueOrDefault(sourceLineId);
|
||||
}
|
||||
|
||||
private static async Task RecomputeItemAsync(
|
||||
IUnitOfWork uow, long itemId, IReadOnlyDictionary<(long, long?), decimal> committed, IReadOnlyDictionary<(long, long?), decimal> ordered, long? defaultWarehouse,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
if (await uow.Repository<Item, long>().GetAsync(itemId, cancellationToken).ConfigureAwait(false) is not { } item)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var repository = uow.Repository<InventoryEntryLine, long>();
|
||||
var lines = (await repository.ListAsync(
|
||||
Query.For<InventoryEntryLine>().Where(l => l.ItemId == itemId).OrderBy(l => l.EntryDate).OrderBy(l => l.EntryId).OrderBy(l => l.SortOrder), cancellationToken)
|
||||
.ConfigureAwait(false)).Items;
|
||||
var invoiced = await InvoicedCostsAsync(uow, lines, cancellationToken).ConfigureAwait(false);
|
||||
var history = StockCostCalculator.Run(
|
||||
lines.Select(l => new CostedMovement(
|
||||
l.Id, l.EntryDate, l.WarehouseId, l.Quantity, l.Valued || invoiced.ContainsKey(l.Id), invoiced.TryGetValue(l.Id, out var cost) ? cost : l.UnitCost)),
|
||||
item.StandardCost ?? 0m);
|
||||
foreach (var line in lines)
|
||||
{
|
||||
var unitCost = history.UnitCosts[line.Id];
|
||||
var value = StockCostCalculator.Value(line.Quantity, unitCost);
|
||||
if (line.UnitCost != unitCost || line.Value != value)
|
||||
{
|
||||
line.UnitCost = unitCost;
|
||||
line.Value = value;
|
||||
await repository.UpdateAsync(line, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
await uow.ExecuteAsync(SqlFragment.Of($"DELETE FROM item_balances WHERE item_id = {itemId}"), cancellationToken).ConfigureAwait(false);
|
||||
var warehouses = history.Warehouses.Keys
|
||||
.Concat(committed.Keys.Concat(ordered.Keys).Where(k => k.Item1 == itemId).Select(k => k.Item2 ?? item.WarehouseId ?? defaultWarehouse).OfType<long>())
|
||||
.Distinct();
|
||||
var balances = uow.Repository<ItemBalance, long>();
|
||||
foreach (var warehouseId in warehouses)
|
||||
{
|
||||
var stock = history.Warehouses.GetValueOrDefault(warehouseId) ?? new WarehouseStock(0m, null, null);
|
||||
await balances.InsertAsync(
|
||||
new ItemBalance
|
||||
{
|
||||
ItemId = itemId,
|
||||
WarehouseId = warehouseId,
|
||||
OnHand = stock.OnHand,
|
||||
Committed = Open(committed, itemId, warehouseId, item.WarehouseId ?? defaultWarehouse),
|
||||
Ordered = Open(ordered, itemId, warehouseId, item.WarehouseId ?? defaultWarehouse),
|
||||
AverageCost = history.AverageCost,
|
||||
Value = StockCostCalculator.Value(stock.OnHand, history.AverageCost),
|
||||
LastCost = history.LastCost,
|
||||
LastLoadDate = stock.LastLoad,
|
||||
LastUnloadDate = stock.LastUnload,
|
||||
},
|
||||
cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
// Only the costs: the card keeps its version, so whoever is editing it does not collide with a posting.
|
||||
decimal? average = lines.Count == 0 ? item.AverageCost : history.AverageCost;
|
||||
var last = history.LastCost ?? item.LastCost;
|
||||
if (average != item.AverageCost || last != item.LastCost)
|
||||
{
|
||||
await uow.ExecuteAsync(SqlFragment.Of($"UPDATE items SET average_cost = {average}, last_cost = {last} WHERE id = {itemId}"), cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
// The quantity still open of an item in a warehouse; the lines without a warehouse count in the usual one.
|
||||
private static decimal Open(IReadOnlyDictionary<(long, long?), decimal> open, long itemId, long warehouseId, long? usual)
|
||||
{
|
||||
var total = open.GetValueOrDefault((itemId, warehouseId));
|
||||
if (usual == warehouseId)
|
||||
{
|
||||
total += open.GetValueOrDefault((itemId, null));
|
||||
}
|
||||
|
||||
return total;
|
||||
}
|
||||
|
||||
// The cost a supplier invoice gives to the loads of the delivery notes it invoices (the difference of price, §11.5).
|
||||
private static async Task<Dictionary<long, decimal>> InvoicedCostsAsync(IUnitOfWork uow, IReadOnlyList<InventoryEntryLine> lines, CancellationToken cancellationToken)
|
||||
{
|
||||
var result = new Dictionary<long, decimal>();
|
||||
var loads = lines.Where(l => l.Quantity > 0m && l.SourceLineId is not null).ToList();
|
||||
if (loads.Count == 0)
|
||||
{
|
||||
return result;
|
||||
}
|
||||
|
||||
var entryIds = loads.Select(l => l.EntryId).Distinct().ToList();
|
||||
var receipts = (await uow.Repository<InventoryEntry, long>()
|
||||
.ListAsync(Query.For<InventoryEntry>().Where(e => entryIds.Contains(e.Id) && e.SourceKind == DocumentKind.PurchaseDeliveryNote), cancellationToken).ConfigureAwait(false))
|
||||
.Items.Select(e => e.Id).ToHashSet();
|
||||
var receiptLines = loads.Where(l => receipts.Contains(l.EntryId)).ToList();
|
||||
if (receiptLines.Count == 0)
|
||||
{
|
||||
return result;
|
||||
}
|
||||
|
||||
var sourceIds = receiptLines.Select(l => l.SourceLineId!.Value).Distinct().ToList();
|
||||
var links = (await uow.Repository<DocumentLink, long>().ListAsync(
|
||||
Query.For<DocumentLink>().Where(k => k.SourceFamily == DocumentFamily.PurchaseDocument && k.TargetFamily == DocumentFamily.PurchaseDocument && sourceIds.Contains(k.SourceLineId)),
|
||||
cancellationToken).ConfigureAwait(false)).Items;
|
||||
foreach (var load in receiptLines)
|
||||
{
|
||||
decimal amount = 0m, quantity = 0m;
|
||||
foreach (var link in links.Where(k => k.SourceLineId == load.SourceLineId))
|
||||
{
|
||||
var target = await StoreLineAsync(uow, DocumentFamily.PurchaseDocument, link.TargetLineId, cancellationToken).ConfigureAwait(false);
|
||||
var header = target is null ? null : await HeaderAsync(uow, DocumentFamily.PurchaseDocument, target.DocumentId, cancellationToken).ConfigureAwait(false);
|
||||
if (target is null || header is null || header.Kind != DocumentKind.PurchaseInvoice || !DocumentStateMachine.IsInForce(header.Status) || target.Quantity == 0m)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var lineAmount = Math.Abs(target.TaxableAmount);
|
||||
if (!string.Equals(header.CurrencyCode, "EUR", StringComparison.Ordinal) && header.ExchangeRate > 0m)
|
||||
{
|
||||
lineAmount /= header.ExchangeRate;
|
||||
}
|
||||
|
||||
// The invoice line in the unit of the delivery note: its share of the load is the linked quantity.
|
||||
var share = Math.Abs(link.Quantity / target.Quantity);
|
||||
amount += lineAmount * share;
|
||||
quantity += Math.Abs(link.Quantity);
|
||||
}
|
||||
|
||||
var source = quantity == 0m ? null : await StoreLineAsync(uow, DocumentFamily.PurchaseDocument, load.SourceLineId!.Value, cancellationToken).ConfigureAwait(false);
|
||||
if (source is null || source.Quantity == 0m)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
// The load is in the base unit; the invoiced part of the delivery line is quantity / source.Quantity of it.
|
||||
var baseQuantity = load.Quantity * (quantity / Math.Abs(source.Quantity));
|
||||
if (baseQuantity > 0m && amount > 0m)
|
||||
{
|
||||
result[load.Id] = Math.Round(amount / baseQuantity, StockCostCalculator.CostDecimals, MidpointRounding.AwayFromZero);
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
// The quantities still to deliver of the open orders of a family, by item and warehouse of the line.
|
||||
private static async Task<Dictionary<(long, long?), decimal>> OpenQuantitiesAsync<THeader, TLine>(IUnitOfWork uow, List<long> itemIds, CancellationToken cancellationToken)
|
||||
where THeader : DocumentHeader, new()
|
||||
where TLine : DocumentLine, new()
|
||||
{
|
||||
var result = new Dictionary<(long, long?), decimal>();
|
||||
var ids = itemIds.Select(i => (long?)i).ToList();
|
||||
var lines = (await uow.Repository<TLine, long>().ListAsync(
|
||||
Query.For<TLine>().Where(l => ids.Contains(l.ItemId) && !l.FulfillmentClosed), cancellationToken).ConfigureAwait(false)).Items;
|
||||
if (lines.Count == 0)
|
||||
{
|
||||
return result;
|
||||
}
|
||||
|
||||
var documentIds = lines.Select(l => l.DocumentId).Distinct().ToList();
|
||||
var open = (await uow.Repository<THeader, long>().ListAsync(
|
||||
Query.For<THeader>().Where(h => documentIds.Contains(h.Id) && (h.Status == DocumentStatus.Confirmed || h.Status == DocumentStatus.PartiallyFulfilled)), cancellationToken)
|
||||
.ConfigureAwait(false)).Items.ToDictionary(h => h.Id);
|
||||
if (open.Count == 0)
|
||||
{
|
||||
return result;
|
||||
}
|
||||
|
||||
var catalog = (await uow.Repository<Item, long>().ListAsync(Query.For<Item>().Where(i => itemIds.Contains(i.Id)), cancellationToken).ConfigureAwait(false)).Items
|
||||
.ToDictionary(i => i.Id);
|
||||
var units = (await uow.Repository<ItemUnit, long>().ListAsync(Query.For<ItemUnit>().Where(u => itemIds.Contains(u.ItemId)), cancellationToken).ConfigureAwait(false)).Items;
|
||||
foreach (var line in lines)
|
||||
{
|
||||
if (!open.TryGetValue(line.DocumentId, out var header) || !catalog.TryGetValue(line.ItemId!.Value, out var item) || !item.Stocked)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var residual = line.Quantity - line.FulfilledQuantity;
|
||||
if (residual <= 0m)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var key = (item.Id, line.WarehouseId ?? header.WarehouseId);
|
||||
result[key] = result.GetValueOrDefault(key) + ToBase(residual, line.UnitOfMeasureId, item, units);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
private static Task<DocumentHeader?> HeaderAsync(IUnitOfWork uow, DocumentFamily family, long id, CancellationToken cancellationToken) =>
|
||||
Documents.DocumentStores.Of(family).GetAsync(uow, id, cancellationToken);
|
||||
|
||||
private static Task<List<DocumentLine>> LinesAsync(IUnitOfWork uow, DocumentFamily family, long id, CancellationToken cancellationToken) =>
|
||||
Documents.DocumentStores.Of(family).LinesAsync(uow, id, cancellationToken);
|
||||
|
||||
private static Task<DocumentLine?> StoreLineAsync(IUnitOfWork uow, DocumentFamily family, long id, CancellationToken cancellationToken) =>
|
||||
Documents.DocumentStores.Of(family).GetLineAsync(uow, id, cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>The step of a rebuild.</summary>
|
||||
public enum RebuildPhase
|
||||
{
|
||||
/// <summary>Posting the documents.</summary>
|
||||
Documents = 0,
|
||||
|
||||
/// <summary>Computing the items.</summary>
|
||||
Items = 1,
|
||||
}
|
||||
|
||||
/// <summary>How far a rebuild is.</summary>
|
||||
/// <param name="Phase">The step.</param>
|
||||
/// <param name="Done">How many done.</param>
|
||||
/// <param name="Total">How many in all.</param>
|
||||
public sealed record RebuildProgress(RebuildPhase Phase, int Done, int Total);
|
||||
@@ -0,0 +1,42 @@
|
||||
using System.Globalization;
|
||||
using Khaemhat.Application.Jobs;
|
||||
using Khaemhat.Core.Instance;
|
||||
using Khaemhat.Data;
|
||||
using Khaemhat.Data.Companies;
|
||||
|
||||
namespace Khaemhat.Application.Inventory;
|
||||
|
||||
/// <summary>
|
||||
/// Rebuilds the warehouse of every active company from its documents, once a week at night (SPEC §11.6): a safety net
|
||||
/// that brings balances and costs back in line after imports or corrections made outside the screens.
|
||||
/// </summary>
|
||||
/// <param name="factory">The units of work.</param>
|
||||
/// <param name="companies">The companies.</param>
|
||||
public sealed class InventoryRebuildJob(IUnitOfWorkFactory factory, ICompanyRegistry companies) : IScheduledJob
|
||||
{
|
||||
/// <summary>The job type.</summary>
|
||||
public const string JobType = "inventory.rebuild";
|
||||
|
||||
/// <inheritdoc />
|
||||
public string Type => JobType;
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<string?> RunAsync(JobContext context, CancellationToken cancellationToken)
|
||||
{
|
||||
int documents = 0, items = 0, done = 0;
|
||||
foreach (var company in await companies.ListAsync(cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
if (company.Status is CompanyStatus.Disabled)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var (d, i) = await InventoryService.RebuildCompanyAsync(factory, company.Code, null, cancellationToken).ConfigureAwait(false);
|
||||
documents += d;
|
||||
items += i;
|
||||
done++;
|
||||
}
|
||||
|
||||
return string.Create(CultureInfo.InvariantCulture, $"{done} aziende, {documents} documenti, {items} articoli ricalcolati.");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,422 @@
|
||||
using Khaemhat.Application.Items;
|
||||
using Khaemhat.Application.Security;
|
||||
using Khaemhat.Application.Tables;
|
||||
using Khaemhat.Core.Documents;
|
||||
using Khaemhat.Core.Inventory;
|
||||
using Khaemhat.Core.Items;
|
||||
using Khaemhat.Core.Parties;
|
||||
using Khaemhat.Core.Tables;
|
||||
using Khaemhat.Data;
|
||||
using Khaemhat.Data.Querying;
|
||||
|
||||
namespace Khaemhat.Application.Inventory;
|
||||
|
||||
/// <summary>What the stock screen asks (mockup 036).</summary>
|
||||
public sealed record StockFilter
|
||||
{
|
||||
/// <summary>Code, description or brand.</summary>
|
||||
public string? Search { get; init; }
|
||||
|
||||
/// <summary>One warehouse, or all together.</summary>
|
||||
public long? WarehouseId { get; init; }
|
||||
|
||||
/// <summary>One category.</summary>
|
||||
public long? CategoryId { get; init; }
|
||||
|
||||
/// <summary>Only the items under their minimum stock or reorder point.</summary>
|
||||
public bool UnderstockOnly { get; init; }
|
||||
|
||||
/// <summary>Also the items with nothing on hand, committed or ordered.</summary>
|
||||
public bool IncludeEmpty { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>The state of an item under its thresholds.</summary>
|
||||
public enum StockLevel
|
||||
{
|
||||
/// <summary>Enough.</summary>
|
||||
Ok = 0,
|
||||
|
||||
/// <summary>The available quantity reached the reorder point.</summary>
|
||||
Reorder = 1,
|
||||
|
||||
/// <summary>The available quantity is under the minimum stock.</summary>
|
||||
Understock = 2,
|
||||
|
||||
/// <summary>Nothing left, or less than nothing.</summary>
|
||||
Out = 3,
|
||||
}
|
||||
|
||||
/// <summary>A row of the stock screen: an item in one warehouse or in all.</summary>
|
||||
/// <param name="ItemId">The item.</param>
|
||||
/// <param name="Code">Its code.</param>
|
||||
/// <param name="Description">Its description.</param>
|
||||
/// <param name="CategoryId">Its category.</param>
|
||||
/// <param name="UnitOfMeasureId">Its base unit.</param>
|
||||
/// <param name="OnHand">On hand.</param>
|
||||
/// <param name="Committed">Committed to customers.</param>
|
||||
/// <param name="Ordered">Ordered from suppliers.</param>
|
||||
/// <param name="Available">On hand less committed.</param>
|
||||
/// <param name="MinimumStock">The minimum stock.</param>
|
||||
/// <param name="ReorderPoint">The reorder point.</param>
|
||||
/// <param name="AverageCost">The weighted average cost (none without the permission on costs).</param>
|
||||
/// <param name="Value">The value at the average (none without the permission).</param>
|
||||
/// <param name="LastLoad">The last load.</param>
|
||||
/// <param name="LastUnload">The last unload.</param>
|
||||
/// <param name="Level">The state under the thresholds.</param>
|
||||
public sealed record StockRow(
|
||||
long ItemId, string Code, string Description, long? CategoryId, long? UnitOfMeasureId, decimal OnHand, decimal Committed, decimal Ordered, decimal Available,
|
||||
decimal? MinimumStock, decimal? ReorderPoint, decimal? AverageCost, decimal? Value, DateOnly? LastLoad, DateOnly? LastUnload, StockLevel Level);
|
||||
|
||||
/// <summary>A movement of an item, with the balance after it.</summary>
|
||||
/// <param name="Id">The movement.</param>
|
||||
/// <param name="Date">The date.</param>
|
||||
/// <param name="Family">The family of the document.</param>
|
||||
/// <param name="DocumentId">The document.</param>
|
||||
/// <param name="Kind">Its kind.</param>
|
||||
/// <param name="Number">Its number.</param>
|
||||
/// <param name="ReasonCode">The warehouse reason.</param>
|
||||
/// <param name="PartyName">The customer or supplier.</param>
|
||||
/// <param name="WarehouseId">The warehouse.</param>
|
||||
/// <param name="Quantity">Positive loads, negative unloads.</param>
|
||||
/// <param name="UnitCost">The cost (none without the permission).</param>
|
||||
/// <param name="Value">The value (none without the permission).</param>
|
||||
/// <param name="Balance">The balance after the movement, in the warehouses shown.</param>
|
||||
public sealed record MovementRow(
|
||||
long Id, DateOnly Date, DocumentFamily? Family, long? DocumentId, DocumentKind? Kind, string? Number, string? ReasonCode, string? PartyName, long WarehouseId,
|
||||
decimal Quantity, decimal? UnitCost, decimal? Value, decimal Balance);
|
||||
|
||||
/// <summary>The value of an item at a date (closing stock, libro inventari).</summary>
|
||||
/// <param name="ItemId">The item.</param>
|
||||
/// <param name="Code">Its code.</param>
|
||||
/// <param name="Description">Its description.</param>
|
||||
/// <param name="Quantity">On hand at the date.</param>
|
||||
/// <param name="UnitCost">The cost of the method.</param>
|
||||
/// <param name="Value">Quantity times cost.</param>
|
||||
/// <param name="AbcClass">A (the first 80% of the value), B (up to 95%) or C.</param>
|
||||
public sealed record ValuationRow(long ItemId, string Code, string Description, decimal Quantity, decimal UnitCost, decimal Value, char AbcClass);
|
||||
|
||||
/// <summary>
|
||||
/// The warehouse as people read it (SPEC §11.6, mockups 036-037): stock and availability, the movements of an item,
|
||||
/// the value at a date. The balances are kept by <see cref="InventoryPoster"/>; this service only reads them.
|
||||
/// </summary>
|
||||
/// <remarks>Permission <c>inventory.stock.read</c>, movements <c>inventory.entry.read</c>; costs only with <c>items.cost.read</c>.</remarks>
|
||||
public sealed class InventoryService
|
||||
{
|
||||
/// <summary>Permission to read the stock.</summary>
|
||||
public const string StockPermission = "inventory.stock.read";
|
||||
|
||||
/// <summary>Permission to read the movements.</summary>
|
||||
public const string EntryReadPermission = "inventory.entry.read";
|
||||
|
||||
/// <summary>Permission to post movements, stock takes and the rebuild.</summary>
|
||||
public const string PostPermission = "inventory.entry.post";
|
||||
|
||||
private readonly IUnitOfWorkFactory _factory;
|
||||
private readonly PermissionService _permissions;
|
||||
|
||||
/// <summary>Creates the service.</summary>
|
||||
/// <param name="factory">The units of work.</param>
|
||||
/// <param name="permissions">The permissions.</param>
|
||||
public InventoryService(IUnitOfWorkFactory factory, PermissionService permissions)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(factory);
|
||||
ArgumentNullException.ThrowIfNull(permissions);
|
||||
_factory = factory;
|
||||
_permissions = permissions;
|
||||
}
|
||||
|
||||
/// <summary>The stock of the items, in a warehouse or in all.</summary>
|
||||
/// <param name="actor">Who reads.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="filter">What to show.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The rows, by code.</returns>
|
||||
public async Task<IReadOnlyList<StockRow>> StockAsync(Actor actor, string companyCode, StockFilter filter, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(filter);
|
||||
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, StockPermission, cancellationToken).ConfigureAwait(false);
|
||||
var costs = await CostsAsync(actor, cancellationToken).ConfigureAwait(false);
|
||||
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
||||
var query = Query.For<Item>().Where(i => i.Stocked && i.Kind == ItemKind.Goods && !i.Disabled);
|
||||
if (filter.CategoryId is { } category)
|
||||
{
|
||||
query = query.Where(i => i.CategoryId == category);
|
||||
}
|
||||
|
||||
if (filter.Search?.Trim() is { Length: > 0 } text)
|
||||
{
|
||||
query = query.Where(i => i.Code.Contains(text) || i.Description.Contains(text) || (i.Brand != null && i.Brand.Contains(text)));
|
||||
}
|
||||
|
||||
var items = (await uow.Repository<Item, long>().ListAsync(query.OrderBy(i => i.Code), cancellationToken).ConfigureAwait(false)).Items;
|
||||
var balances = await BalancesByItemAsync(uow, filter.WarehouseId, cancellationToken).ConfigureAwait(false);
|
||||
var rows = new List<StockRow>();
|
||||
foreach (var item in items)
|
||||
{
|
||||
var mine = balances.GetValueOrDefault(item.Id) ?? [];
|
||||
var row = RowOf(item, mine, costs);
|
||||
if (!filter.IncludeEmpty && mine.Count == 0)
|
||||
{
|
||||
// No movement and no order: shown only when asked, or when it has a minimum to keep.
|
||||
if (row.Level == StockLevel.Ok)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
if (filter.UnderstockOnly && row.Level == StockLevel.Ok)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
rows.Add(row);
|
||||
}
|
||||
|
||||
return rows;
|
||||
}
|
||||
|
||||
/// <summary>The balances of an item in each warehouse.</summary>
|
||||
/// <param name="actor">Who reads.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="itemId">The item.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The balances, costs hidden without the permission.</returns>
|
||||
public async Task<IReadOnlyList<ItemBalance>> BalancesAsync(Actor actor, string companyCode, long itemId, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, StockPermission, cancellationToken).ConfigureAwait(false);
|
||||
var costs = await CostsAsync(actor, cancellationToken).ConfigureAwait(false);
|
||||
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
||||
var rows = (await uow.Repository<ItemBalance, long>().ListAsync(Query.For<ItemBalance>().Where(b => b.ItemId == itemId), cancellationToken).ConfigureAwait(false)).Items;
|
||||
if (!costs)
|
||||
{
|
||||
foreach (var row in rows)
|
||||
{
|
||||
row.AverageCost = 0m;
|
||||
row.Value = 0m;
|
||||
row.LastCost = null;
|
||||
}
|
||||
}
|
||||
|
||||
return rows;
|
||||
}
|
||||
|
||||
/// <summary>The movements of an item in a period, with the running balance (mockup 036, dialog of the item).</summary>
|
||||
/// <param name="actor">Who reads.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="itemId">The item.</param>
|
||||
/// <param name="warehouseId">One warehouse, or all.</param>
|
||||
/// <param name="from">The first day, or the beginning.</param>
|
||||
/// <param name="to">The last day, or today.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The movements, oldest first; the balance starts from what was on hand before <paramref name="from"/>.</returns>
|
||||
public async Task<IReadOnlyList<MovementRow>> MovementsAsync(
|
||||
Actor actor, string companyCode, long itemId, long? warehouseId, DateOnly? from, DateOnly? to, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, EntryReadPermission, cancellationToken).ConfigureAwait(false);
|
||||
var costs = await CostsAsync(actor, cancellationToken).ConfigureAwait(false);
|
||||
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
||||
var query = Query.For<InventoryEntryLine>().Where(l => l.ItemId == itemId);
|
||||
if (warehouseId is { } warehouse)
|
||||
{
|
||||
query = query.Where(l => l.WarehouseId == warehouse);
|
||||
}
|
||||
|
||||
var lines = (await uow.Repository<InventoryEntryLine, long>().ListAsync(query.OrderBy(l => l.EntryDate).OrderBy(l => l.EntryId).OrderBy(l => l.SortOrder), cancellationToken)
|
||||
.ConfigureAwait(false)).Items;
|
||||
var entryIds = lines.Select(l => l.EntryId).Distinct().ToList();
|
||||
var entries = entryIds.Count == 0 ? [] : (await uow.Repository<InventoryEntry, long>().ListAsync(Query.For<InventoryEntry>().Where(e => entryIds.Contains(e.Id)), cancellationToken)
|
||||
.ConfigureAwait(false)).Items.ToDictionary(e => e.Id);
|
||||
var reasons = (await uow.Repository<InventoryReason, long>().ListAsync(Query.For<InventoryReason>(), cancellationToken).ConfigureAwait(false)).Items.ToDictionary(r => r.Id, r => r.Code);
|
||||
var partyIds = entries.Values.Where(e => e.PartyId is not null).Select(e => e.PartyId!.Value).Distinct().ToList();
|
||||
var parties = partyIds.Count == 0 ? [] : (await uow.Repository<Party, long>().ListAsync(Query.For<Party>().Where(p => partyIds.Contains(p.Id)), cancellationToken)
|
||||
.ConfigureAwait(false)).Items.ToDictionary(p => p.Id, p => p.Name);
|
||||
var result = new List<MovementRow>();
|
||||
var balance = 0m;
|
||||
foreach (var line in lines)
|
||||
{
|
||||
balance += line.Quantity;
|
||||
if ((from is { } first && line.EntryDate < first) || (to is { } last && line.EntryDate > last))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var entry = entries.GetValueOrDefault(line.EntryId);
|
||||
result.Add(new MovementRow(
|
||||
line.Id, line.EntryDate, entry?.SourceFamily, entry?.SourceDocumentId, entry?.SourceKind, entry?.SourceNumber,
|
||||
entry?.InventoryReasonId is { } r ? reasons.GetValueOrDefault(r) : null,
|
||||
entry?.PartyId is { } p ? parties.GetValueOrDefault(p) : null,
|
||||
line.WarehouseId, line.Quantity, costs ? line.UnitCost : null, costs ? line.Value : null, balance));
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The value of the stock at a date (closing stock, libro inventari): the history of each item up to that day,
|
||||
/// valued with a method, with its ABC class by value.
|
||||
/// </summary>
|
||||
/// <param name="actor">Who reads: needs the permission on costs too.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="date">The day.</param>
|
||||
/// <param name="warehouseId">One warehouse, or all.</param>
|
||||
/// <param name="method">The cost used.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The items with something on hand, by value.</returns>
|
||||
public async Task<IReadOnlyList<ValuationRow>> ValuationAsync(
|
||||
Actor actor, string companyCode, DateOnly date, long? warehouseId, StockValuationMethod method, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, StockPermission, cancellationToken).ConfigureAwait(false);
|
||||
await _permissions.DemandAsync(actor, ItemService.CostPermission, cancellationToken).ConfigureAwait(false);
|
||||
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
||||
var lines = (await uow.Repository<InventoryEntryLine, long>().ListAsync(
|
||||
Query.For<InventoryEntryLine>().Where(l => l.EntryDate <= date).OrderBy(l => l.EntryDate).OrderBy(l => l.EntryId).OrderBy(l => l.SortOrder), cancellationToken)
|
||||
.ConfigureAwait(false)).Items;
|
||||
var itemIds = lines.Select(l => l.ItemId).Distinct().ToList();
|
||||
var items = itemIds.Count == 0 ? [] : (await uow.Repository<Item, long>().ListAsync(Query.For<Item>().Where(i => itemIds.Contains(i.Id)), cancellationToken)
|
||||
.ConfigureAwait(false)).Items.ToDictionary(i => i.Id);
|
||||
var rows = new List<ValuationRow>();
|
||||
foreach (var group in lines.GroupBy(l => l.ItemId))
|
||||
{
|
||||
if (!items.TryGetValue(group.Key, out var item))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
// The costs written on the movements are those of the last run: the history up to the day gives the average then.
|
||||
var history = StockCostCalculator.Run(group.Select(l => new CostedMovement(l.Id, l.EntryDate, l.WarehouseId, l.Quantity, l.Valued, l.Valued ? l.UnitCost : 0m)), item.StandardCost ?? 0m);
|
||||
var quantity = warehouseId is { } w ? history.Warehouses.GetValueOrDefault(w)?.OnHand ?? 0m : history.OnHand;
|
||||
if (quantity == 0m)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var cost = method switch
|
||||
{
|
||||
StockValuationMethod.LastCost => history.LastCost ?? history.AverageCost,
|
||||
StockValuationMethod.StandardCost => item.StandardCost ?? history.AverageCost,
|
||||
_ => history.AverageCost,
|
||||
};
|
||||
rows.Add(new ValuationRow(item.Id, item.Code, item.Description, quantity, cost, StockCostCalculator.Value(quantity, cost), 'C'));
|
||||
}
|
||||
|
||||
return Classify(rows);
|
||||
}
|
||||
|
||||
/// <summary>The items under their thresholds, the most urgent first (dashboard widget and reorder).</summary>
|
||||
/// <param name="actor">Who reads.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="limit">How many.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The rows.</returns>
|
||||
public async Task<IReadOnlyList<StockRow>> UnderstockAsync(Actor actor, string companyCode, int limit = 10, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var rows = await StockAsync(actor, companyCode, new StockFilter { UnderstockOnly = true }, cancellationToken).ConfigureAwait(false);
|
||||
return [.. rows.OrderByDescending(r => r.Level).ThenBy(r => r.Available - (r.MinimumStock ?? r.ReorderPoint ?? 0m)).ThenBy(r => r.Code, StringComparer.Ordinal).Take(limit)];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Rebuilds the warehouse of the company from its documents (SPEC §11.6): every movement is written again and every
|
||||
/// item computed again, in one transaction.
|
||||
/// </summary>
|
||||
/// <param name="actor">Who rebuilds: needs <c>inventory.entry.post</c>.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="progress">How far it is.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The documents posted and the items computed.</returns>
|
||||
public async Task<(int Documents, int Items)> RebuildAsync(Actor actor, string companyCode, IProgress<RebuildProgress>? progress = null, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, PostPermission, cancellationToken).ConfigureAwait(false);
|
||||
return await RebuildCompanyAsync(_factory, company, progress, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>Rebuilds the warehouse of a company, without checks (the scheduled job).</summary>
|
||||
/// <param name="factory">The units of work.</param>
|
||||
/// <param name="company">The company.</param>
|
||||
/// <param name="progress">How far it is.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The documents posted and the items computed.</returns>
|
||||
internal static async Task<(int Documents, int Items)> RebuildCompanyAsync(
|
||||
IUnitOfWorkFactory factory, string company, IProgress<RebuildProgress>? progress, CancellationToken cancellationToken)
|
||||
{
|
||||
await using var uow = await factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
||||
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
|
||||
var result = await InventoryPoster.RebuildAsync(uow, progress, cancellationToken).ConfigureAwait(false);
|
||||
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The level of an item: out when nothing is available (or less than nothing), under stock below the minimum,
|
||||
/// to reorder when what is available and on order no longer covers the reorder point.
|
||||
/// </summary>
|
||||
/// <param name="available">On hand less committed.</param>
|
||||
/// <param name="ordered">Ordered from suppliers.</param>
|
||||
/// <param name="minimum">The minimum stock.</param>
|
||||
/// <param name="reorderPoint">The reorder point.</param>
|
||||
/// <returns>The level.</returns>
|
||||
public static StockLevel LevelOf(decimal available, decimal ordered, decimal? minimum, decimal? reorderPoint)
|
||||
{
|
||||
var watched = minimum is not null || reorderPoint is not null;
|
||||
if (available < 0m || (watched && available <= 0m))
|
||||
{
|
||||
return StockLevel.Out;
|
||||
}
|
||||
|
||||
if (minimum is { } min && available < min)
|
||||
{
|
||||
return StockLevel.Understock;
|
||||
}
|
||||
|
||||
return reorderPoint is { } point && available + ordered <= point ? StockLevel.Reorder : StockLevel.Ok;
|
||||
}
|
||||
|
||||
/// <summary>Gives the ABC class by value: A up to 80% of the total, B up to 95%, C the rest.</summary>
|
||||
/// <param name="rows">The rows.</param>
|
||||
/// <returns>The rows by value, with their class.</returns>
|
||||
public static IReadOnlyList<ValuationRow> Classify(IEnumerable<ValuationRow> rows)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(rows);
|
||||
var sorted = rows.OrderByDescending(r => r.Value).ThenBy(r => r.Code, StringComparer.Ordinal).ToList();
|
||||
var total = sorted.Where(r => r.Value > 0m).Sum(r => r.Value);
|
||||
var running = 0m;
|
||||
var result = new List<ValuationRow>(sorted.Count);
|
||||
foreach (var row in sorted)
|
||||
{
|
||||
// The class of an item is where its value starts: the first item is always A.
|
||||
var share = total <= 0m ? 1m : running / total;
|
||||
running += Math.Max(row.Value, 0m);
|
||||
result.Add(row with { AbcClass = share < 0.80m ? 'A' : share < 0.95m ? 'B' : 'C' });
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
internal static StockRow RowOf(Item item, IReadOnlyList<ItemBalance> balances, bool costs)
|
||||
{
|
||||
var onHand = balances.Sum(b => b.OnHand);
|
||||
var committed = balances.Sum(b => b.Committed);
|
||||
var ordered = balances.Sum(b => b.Ordered);
|
||||
var available = onHand - committed;
|
||||
var average = balances.Count > 0 ? balances[0].AverageCost : item.AverageCost ?? 0m;
|
||||
return new StockRow(
|
||||
item.Id, item.Code, item.Description, item.CategoryId, item.UnitOfMeasureId, onHand, committed, ordered, available, item.MinimumStock, item.ReorderPoint,
|
||||
costs ? average : null, costs ? balances.Sum(b => b.Value) : null,
|
||||
balances.Max(b => b.LastLoadDate), balances.Max(b => b.LastUnloadDate),
|
||||
LevelOf(available, ordered, item.MinimumStock, item.ReorderPoint));
|
||||
}
|
||||
|
||||
internal static async Task<Dictionary<long, List<ItemBalance>>> BalancesByItemAsync(IUnitOfWork uow, long? warehouseId, CancellationToken cancellationToken)
|
||||
{
|
||||
var query = Query.For<ItemBalance>();
|
||||
if (warehouseId is { } warehouse)
|
||||
{
|
||||
query = query.Where(b => b.WarehouseId == warehouse);
|
||||
}
|
||||
|
||||
return (await uow.Repository<ItemBalance, long>().ListAsync(query, cancellationToken).ConfigureAwait(false)).Items
|
||||
.GroupBy(b => b.ItemId).ToDictionary(g => g.Key, g => g.ToList());
|
||||
}
|
||||
|
||||
private async Task<bool> CostsAsync(Actor actor, CancellationToken cancellationToken) =>
|
||||
(await _permissions.CheckAsync(actor, ItemService.CostPermission, cancellationToken).ConfigureAwait(false)).Allowed;
|
||||
}
|
||||
@@ -0,0 +1,183 @@
|
||||
using Khaemhat.Application.Documents;
|
||||
using Khaemhat.Application.Security;
|
||||
using Khaemhat.Application.Tables;
|
||||
using Khaemhat.Core.Documents;
|
||||
using Khaemhat.Core.Items;
|
||||
using Khaemhat.Core.Parties;
|
||||
using Khaemhat.Data;
|
||||
using Khaemhat.Data.Querying;
|
||||
|
||||
namespace Khaemhat.Application.Inventory;
|
||||
|
||||
/// <summary>An item to reorder (mockup 039).</summary>
|
||||
/// <param name="ItemId">The item.</param>
|
||||
/// <param name="Code">Its code.</param>
|
||||
/// <param name="Description">Its description.</param>
|
||||
/// <param name="UnitOfMeasureId">Its unit.</param>
|
||||
/// <param name="Available">On hand less committed.</param>
|
||||
/// <param name="Ordered">Already ordered.</param>
|
||||
/// <param name="MinimumStock">The minimum stock.</param>
|
||||
/// <param name="ReorderPoint">The reorder point.</param>
|
||||
/// <param name="Quantity">The quantity proposed.</param>
|
||||
/// <param name="SupplierId">The usual supplier, if any.</param>
|
||||
/// <param name="SupplierName">Its name.</param>
|
||||
/// <param name="Price">Its price.</param>
|
||||
/// <param name="ExpectedDate">When it would arrive, from the lead time.</param>
|
||||
public sealed record ReorderProposal(
|
||||
long ItemId, string Code, string Description, long? UnitOfMeasureId, decimal Available, decimal Ordered, decimal? MinimumStock, decimal? ReorderPoint,
|
||||
decimal Quantity, long? SupplierId, string? SupplierName, decimal? Price, DateOnly? ExpectedDate);
|
||||
|
||||
/// <summary>A proposal the user accepts, perhaps with another quantity or supplier.</summary>
|
||||
/// <param name="ItemId">The item.</param>
|
||||
/// <param name="SupplierId">The supplier.</param>
|
||||
/// <param name="Quantity">The quantity.</param>
|
||||
public sealed record ReorderChoice(long ItemId, long SupplierId, decimal Quantity);
|
||||
|
||||
/// <summary>
|
||||
/// The reorder proposal (SPEC §11.6, mockup 039): the items whose available and ordered quantity no longer covers the
|
||||
/// reorder point (or the minimum stock), with the quantity to order (the lot, or what brings back to the threshold, at
|
||||
/// least the minimum of the supplier) and the usual supplier; accepted, the proposals become draft supplier orders,
|
||||
/// one per supplier.
|
||||
/// </summary>
|
||||
public sealed class ReorderService
|
||||
{
|
||||
/// <summary>Error: a chosen line without a supplier or a quantity.</summary>
|
||||
public const string ChoiceInvalid = "inventory.reorder.choice-invalid";
|
||||
|
||||
private readonly IUnitOfWorkFactory _factory;
|
||||
private readonly PermissionService _permissions;
|
||||
private readonly DocumentEngine _engine;
|
||||
private readonly DocumentEditor _editor;
|
||||
private readonly TimeProvider _clock;
|
||||
|
||||
/// <summary>Creates the service.</summary>
|
||||
/// <param name="factory">The units of work.</param>
|
||||
/// <param name="permissions">The permissions.</param>
|
||||
/// <param name="engine">The document engine.</param>
|
||||
/// <param name="editor">The editor (prices and terms of the supplier).</param>
|
||||
/// <param name="clock">The clock.</param>
|
||||
public ReorderService(IUnitOfWorkFactory factory, PermissionService permissions, DocumentEngine engine, DocumentEditor editor, TimeProvider clock)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(factory);
|
||||
ArgumentNullException.ThrowIfNull(permissions);
|
||||
ArgumentNullException.ThrowIfNull(engine);
|
||||
ArgumentNullException.ThrowIfNull(editor);
|
||||
ArgumentNullException.ThrowIfNull(clock);
|
||||
_factory = factory;
|
||||
_permissions = permissions;
|
||||
_engine = engine;
|
||||
_editor = editor;
|
||||
_clock = clock;
|
||||
}
|
||||
|
||||
/// <summary>The items to reorder, by supplier and code.</summary>
|
||||
/// <param name="actor">Who reads.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The proposals.</returns>
|
||||
public async Task<IReadOnlyList<ReorderProposal>> ProposalsAsync(Actor actor, string companyCode, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, InventoryService.StockPermission, cancellationToken).ConfigureAwait(false);
|
||||
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
||||
var items = (await uow.Repository<Item, long>().ListAsync(
|
||||
Query.For<Item>().Where(i => i.Stocked && i.Kind == ItemKind.Goods && !i.Disabled && (i.MinimumStock != null || i.ReorderPoint != null)).OrderBy(i => i.Code), cancellationToken)
|
||||
.ConfigureAwait(false)).Items;
|
||||
if (items.Count == 0)
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
var balances = await InventoryService.BalancesByItemAsync(uow, null, cancellationToken).ConfigureAwait(false);
|
||||
var ids = items.Select(i => i.Id).ToList();
|
||||
var suppliers = (await uow.Repository<ItemSupplier, long>().ListAsync(Query.For<ItemSupplier>().Where(s => ids.Contains(s.ItemId)), cancellationToken)
|
||||
.ConfigureAwait(false)).Items.GroupBy(s => s.ItemId).ToDictionary(g => g.Key, g => g.OrderByDescending(s => s.IsDefault).ThenBy(s => s.Id).First());
|
||||
var partyIds = suppliers.Values.Select(s => s.PartyId).Distinct().ToList();
|
||||
var names = partyIds.Count == 0 ? [] : (await uow.Repository<Party, long>().ListAsync(Query.For<Party>().Where(p => partyIds.Contains(p.Id)), cancellationToken)
|
||||
.ConfigureAwait(false)).Items.ToDictionary(p => p.Id, p => p.Name);
|
||||
var today = DateOnly.FromDateTime(_clock.GetLocalNow().DateTime);
|
||||
var result = new List<ReorderProposal>();
|
||||
foreach (var item in items)
|
||||
{
|
||||
var mine = balances.GetValueOrDefault(item.Id) ?? [];
|
||||
var available = mine.Sum(b => b.OnHand - b.Committed);
|
||||
var ordered = mine.Sum(b => b.Ordered);
|
||||
var supplier = suppliers.GetValueOrDefault(item.Id);
|
||||
var quantity = Quantity(available + ordered, item.MinimumStock, item.ReorderPoint, item.ReorderLot, supplier?.MinimumQuantity);
|
||||
if (quantity <= 0m)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
result.Add(new ReorderProposal(
|
||||
item.Id, item.Code, item.Description, item.UnitOfMeasureId, available, ordered, item.MinimumStock, item.ReorderPoint, quantity,
|
||||
supplier?.PartyId, supplier is null ? null : names.GetValueOrDefault(supplier.PartyId), supplier?.Price ?? item.LastCost,
|
||||
supplier?.LeadTimeDays is { } days ? today.AddDays(days) : null));
|
||||
}
|
||||
|
||||
return [.. result.OrderBy(r => r.SupplierName is null).ThenBy(r => r.SupplierName, StringComparer.CurrentCulture).ThenBy(r => r.Code, StringComparer.Ordinal)];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The quantity to order: nothing while what is available and ordered covers the reorder point (or the minimum);
|
||||
/// otherwise the lot of the item, or what brings back to the higher of the two thresholds, at least the minimum
|
||||
/// quantity of the supplier.
|
||||
/// </summary>
|
||||
/// <param name="cover">Available plus ordered.</param>
|
||||
/// <param name="minimum">The minimum stock.</param>
|
||||
/// <param name="reorderPoint">The reorder point.</param>
|
||||
/// <param name="lot">The reorder lot.</param>
|
||||
/// <param name="supplierMinimum">The minimum of the supplier.</param>
|
||||
/// <returns>The quantity.</returns>
|
||||
public static decimal Quantity(decimal cover, decimal? minimum, decimal? reorderPoint, decimal? lot, decimal? supplierMinimum)
|
||||
{
|
||||
var threshold = reorderPoint ?? minimum;
|
||||
if (threshold is not { } point || cover > point || (reorderPoint is null && cover >= point))
|
||||
{
|
||||
return 0m;
|
||||
}
|
||||
|
||||
var target = Math.Max(minimum ?? 0m, reorderPoint ?? 0m);
|
||||
var quantity = lot is > 0m ? lot.Value : Math.Max(target - cover, 0m);
|
||||
if (lot is > 0m && cover + quantity < target)
|
||||
{
|
||||
// One lot is not enough: as many lots as it takes.
|
||||
quantity = Math.Ceiling((target - cover) / lot.Value) * lot.Value;
|
||||
}
|
||||
|
||||
return Math.Max(quantity, supplierMinimum ?? 0m);
|
||||
}
|
||||
|
||||
/// <summary>Creates the draft supplier orders of the chosen proposals, one per supplier.</summary>
|
||||
/// <param name="actor">Who orders: needs <c>purchases.order.write</c>.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="choices">The proposals accepted.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The orders, saved as drafts.</returns>
|
||||
public async Task<IReadOnlyList<DocumentRecord>> CreateOrdersAsync(Actor actor, string companyCode, IReadOnlyList<ReorderChoice> choices, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(choices);
|
||||
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, "purchases.order.write", cancellationToken).ConfigureAwait(false);
|
||||
if (choices.Any(c => c.Quantity <= 0m || c.SupplierId <= 0))
|
||||
{
|
||||
throw new ValidationFailedException([":" + ChoiceInvalid]);
|
||||
}
|
||||
|
||||
var result = new List<DocumentRecord>();
|
||||
foreach (var group in choices.GroupBy(c => c.SupplierId))
|
||||
{
|
||||
var order = await _engine.NewAsync(actor, company, "OF", cancellationToken).ConfigureAwait(false);
|
||||
await _editor.ApplyPartyAsync(actor, company, order, group.Key, cancellationToken).ConfigureAwait(false);
|
||||
foreach (var choice in group)
|
||||
{
|
||||
var line = new PurchaseOrderLine { Kind = DocumentLineKind.Item, ItemId = choice.ItemId, Quantity = choice.Quantity };
|
||||
order.Lines.Add(line);
|
||||
await _editor.FillLineAsync(actor, company, order, line, choice.ItemId, cancellationToken).ConfigureAwait(false);
|
||||
line.Quantity = choice.Quantity;
|
||||
}
|
||||
|
||||
result.Add(await _engine.SaveAsync(actor, company, order, cancellationToken).ConfigureAwait(false));
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,405 @@
|
||||
using System.Globalization;
|
||||
using System.Text;
|
||||
using Khaemhat.Application.Documents;
|
||||
using Khaemhat.Application.Security;
|
||||
using Khaemhat.Application.Tables;
|
||||
using Khaemhat.Core.Documents;
|
||||
using Khaemhat.Core.Inventory;
|
||||
using Khaemhat.Core.Items;
|
||||
using Khaemhat.Core.Tables;
|
||||
using Khaemhat.Data;
|
||||
using Khaemhat.Data.Querying;
|
||||
|
||||
namespace Khaemhat.Application.Inventory;
|
||||
|
||||
/// <summary>A line of a stock take with its item.</summary>
|
||||
/// <param name="Line">The line.</param>
|
||||
/// <param name="Code">The code of the item.</param>
|
||||
/// <param name="Description">Its description.</param>
|
||||
/// <param name="UnitOfMeasureId">Its base unit.</param>
|
||||
public sealed record StockTakeLineView(StockTakeLine Line, string Code, string Description, long? UnitOfMeasureId);
|
||||
|
||||
/// <summary>A stock take with its lines.</summary>
|
||||
/// <param name="Take">The stock take.</param>
|
||||
/// <param name="Lines">Its lines, by code.</param>
|
||||
public sealed record StockTakeView(StockTake Take, IReadOnlyList<StockTakeLineView> Lines)
|
||||
{
|
||||
/// <summary>How many lines are counted.</summary>
|
||||
public int Counted => Lines.Count(l => l.Line.CountedQuantity is not null);
|
||||
|
||||
/// <summary>The value of the differences at the cost of the lines.</summary>
|
||||
public decimal DifferenceValue => Lines.Sum(l => StockCostCalculator.Value(l.Line.Difference, l.Line.UnitCost));
|
||||
}
|
||||
|
||||
/// <summary>What the import of the counts found.</summary>
|
||||
/// <param name="Applied">The lines counted.</param>
|
||||
/// <param name="Unknown">The codes not on the list, with their row.</param>
|
||||
public sealed record StockCountImport(int Applied, IReadOnlyList<string> Unknown);
|
||||
|
||||
/// <summary>
|
||||
/// The physical inventory (SPEC §11.6, mockup 038): a list of the items of a warehouse with what the books say at the
|
||||
/// date, the counts typed or read from a file, and the posting that writes the differences as two warehouse movements
|
||||
/// (gains with reason INVP, losses with INVN) through the document engine.
|
||||
/// </summary>
|
||||
/// <remarks>Permissions <c>inventory.entry.read</c>, <c>write</c> (lists and counts) and <c>post</c>.</remarks>
|
||||
public sealed class StockTakeService
|
||||
{
|
||||
/// <summary>Error: the stock take is no longer open.</summary>
|
||||
public const string NotOpen = "inventory.stock-take.not-open";
|
||||
|
||||
/// <summary>Error: nothing is counted.</summary>
|
||||
public const string NothingCounted = "inventory.stock-take.nothing-counted";
|
||||
|
||||
/// <summary>Error: a counted quantity below zero.</summary>
|
||||
public const string NegativeCount = "inventory.stock-take.negative";
|
||||
|
||||
/// <summary>Error: the reasons of the adjustments are missing from the base tables.</summary>
|
||||
public const string ReasonMissing = "inventory.stock-take.reason-missing";
|
||||
|
||||
/// <summary>The reason of the gains.</summary>
|
||||
public const string GainReason = "INVP";
|
||||
|
||||
/// <summary>The reason of the losses.</summary>
|
||||
public const string LossReason = "INVN";
|
||||
|
||||
private readonly IUnitOfWorkFactory _factory;
|
||||
private readonly PermissionService _permissions;
|
||||
private readonly DocumentEngine _engine;
|
||||
private readonly TimeProvider _clock;
|
||||
|
||||
/// <summary>Creates the service.</summary>
|
||||
/// <param name="factory">The units of work.</param>
|
||||
/// <param name="permissions">The permissions.</param>
|
||||
/// <param name="engine">The document engine, for the adjustments.</param>
|
||||
/// <param name="clock">The clock.</param>
|
||||
public StockTakeService(IUnitOfWorkFactory factory, PermissionService permissions, DocumentEngine engine, TimeProvider clock)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(factory);
|
||||
ArgumentNullException.ThrowIfNull(permissions);
|
||||
ArgumentNullException.ThrowIfNull(engine);
|
||||
ArgumentNullException.ThrowIfNull(clock);
|
||||
_factory = factory;
|
||||
_permissions = permissions;
|
||||
_engine = engine;
|
||||
_clock = clock;
|
||||
}
|
||||
|
||||
/// <summary>The stock takes, the latest first.</summary>
|
||||
/// <param name="actor">Who reads.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The stock takes.</returns>
|
||||
public async Task<IReadOnlyList<StockTake>> ListAsync(Actor actor, string companyCode, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, InventoryService.EntryReadPermission, cancellationToken).ConfigureAwait(false);
|
||||
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
||||
return (await uow.Repository<StockTake, long>().ListAsync(Query.For<StockTake>().OrderByDescending(t => t.TakeDate).OrderByDescending(t => t.Id), cancellationToken)
|
||||
.ConfigureAwait(false)).Items;
|
||||
}
|
||||
|
||||
/// <summary>A stock take with its lines.</summary>
|
||||
/// <param name="actor">Who reads.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="id">The stock take.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The stock take, or none.</returns>
|
||||
public async Task<StockTakeView?> GetAsync(Actor actor, string companyCode, long id, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, InventoryService.EntryReadPermission, cancellationToken).ConfigureAwait(false);
|
||||
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
||||
return await ViewAsync(uow, id, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Opens a stock take: the stocked goods of the warehouse (of a category, if given) with the quantity the books
|
||||
/// give at the date and the average cost.
|
||||
/// </summary>
|
||||
/// <param name="actor">Who opens it.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="warehouseId">The warehouse.</param>
|
||||
/// <param name="date">The day of the count.</param>
|
||||
/// <param name="categoryId">Only a category.</param>
|
||||
/// <param name="description">A description; the warehouse and date when empty.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The new stock take.</returns>
|
||||
public async Task<StockTakeView> CreateAsync(
|
||||
Actor actor, string companyCode, long warehouseId, DateOnly date, long? categoryId, string? description, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, "inventory.entry.write", cancellationToken).ConfigureAwait(false);
|
||||
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
||||
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
|
||||
var warehouse = await uow.Repository<Warehouse, long>().GetAsync(warehouseId, cancellationToken).ConfigureAwait(false)
|
||||
?? throw new ValidationFailedException([nameof(StockTake.WarehouseId) + ":" + "inventory.warehouse.missing"]);
|
||||
var query = Query.For<Item>().Where(i => i.Stocked && i.Kind == ItemKind.Goods && !i.Disabled);
|
||||
if (categoryId is { } category)
|
||||
{
|
||||
query = query.Where(i => i.CategoryId == category);
|
||||
}
|
||||
|
||||
var items = (await uow.Repository<Item, long>().ListAsync(query.OrderBy(i => i.Code), cancellationToken).ConfigureAwait(false)).Items;
|
||||
var book = await BookAsync(uow, warehouseId, date, cancellationToken).ConfigureAwait(false);
|
||||
var balances = (await uow.Repository<ItemBalance, long>().ListAsync(Query.For<ItemBalance>().Where(b => b.WarehouseId == warehouseId), cancellationToken)
|
||||
.ConfigureAwait(false)).Items.ToDictionary(b => b.ItemId);
|
||||
var take = new StockTake
|
||||
{
|
||||
TakeDate = date,
|
||||
WarehouseId = warehouseId,
|
||||
CategoryId = categoryId,
|
||||
Description = string.IsNullOrWhiteSpace(description)
|
||||
? "Inventario " + warehouse.Code + " al " + date.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture)
|
||||
: description.Trim()[..Math.Min(description.Trim().Length, 100)],
|
||||
Status = StockTakeStatus.Open,
|
||||
};
|
||||
await uow.Repository<StockTake, long>().InsertAsync(take, cancellationToken).ConfigureAwait(false);
|
||||
var lines = uow.Repository<StockTakeLine, long>();
|
||||
var order = 0;
|
||||
foreach (var item in items)
|
||||
{
|
||||
await lines.InsertAsync(
|
||||
new StockTakeLine
|
||||
{
|
||||
StockTakeId = take.Id,
|
||||
ItemId = item.Id,
|
||||
BookQuantity = book.GetValueOrDefault(item.Id),
|
||||
UnitCost = balances.TryGetValue(item.Id, out var balance) ? balance.AverageCost : item.AverageCost ?? item.StandardCost ?? 0m,
|
||||
SortOrder = ++order,
|
||||
},
|
||||
cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
|
||||
return (await ViewAsync(uow, take.Id, cancellationToken).ConfigureAwait(false))!;
|
||||
}
|
||||
|
||||
/// <summary>Writes the counts typed on the list; an empty count means not counted yet.</summary>
|
||||
/// <param name="actor">Who counts.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="id">The stock take.</param>
|
||||
/// <param name="counts">The counted quantity of each line, by line.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The stock take.</returns>
|
||||
public async Task<StockTakeView> SaveCountsAsync(
|
||||
Actor actor, string companyCode, long id, IReadOnlyDictionary<long, decimal?> counts, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(counts);
|
||||
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, "inventory.entry.write", cancellationToken).ConfigureAwait(false);
|
||||
if (counts.Values.Any(v => v < 0m))
|
||||
{
|
||||
throw new ValidationFailedException(["CountedQuantity:" + NegativeCount]);
|
||||
}
|
||||
|
||||
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
||||
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
|
||||
await OpenTakeAsync(uow, id, cancellationToken).ConfigureAwait(false);
|
||||
var repository = uow.Repository<StockTakeLine, long>();
|
||||
foreach (var line in (await repository.ListAsync(Query.For<StockTakeLine>().Where(l => l.StockTakeId == id), cancellationToken).ConfigureAwait(false)).Items)
|
||||
{
|
||||
if (counts.TryGetValue(line.Id, out var counted) && counted != line.CountedQuantity)
|
||||
{
|
||||
line.CountedQuantity = counted;
|
||||
await repository.UpdateAsync(line, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
|
||||
return (await ViewAsync(uow, id, cancellationToken).ConfigureAwait(false))!;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reads the counts from a text file (from a barcode reader or a spreadsheet): one row per item, the code and the
|
||||
/// quantity separated by semicolon, tab or comma; a header and empty rows are skipped; the same code twice adds up.
|
||||
/// </summary>
|
||||
/// <param name="actor">Who counts.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="id">The stock take.</param>
|
||||
/// <param name="content">The file.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>How many lines were counted and the codes not on the list.</returns>
|
||||
public async Task<StockCountImport> ImportCountsAsync(Actor actor, string companyCode, long id, Stream content, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(content);
|
||||
var view = await GetAsync(actor, companyCode, id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(NotOpen);
|
||||
var byCode = view.Lines.ToDictionary(l => l.Code, l => l.Line.Id, StringComparer.OrdinalIgnoreCase);
|
||||
var counts = new Dictionary<long, decimal?>();
|
||||
var unknown = new List<string>();
|
||||
using var reader = new StreamReader(content, Encoding.UTF8, detectEncodingFromByteOrderMarks: true);
|
||||
var row = 0;
|
||||
while (await reader.ReadLineAsync(cancellationToken).ConfigureAwait(false) is { } text)
|
||||
{
|
||||
row++;
|
||||
if (ParseCount(text) is not { } parsed)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var (code, quantity) = parsed;
|
||||
|
||||
if (byCode.TryGetValue(code, out var lineId))
|
||||
{
|
||||
counts[lineId] = (counts.GetValueOrDefault(lineId) ?? 0m) + quantity;
|
||||
}
|
||||
else
|
||||
{
|
||||
unknown.Add(row.ToString(CultureInfo.InvariantCulture) + ": " + code);
|
||||
}
|
||||
}
|
||||
|
||||
if (counts.Count > 0)
|
||||
{
|
||||
await SaveCountsAsync(actor, companyCode, id, counts, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
return new StockCountImport(counts.Count, unknown);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Posts a stock take: the counted lines that differ from the books become a movement of gains (INVP, at the cost
|
||||
/// of the line) and one of losses (INVN), confirmed at the date of the count. The lines not counted are left as
|
||||
/// they are.
|
||||
/// </summary>
|
||||
/// <param name="actor">Who posts: needs <c>inventory.entry.post</c>.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="id">The stock take.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The stock take as posted.</returns>
|
||||
public async Task<StockTakeView> PostAsync(Actor actor, string companyCode, long id, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, InventoryService.PostPermission, cancellationToken).ConfigureAwait(false);
|
||||
StockTakeView view;
|
||||
long? gainReason, lossReason;
|
||||
await using (var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
await OpenTakeAsync(uow, id, cancellationToken).ConfigureAwait(false);
|
||||
view = (await ViewAsync(uow, id, cancellationToken).ConfigureAwait(false))!;
|
||||
var reasons = (await uow.Repository<InventoryReason, long>().ListAsync(Query.For<InventoryReason>(), cancellationToken).ConfigureAwait(false)).Items;
|
||||
gainReason = reasons.FirstOrDefault(r => r.Code == GainReason)?.Id;
|
||||
lossReason = reasons.FirstOrDefault(r => r.Code == LossReason)?.Id;
|
||||
}
|
||||
|
||||
if (view.Counted == 0)
|
||||
{
|
||||
throw new ValidationFailedException([":" + NothingCounted]);
|
||||
}
|
||||
|
||||
if (gainReason is null || lossReason is null)
|
||||
{
|
||||
throw new ValidationFailedException([":" + ReasonMissing]);
|
||||
}
|
||||
|
||||
var take = view.Take;
|
||||
var gains = view.Lines.Where(l => l.Line.CountedQuantity is not null && l.Line.Difference > 0m).ToList();
|
||||
var losses = view.Lines.Where(l => l.Line.CountedQuantity is not null && l.Line.Difference < 0m).ToList();
|
||||
take.AdjustmentDocumentId = await AdjustAsync(actor, company, take, gainReason.Value, gains, cancellationToken).ConfigureAwait(false);
|
||||
take.LossDocumentId = await AdjustAsync(actor, company, take, lossReason.Value, losses, cancellationToken).ConfigureAwait(false);
|
||||
take.Status = StockTakeStatus.Posted;
|
||||
take.PostedAt = _clock.GetUtcNow().UtcDateTime;
|
||||
take.PostedBy = actor.UserName;
|
||||
await using (var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
await uow.Repository<StockTake, long>().UpdateAsync(take, cancellationToken).ConfigureAwait(false);
|
||||
return (await ViewAsync(uow, id, cancellationToken).ConfigureAwait(false))!;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Cancels an open stock take; its counts stay for the record.</summary>
|
||||
/// <param name="actor">Who cancels.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="id">The stock take.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>A task.</returns>
|
||||
public async Task CancelAsync(Actor actor, string companyCode, long id, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, "inventory.entry.write", cancellationToken).ConfigureAwait(false);
|
||||
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
||||
var take = await OpenTakeAsync(uow, id, cancellationToken).ConfigureAwait(false);
|
||||
take.Status = StockTakeStatus.Cancelled;
|
||||
await uow.Repository<StockTake, long>().UpdateAsync(take, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>A code and a quantity from a row of a count file, or none for a header or an empty row.</summary>
|
||||
/// <param name="text">The row.</param>
|
||||
/// <returns>The code and the quantity.</returns>
|
||||
public static (string Code, decimal Quantity)? ParseCount(string? text)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(text))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var separator = text.Contains(';', StringComparison.Ordinal) ? ';' : text.Contains('\t', StringComparison.Ordinal) ? '\t' : ',';
|
||||
var parts = text.Split(separator, StringSplitOptions.TrimEntries);
|
||||
if (parts.Length < 2 || parts[0].Length == 0)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var number = parts[1].Trim('"');
|
||||
|
||||
// With a comma as separator the quantity is in the invariant form; otherwise the Italian one is accepted too.
|
||||
var parsed = separator == ','
|
||||
? decimal.TryParse(number, NumberStyles.Number, CultureInfo.InvariantCulture, out var value)
|
||||
: decimal.TryParse(number.Replace(".", string.Empty, StringComparison.Ordinal), NumberStyles.Number, CultureInfo.GetCultureInfo("it-IT"), out value);
|
||||
return parsed && value >= 0m ? (parts[0].Trim('"'), value) : null;
|
||||
}
|
||||
|
||||
// The quantity of each item in a warehouse at the end of a day.
|
||||
internal static async Task<Dictionary<long, decimal>> BookAsync(IUnitOfWork uow, long warehouseId, DateOnly date, CancellationToken cancellationToken) =>
|
||||
(await uow.Repository<InventoryEntryLine, long>().ListAsync(
|
||||
Query.For<InventoryEntryLine>().Where(l => l.WarehouseId == warehouseId && l.EntryDate <= date), cancellationToken).ConfigureAwait(false)).Items
|
||||
.GroupBy(l => l.ItemId).ToDictionary(g => g.Key, g => g.Sum(l => l.Quantity));
|
||||
|
||||
private async Task<long?> AdjustAsync(
|
||||
Actor actor, string company, StockTake take, long reasonId, List<StockTakeLineView> lines, CancellationToken cancellationToken)
|
||||
{
|
||||
if (lines.Count == 0)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var entry = await _engine.NewAsync(actor, company, "MM", cancellationToken).ConfigureAwait(false);
|
||||
entry.Header.DocumentDate = take.TakeDate;
|
||||
entry.Header.InventoryReasonId = reasonId;
|
||||
entry.Header.WarehouseId = take.WarehouseId;
|
||||
entry.Header.ExternalReference = take.Description.Length > 40 ? take.Description[..40] : take.Description;
|
||||
entry.Header.IsDemo = take.IsDemo;
|
||||
foreach (var line in lines)
|
||||
{
|
||||
entry.Lines.Add(new InventoryDocumentLine
|
||||
{
|
||||
Kind = DocumentLineKind.Item,
|
||||
ItemId = line.Line.ItemId,
|
||||
Description = line.Description,
|
||||
UnitOfMeasureId = line.UnitOfMeasureId,
|
||||
Quantity = Math.Abs(line.Line.Difference),
|
||||
Price = line.Line.UnitCost,
|
||||
WarehouseId = take.WarehouseId,
|
||||
});
|
||||
}
|
||||
|
||||
entry = await _engine.SaveAsync(actor, company, entry, cancellationToken).ConfigureAwait(false);
|
||||
return (await _engine.ConfirmAsync(actor, company, DocumentFamily.InventoryDocument, entry.Header.Id, cancellationToken).ConfigureAwait(false)).Header.Id;
|
||||
}
|
||||
|
||||
private static async Task<StockTake> OpenTakeAsync(IUnitOfWork uow, long id, CancellationToken cancellationToken)
|
||||
{
|
||||
var take = await uow.Repository<StockTake, long>().GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(NotOpen);
|
||||
return take.Status == StockTakeStatus.Open ? take : throw new ValidationFailedException([":" + NotOpen]);
|
||||
}
|
||||
|
||||
private static async Task<StockTakeView?> ViewAsync(IUnitOfWork uow, long id, CancellationToken cancellationToken)
|
||||
{
|
||||
if (await uow.Repository<StockTake, long>().GetAsync(id, cancellationToken).ConfigureAwait(false) is not { } take)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var lines = (await uow.Repository<StockTakeLine, long>().ListAsync(Query.For<StockTakeLine>().Where(l => l.StockTakeId == id).OrderBy(l => l.SortOrder), cancellationToken)
|
||||
.ConfigureAwait(false)).Items;
|
||||
var ids = lines.Select(l => l.ItemId).Distinct().ToList();
|
||||
var items = ids.Count == 0 ? [] : (await uow.Repository<Item, long>().ListAsync(Query.For<Item>().Where(i => ids.Contains(i.Id)), cancellationToken).ConfigureAwait(false))
|
||||
.Items.ToDictionary(i => i.Id);
|
||||
return new StockTakeView(take, [.. lines.Select(l => items.TryGetValue(l.ItemId, out var item)
|
||||
? new StockTakeLineView(l, item.Code, item.Description, item.UnitOfMeasureId)
|
||||
: new StockTakeLineView(l, "?", string.Empty, null))]);
|
||||
}
|
||||
}
|
||||
@@ -50,7 +50,7 @@ public sealed record SystemTaskDefinition(string Code, string Name, string JobTy
|
||||
/// </summary>
|
||||
public sealed class JobScheduler
|
||||
{
|
||||
/// <summary>The system tasks (M2, attachments trash from M3, ECB rates from M4).</summary>
|
||||
/// <summary>The system tasks (M2, attachments trash from M3, ECB rates from M4, warehouse rebuild from M6).</summary>
|
||||
public static readonly IReadOnlyList<SystemTaskDefinition> SystemTasks =
|
||||
[
|
||||
new("system.sessions-cleanup", "Pulizia sessioni scadute", SessionCleanupJob.JobType, "15 * * * *", 300),
|
||||
@@ -58,6 +58,10 @@ public sealed class JobScheduler
|
||||
new("system.log-retention", "Conservazione del log", LogRetentionJob.JobType, "30 3 * * *", 1800),
|
||||
new("system.attachments-trash", "Svuotamento cestino allegati", Files.AttachmentTrashPurgeJob.JobType, "45 3 * * *", 1800),
|
||||
new("system.ecb-rates", "Cambi di riferimento BCE", Tables.EcbRatesJob.JobType, "30 16 * * 1-5", 300, UsesNetwork: true),
|
||||
new("inventory.rebuild", "Ricostruzione del magazzino", Inventory.InventoryRebuildJob.JobType, "15 2 * * 0", 3600),
|
||||
new("ledger.recurring", "Registrazioni ricorrenti", Ledger.RecurringEntriesJob.JobType, "0 5 * * *", 1800),
|
||||
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;
|
||||
|
||||
@@ -0,0 +1,565 @@
|
||||
using Khaemhat.Application.Audit;
|
||||
using Khaemhat.Application.Security;
|
||||
using Khaemhat.Application.Tables;
|
||||
using Khaemhat.Core.Accounting;
|
||||
using Khaemhat.Core.Parties;
|
||||
using Khaemhat.Core.Tables;
|
||||
using Khaemhat.Data;
|
||||
using Khaemhat.Data.Querying;
|
||||
|
||||
namespace Khaemhat.Application.Ledger;
|
||||
|
||||
/// <summary>An entry with its lines and VAT lines.</summary>
|
||||
/// <param name="Entry">The entry.</param>
|
||||
/// <param name="Lines">The lines.</param>
|
||||
/// <param name="Vat">The VAT lines.</param>
|
||||
/// <param name="PartyName">The name of the customer or supplier of the entry.</param>
|
||||
public sealed record EntryView(GlEntry Entry, IReadOnlyList<GlEntryLine> Lines, IReadOnlyList<GlEntryVat> Vat, string? PartyName)
|
||||
{
|
||||
/// <summary>Debit minus credit.</summary>
|
||||
public decimal Difference => Lines.Sum(l => l.Debit - l.Credit);
|
||||
}
|
||||
|
||||
/// <summary>An entry as the journal lists it.</summary>
|
||||
/// <param name="Entry">The entry.</param>
|
||||
/// <param name="PartyName">The customer or supplier.</param>
|
||||
public sealed record EntryRow(GlEntry Entry, string? PartyName);
|
||||
|
||||
/// <summary>What the journal list shows.</summary>
|
||||
/// <param name="From">From this day.</param>
|
||||
/// <param name="To">Up to this day.</param>
|
||||
/// <param name="Status">Only this state.</param>
|
||||
/// <param name="TemplateCode">Only this template.</param>
|
||||
/// <param name="Text">Text in the description or the document number.</param>
|
||||
/// <param name="Offset">The first row.</param>
|
||||
/// <param name="Limit">How many rows.</param>
|
||||
public sealed record EntryFilter(
|
||||
DateOnly? From = null, DateOnly? To = null, GlEntryStatus? Status = null, string? TemplateCode = null, string? Text = null, int Offset = 0, int Limit = 50);
|
||||
|
||||
/// <summary>An entry typed in the journal.</summary>
|
||||
/// <param name="Id">The entry, for a change.</param>
|
||||
/// <param name="EntryDate">The date of registration.</param>
|
||||
/// <param name="Description">The description.</param>
|
||||
/// <param name="Lines">The lines.</param>
|
||||
public sealed record EntryInput(long? Id, DateOnly EntryDate, string Description, IReadOnlyList<EntryLineDraft> Lines)
|
||||
{
|
||||
/// <summary>The template.</summary>
|
||||
public long? JournalTemplateId { get; init; }
|
||||
|
||||
/// <summary>The date of competence.</summary>
|
||||
public DateOnly? CompetenceDate { get; init; }
|
||||
|
||||
/// <summary>The number of the document.</summary>
|
||||
public string? DocumentNumber { get; init; }
|
||||
|
||||
/// <summary>The date of the document.</summary>
|
||||
public DateOnly? DocumentDate { get; init; }
|
||||
|
||||
/// <summary>The customer or supplier.</summary>
|
||||
public long? PartyId { get; init; }
|
||||
|
||||
/// <summary>The VAT register.</summary>
|
||||
public long? VatRegisterId { get; init; }
|
||||
|
||||
/// <summary>The VAT date.</summary>
|
||||
public DateOnly? VatDate { get; init; }
|
||||
|
||||
/// <summary>The VAT lines.</summary>
|
||||
public IReadOnlyList<EntryVatDraft> Vat { get; init; } = [];
|
||||
|
||||
/// <summary>Notes.</summary>
|
||||
public string? Notes { get; init; }
|
||||
|
||||
/// <summary>Post it (it must balance) rather than keep it as a draft.</summary>
|
||||
public bool Post { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>A journal template with its lines, for the guided entry.</summary>
|
||||
/// <param name="Template">The template.</param>
|
||||
/// <param name="Lines">Its lines.</param>
|
||||
public sealed record TemplateView(JournalTemplate Template, IReadOnlyList<JournalTemplateLine> Lines);
|
||||
|
||||
/// <summary>
|
||||
/// The journal (prima nota, SPEC §11.7, issue #63, mockups 040-041, ADR 0036): drafts that may not balance, posted
|
||||
/// entries (provvisorie) numbered per year in the order of registration, final entries (definitive) numbered on the
|
||||
/// general journal in date order and never changed again; a reversal corrects them. The guided entry starts from the
|
||||
/// lines of a template; the manual one shows the imbalance while it is typed. The period must be open (for VAT too when
|
||||
/// the entry has VAT lines). Entries of documents change only through their document.
|
||||
/// </summary>
|
||||
public sealed class JournalEntryService
|
||||
{
|
||||
private readonly IUnitOfWorkFactory _factory;
|
||||
private readonly PermissionService _permissions;
|
||||
private readonly FiscalYearService _fiscal;
|
||||
private readonly AuditTrail _audit;
|
||||
private readonly TimeProvider _clock;
|
||||
|
||||
/// <summary>Creates the service.</summary>
|
||||
/// <param name="factory">The units of work.</param>
|
||||
/// <param name="permissions">The permissions.</param>
|
||||
/// <param name="fiscal">The fiscal calendar.</param>
|
||||
/// <param name="audit">The history.</param>
|
||||
/// <param name="clock">The clock.</param>
|
||||
public JournalEntryService(IUnitOfWorkFactory factory, PermissionService permissions, FiscalYearService fiscal, AuditTrail audit, TimeProvider clock)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(factory);
|
||||
ArgumentNullException.ThrowIfNull(permissions);
|
||||
ArgumentNullException.ThrowIfNull(fiscal);
|
||||
ArgumentNullException.ThrowIfNull(audit);
|
||||
ArgumentNullException.ThrowIfNull(clock);
|
||||
_factory = factory;
|
||||
_permissions = permissions;
|
||||
_fiscal = fiscal;
|
||||
_audit = audit;
|
||||
_clock = clock;
|
||||
}
|
||||
|
||||
/// <summary>The entries, the latest first.</summary>
|
||||
/// <param name="actor">Who reads.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="filter">The filter and the page.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The page and the total.</returns>
|
||||
public async Task<(IReadOnlyList<EntryRow> Rows, int Total)> ListAsync(Actor actor, string companyCode, EntryFilter filter, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(filter);
|
||||
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.EntryRead, cancellationToken).ConfigureAwait(false);
|
||||
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
||||
var query = Query.For<GlEntry>();
|
||||
if (filter.From is { } from)
|
||||
{
|
||||
query = query.Where(e => e.EntryDate >= from);
|
||||
}
|
||||
|
||||
if (filter.To is { } to)
|
||||
{
|
||||
query = query.Where(e => e.EntryDate <= to);
|
||||
}
|
||||
|
||||
if (filter.Status is { } status)
|
||||
{
|
||||
query = query.Where(e => e.Status == status);
|
||||
}
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(filter.TemplateCode))
|
||||
{
|
||||
var code = filter.TemplateCode;
|
||||
query = query.Where(e => e.TemplateCode == code);
|
||||
}
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(filter.Text))
|
||||
{
|
||||
var text = filter.Text.Trim();
|
||||
query = query.Where(e => e.Description.Contains(text) || e.DocumentNumber!.Contains(text) || e.EntryNumber!.Contains(text));
|
||||
}
|
||||
|
||||
var repository = uow.Repository<GlEntry, long>();
|
||||
var total = await repository.CountAsync(query, cancellationToken).ConfigureAwait(false);
|
||||
var page = (await repository.ListAsync(
|
||||
query.OrderByDescending(e => e.EntryDate).OrderByDescending(e => e.Id).Page(Math.Max(0, filter.Offset), Math.Clamp(filter.Limit, 1, 500)),
|
||||
cancellationToken).ConfigureAwait(false)).Items;
|
||||
var names = await PartyNamesAsync(uow, page.Select(e => e.PartyId), cancellationToken).ConfigureAwait(false);
|
||||
return ([.. page.Select(e => new EntryRow(e, e.PartyId is { } p && names.TryGetValue(p, out var n) ? n : null))], total);
|
||||
}
|
||||
|
||||
/// <summary>An entry with its lines.</summary>
|
||||
/// <param name="actor">Who reads.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="id">The entry.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The entry, or none.</returns>
|
||||
public async Task<EntryView?> GetAsync(Actor actor, string companyCode, long id, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.EntryRead, cancellationToken).ConfigureAwait(false);
|
||||
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
||||
return await ViewAsync(uow, id, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>The journal templates with their lines, for the guided entry.</summary>
|
||||
/// <param name="actor">Who reads.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The active templates, by code.</returns>
|
||||
public async Task<IReadOnlyList<TemplateView>> TemplatesAsync(Actor actor, string companyCode, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.EntryRead, cancellationToken).ConfigureAwait(false);
|
||||
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
||||
var templates = (await uow.Repository<JournalTemplate, long>().ListAsync(Query.For<JournalTemplate>().Where(t => !t.Disabled).OrderBy(t => t.Code), cancellationToken)
|
||||
.ConfigureAwait(false)).Items;
|
||||
var lines = (await uow.Repository<JournalTemplateLine, long>().ListAsync(Query.For<JournalTemplateLine>().OrderBy(l => l.SortOrder), cancellationToken).ConfigureAwait(false)).Items;
|
||||
return [.. templates.Select(t => new TemplateView(t, [.. lines.Where(l => l.JournalTemplateId == t.Id)]))];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Saves an entry typed in the journal: a draft may not balance, a posted entry must and gets its number. Final
|
||||
/// entries and entries of documents cannot change.
|
||||
/// </summary>
|
||||
/// <param name="actor">Who writes.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="input">The entry.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The entry as saved.</returns>
|
||||
public async Task<EntryView> SaveAsync(Actor actor, string companyCode, EntryInput input, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(input);
|
||||
ArgumentNullException.ThrowIfNull(actor);
|
||||
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.EntryWrite, cancellationToken).ConfigureAwait(false);
|
||||
if (input.EntryDate == default)
|
||||
{
|
||||
throw new ValidationFailedException(["EntryDate:" + LedgerErrors.DateRequired]);
|
||||
}
|
||||
|
||||
if (input.Post)
|
||||
{
|
||||
await _fiscal.DemandOpenAsync(company, input.EntryDate, input.Vat.Count > 0 ? PeriodUse.Vat : PeriodUse.NoVat, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
long id;
|
||||
await using (var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
|
||||
var entries = uow.Repository<GlEntry, long>();
|
||||
GlEntry? before = null;
|
||||
if (input.Id is { } existingId)
|
||||
{
|
||||
before = await entries.GetAsync(existingId, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(LedgerErrors.NotFound);
|
||||
if (before.Status == GlEntryStatus.Final)
|
||||
{
|
||||
throw new ValidationFailedException(["Status:" + LedgerErrors.Final]);
|
||||
}
|
||||
|
||||
if (before.Source == GlEntrySource.Document)
|
||||
{
|
||||
throw new ValidationFailedException(["Source:" + LedgerErrors.FromDocument]);
|
||||
}
|
||||
}
|
||||
|
||||
var accounts = await LedgerStore.AccountsAsync(uow, cancellationToken).ConfigureAwait(false);
|
||||
var lines = input.Lines.Where(l => l.AccountId is not null || l.Debit != 0m || l.Credit != 0m).ToList();
|
||||
var errors = JournalEntryValidator.Check(
|
||||
input.Description,
|
||||
[.. lines.Select(l => new EntryLineCheck(l.AccountId, l.PartyId, l.Debit, l.Credit))],
|
||||
input.Vat.Count,
|
||||
input.VatRegisterId is not null,
|
||||
LedgerStore.Rules(accounts),
|
||||
input.Post).ToList();
|
||||
if (input.Post)
|
||||
{
|
||||
await CheckFinalOrderAsync(uow, input.EntryDate, errors, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
if (errors.Count > 0)
|
||||
{
|
||||
throw new ValidationFailedException(errors);
|
||||
}
|
||||
|
||||
var template = input.JournalTemplateId is { } templateId
|
||||
? await uow.Repository<JournalTemplate, long>().GetAsync(templateId, cancellationToken).ConfigureAwait(false)
|
||||
: null;
|
||||
var entry = before is null ? new GlEntry { Source = GlEntrySource.Manual } : Clone(before);
|
||||
entry.EntryDate = input.EntryDate;
|
||||
entry.CompetenceDate = input.CompetenceDate;
|
||||
entry.JournalTemplateId = template?.Id;
|
||||
entry.TemplateCode = template?.Code;
|
||||
entry.Description = LedgerStore.Trim(input.Description.Trim(), 200)!;
|
||||
entry.DocumentNumber = LedgerStore.Trim(input.DocumentNumber, 30);
|
||||
entry.DocumentDate = input.DocumentDate;
|
||||
entry.PartyId = input.PartyId;
|
||||
entry.VatRegisterId = input.VatRegisterId;
|
||||
entry.VatDate = input.VatRegisterId is null ? null : input.VatDate ?? input.EntryDate;
|
||||
entry.Notes = LedgerStore.Trim(input.Notes, 500);
|
||||
entry.Status = input.Post ? GlEntryStatus.Posted : before?.Status ?? GlEntryStatus.Draft;
|
||||
if (before is not null && before.Number is not null && before.Year != input.EntryDate.Year)
|
||||
{
|
||||
entry.Number = null;
|
||||
entry.EntryNumber = null;
|
||||
}
|
||||
|
||||
if (before is null)
|
||||
{
|
||||
entry = await LedgerStore.InsertAsync(uow, entry, lines, input.Vat, cancellationToken).ConfigureAwait(false);
|
||||
await _audit.RecordAsync(uow, AuditAction.Insert, entry.Id, null, entry, actor.UserName, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
else
|
||||
{
|
||||
await LedgerStore.UpdateAsync(uow, entry, lines, input.Vat, cancellationToken).ConfigureAwait(false);
|
||||
await _audit.RecordAsync(uow, AuditAction.Update, entry.Id, before, entry, actor.UserName, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
id = entry.Id;
|
||||
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
return await GetAsync(actor, company, id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(LedgerErrors.NotFound);
|
||||
}
|
||||
|
||||
/// <summary>Removes an entry that is not final and does not come from a document.</summary>
|
||||
/// <param name="actor">Who removes it.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="id">The entry.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>A task.</returns>
|
||||
public async Task DeleteAsync(Actor actor, string companyCode, long id, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(actor);
|
||||
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.EntryWrite, cancellationToken).ConfigureAwait(false);
|
||||
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
||||
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
|
||||
var entry = await uow.Repository<GlEntry, long>().GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(LedgerErrors.NotFound);
|
||||
if (entry.Status == GlEntryStatus.Final)
|
||||
{
|
||||
throw new ValidationFailedException(["Status:" + LedgerErrors.Final]);
|
||||
}
|
||||
|
||||
if (entry.Source == GlEntrySource.Document)
|
||||
{
|
||||
throw new ValidationFailedException(["Source:" + LedgerErrors.FromDocument]);
|
||||
}
|
||||
|
||||
await uow.ExecuteAsync(SqlFragment.Of($"UPDATE gl_recurring_entries SET last_entry_id = NULL WHERE last_entry_id = {id}"), cancellationToken).ConfigureAwait(false);
|
||||
if (await uow.Repository<RecurringEntry, long>().CountAsync(Query.For<RecurringEntry>().Where(r => r.ModelEntryId == id), cancellationToken).ConfigureAwait(false) > 0)
|
||||
{
|
||||
throw new ValidationFailedException(["Id:" + LedgerErrors.RecurringModel]);
|
||||
}
|
||||
|
||||
await LedgerStore.DeleteAsync(uow, id, cancellationToken).ConfigureAwait(false);
|
||||
await _audit.RecordAsync(uow, AuditAction.Delete, id, entry, (GlEntry?)null, actor.UserName, cancellationToken).ConfigureAwait(false);
|
||||
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reverses an entry (storno): a new posted entry with the same lines on the other side and the VAT with the
|
||||
/// opposite sign; the open items of the entry not yet settled are removed.
|
||||
/// </summary>
|
||||
/// <param name="actor">Who reverses.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="id">The entry.</param>
|
||||
/// <param name="date">The date of the reversal.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The reversal.</returns>
|
||||
public async Task<EntryView> ReverseAsync(Actor actor, string companyCode, long id, DateOnly date, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(actor);
|
||||
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.EntryWrite, cancellationToken).ConfigureAwait(false);
|
||||
await _fiscal.DemandOpenAsync(company, date, PeriodUse.NoVat, cancellationToken).ConfigureAwait(false);
|
||||
long reversalId;
|
||||
await using (var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
|
||||
var entry = await uow.Repository<GlEntry, long>().GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(LedgerErrors.NotFound);
|
||||
if (entry.Source == GlEntrySource.Document && entry.Status != GlEntryStatus.Final)
|
||||
{
|
||||
throw new ValidationFailedException(["Source:" + LedgerErrors.FromDocument]);
|
||||
}
|
||||
|
||||
var reversal = await ReverseAsync(uow, entry, date, actor.UserName, cancellationToken).ConfigureAwait(false);
|
||||
await _audit.RecordAsync(uow, AuditAction.Insert, reversal.Id, null, reversal, actor.UserName, cancellationToken).ConfigureAwait(false);
|
||||
reversalId = reversal.Id;
|
||||
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
return await GetAsync(actor, company, reversalId, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(LedgerErrors.NotFound);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Makes final the posted entries up to a day (stampa definitiva del libro giornale): in date order each gets the
|
||||
/// next number of the journal of its fiscal year, then never changes again.
|
||||
/// </summary>
|
||||
/// <param name="actor">Who does it: needs <c>ledger.entry.finalize</c>.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="upTo">The last day.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>How many entries became final.</returns>
|
||||
public async Task<int> FinalizeAsync(Actor actor, string companyCode, DateOnly upTo, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(actor);
|
||||
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.EntryFinalize, cancellationToken).ConfigureAwait(false);
|
||||
var done = 0;
|
||||
await using (var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
|
||||
var drafts = await uow.Repository<GlEntry, long>().CountAsync(
|
||||
Query.For<GlEntry>().Where(e => e.Status == GlEntryStatus.Draft && e.EntryDate <= upTo), cancellationToken).ConfigureAwait(false);
|
||||
if (drafts > 0)
|
||||
{
|
||||
throw new ValidationFailedException(["UpTo:" + LedgerErrors.DraftsBeforeFinal]);
|
||||
}
|
||||
|
||||
var entries = (await uow.Repository<GlEntry, long>().ListAsync(
|
||||
Query.For<GlEntry>().Where(e => e.Status == GlEntryStatus.Posted && e.EntryDate <= upTo).OrderBy(e => e.EntryDate).OrderBy(e => e.Number).OrderBy(e => e.Id),
|
||||
cancellationToken).ConfigureAwait(false)).Items;
|
||||
var years = (await uow.Repository<FiscalYear, long>().ListAsync(Query.For<FiscalYear>(), cancellationToken).ConfigureAwait(false)).Items;
|
||||
var now = _clock.GetUtcNow().UtcDateTime;
|
||||
foreach (var entry in entries)
|
||||
{
|
||||
var year = years.FirstOrDefault(y => y.StartDate <= entry.EntryDate && y.EndDate >= entry.EntryDate)
|
||||
?? throw new ValidationFailedException(["UpTo:" + LedgerErrors.NoFiscalYear]);
|
||||
year.LastFinalEntryNumber++;
|
||||
year.LastFinalEntryDate = entry.EntryDate;
|
||||
entry.JournalNumber = year.LastFinalEntryNumber;
|
||||
entry.FinalizedAt = now;
|
||||
entry.FinalizedBy = actor.UserName;
|
||||
await LedgerStore.SetStatusAsync(uow, entry, GlEntryStatus.Final, cancellationToken).ConfigureAwait(false);
|
||||
done++;
|
||||
}
|
||||
|
||||
foreach (var year in years.Where(y => entries.Any(e => y.StartDate <= e.EntryDate && y.EndDate >= e.EntryDate)))
|
||||
{
|
||||
await uow.Repository<FiscalYear, long>().UpdateAsync(year, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
await _fiscal.InvalidateAsync(company, cancellationToken).ConfigureAwait(false);
|
||||
return done;
|
||||
}
|
||||
|
||||
/// <summary>Posts a draft: it must balance.</summary>
|
||||
/// <param name="actor">Who posts.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="id">The entry.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The entry as posted.</returns>
|
||||
public async Task<EntryView> PostAsync(Actor actor, string companyCode, long id, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var view = await GetAsync(actor, companyCode, id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(LedgerErrors.NotFound);
|
||||
var e = view.Entry;
|
||||
return await SaveAsync(actor, companyCode, new EntryInput(e.Id, e.EntryDate, e.Description, [.. view.Lines.Select(Draft)])
|
||||
{
|
||||
JournalTemplateId = e.JournalTemplateId,
|
||||
CompetenceDate = e.CompetenceDate,
|
||||
DocumentNumber = e.DocumentNumber,
|
||||
DocumentDate = e.DocumentDate,
|
||||
PartyId = e.PartyId,
|
||||
VatRegisterId = e.VatRegisterId,
|
||||
VatDate = e.VatDate,
|
||||
Vat = [.. view.Vat.Select(Draft)],
|
||||
Notes = e.Notes,
|
||||
Post = true,
|
||||
}, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>A line of an entry as a draft line.</summary>
|
||||
/// <param name="line">The line.</param>
|
||||
/// <returns>The draft.</returns>
|
||||
public static EntryLineDraft Draft(GlEntryLine line)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(line);
|
||||
return new EntryLineDraft(line.AccountId, line.PartyId, line.Description, line.Debit, line.Credit, line.CostCenterId, line.JobId);
|
||||
}
|
||||
|
||||
/// <summary>A VAT line of an entry as a draft line.</summary>
|
||||
/// <param name="line">The line.</param>
|
||||
/// <returns>The draft.</returns>
|
||||
public static EntryVatDraft Draft(GlEntryVat line)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(line);
|
||||
return new EntryVatDraft(line.TaxCodeId, line.Rate, line.Nature, line.Taxable, line.Tax, line.NonDeductibleTax, line.Exigibility, line.VatRegisterId);
|
||||
}
|
||||
|
||||
/// <summary>Writes the reversal of an entry in the open transaction.</summary>
|
||||
internal static async Task<GlEntry> ReverseAsync(IUnitOfWork uow, GlEntry entry, DateOnly date, string? userName, CancellationToken cancellationToken)
|
||||
{
|
||||
if (entry.ReversedById is not null)
|
||||
{
|
||||
throw new ValidationFailedException(["Id:" + LedgerErrors.AlreadyReversed]);
|
||||
}
|
||||
|
||||
if (entry.Status == GlEntryStatus.Draft)
|
||||
{
|
||||
throw new ValidationFailedException(["Status:" + LedgerErrors.NotPosted]);
|
||||
}
|
||||
|
||||
var lines = await LedgerStore.LinesAsync(uow, entry.Id, cancellationToken).ConfigureAwait(false);
|
||||
var vat = await LedgerStore.VatAsync(uow, entry.Id, cancellationToken).ConfigureAwait(false);
|
||||
var reversal = new GlEntry
|
||||
{
|
||||
EntryDate = date < entry.EntryDate ? entry.EntryDate : date,
|
||||
JournalTemplateId = entry.JournalTemplateId,
|
||||
TemplateCode = entry.TemplateCode,
|
||||
Description = LedgerStore.Trim("Storno " + (entry.EntryNumber ?? string.Empty) + " " + entry.Description, 200)!,
|
||||
Status = GlEntryStatus.Posted,
|
||||
Source = GlEntrySource.Reversal,
|
||||
SourceFamily = entry.SourceFamily,
|
||||
SourceDocumentId = entry.SourceDocumentId,
|
||||
SourceKind = entry.SourceKind,
|
||||
DocumentNumber = entry.DocumentNumber,
|
||||
DocumentDate = entry.DocumentDate,
|
||||
PartyId = entry.PartyId,
|
||||
VatRegisterId = entry.VatRegisterId,
|
||||
VatProtocol = entry.VatProtocol,
|
||||
VatDate = date < entry.EntryDate ? entry.VatDate : date,
|
||||
ReversalOfId = entry.Id,
|
||||
IsDemo = entry.IsDemo,
|
||||
Notes = userName is null ? null : "Storno di " + userName,
|
||||
};
|
||||
reversal = await LedgerStore.InsertAsync(
|
||||
uow,
|
||||
reversal,
|
||||
[.. lines.Select(l => new EntryLineDraft(l.AccountId, l.PartyId, l.Description, l.Credit, l.Debit, l.CostCenterId, l.JobId))],
|
||||
[.. vat.Select(v => new EntryVatDraft(v.TaxCodeId, v.Rate, v.Nature, -v.Taxable, -v.Tax, -v.NonDeductibleTax, v.Exigibility, v.VatRegisterId))],
|
||||
cancellationToken).ConfigureAwait(false);
|
||||
entry.ReversedById = reversal.Id;
|
||||
await uow.Repository<GlEntry, long>().UpdateAsync(entry, cancellationToken).ConfigureAwait(false);
|
||||
// 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;
|
||||
}
|
||||
|
||||
internal static async Task<EntryView?> ViewAsync(IUnitOfWork uow, long id, CancellationToken cancellationToken)
|
||||
{
|
||||
if (await uow.Repository<GlEntry, long>().GetAsync(id, cancellationToken).ConfigureAwait(false) is not { } entry)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var lines = await LedgerStore.LinesAsync(uow, id, cancellationToken).ConfigureAwait(false);
|
||||
var vat = await LedgerStore.VatAsync(uow, id, cancellationToken).ConfigureAwait(false);
|
||||
var names = await PartyNamesAsync(uow, [entry.PartyId], cancellationToken).ConfigureAwait(false);
|
||||
return new EntryView(entry, lines, vat, entry.PartyId is { } p && names.TryGetValue(p, out var name) ? name : null);
|
||||
}
|
||||
|
||||
internal static async Task<Dictionary<long, string>> PartyNamesAsync(IUnitOfWork uow, IEnumerable<long?> ids, CancellationToken cancellationToken)
|
||||
{
|
||||
var list = ids.Where(i => i is not null).Select(i => i!.Value).Distinct().ToList();
|
||||
if (list.Count == 0)
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
return (await uow.Repository<Party, long>().ListAsync(Query.For<Party>().Where(p => list.Contains(p.Id)), cancellationToken).ConfigureAwait(false)).Items
|
||||
.ToDictionary(p => p.Id, p => p.Name);
|
||||
}
|
||||
|
||||
private static async Task CheckFinalOrderAsync(IUnitOfWork uow, DateOnly date, List<string> errors, CancellationToken cancellationToken)
|
||||
{
|
||||
var year = await uow.Repository<FiscalYear, long>().FindAsync(
|
||||
Query.For<FiscalYear>().Where(y => y.StartDate <= date && y.EndDate >= date), cancellationToken).ConfigureAwait(false);
|
||||
if (year?.LastFinalEntryDate is { } last && date < last)
|
||||
{
|
||||
errors.Add("EntryDate:" + LedgerErrors.FinalOrder);
|
||||
}
|
||||
}
|
||||
|
||||
private static GlEntry Clone(GlEntry entry) => new()
|
||||
{
|
||||
Id = entry.Id,
|
||||
Year = entry.Year,
|
||||
Number = entry.Number,
|
||||
EntryNumber = entry.EntryNumber,
|
||||
JournalNumber = entry.JournalNumber,
|
||||
EntryDate = entry.EntryDate,
|
||||
Description = entry.Description,
|
||||
Status = entry.Status,
|
||||
Source = entry.Source,
|
||||
IsDemo = entry.IsDemo,
|
||||
RowVersion = entry.RowVersion,
|
||||
CreatedAt = entry.CreatedAt,
|
||||
CreatedBy = entry.CreatedBy,
|
||||
UpdatedAt = entry.UpdatedAt,
|
||||
UpdatedBy = entry.UpdatedBy,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,493 @@
|
||||
using Khaemhat.Application.Documents;
|
||||
using Khaemhat.Application.Licensing;
|
||||
using Khaemhat.Application.Modules;
|
||||
using Khaemhat.Application.Security;
|
||||
using Khaemhat.Core.Accounting;
|
||||
using Khaemhat.Core.Documents;
|
||||
using Khaemhat.Core.Items;
|
||||
using Khaemhat.Core.Parties;
|
||||
using Khaemhat.Core.Tables;
|
||||
using Khaemhat.Data;
|
||||
using Khaemhat.Data.Querying;
|
||||
|
||||
namespace Khaemhat.Application.Ledger;
|
||||
|
||||
/// <summary>
|
||||
/// Posts the documents to the ledger (SPEC §11.7, issue #64, ADR 0037) inside the transaction of the document engine,
|
||||
/// like <see cref="Inventory.InventoryPoster"/> does with the warehouse: an invoice, credit note or self-invoice in
|
||||
/// force writes its entry (with the VAT lines of its register, the open items of its installments and its
|
||||
/// withholding); a change writes it again with the same number; a cancelled document loses it, or gets a reversal when
|
||||
/// its entry is already final. Nothing is posted while the module ACCT is not licensed: the documents can be posted
|
||||
/// later in bulk (<see cref="LedgerService.PostPendingAsync"/>).
|
||||
/// </summary>
|
||||
public sealed class LedgerPoster
|
||||
{
|
||||
private readonly ILicenseGate _licence;
|
||||
|
||||
/// <summary>Creates the poster.</summary>
|
||||
/// <param name="licence">The licence (module ACCT).</param>
|
||||
public LedgerPoster(ILicenseGate licence)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(licence);
|
||||
_licence = licence;
|
||||
}
|
||||
|
||||
/// <summary>Whether the documents post to the ledger.</summary>
|
||||
public bool Active => _licence.IsModuleActive(ModuleCodes.Accounting);
|
||||
|
||||
/// <summary>What a kind of document posts, if anything.</summary>
|
||||
/// <param name="kind">The kind.</param>
|
||||
/// <returns>The posting kind and whether the sides are reversed, or <see langword="null"/>.</returns>
|
||||
public static (PostingKind Kind, bool Reverse)? PostingOf(DocumentKind kind) => kind switch
|
||||
{
|
||||
DocumentKind.ImmediateInvoice or DocumentKind.AccompanyingInvoice or DocumentKind.DeferredInvoice or DocumentKind.DownPaymentInvoice
|
||||
or DocumentKind.DebitNote or DocumentKind.Fee => (PostingKind.Sale, false),
|
||||
DocumentKind.CreditNote => (PostingKind.Sale, true),
|
||||
DocumentKind.SelfInvoice => (PostingKind.SelfInvoice, false),
|
||||
DocumentKind.PurchaseInvoice => (PostingKind.Purchase, false),
|
||||
DocumentKind.PurchaseCreditNote => (PostingKind.Purchase, true),
|
||||
_ => null,
|
||||
};
|
||||
|
||||
/// <summary>Writes again the entry of a document from its current state.</summary>
|
||||
/// <param name="uow">The unit of work of the company, in a transaction.</param>
|
||||
/// <param name="family">The family.</param>
|
||||
/// <param name="documentId">The document.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The entry, or <see langword="null"/> when the document posts nothing.</returns>
|
||||
public async Task<GlEntry?> SyncAsync(IUnitOfWork uow, DocumentFamily family, long documentId, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(uow);
|
||||
if (!Active || family is not (DocumentFamily.SaleDocument or DocumentFamily.PurchaseDocument))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
return await PostAsync(uow, family, documentId, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>Posts or removes the entry of a document whatever the licence (bulk posting, tests).</summary>
|
||||
/// <param name="uow">The unit of work of the company, in a transaction.</param>
|
||||
/// <param name="family">The family.</param>
|
||||
/// <param name="documentId">The document.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The entry, or <see langword="null"/>.</returns>
|
||||
internal static async Task<GlEntry?> PostAsync(IUnitOfWork uow, DocumentFamily family, long documentId, CancellationToken cancellationToken)
|
||||
{
|
||||
var store = DocumentStores.Of(family);
|
||||
var header = await store.GetAsync(uow, documentId, cancellationToken).ConfigureAwait(false);
|
||||
var existing = await CurrentEntryAsync(uow, family, documentId, cancellationToken).ConfigureAwait(false);
|
||||
var posting = header is null ? null : PostingOf(header.Kind);
|
||||
if (header is null || posting is null || !DocumentStateMachine.IsInForce(header.Status))
|
||||
{
|
||||
await RemoveAsync(uow, existing, cancellationToken).ConfigureAwait(false);
|
||||
await RemoveWithholdingsAsync(uow, family, documentId, cancellationToken).ConfigureAwait(false);
|
||||
if (header is not null && (header.Posted || header.GlEntryId is not null))
|
||||
{
|
||||
header.Posted = false;
|
||||
header.GlEntryId = null;
|
||||
await store.UpdateAsync(uow, header, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
var built = await BuildAsync(uow, family, header, posting.Value, cancellationToken).ConfigureAwait(false);
|
||||
if (built is null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var (entry, lines, vat) = built.Value;
|
||||
GlEntry result;
|
||||
if (existing is null)
|
||||
{
|
||||
result = await LedgerStore.InsertAsync(uow, entry, lines, vat, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
else if (existing.Status != GlEntryStatus.Final)
|
||||
{
|
||||
Copy(entry, existing);
|
||||
await LedgerStore.UpdateAsync(uow, existing, lines, vat, cancellationToken).ConfigureAwait(false);
|
||||
result = existing;
|
||||
}
|
||||
else if (await SameAsync(uow, existing, lines, cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
return existing;
|
||||
}
|
||||
else
|
||||
{
|
||||
// A final entry never changes: the reversal cancels it and a new entry posts the document as it is now.
|
||||
await JournalEntryService.ReverseAsync(uow, existing, existing.EntryDate, null, cancellationToken).ConfigureAwait(false);
|
||||
result = await LedgerStore.InsertAsync(uow, entry, lines, vat, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
await OpenItemsAsync(uow, family, header, posting.Value, result, lines, cancellationToken).ConfigureAwait(false);
|
||||
await WithholdingAsync(uow, family, header, result, cancellationToken).ConfigureAwait(false);
|
||||
if (!header.Posted || header.GlEntryId != result.Id)
|
||||
{
|
||||
header.Posted = true;
|
||||
header.GlEntryId = result.Id;
|
||||
await store.UpdateAsync(uow, header, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>The entry of a document that is not reversed, if any.</summary>
|
||||
internal static async Task<GlEntry?> CurrentEntryAsync(IUnitOfWork uow, DocumentFamily family, long documentId, CancellationToken cancellationToken)
|
||||
{
|
||||
var entries = (await uow.Repository<GlEntry, long>().ListAsync(
|
||||
Query.For<GlEntry>().Where(e => e.SourceFamily == family && e.SourceDocumentId == documentId && e.Source == GlEntrySource.Document)
|
||||
.OrderByDescending(e => e.Id), cancellationToken).ConfigureAwait(false)).Items;
|
||||
return entries.FirstOrDefault(e => e.ReversedById is null);
|
||||
}
|
||||
|
||||
private static async Task RemoveAsync(IUnitOfWork uow, GlEntry? existing, CancellationToken cancellationToken)
|
||||
{
|
||||
if (existing is null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
else
|
||||
{
|
||||
await LedgerStore.DeleteAsync(uow, existing.Id, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
private static async Task RemoveWithholdingsAsync(IUnitOfWork uow, DocumentFamily family, long documentId, CancellationToken cancellationToken)
|
||||
{
|
||||
var waiting = nameof(WithholdingStatus.Waiting);
|
||||
var suffered = nameof(WithholdingStatus.Suffered);
|
||||
var text = family.ToString();
|
||||
await uow.ExecuteAsync(
|
||||
SqlFragment.Of($"DELETE FROM withholdings WHERE source_family = {text} AND source_document_id = {documentId} AND status IN ({waiting}, {suffered})"),
|
||||
cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private static void Copy(GlEntry from, GlEntry to)
|
||||
{
|
||||
to.EntryDate = from.EntryDate;
|
||||
to.JournalTemplateId = from.JournalTemplateId;
|
||||
to.TemplateCode = from.TemplateCode;
|
||||
to.Description = from.Description;
|
||||
to.SourceKind = from.SourceKind;
|
||||
to.DocumentNumber = from.DocumentNumber;
|
||||
to.DocumentDate = from.DocumentDate;
|
||||
to.PartyId = from.PartyId;
|
||||
to.VatRegisterId = from.VatRegisterId;
|
||||
to.VatProtocol = from.VatProtocol;
|
||||
to.VatDate = from.VatDate;
|
||||
to.IsDemo = from.IsDemo;
|
||||
if (to.Year != from.EntryDate.Year)
|
||||
{
|
||||
// A new year means a new number.
|
||||
to.Number = null;
|
||||
to.EntryNumber = null;
|
||||
}
|
||||
}
|
||||
|
||||
private static async Task<bool> SameAsync(IUnitOfWork uow, GlEntry existing, IReadOnlyList<EntryLineDraft> lines, CancellationToken cancellationToken)
|
||||
{
|
||||
var stored = await LedgerStore.LinesAsync(uow, existing.Id, cancellationToken).ConfigureAwait(false);
|
||||
static string Key(long? account, long? party, decimal debit, decimal credit) => $"{account}|{party}|{debit:0.00}|{credit:0.00}";
|
||||
var left = stored.Select(l => Key(l.AccountId, l.PartyId, l.Debit, l.Credit)).Order(StringComparer.Ordinal);
|
||||
var right = lines.Select(l => Key(l.AccountId, l.PartyId, l.Debit, l.Credit)).Order(StringComparer.Ordinal);
|
||||
return left.SequenceEqual(right, StringComparer.Ordinal);
|
||||
}
|
||||
|
||||
private static async Task<(GlEntry Entry, List<EntryLineDraft> Lines, List<EntryVatDraft> Vat)?> BuildAsync(
|
||||
IUnitOfWork uow, DocumentFamily family, DocumentHeader header, (PostingKind Kind, bool Reverse) posting, CancellationToken cancellationToken)
|
||||
{
|
||||
var type = await uow.Repository<DocumentType, long>().GetAsync(header.DocumentTypeId, cancellationToken).ConfigureAwait(false);
|
||||
var templateCode = type?.JournalTemplateCode ?? DefaultTemplate(posting);
|
||||
if (await LedgerStore.TemplateAsync(uow, templateCode, cancellationToken).ConfigureAwait(false) is not { } found)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var (template, templateLines) = found;
|
||||
PartyPurchaseTerms? purchaseTerms = null;
|
||||
if (posting.Kind == PostingKind.Purchase && header.PartyId is { } supplierId)
|
||||
{
|
||||
purchaseTerms = await uow.Repository<PartyPurchaseTerms, long>().FindAsync(
|
||||
Query.For<PartyPurchaseTerms>().Where(t => t.PartyId == supplierId), cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
var registerCode = purchaseTerms?.VatRegisterCode ?? type?.VatRegisterCode ?? template.VatRegisterCode;
|
||||
var register = await LedgerStore.RegisterAsync(uow, registerCode, cancellationToken).ConfigureAwait(false);
|
||||
var accounts = (await uow.Repository<GlAccount, long>().ListAsync(Query.For<GlAccount>(), cancellationToken).ConfigureAwait(false)).Items;
|
||||
var byCode = accounts.ToDictionary(a => a.Code, StringComparer.Ordinal);
|
||||
long? Of(string? code) => code is not null && byCode.TryGetValue(code, out var account) && account.Postable ? account.Id : null;
|
||||
long? Role(PostingRole role) => templateLines.FirstOrDefault(l => l.Role == role && l.AccountId is not null)?.AccountId;
|
||||
|
||||
var party = header.PartyId is { } partyId ? await uow.Repository<Party, long>().GetAsync(partyId, cancellationToken).ConfigureAwait(false) : null;
|
||||
var record = await DocumentEngine.LoadAsync(uow, family, header.Id, cancellationToken).ConfigureAwait(false);
|
||||
if (record is null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var sale = posting.Kind == PostingKind.Sale;
|
||||
var items = await ItemsAsync(uow, record.Lines, cancellationToken).ConfigureAwait(false);
|
||||
var taxCodes = (await uow.Repository<TaxCode, long>().ListAsync(Query.For<TaxCode>(), cancellationToken).ConfigureAwait(false)).Items.ToDictionary(t => t.Id);
|
||||
var inputLines = new List<PostingLineInput>();
|
||||
foreach (var line in record.Lines.Where(l => l.Kind != DocumentLineKind.Description && l.TaxableAmount != 0m))
|
||||
{
|
||||
var item = line.ItemId is { } itemId && items.TryGetValue(itemId, out var found2) ? found2 : null;
|
||||
var tax = line.TaxCodeId is { } taxId && taxCodes.TryGetValue(taxId, out var code) ? code : null;
|
||||
var account = Of(line.AccountCode)
|
||||
?? Of(sale ? item?.RevenueAccountCode : item?.CostAccountCode)
|
||||
?? Of(purchaseTerms?.CostAccountCode)
|
||||
?? Of(sale ? tax?.SalesAccountCode : tax?.PurchaseAccountCode);
|
||||
inputLines.Add(new PostingLineInput(account, line.TaxableAmount, line.TaxCodeId, line.CostCenterId, line.JobId));
|
||||
}
|
||||
|
||||
var taxes = record.Figures.Summary
|
||||
.Select(s => new PostingTaxInput(s.TaxCodeId, s.Rate, s.Nature, s.Exigibility, s.Taxable, s.Tax, s.NonDeductibleTax))
|
||||
.ToList();
|
||||
var stamp = header.StampDutyCharged ? header.StampDuty : 0m;
|
||||
var total = taxes.Sum(t => t.Taxable) + taxes.Sum(t => t.Tax) + stamp;
|
||||
var partyAccount = posting.Kind switch
|
||||
{
|
||||
PostingKind.Sale => Of(party?.CustomerAccountCode) ?? Role(PostingRole.Customer),
|
||||
PostingKind.Purchase => Of(party?.SupplierAccountCode) ?? Role(PostingRole.Supplier),
|
||||
_ => null,
|
||||
};
|
||||
var accountsOfPosting = new PostingAccounts(
|
||||
partyAccount,
|
||||
Role(sale ? PostingRole.Revenue : PostingRole.Cost),
|
||||
Role(PostingRole.SalesVat),
|
||||
Role(PostingRole.PurchaseVat),
|
||||
Role(PostingRole.StampDuty),
|
||||
Role(PostingRole.SocialSecurity));
|
||||
PostingResult result;
|
||||
try
|
||||
{
|
||||
result = PostingEngine.Post(
|
||||
new PostingInput(posting.Kind, posting.Reverse, header.PartyId, inputLines, taxes, total, stamp, sale ? header.SocialSecurityAmount : 0m),
|
||||
accountsOfPosting);
|
||||
}
|
||||
catch (PostingAccountMissingException exception)
|
||||
{
|
||||
throw new ValidationFailedException("Ledger:" + LedgerErrors.RoleAccountMissing, exception);
|
||||
}
|
||||
|
||||
if (result.Vat.Count > 0 && register is null)
|
||||
{
|
||||
throw new ValidationFailedException(["VatRegisterId:" + LedgerErrors.VatRegisterRequired]);
|
||||
}
|
||||
|
||||
// A self-invoice is annotated also in the purchase register of reverse charge (double annotation, §11.5).
|
||||
VatRegister? purchaseRegister = null;
|
||||
if (posting.Kind == PostingKind.SelfInvoice)
|
||||
{
|
||||
var registers = (await uow.Repository<VatRegister, long>().ListAsync(Query.For<VatRegister>(), cancellationToken).ConfigureAwait(false)).Items;
|
||||
purchaseRegister = registers.FirstOrDefault(r => r.Kind == VatRegisterKind.Purchases && r.ReverseCharge && !r.Disabled)
|
||||
?? registers.FirstOrDefault(r => r.Kind == VatRegisterKind.Purchases && !r.Disabled);
|
||||
}
|
||||
|
||||
var purchase = family == DocumentFamily.PurchaseDocument;
|
||||
var documentNumber = purchase ? header.ExternalReference ?? header.DocumentNumber : header.DocumentNumber;
|
||||
var documentDate = purchase ? header.ExternalDate ?? header.DocumentDate : header.DocumentDate;
|
||||
var entryDate = purchase ? header.VatDate ?? header.DocumentDate : header.DocumentDate;
|
||||
var entry = new GlEntry
|
||||
{
|
||||
EntryDate = entryDate,
|
||||
JournalTemplateId = template.Id,
|
||||
TemplateCode = template.Code,
|
||||
Description = LedgerStore.Trim(Describe(template.Description, documentNumber, documentDate, party), 200)!,
|
||||
Status = GlEntryStatus.Posted,
|
||||
Source = GlEntrySource.Document,
|
||||
SourceFamily = family,
|
||||
SourceDocumentId = header.Id,
|
||||
SourceKind = header.Kind,
|
||||
DocumentNumber = LedgerStore.Trim(documentNumber, 30),
|
||||
DocumentDate = documentDate,
|
||||
PartyId = header.PartyId,
|
||||
VatRegisterId = result.Vat.Count > 0 ? register?.Id : null,
|
||||
VatProtocol = purchase ? header.VatProtocol ?? header.Number : header.Number,
|
||||
VatDate = header.VatDate ?? entryDate,
|
||||
IsDemo = header.IsDemo,
|
||||
};
|
||||
var description = LedgerStore.Trim(documentNumber is null ? template.Description : template.Description + " " + documentNumber, 200);
|
||||
var lines = result.Lines
|
||||
.Select(l => new EntryLineDraft(l.AccountId, l.PartyId, description, l.Debit, l.Credit, l.CostCenterId, l.JobId))
|
||||
.ToList();
|
||||
var vat = result.Vat
|
||||
.Select(v => new EntryVatDraft(
|
||||
v.Tax.TaxCodeId, v.Tax.Rate, v.Tax.Nature, v.Tax.Taxable, v.Tax.Tax, v.Tax.NonDeductibleTax, v.Tax.Exigibility,
|
||||
v.RegisterKind == VatRegisterKind.Purchases && purchaseRegister is not null ? purchaseRegister.Id : register?.Id))
|
||||
.ToList();
|
||||
return (entry, lines, vat);
|
||||
}
|
||||
|
||||
private static string DefaultTemplate((PostingKind Kind, bool Reverse) posting) => posting switch
|
||||
{
|
||||
(PostingKind.Sale, false) => "FV",
|
||||
(PostingKind.Sale, true) => "NCV",
|
||||
(PostingKind.Purchase, false) => "FA",
|
||||
(PostingKind.Purchase, true) => "NCA",
|
||||
_ => "AFRC",
|
||||
};
|
||||
|
||||
private static string Describe(string template, string? number, DateOnly date, Party? party)
|
||||
{
|
||||
var text = template;
|
||||
if (number is not null)
|
||||
{
|
||||
text += " n. " + number;
|
||||
}
|
||||
|
||||
text += " del " + date.ToString("dd/MM/yyyy", System.Globalization.CultureInfo.InvariantCulture);
|
||||
if (party is not null)
|
||||
{
|
||||
text += " - " + party.Name;
|
||||
}
|
||||
|
||||
return text;
|
||||
}
|
||||
|
||||
private static async Task<Dictionary<long, Item>> ItemsAsync(IUnitOfWork uow, IReadOnlyList<DocumentLine> lines, CancellationToken cancellationToken)
|
||||
{
|
||||
var ids = lines.Where(l => l.ItemId is not null).Select(l => l.ItemId!.Value).Distinct().ToList();
|
||||
if (ids.Count == 0)
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
return (await uow.Repository<Item, long>().ListAsync(Query.For<Item>().Where(i => ids.Contains(i.Id)), cancellationToken).ConfigureAwait(false)).Items.ToDictionary(i => i.Id);
|
||||
}
|
||||
|
||||
private static async Task OpenItemsAsync(
|
||||
IUnitOfWork uow, DocumentFamily family, DocumentHeader header, (PostingKind Kind, bool Reverse) posting, GlEntry entry,
|
||||
IReadOnlyList<EntryLineDraft> lines, CancellationToken cancellationToken)
|
||||
{
|
||||
if (posting.Kind == PostingKind.SelfInvoice || header.PartyId is not { } partyId)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var partyLine = lines.FirstOrDefault(l => l.PartyId == partyId);
|
||||
if (partyLine?.AccountId is not { } accountId)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var installments = (await uow.Repository<DocumentInstallment, long>().ListAsync(
|
||||
Query.For<DocumentInstallment>().Where(i => i.Family == family && i.DocumentId == header.Id).OrderBy(i => i.Number), cancellationToken).ConfigureAwait(false)).Items;
|
||||
var sign = posting.Reverse ? -1m : 1m;
|
||||
var rows = installments.Count > 0
|
||||
? installments.Select(i => (i.Number, i.DueDate, i.Amount, i.PaymentMethodId)).ToList()
|
||||
: [(1, header.DocumentDate, header.NetAmount != 0m ? header.NetAmount : header.TotalAmount, header.PaymentMethodId)];
|
||||
// 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>();
|
||||
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)
|
||||
{
|
||||
var amount = sign * value;
|
||||
var item = current.FirstOrDefault(o => o.Installment == number);
|
||||
if (item is null)
|
||||
{
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
private static async Task WithholdingAsync(IUnitOfWork uow, DocumentFamily family, DocumentHeader header, GlEntry entry, CancellationToken cancellationToken)
|
||||
{
|
||||
await RemoveWithholdingsAsync(uow, family, header.Id, cancellationToken).ConfigureAwait(false);
|
||||
if (header.WithholdingAmount == 0m || header.PartyId is not { } partyId)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var existing = await uow.Repository<Withholding, long>().CountAsync(
|
||||
Query.For<Withholding>().Where(w => w.SourceFamily == family && w.SourceDocumentId == header.Id), cancellationToken).ConfigureAwait(false);
|
||||
if (existing > 0)
|
||||
{
|
||||
// Already due or paid: the payment stays as it was.
|
||||
return;
|
||||
}
|
||||
|
||||
var operated = family == DocumentFamily.PurchaseDocument;
|
||||
var sign = header.Kind is DocumentKind.CreditNote or DocumentKind.PurchaseCreditNote ? -1m : 1m;
|
||||
await uow.Repository<Withholding, long>().InsertAsync(new Withholding
|
||||
{
|
||||
Direction = operated ? WithholdingDirection.Operated : WithholdingDirection.Suffered,
|
||||
SourceFamily = family,
|
||||
SourceDocumentId = header.Id,
|
||||
DocumentNumber = entry.DocumentNumber,
|
||||
DocumentDate = entry.DocumentDate ?? header.DocumentDate,
|
||||
PartyId = partyId,
|
||||
WithholdingType = header.WithholdingType,
|
||||
Reason = header.WithholdingReason,
|
||||
Taxable = sign * (header.TaxableAmount - header.SocialSecurityAmount),
|
||||
SocialSecurityFund = header.SocialSecurityFund,
|
||||
SocialSecurityAmount = sign * header.SocialSecurityAmount,
|
||||
Rate = header.WithholdingRate ?? 0m,
|
||||
BasePercent = header.WithholdingBasePercent,
|
||||
Amount = sign * header.WithholdingAmount,
|
||||
Status = operated ? WithholdingStatus.Waiting : WithholdingStatus.Suffered,
|
||||
IsDemo = header.IsDemo,
|
||||
}, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,436 @@
|
||||
using System.Globalization;
|
||||
using Khaemhat.Application.Security;
|
||||
using Khaemhat.Application.Tables;
|
||||
using Khaemhat.Core.Accounting;
|
||||
using Khaemhat.Core.Tables;
|
||||
using Khaemhat.Data;
|
||||
using Khaemhat.Data.Querying;
|
||||
|
||||
namespace Khaemhat.Application.Ledger;
|
||||
|
||||
/// <summary>A movement of an account (or of a party on an account), with the running balance.</summary>
|
||||
/// <param name="EntryId">The entry, for the drill-down.</param>
|
||||
/// <param name="EntryNumber">The number of the entry.</param>
|
||||
/// <param name="EntryDate">The date.</param>
|
||||
/// <param name="Description">The description of the line, or of the entry.</param>
|
||||
/// <param name="DocumentNumber">The number of the document.</param>
|
||||
/// <param name="DocumentDate">The date of the document.</param>
|
||||
/// <param name="TemplateCode">The journal template.</param>
|
||||
/// <param name="AccountCode">The account (when the view is of a party).</param>
|
||||
/// <param name="Debit">The debit.</param>
|
||||
/// <param name="Credit">The credit.</param>
|
||||
/// <param name="Balance">The balance after the movement, debit positive.</param>
|
||||
/// <param name="Status">The state of the entry.</param>
|
||||
public sealed record LedgerMovement(
|
||||
long EntryId, string? EntryNumber, DateOnly EntryDate, string? Description, string? DocumentNumber, DateOnly? DocumentDate, string? TemplateCode, string? AccountCode,
|
||||
decimal Debit, decimal Credit, decimal Balance, GlEntryStatus Status);
|
||||
|
||||
/// <summary>A page of the movements of an account or a party.</summary>
|
||||
/// <param name="Opening">The balance before the period.</param>
|
||||
/// <param name="Movements">The movements of the page.</param>
|
||||
/// <param name="TotalCount">How many movements the period has.</param>
|
||||
/// <param name="TotalDebit">The debits of the period.</param>
|
||||
/// <param name="TotalCredit">The credits of the period.</param>
|
||||
/// <param name="Closing">The balance at the end of the period.</param>
|
||||
public sealed record LedgerPage(decimal Opening, IReadOnlyList<LedgerMovement> Movements, long TotalCount, decimal TotalDebit, decimal TotalCredit, decimal Closing);
|
||||
|
||||
/// <summary>What the movements are asked for.</summary>
|
||||
/// <param name="AccountId">The account; with <paramref name="PartyId"/>, its sub-ledger.</param>
|
||||
/// <param name="PartyId">The customer or supplier (partitario, estratto conto).</param>
|
||||
/// <param name="From">From this day.</param>
|
||||
/// <param name="To">Up to this day.</param>
|
||||
/// <param name="IncludeDrafts">Count the drafts too.</param>
|
||||
/// <param name="Offset">The first movement of the page.</param>
|
||||
/// <param name="Limit">The size of the page.</param>
|
||||
public sealed record LedgerFilter(long? AccountId, long? PartyId, DateOnly From, DateOnly To, bool IncludeDrafts = false, int Offset = 0, int Limit = 50);
|
||||
|
||||
/// <summary>A line of the trial balance.</summary>
|
||||
/// <param name="AccountId">The account.</param>
|
||||
/// <param name="Code">The code.</param>
|
||||
/// <param name="Description">The description.</param>
|
||||
/// <param name="Level">The level (1 mastro, 2 conto, 3 sottoconto).</param>
|
||||
/// <param name="Nature">The nature.</param>
|
||||
/// <param name="Opening">The balance before the period.</param>
|
||||
/// <param name="Debit">The debits of the period.</param>
|
||||
/// <param name="Credit">The credits of the period.</param>
|
||||
/// <param name="Closing">The balance at the end, debit positive.</param>
|
||||
public sealed record TrialBalanceLine(long AccountId, string Code, string Description, int Level, AccountNature Nature, decimal Opening, decimal Debit, decimal Credit, decimal Closing);
|
||||
|
||||
/// <summary>The trial balance of a period.</summary>
|
||||
/// <param name="Lines">The accounts with movements or a balance, with the totals of their parents.</param>
|
||||
/// <param name="TotalDebit">The debits of the period.</param>
|
||||
/// <param name="TotalCredit">The credits of the period.</param>
|
||||
/// <param name="Result">The result of the period (revenues minus costs).</param>
|
||||
public sealed record TrialBalance(IReadOnlyList<TrialBalanceLine> Lines, decimal TotalDebit, decimal TotalCredit, decimal Result)
|
||||
{
|
||||
/// <summary>Whether debits and credits match.</summary>
|
||||
public bool Balanced => TotalDebit == TotalCredit;
|
||||
}
|
||||
|
||||
/// <summary>A party with a balance on the customer or supplier accounts.</summary>
|
||||
/// <param name="PartyId">The party.</param>
|
||||
/// <param name="Name">The name.</param>
|
||||
/// <param name="Debit">The debits.</param>
|
||||
/// <param name="Credit">The credits.</param>
|
||||
/// <param name="Balance">The balance, debit positive.</param>
|
||||
/// <param name="OpenItems">The open items not closed.</param>
|
||||
public sealed record PartyBalance(long PartyId, string Name, decimal Debit, decimal Credit, decimal Balance, int OpenItems);
|
||||
|
||||
/// <summary>
|
||||
/// What the ledger tells (SPEC §11.7, issue #67, mockup 044): the movements of an account (mastrino) and of a customer
|
||||
/// or supplier (partitario, estratto conto) with the running balance and the way to the entry; the open items; the
|
||||
/// trial balance of a period, by cost center too, with the balances of the parents; the general journal (libro
|
||||
/// giornale), provisional or as numbered. All the lists are paged in the database.
|
||||
/// </summary>
|
||||
public sealed class LedgerQueryService
|
||||
{
|
||||
private readonly IUnitOfWorkFactory _factory;
|
||||
private readonly PermissionService _permissions;
|
||||
|
||||
/// <summary>Creates the service.</summary>
|
||||
/// <param name="factory">The units of work.</param>
|
||||
/// <param name="permissions">The permissions.</param>
|
||||
public LedgerQueryService(IUnitOfWorkFactory factory, PermissionService permissions)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(factory);
|
||||
ArgumentNullException.ThrowIfNull(permissions);
|
||||
_factory = factory;
|
||||
_permissions = permissions;
|
||||
}
|
||||
|
||||
/// <summary>The movements of an account or of a party in a period, with the running balance.</summary>
|
||||
/// <param name="actor">Who reads.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="filter">The account or party, the period, the page.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The page.</returns>
|
||||
public async Task<LedgerPage> MovementsAsync(Actor actor, string companyCode, LedgerFilter filter, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(filter);
|
||||
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.EntryRead, cancellationToken).ConfigureAwait(false);
|
||||
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
||||
return await MovementsAsync(uow, filter, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>The customers or suppliers with their balance on the sub-ledger accounts.</summary>
|
||||
/// <param name="actor">Who reads.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="type">Customers or suppliers.</param>
|
||||
/// <param name="to">Up to this day.</param>
|
||||
/// <param name="search">Part of the name.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The parties, by name.</returns>
|
||||
public async Task<IReadOnlyList<PartyBalance>> PartyBalancesAsync(
|
||||
Actor actor, string companyCode, AccountType type, DateOnly to, string? search = null, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.EntryRead, cancellationToken).ConfigureAwait(false);
|
||||
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
||||
var draft = nameof(GlEntryStatus.Draft);
|
||||
var typeText = type.ToString();
|
||||
var direction = (type == AccountType.Suppliers ? OpenItemDirection.Payable : OpenItemDirection.Receivable).ToString();
|
||||
var like = "%" + (search ?? string.Empty).Trim().ToUpperInvariant() + "%";
|
||||
var rows = await uow.QueryAsync<PartyRow>(SqlFragment.Of($"""
|
||||
SELECT l.party_id AS party_id, p.name AS name, SUM(l.debit) AS debit, SUM(l.credit) AS credit,
|
||||
(SELECT COUNT(*) FROM gl_open_items o WHERE o.party_id = l.party_id AND o.direction = {direction} AND o.closed = {false}) AS open_items
|
||||
FROM gl_entry_lines l JOIN gl_accounts a ON a.id = l.account_id JOIN parties p ON p.id = l.party_id
|
||||
WHERE a.type = {typeText} AND l.status <> {draft} AND l.entry_date <= {to} AND UPPER(p.name) LIKE {like}
|
||||
GROUP BY l.party_id, p.name
|
||||
ORDER BY p.name
|
||||
"""), cancellationToken).ConfigureAwait(false);
|
||||
return [.. rows.Select(r => new PartyBalance(r.PartyId, r.Name, r.Debit ?? 0m, r.Credit ?? 0m, (r.Debit ?? 0m) - (r.Credit ?? 0m), (int)r.OpenItems))];
|
||||
}
|
||||
|
||||
/// <summary>The open items of a party (or of all), by due date.</summary>
|
||||
/// <param name="actor">Who reads.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="partyId">The party, or <see langword="null"/> for all.</param>
|
||||
/// <param name="direction">Receivables or payables.</param>
|
||||
/// <param name="includeClosed">Show the closed items too.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The items.</returns>
|
||||
public async Task<IReadOnlyList<OpenItem>> OpenItemsAsync(
|
||||
Actor actor, string companyCode, long? partyId, OpenItemDirection direction, bool includeClosed = false, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.EntryRead, cancellationToken).ConfigureAwait(false);
|
||||
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
||||
var query = Query.For<OpenItem>().Where(o => o.Direction == direction);
|
||||
if (partyId is { } id)
|
||||
{
|
||||
query = query.Where(o => o.PartyId == id);
|
||||
}
|
||||
|
||||
if (!includeClosed)
|
||||
{
|
||||
query = query.Where(o => !o.Closed);
|
||||
}
|
||||
|
||||
return (await uow.Repository<OpenItem, long>().ListAsync(query.OrderBy(o => o.DueDate).OrderBy(o => o.Id), cancellationToken).ConfigureAwait(false)).Items;
|
||||
}
|
||||
|
||||
/// <summary>The trial balance of a period (bilancio di verifica), optionally of one cost center.</summary>
|
||||
/// <param name="actor">Who reads.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="from">From this day.</param>
|
||||
/// <param name="to">Up to this day.</param>
|
||||
/// <param name="costCenterId">Only the lines of this cost center.</param>
|
||||
/// <param name="includeDrafts">Count the drafts too.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The trial balance.</returns>
|
||||
public async Task<TrialBalance> TrialBalanceAsync(
|
||||
Actor actor, string companyCode, DateOnly from, DateOnly to, long? costCenterId = null, bool includeDrafts = false, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.EntryRead, cancellationToken).ConfigureAwait(false);
|
||||
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
||||
return await TrialBalanceAsync(uow, from, to, costCenterId, includeDrafts, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>The trial balance as PDF.</summary>
|
||||
/// <param name="actor">Who prints.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="from">From this day.</param>
|
||||
/// <param name="to">Up to this day.</param>
|
||||
/// <param name="costCenterId">Only the lines of this cost center.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The file.</returns>
|
||||
public async Task<LedgerFile> PrintTrialBalanceAsync(Actor actor, string companyCode, DateOnly from, DateOnly to, long? costCenterId = null, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.EntryRead, cancellationToken).ConfigureAwait(false);
|
||||
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
||||
var balance = await TrialBalanceAsync(uow, from, to, costCenterId, includeDrafts: false, cancellationToken).ConfigureAwait(false);
|
||||
var profile = await uow.Repository<CompanyProfile, long>().FindAsync(Query.For<CompanyProfile>(), cancellationToken).ConfigureAwait(false);
|
||||
var center = costCenterId is { } c ? await uow.Repository<CostCenter, long>().GetAsync(c, cancellationToken).ConfigureAwait(false) : null;
|
||||
var rows = new List<IReadOnlyList<string?>>();
|
||||
foreach (var line in balance.Lines)
|
||||
{
|
||||
var bold = line.Level < 3 ? "**" : string.Empty;
|
||||
rows.Add([
|
||||
bold + line.Code, new string(' ', (line.Level - 1) * 2) + line.Description, LedgerReport.Money(line.Opening), LedgerReport.Money(line.Debit),
|
||||
LedgerReport.Money(line.Credit), line.Closing > 0m ? LedgerReport.Money(line.Closing) : null, line.Closing < 0m ? LedgerReport.Money(-line.Closing) : null,
|
||||
]);
|
||||
}
|
||||
|
||||
rows.Add(["**Totali", null, null, LedgerReport.Money(balance.TotalDebit), LedgerReport.Money(balance.TotalCredit), null, null]);
|
||||
rows.Add(["**Risultato", balance.Result >= 0m ? "Utile del periodo" : "Perdita del periodo", null, null, null, null, LedgerReport.Money(Math.Abs(balance.Result))]);
|
||||
var (file, _) = await LedgerReport.WriteAsync(
|
||||
VatService.CompanyLine(profile),
|
||||
"Bilancio di verifica" + (center is null ? string.Empty : " - centro di costo " + center.Code + " " + center.Description),
|
||||
"Dal " + LedgerReport.Date(from) + " al " + LedgerReport.Date(to),
|
||||
[new("Conto", 70), new("Descrizione", 260), new("Saldo iniziale", 85, true), new("Dare", 85, true), new("Avere", 85, true), new("Saldo dare", 85, true),
|
||||
new("Saldo avere", 85, true)],
|
||||
rows,
|
||||
to.Year,
|
||||
1,
|
||||
cancellationToken).ConfigureAwait(false);
|
||||
return new LedgerFile(string.Create(CultureInfo.InvariantCulture, $"bilancio_verifica_{from:yyyyMMdd}_{to:yyyyMMdd}.pdf"), Infrastructure.Files.PdfWriter.MediaType, file);
|
||||
}
|
||||
|
||||
/// <summary>The movements of an account or party as PDF (mastrino, estratto conto).</summary>
|
||||
/// <param name="actor">Who prints.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="filter">The account or party and the period (the page is ignored).</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The file.</returns>
|
||||
public async Task<LedgerFile> PrintMovementsAsync(Actor actor, string companyCode, LedgerFilter filter, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(filter);
|
||||
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.EntryRead, cancellationToken).ConfigureAwait(false);
|
||||
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
||||
var page = await MovementsAsync(uow, filter with { Offset = 0, Limit = 100_000 }, cancellationToken).ConfigureAwait(false);
|
||||
var profile = await uow.Repository<CompanyProfile, long>().FindAsync(Query.For<CompanyProfile>(), cancellationToken).ConfigureAwait(false);
|
||||
var account = filter.AccountId is { } a ? await uow.Repository<GlAccount, long>().GetAsync(a, cancellationToken).ConfigureAwait(false) : null;
|
||||
var party = filter.PartyId is { } p ? await uow.Repository<Core.Parties.Party, long>().GetAsync(p, cancellationToken).ConfigureAwait(false) : null;
|
||||
var title = party is not null ? "Estratto conto " + party.Name : "Mastrino " + account?.Code + " " + account?.Description;
|
||||
var rows = new List<IReadOnlyList<string?>> { new[] { "**Saldo iniziale", null, null, null, null, null, Signed(page.Opening) } };
|
||||
foreach (var m in page.Movements)
|
||||
{
|
||||
rows.Add([LedgerReport.Date(m.EntryDate), m.EntryNumber, m.DocumentNumber, m.Description, LedgerReport.Money(m.Debit), LedgerReport.Money(m.Credit), Signed(m.Balance)]);
|
||||
}
|
||||
|
||||
rows.Add(["**Totali", null, null, null, LedgerReport.Money(page.TotalDebit), LedgerReport.Money(page.TotalCredit), Signed(page.Closing)]);
|
||||
var (file, _) = await LedgerReport.WriteAsync(
|
||||
VatService.CompanyLine(profile), title, "Dal " + LedgerReport.Date(filter.From) + " al " + LedgerReport.Date(filter.To),
|
||||
[new("Data", 55), new("Registrazione", 70), new("Documento", 80), new("Descrizione", 300), new("Dare", 80, true), new("Avere", 80, true), new("Saldo", 90, true)],
|
||||
rows, filter.To.Year, 1, cancellationToken).ConfigureAwait(false);
|
||||
return new LedgerFile(
|
||||
string.Create(CultureInfo.InvariantCulture, $"{(party is not null ? "estratto_conto_" + party.Code : "mastrino_" + account?.Code)}_{filter.To:yyyyMMdd}.pdf"),
|
||||
Infrastructure.Files.PdfWriter.MediaType,
|
||||
file);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The general journal (libro giornale) of a period: every entry in date order with its lines. The provisional
|
||||
/// print shows the posted entries too; the final one only the final entries, with their journal numbers and the
|
||||
/// pages numbered from the first page of the year.
|
||||
/// </summary>
|
||||
/// <param name="actor">Who prints.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="from">From this day.</param>
|
||||
/// <param name="to">Up to this day.</param>
|
||||
/// <param name="final">Only the final entries.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The file.</returns>
|
||||
public async Task<LedgerFile> PrintJournalAsync(Actor actor, string companyCode, DateOnly from, DateOnly to, bool final = false, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.EntryRead, cancellationToken).ConfigureAwait(false);
|
||||
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
||||
var profile = await uow.Repository<CompanyProfile, long>().FindAsync(Query.For<CompanyProfile>(), cancellationToken).ConfigureAwait(false);
|
||||
var fiscalYear = await uow.Repository<FiscalYear, long>().FindAsync(Query.For<FiscalYear>().Where(y => y.StartDate <= to && y.EndDate >= to), cancellationToken).ConfigureAwait(false);
|
||||
var draft = nameof(GlEntryStatus.Draft);
|
||||
var finalText = nameof(GlEntryStatus.Final);
|
||||
var condition = final ? SqlFragment.Of($"e.status = {finalText}") : SqlFragment.Of($"e.status <> {draft}");
|
||||
var lines = await uow.QueryAsync<JournalRow>(SqlFragment.Of($"""
|
||||
SELECT e.id AS entry_id, e.entry_number AS entry_number, e.journal_number AS journal_number, e.entry_date AS entry_date, e.description AS entry_description,
|
||||
e.document_number AS document_number, a.code AS account_code, a.description AS account_description, p.name AS party_name,
|
||||
l.description AS description, l.debit AS debit, l.credit AS credit
|
||||
FROM gl_entries e JOIN gl_entry_lines l ON l.entry_id = e.id JOIN gl_accounts a ON a.id = l.account_id LEFT JOIN parties p ON p.id = l.party_id
|
||||
WHERE e.entry_date >= {from} AND e.entry_date <= {to} AND {condition}
|
||||
ORDER BY e.entry_date, e.journal_number, e.number, e.id, l.line_number
|
||||
"""), cancellationToken).ConfigureAwait(false);
|
||||
var rows = new List<IReadOnlyList<string?>>();
|
||||
long? current = null;
|
||||
foreach (var line in lines)
|
||||
{
|
||||
if (line.EntryId != current)
|
||||
{
|
||||
current = line.EntryId;
|
||||
rows.Add([
|
||||
"**" + LedgerReport.Date(line.EntryDate), line.JournalNumber?.ToString(CultureInfo.InvariantCulture) ?? line.EntryNumber, null,
|
||||
line.EntryDescription + (line.DocumentNumber is { Length: > 0 } d ? " - doc. " + d : string.Empty), null, null,
|
||||
]);
|
||||
}
|
||||
|
||||
rows.Add([null, null, line.AccountCode, line.AccountDescription + (line.PartyName is { Length: > 0 } n ? " - " + n : string.Empty) + (line.Description is { Length: > 0 } t && t != line.EntryDescription ? " (" + t + ")" : string.Empty),
|
||||
LedgerReport.Money(line.Debit), LedgerReport.Money(line.Credit)]);
|
||||
}
|
||||
|
||||
rows.Add(["**Totali del periodo", null, null, null, LedgerReport.Money(lines.Sum(l => l.Debit)), LedgerReport.Money(lines.Sum(l => l.Credit))]);
|
||||
var (file, _) = await LedgerReport.WriteAsync(
|
||||
VatService.CompanyLine(profile),
|
||||
"Libro giornale",
|
||||
(final ? "Registrazioni definitive" : "Stampa provvisoria") + " dal " + LedgerReport.Date(from) + " al " + LedgerReport.Date(to),
|
||||
[new("Data", 60), new("Numero", 65), new("Conto", 65), new("Descrizione", 400), new("Dare", 90, true), new("Avere", 90, true)],
|
||||
rows,
|
||||
to.Year,
|
||||
final ? Math.Max(1, fiscalYear?.JournalFirstPage ?? 1) : 1,
|
||||
cancellationToken).ConfigureAwait(false);
|
||||
return new LedgerFile(
|
||||
string.Create(CultureInfo.InvariantCulture, $"libro_giornale_{from:yyyyMMdd}_{to:yyyyMMdd}{(final ? "_definitivo" : "_provvisorio")}.pdf"),
|
||||
Infrastructure.Files.PdfWriter.MediaType,
|
||||
file);
|
||||
}
|
||||
|
||||
/// <summary>The movements of an account or party, paged in the database, with the running balance.</summary>
|
||||
internal static async Task<LedgerPage> MovementsAsync(IUnitOfWork uow, LedgerFilter filter, CancellationToken cancellationToken)
|
||||
{
|
||||
if (filter.AccountId is null && filter.PartyId is null)
|
||||
{
|
||||
throw new ValidationFailedException(["AccountId:" + LedgerErrors.AccountRequired]);
|
||||
}
|
||||
|
||||
var where = Condition(filter);
|
||||
var from = filter.From;
|
||||
var to = filter.To;
|
||||
var opening = await uow.QuerySingleAsync<decimal?>(SqlFragment.Of($"SELECT SUM(l.debit - l.credit) FROM gl_entry_lines l WHERE {where} AND l.entry_date < {from}"), cancellationToken)
|
||||
.ConfigureAwait(false) ?? 0m;
|
||||
var totals = (await uow.QueryAsync<TotalsRow>(SqlFragment.Of($"""
|
||||
SELECT COUNT(*) AS lines, SUM(l.debit) AS debit, SUM(l.credit) AS credit FROM gl_entry_lines l
|
||||
WHERE {where} AND l.entry_date >= {from} AND l.entry_date <= {to}
|
||||
"""), cancellationToken).ConfigureAwait(false))[0];
|
||||
var offset = Math.Max(0, filter.Offset);
|
||||
var limit = Math.Clamp(filter.Limit, 1, 100_000);
|
||||
var before = offset == 0
|
||||
? 0m
|
||||
: await uow.QuerySingleAsync<decimal?>(SqlFragment.Of($"""
|
||||
SELECT SUM(x.amount) FROM (
|
||||
SELECT l.debit - l.credit AS amount FROM gl_entry_lines l JOIN gl_entries e ON e.id = l.entry_id
|
||||
WHERE {where} AND l.entry_date >= {from} AND l.entry_date <= {to}
|
||||
ORDER BY l.entry_date, e.number, l.entry_id, l.line_number LIMIT {offset}) x
|
||||
"""), cancellationToken).ConfigureAwait(false) ?? 0m;
|
||||
var rows = await uow.QueryAsync<MovementRow>(SqlFragment.Of($"""
|
||||
SELECT l.entry_id AS entry_id, e.entry_number AS entry_number, l.entry_date AS entry_date, COALESCE(l.description, e.description) AS description,
|
||||
e.document_number AS document_number, e.document_date AS document_date, e.template_code AS template_code, a.code AS account_code,
|
||||
l.debit AS debit, l.credit AS credit, l.status AS status
|
||||
FROM gl_entry_lines l JOIN gl_entries e ON e.id = l.entry_id JOIN gl_accounts a ON a.id = l.account_id
|
||||
WHERE {where} AND l.entry_date >= {from} AND l.entry_date <= {to}
|
||||
ORDER BY l.entry_date, e.number, l.entry_id, l.line_number
|
||||
LIMIT {limit} OFFSET {offset}
|
||||
"""), cancellationToken).ConfigureAwait(false);
|
||||
var balance = opening + before;
|
||||
var movements = new List<LedgerMovement>(rows.Count);
|
||||
foreach (var r in rows)
|
||||
{
|
||||
balance += r.Debit - r.Credit;
|
||||
movements.Add(new LedgerMovement(r.EntryId, r.EntryNumber, r.EntryDate, r.Description, r.DocumentNumber, r.DocumentDate, r.TemplateCode, r.AccountCode, r.Debit, r.Credit, balance, r.Status));
|
||||
}
|
||||
|
||||
var debit = totals.Debit ?? 0m;
|
||||
var credit = totals.Credit ?? 0m;
|
||||
return new LedgerPage(opening, movements, totals.Lines, debit, credit, opening + debit - credit);
|
||||
}
|
||||
|
||||
/// <summary>The trial balance, with the totals of the parent accounts.</summary>
|
||||
internal static async Task<TrialBalance> TrialBalanceAsync(IUnitOfWork uow, DateOnly from, DateOnly to, long? costCenterId, bool includeDrafts, CancellationToken cancellationToken)
|
||||
{
|
||||
var draft = nameof(GlEntryStatus.Draft);
|
||||
var status = includeDrafts ? SqlFragment.Literal("1 = 1") : SqlFragment.Of($"l.status <> {draft}");
|
||||
var center = costCenterId is { } c ? SqlFragment.Of($"l.cost_center_id = {c}") : SqlFragment.Literal("1 = 1");
|
||||
var sums = await uow.QueryAsync<BalanceRow>(SqlFragment.Of($"""
|
||||
SELECT l.account_id AS account_id,
|
||||
SUM(CASE WHEN l.entry_date < {from} THEN l.debit - l.credit ELSE 0 END) AS opening,
|
||||
SUM(CASE WHEN l.entry_date >= {from} THEN l.debit ELSE 0 END) AS debit,
|
||||
SUM(CASE WHEN l.entry_date >= {from} THEN l.credit ELSE 0 END) AS credit
|
||||
FROM gl_entry_lines l
|
||||
WHERE l.entry_date <= {to} AND {status} AND {center}
|
||||
GROUP BY l.account_id
|
||||
"""), cancellationToken).ConfigureAwait(false);
|
||||
var accounts = await LedgerStore.AccountsAsync(uow, cancellationToken).ConfigureAwait(false);
|
||||
var totals = new Dictionary<long, (decimal Opening, decimal Debit, decimal Credit)>();
|
||||
foreach (var s in sums)
|
||||
{
|
||||
var id = (long?)s.AccountId;
|
||||
while (id is { } current && accounts.TryGetValue(current, out var account))
|
||||
{
|
||||
totals.TryGetValue(current, out var t);
|
||||
totals[current] = (t.Opening + (s.Opening ?? 0m), t.Debit + (s.Debit ?? 0m), t.Credit + (s.Credit ?? 0m));
|
||||
id = account.ParentId;
|
||||
}
|
||||
}
|
||||
|
||||
var lines = totals
|
||||
.Select(kv => (Account: accounts[kv.Key], kv.Value))
|
||||
.Where(x => x.Value.Opening != 0m || x.Value.Debit != 0m || x.Value.Credit != 0m)
|
||||
.OrderBy(x => x.Account.Code, StringComparer.Ordinal)
|
||||
.Select(x => new TrialBalanceLine(
|
||||
x.Account.Id, x.Account.Code, x.Account.Description, x.Account.Level, x.Account.Nature, x.Value.Opening, x.Value.Debit, x.Value.Credit,
|
||||
x.Value.Opening + x.Value.Debit - x.Value.Credit))
|
||||
.ToList();
|
||||
var leaves = lines.Where(l => accounts[l.AccountId].Postable).ToList();
|
||||
var result = -leaves.Where(l => l.Nature is AccountNature.Revenue or AccountNature.Cost).Sum(l => l.Debit - l.Credit);
|
||||
return new TrialBalance(lines, leaves.Sum(l => l.Debit), leaves.Sum(l => l.Credit), result);
|
||||
}
|
||||
|
||||
private static SqlFragment Condition(LedgerFilter filter)
|
||||
{
|
||||
var draft = nameof(GlEntryStatus.Draft);
|
||||
var status = filter.IncludeDrafts ? SqlFragment.Literal("1 = 1") : SqlFragment.Of($"l.status <> {draft}");
|
||||
var account = filter.AccountId is { } a ? SqlFragment.Of($"l.account_id = {a}") : SqlFragment.Literal("1 = 1");
|
||||
var party = filter.PartyId is { } p ? SqlFragment.Of($"l.party_id = {p}") : SqlFragment.Literal("1 = 1");
|
||||
return SqlFragment.Of($"{status} AND {account} AND {party}");
|
||||
}
|
||||
|
||||
private static string? Signed(decimal amount) => amount == 0m ? "0,00" : LedgerReport.Money(Math.Abs(amount)) + (amount > 0m ? " D" : " A");
|
||||
|
||||
private sealed record MovementRow(
|
||||
long EntryId, string? EntryNumber, DateOnly EntryDate, string? Description, string? DocumentNumber, DateOnly? DocumentDate, string? TemplateCode, string? AccountCode,
|
||||
decimal Debit, decimal Credit, GlEntryStatus Status);
|
||||
|
||||
private sealed record TotalsRow(long Lines, decimal? Debit, decimal? Credit);
|
||||
|
||||
private sealed record BalanceRow(long AccountId, decimal? Opening, decimal? Debit, decimal? Credit);
|
||||
|
||||
private sealed record PartyRow(long PartyId, string Name, decimal? Debit, decimal? Credit, long OpenItems);
|
||||
|
||||
private sealed record JournalRow(
|
||||
long EntryId, string? EntryNumber, long? JournalNumber, DateOnly EntryDate, string EntryDescription, string? DocumentNumber, string AccountCode, string AccountDescription,
|
||||
string? PartyName, string? Description, decimal Debit, decimal Credit);
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
using System.Globalization;
|
||||
using Khaemhat.Infrastructure.Files;
|
||||
|
||||
namespace Khaemhat.Application.Ledger;
|
||||
|
||||
/// <summary>A column of a ledger print.</summary>
|
||||
/// <param name="Title">The heading.</param>
|
||||
/// <param name="Width">The width in points.</param>
|
||||
/// <param name="Right">Aligned on the right (amounts).</param>
|
||||
public sealed record ReportColumn(string Title, double Width, bool Right = false);
|
||||
|
||||
/// <summary>
|
||||
/// The prints of the ledger (VAT registers, general journal, ledgers, trial balance, issue #65 and #67): A4 landscape,
|
||||
/// the company and the title on every page, the headings repeated, the pages numbered from a first page in the form
|
||||
/// <c>year/page</c> as the final prints of the books want (art. 2215-bis c.c., numbering by year).
|
||||
/// </summary>
|
||||
internal static class LedgerReport
|
||||
{
|
||||
private const double Margin = 28;
|
||||
private const double LineHeight = 11;
|
||||
private static readonly PdfColor Rule = PdfColor.Gray(180);
|
||||
|
||||
/// <summary>Writes a print.</summary>
|
||||
/// <param name="company">The name, VAT number and address of the company.</param>
|
||||
/// <param name="title">The title, such as <c>Registro IVA vendite</c>.</param>
|
||||
/// <param name="subtitle">The period and the kind of print.</param>
|
||||
/// <param name="columns">The columns.</param>
|
||||
/// <param name="rows">The rows; a row whose first cell starts with <c>**</c> is a bold total.</param>
|
||||
/// <param name="year">The year of the page numbers.</param>
|
||||
/// <param name="firstPage">The number of the first page.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The file and the number of pages.</returns>
|
||||
public static async Task<(byte[] File, int Pages)> WriteAsync(
|
||||
string company, string title, string subtitle, IReadOnlyList<ReportColumn> columns, IReadOnlyList<IReadOnlyList<string?>> rows, int year, int firstPage,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
using var buffer = new MemoryStream();
|
||||
int pages;
|
||||
await using (var pdf = new PdfWriter(buffer, new PdfDocumentInfo { Title = title }, leaveOpen: true))
|
||||
{
|
||||
var width = PdfWriter.A4Height;
|
||||
var height = PdfWriter.A4Width;
|
||||
var scale = Math.Min(1d, (width - (2 * Margin)) / Math.Max(1d, columns.Sum(c => c.Width)));
|
||||
PdfPage? page = null;
|
||||
var y = 0d;
|
||||
var number = firstPage;
|
||||
async Task NewPageAsync()
|
||||
{
|
||||
page = await pdf.AddPageAsync(width, height, cancellationToken).ConfigureAwait(false);
|
||||
y = height - Margin;
|
||||
page.DrawText(company, Margin, y, PdfFont.HelveticaBold, 9);
|
||||
page.DrawTextRight(year.ToString(CultureInfo.InvariantCulture) + "/" + number.ToString(CultureInfo.InvariantCulture), width - Margin, y, PdfFont.Helvetica, 9);
|
||||
y -= 14;
|
||||
page.DrawText(title, Margin, y, PdfFont.HelveticaBold, 12);
|
||||
y -= 12;
|
||||
page.DrawText(subtitle, Margin, y, PdfFont.Helvetica, 8.5);
|
||||
y -= 16;
|
||||
var x = Margin;
|
||||
foreach (var column in columns)
|
||||
{
|
||||
var w = column.Width * scale;
|
||||
if (column.Right)
|
||||
{
|
||||
page.DrawTextRight(column.Title, x + w - 2, y, PdfFont.HelveticaBold, 7.5);
|
||||
}
|
||||
else
|
||||
{
|
||||
page.DrawText(column.Title, x + 2, y, PdfFont.HelveticaBold, 7.5);
|
||||
}
|
||||
|
||||
x += w;
|
||||
}
|
||||
|
||||
page.DrawLine(Margin, y - 3, width - Margin, y - 3, 0.6, Rule);
|
||||
y -= LineHeight + 2;
|
||||
number++;
|
||||
}
|
||||
|
||||
await NewPageAsync().ConfigureAwait(false);
|
||||
foreach (var row in rows)
|
||||
{
|
||||
if (y < Margin + LineHeight)
|
||||
{
|
||||
await NewPageAsync().ConfigureAwait(false);
|
||||
}
|
||||
|
||||
var bold = row.Count > 0 && row[0] is { } first && first.StartsWith("**", StringComparison.Ordinal);
|
||||
var font = bold ? PdfFont.HelveticaBold : PdfFont.Helvetica;
|
||||
var x = Margin;
|
||||
for (var i = 0; i < columns.Count; i++)
|
||||
{
|
||||
var w = columns[i].Width * scale;
|
||||
var text = i < row.Count ? row[i] : null;
|
||||
if (i == 0 && bold)
|
||||
{
|
||||
text = text![2..];
|
||||
}
|
||||
|
||||
text = PdfTextLayout.Fit(text, font, 7.5, w - 4);
|
||||
if (columns[i].Right)
|
||||
{
|
||||
page!.DrawTextRight(text, x + w - 2, y, font, 7.5);
|
||||
}
|
||||
else
|
||||
{
|
||||
page!.DrawText(text, x + 2, y, font, 7.5);
|
||||
}
|
||||
|
||||
x += w;
|
||||
}
|
||||
|
||||
if (bold)
|
||||
{
|
||||
page!.DrawLine(Margin, y + LineHeight - 2, width - Margin, y + LineHeight - 2, 0.4, Rule);
|
||||
}
|
||||
|
||||
y -= LineHeight;
|
||||
}
|
||||
|
||||
pages = pdf.PageCount;
|
||||
await pdf.CloseAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
return (buffer.ToArray(), pages);
|
||||
}
|
||||
|
||||
/// <summary>An amount as the prints show it, with the Italian separators.</summary>
|
||||
/// <param name="amount">The amount.</param>
|
||||
/// <returns>The text; empty for zero.</returns>
|
||||
public static string Money(decimal amount) => amount == 0m ? string.Empty : amount.ToString("#,##0.00", Italian);
|
||||
|
||||
/// <summary>A date as the prints show it.</summary>
|
||||
/// <param name="date">The date.</param>
|
||||
/// <returns>The text.</returns>
|
||||
public static string Date(DateOnly? date) => date?.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture) ?? string.Empty;
|
||||
|
||||
private static readonly CultureInfo Italian = CultureInfo.GetCultureInfo("it-IT");
|
||||
}
|
||||
@@ -0,0 +1,508 @@
|
||||
using Khaemhat.Application.Audit;
|
||||
using Khaemhat.Application.Documents;
|
||||
using Khaemhat.Application.ImportExport;
|
||||
using Khaemhat.Application.Security;
|
||||
using Khaemhat.Application.Tables;
|
||||
using Khaemhat.Core.Accounting;
|
||||
using Khaemhat.Core.Documents;
|
||||
using Khaemhat.Data;
|
||||
using Khaemhat.Data.Querying;
|
||||
|
||||
namespace Khaemhat.Application.Ledger;
|
||||
|
||||
/// <summary>An account typed in the chart.</summary>
|
||||
/// <param name="Id">The account, for a change.</param>
|
||||
/// <param name="Code">The code, such as <c>05.01.003</c>.</param>
|
||||
/// <param name="Description">The description.</param>
|
||||
/// <param name="Nature">The statement it ends up in (taken from the parent below the first level).</param>
|
||||
/// <param name="Type">What the automatic postings look for.</param>
|
||||
public sealed record AccountInput(long? Id, string Code, string Description, AccountNature Nature, AccountType Type = AccountType.Generic)
|
||||
{
|
||||
/// <summary>The line of the legal statements.</summary>
|
||||
public string? StatementLine { get; init; }
|
||||
|
||||
/// <summary>The line of the reclassified statements.</summary>
|
||||
public string? Reclassification { get; init; }
|
||||
|
||||
/// <summary>The lines carry a customer or supplier.</summary>
|
||||
public bool SubLedger { get; init; }
|
||||
|
||||
/// <summary>Relevant for VAT.</summary>
|
||||
public bool VatRelevant { get; init; }
|
||||
|
||||
/// <summary>Closed at the year end.</summary>
|
||||
public bool ClosesAutomatically { get; init; } = true;
|
||||
|
||||
/// <summary>No longer used.</summary>
|
||||
public bool Disabled { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>A line of a journal template typed on its screen.</summary>
|
||||
/// <param name="Role">What it stands for.</param>
|
||||
/// <param name="Side">Debit or credit.</param>
|
||||
/// <param name="AccountId">The account.</param>
|
||||
/// <param name="Description">The description proposed.</param>
|
||||
public sealed record TemplateLineInput(PostingRole Role, AccountSide Side, long? AccountId, string? Description);
|
||||
|
||||
/// <summary>A journal template typed on its screen (mockup 043).</summary>
|
||||
/// <param name="Id">The template, for a change.</param>
|
||||
/// <param name="Code">The code.</param>
|
||||
/// <param name="Description">The description.</param>
|
||||
/// <param name="Area">The kind of operations.</param>
|
||||
/// <param name="Lines">The model of the lines.</param>
|
||||
public sealed record TemplateInput(long? Id, string Code, string Description, JournalArea Area, IReadOnlyList<TemplateLineInput> Lines)
|
||||
{
|
||||
/// <summary>The VAT register.</summary>
|
||||
public string? VatRegisterCode { get; init; }
|
||||
|
||||
/// <summary>Opens items of customers or suppliers.</summary>
|
||||
public bool OpensItems { get; init; }
|
||||
|
||||
/// <summary>Reverses the sides (credit notes).</summary>
|
||||
public bool Reverses { get; init; }
|
||||
|
||||
/// <summary>No longer used.</summary>
|
||||
public bool Disabled { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>What a bulk posting did.</summary>
|
||||
/// <param name="Posted">Documents posted or posted again.</param>
|
||||
/// <param name="Failed">Documents that could not be posted, with the reason.</param>
|
||||
public sealed record PostingReport(int Posted, IReadOnlyList<string> Failed);
|
||||
|
||||
/// <summary>
|
||||
/// The chart of accounts and the journal templates (SPEC §11.7, issue #62, mockups 042-043, ADR 0036): three levels
|
||||
/// where only the leaves receive postings, the nature inherited from the mastro, no removal of accounts with postings or
|
||||
/// children; the import of a chart (CSV, XLSX, JSON) through the guided import; the bulk posting of the documents not yet
|
||||
/// posted and the posting again of a period (issue #64).
|
||||
/// </summary>
|
||||
public sealed class LedgerService
|
||||
{
|
||||
private readonly IUnitOfWorkFactory _factory;
|
||||
private readonly PermissionService _permissions;
|
||||
private readonly AuditTrail _audit;
|
||||
|
||||
/// <summary>Creates the service.</summary>
|
||||
/// <param name="factory">The units of work.</param>
|
||||
/// <param name="permissions">The permissions.</param>
|
||||
/// <param name="audit">The history.</param>
|
||||
public LedgerService(IUnitOfWorkFactory factory, PermissionService permissions, AuditTrail audit)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(factory);
|
||||
ArgumentNullException.ThrowIfNull(permissions);
|
||||
ArgumentNullException.ThrowIfNull(audit);
|
||||
_factory = factory;
|
||||
_permissions = permissions;
|
||||
_audit = audit;
|
||||
}
|
||||
|
||||
/// <summary>The chart of accounts, by code.</summary>
|
||||
/// <param name="actor">Who reads.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>Every account.</returns>
|
||||
public async Task<IReadOnlyList<GlAccount>> AccountsAsync(Actor actor, string companyCode, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.EntryRead, cancellationToken).ConfigureAwait(false);
|
||||
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
||||
return [.. (await uow.Repository<GlAccount, long>().ListAsync(Query.For<GlAccount>(), cancellationToken).ConfigureAwait(false)).Items.OrderBy(a => a.Code, StringComparer.Ordinal)];
|
||||
}
|
||||
|
||||
/// <summary>The VAT registers, by code.</summary>
|
||||
/// <param name="actor">Who reads.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>Every register.</returns>
|
||||
public async Task<IReadOnlyList<VatRegister>> RegistersAsync(Actor actor, string companyCode, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.EntryRead, cancellationToken).ConfigureAwait(false);
|
||||
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
||||
// Sales first, then purchases and receipts; the ordinary register before the reverse charge one (enums are stored as text).
|
||||
var registers = (await uow.Repository<VatRegister, long>().ListAsync(Query.For<VatRegister>(), cancellationToken).ConfigureAwait(false)).Items;
|
||||
return [.. registers.OrderBy(r => r.Kind).ThenBy(r => r.ReverseCharge).ThenBy(r => r.Code, StringComparer.Ordinal)];
|
||||
}
|
||||
|
||||
/// <summary>Saves an account: a new one under a leaf with postings is refused, the parent stops being postable.</summary>
|
||||
/// <param name="actor">Who writes.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="input">The account.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The account as saved.</returns>
|
||||
public async Task<GlAccount> SaveAccountAsync(Actor actor, string companyCode, AccountInput input, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(input);
|
||||
ArgumentNullException.ThrowIfNull(actor);
|
||||
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.AccountWrite, cancellationToken).ConfigureAwait(false);
|
||||
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
||||
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
|
||||
var repository = uow.Repository<GlAccount, long>();
|
||||
var code = (input.Code ?? string.Empty).Trim();
|
||||
var errors = new List<string>();
|
||||
var level = AccountCodes.LevelOf(code);
|
||||
if (level == 0)
|
||||
{
|
||||
errors.Add("Code:" + LedgerErrors.AccountCode);
|
||||
}
|
||||
|
||||
if (string.IsNullOrWhiteSpace(input.Description))
|
||||
{
|
||||
errors.Add("Description:" + LedgerErrors.DescriptionRequired);
|
||||
}
|
||||
|
||||
GlAccount? before = null;
|
||||
if (input.Id is { } id)
|
||||
{
|
||||
before = await repository.GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(LedgerErrors.AccountMissing);
|
||||
if (!string.Equals(before.Code, code, StringComparison.Ordinal))
|
||||
{
|
||||
errors.Add("Code:" + LedgerErrors.AccountUsed);
|
||||
}
|
||||
}
|
||||
else if (level > 0 && await repository.FindAsync(Query.For<GlAccount>().Where(a => a.Code == code), cancellationToken).ConfigureAwait(false) is not null)
|
||||
{
|
||||
errors.Add("Code:" + LedgerErrors.AccountDuplicate);
|
||||
}
|
||||
|
||||
GlAccount? parent = null;
|
||||
if (level > 1)
|
||||
{
|
||||
var parentCode = AccountCodes.ParentOf(code);
|
||||
parent = await repository.FindAsync(Query.For<GlAccount>().Where(a => a.Code == parentCode), cancellationToken).ConfigureAwait(false);
|
||||
if (parent is null)
|
||||
{
|
||||
errors.Add("Code:" + LedgerErrors.AccountParent);
|
||||
}
|
||||
else if (before is null && parent.Postable && await UsedAsync(uow, parent.Id, cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
errors.Add("Code:" + LedgerErrors.AccountUsed);
|
||||
}
|
||||
}
|
||||
|
||||
if (errors.Count > 0)
|
||||
{
|
||||
throw new ValidationFailedException(errors);
|
||||
}
|
||||
|
||||
var account = before is null ? new GlAccount { Code = code, Level = level, ParentId = parent?.Id } : Clone(before);
|
||||
account.Description = input.Description.Trim();
|
||||
account.Nature = parent?.Nature ?? input.Nature;
|
||||
account.Type = input.Type;
|
||||
account.StatementLine = LedgerStore.Trim(input.StatementLine?.Trim(), 20);
|
||||
account.Reclassification = LedgerStore.Trim(input.Reclassification?.Trim(), 20);
|
||||
account.SubLedger = input.SubLedger;
|
||||
account.VatRelevant = input.VatRelevant;
|
||||
account.ClosesAutomatically = input.ClosesAutomatically;
|
||||
account.Disabled = input.Disabled;
|
||||
if (before is null)
|
||||
{
|
||||
account.Postable = level > 1;
|
||||
account.Id = await repository.InsertAsync(account, cancellationToken).ConfigureAwait(false);
|
||||
await _audit.RecordAsync(uow, AuditAction.Insert, account.Id, null, account, actor.UserName, cancellationToken).ConfigureAwait(false);
|
||||
if (parent is { Postable: true })
|
||||
{
|
||||
parent.Postable = false;
|
||||
await repository.UpdateAsync(parent, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
await repository.UpdateAsync(account, cancellationToken).ConfigureAwait(false);
|
||||
await _audit.RecordAsync(uow, AuditAction.Update, account.Id, before, account, actor.UserName, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
|
||||
return account;
|
||||
}
|
||||
|
||||
/// <summary>Removes an account without children, postings or use in the templates.</summary>
|
||||
/// <param name="actor">Who removes it.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="id">The account.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>A task.</returns>
|
||||
public async Task DeleteAccountAsync(Actor actor, string companyCode, long id, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(actor);
|
||||
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.AccountWrite, cancellationToken).ConfigureAwait(false);
|
||||
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
||||
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
|
||||
var repository = uow.Repository<GlAccount, long>();
|
||||
var account = await repository.GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(LedgerErrors.AccountMissing);
|
||||
if (await repository.CountAsync(Query.For<GlAccount>().Where(a => a.ParentId == id), cancellationToken).ConfigureAwait(false) > 0)
|
||||
{
|
||||
throw new ValidationFailedException(["Id:" + LedgerErrors.AccountHasChildren]);
|
||||
}
|
||||
|
||||
var inTemplates = await uow.Repository<JournalTemplateLine, long>().CountAsync(Query.For<JournalTemplateLine>().Where(l => l.AccountId == id), cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
if (inTemplates > 0 || await UsedAsync(uow, id, cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
throw new ValidationFailedException(["Id:" + LedgerErrors.AccountUsed]);
|
||||
}
|
||||
|
||||
await repository.DeleteAsync(id, cancellationToken).ConfigureAwait(false);
|
||||
await _audit.RecordAsync(uow, AuditAction.Delete, id, account, (GlAccount?)null, actor.UserName, cancellationToken).ConfigureAwait(false);
|
||||
if (account.ParentId is { } parentId
|
||||
&& await repository.CountAsync(Query.For<GlAccount>().Where(a => a.ParentId == parentId), cancellationToken).ConfigureAwait(false) == 0
|
||||
&& await repository.GetAsync(parentId, cancellationToken).ConfigureAwait(false) is { Level: > 1 } parent)
|
||||
{
|
||||
parent.Postable = true;
|
||||
await repository.UpdateAsync(parent, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>The journal templates with their lines.</summary>
|
||||
/// <param name="actor">Who reads.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>Every template, by code.</returns>
|
||||
public async Task<IReadOnlyList<TemplateView>> TemplatesAsync(Actor actor, string companyCode, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.EntryRead, cancellationToken).ConfigureAwait(false);
|
||||
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
||||
var templates = (await uow.Repository<JournalTemplate, long>().ListAsync(Query.For<JournalTemplate>().OrderBy(t => t.Code), cancellationToken).ConfigureAwait(false)).Items;
|
||||
var lines = (await uow.Repository<JournalTemplateLine, long>().ListAsync(Query.For<JournalTemplateLine>().OrderBy(l => l.SortOrder), cancellationToken).ConfigureAwait(false)).Items;
|
||||
return [.. templates.Select(t => new TemplateView(t, [.. lines.Where(l => l.JournalTemplateId == t.Id)]))];
|
||||
}
|
||||
|
||||
/// <summary>Saves a journal template with its lines.</summary>
|
||||
/// <param name="actor">Who writes.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="input">The template.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The template as saved.</returns>
|
||||
public async Task<TemplateView> SaveTemplateAsync(Actor actor, string companyCode, TemplateInput input, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(input);
|
||||
ArgumentNullException.ThrowIfNull(actor);
|
||||
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.AccountWrite, cancellationToken).ConfigureAwait(false);
|
||||
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
||||
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
|
||||
var repository = uow.Repository<JournalTemplate, long>();
|
||||
var code = (input.Code ?? string.Empty).Trim().ToUpperInvariant();
|
||||
var errors = new List<string>();
|
||||
if (code.Length is 0 or > 10)
|
||||
{
|
||||
errors.Add("Code:" + LedgerErrors.TemplateCode);
|
||||
}
|
||||
|
||||
if (string.IsNullOrWhiteSpace(input.Description))
|
||||
{
|
||||
errors.Add("Description:" + LedgerErrors.DescriptionRequired);
|
||||
}
|
||||
|
||||
var other = await repository.FindAsync(Query.For<JournalTemplate>().Where(t => t.Code == code), cancellationToken).ConfigureAwait(false);
|
||||
if (other is not null && other.Id != input.Id)
|
||||
{
|
||||
errors.Add("Code:" + LedgerErrors.TemplateDuplicate);
|
||||
}
|
||||
|
||||
if (input.VatRegisterCode is { Length: > 0 } registerCode && await LedgerStore.RegisterAsync(uow, registerCode, cancellationToken).ConfigureAwait(false) is null)
|
||||
{
|
||||
errors.Add("VatRegisterCode:" + LedgerErrors.VatRegisterRequired);
|
||||
}
|
||||
|
||||
if (errors.Count > 0)
|
||||
{
|
||||
throw new ValidationFailedException(errors);
|
||||
}
|
||||
|
||||
JournalTemplate? before = input.Id is { } id ? await repository.GetAsync(id, cancellationToken).ConfigureAwait(false) : null;
|
||||
var template = before is null ? new JournalTemplate() : new JournalTemplate { Id = before.Id, RowVersion = before.RowVersion, CreatedAt = before.CreatedAt, CreatedBy = before.CreatedBy, IsDemo = before.IsDemo };
|
||||
template.Code = code;
|
||||
template.Description = input.Description.Trim();
|
||||
template.Area = input.Area;
|
||||
template.VatRegisterCode = string.IsNullOrWhiteSpace(input.VatRegisterCode) ? null : input.VatRegisterCode.Trim();
|
||||
template.OpensItems = input.OpensItems;
|
||||
template.Reverses = input.Reverses;
|
||||
template.Disabled = input.Disabled;
|
||||
if (before is null)
|
||||
{
|
||||
template.Id = await repository.InsertAsync(template, cancellationToken).ConfigureAwait(false);
|
||||
await _audit.RecordAsync(uow, AuditAction.Insert, template.Id, null, template, actor.UserName, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
else
|
||||
{
|
||||
await repository.UpdateAsync(template, cancellationToken).ConfigureAwait(false);
|
||||
await _audit.RecordAsync(uow, AuditAction.Update, template.Id, before, template, actor.UserName, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
var templateId = template.Id;
|
||||
await uow.ExecuteAsync(SqlFragment.Of($"DELETE FROM gl_journal_template_lines WHERE journal_template_id = {templateId}"), cancellationToken).ConfigureAwait(false);
|
||||
var lines = new List<JournalTemplateLine>();
|
||||
for (var i = 0; i < input.Lines.Count; i++)
|
||||
{
|
||||
var line = input.Lines[i];
|
||||
var row = new JournalTemplateLine
|
||||
{
|
||||
JournalTemplateId = templateId,
|
||||
SortOrder = (i + 1) * 10,
|
||||
Role = line.Role,
|
||||
Side = line.Side,
|
||||
AccountId = line.AccountId,
|
||||
Description = LedgerStore.Trim(line.Description, 100),
|
||||
};
|
||||
row.Id = await uow.Repository<JournalTemplateLine, long>().InsertAsync(row, cancellationToken).ConfigureAwait(false);
|
||||
lines.Add(row);
|
||||
}
|
||||
|
||||
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
|
||||
return new TemplateView(template, lines);
|
||||
}
|
||||
|
||||
/// <summary>Removes a template that no entry or document type uses.</summary>
|
||||
/// <param name="actor">Who removes it.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="id">The template.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>A task.</returns>
|
||||
public async Task DeleteTemplateAsync(Actor actor, string companyCode, long id, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(actor);
|
||||
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.AccountWrite, cancellationToken).ConfigureAwait(false);
|
||||
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
||||
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
|
||||
var template = await uow.Repository<JournalTemplate, long>().GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(LedgerErrors.TemplateMissing);
|
||||
var code = template.Code;
|
||||
var entries = await uow.Repository<GlEntry, long>().CountAsync(Query.For<GlEntry>().Where(e => e.JournalTemplateId == id), cancellationToken).ConfigureAwait(false);
|
||||
var types = await uow.Repository<Core.Tables.DocumentType, long>().CountAsync(Query.For<Core.Tables.DocumentType>().Where(t => t.JournalTemplateCode == code), cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
if (entries > 0 || types > 0)
|
||||
{
|
||||
throw new ValidationFailedException(["Id:" + LedgerErrors.TemplateUsed]);
|
||||
}
|
||||
|
||||
await uow.ExecuteAsync(SqlFragment.Of($"DELETE FROM gl_journal_template_lines WHERE journal_template_id = {id}"), cancellationToken).ConfigureAwait(false);
|
||||
await uow.Repository<JournalTemplate, long>().DeleteAsync(id, cancellationToken).ConfigureAwait(false);
|
||||
await _audit.RecordAsync(uow, AuditAction.Delete, id, template, (JournalTemplate?)null, actor.UserName, cancellationToken).ConfigureAwait(false);
|
||||
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Posts the documents in force of a period that have no entry (issue #64: posting in bulk, for instance after the
|
||||
/// module is licensed), or with <paramref name="again"/> writes again the entries that are not final.
|
||||
/// </summary>
|
||||
/// <param name="actor">Who posts.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="from">From this day.</param>
|
||||
/// <param name="to">Up to this day.</param>
|
||||
/// <param name="again">Post again also the documents already posted.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>What was posted.</returns>
|
||||
public async Task<PostingReport> PostPendingAsync(Actor actor, string companyCode, DateOnly from, DateOnly to, bool again = false, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.EntryWrite, cancellationToken).ConfigureAwait(false);
|
||||
var posted = 0;
|
||||
var failed = new List<string>();
|
||||
foreach (var family in new[] { DocumentFamily.SaleDocument, DocumentFamily.PurchaseDocument })
|
||||
{
|
||||
List<DocumentHeader> headers;
|
||||
await using (var read = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
headers = [.. (await DocumentStores.Of(family).InForceAsync(read, cancellationToken).ConfigureAwait(false))
|
||||
.Where(h => h.DocumentDate >= from && h.DocumentDate <= to && LedgerPoster.PostingOf(h.Kind) is not null && (again || !h.Posted))
|
||||
.OrderBy(h => h.DocumentDate).ThenBy(h => h.Id)];
|
||||
}
|
||||
|
||||
foreach (var header in headers)
|
||||
{
|
||||
// One transaction per document: one that cannot post does not stop the others.
|
||||
try
|
||||
{
|
||||
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
||||
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
|
||||
if (await LedgerPoster.PostAsync(uow, family, header.Id, cancellationToken).ConfigureAwait(false) is not null)
|
||||
{
|
||||
posted++;
|
||||
}
|
||||
|
||||
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
catch (ValidationFailedException exception)
|
||||
{
|
||||
failed.Add((header.DocumentNumber ?? header.Id.ToString(System.Globalization.CultureInfo.InvariantCulture)) + ": " + string.Join(", ", exception.Errors));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return new PostingReport(posted, failed);
|
||||
}
|
||||
|
||||
/// <summary>Writes the accounts the import of a chart accepted: new codes are added, existing ones updated.</summary>
|
||||
/// <param name="uow">The unit of work, in a transaction.</param>
|
||||
/// <param name="accounts">The accounts, parents first or in any order.</param>
|
||||
/// <param name="update">Update the accounts that exist.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>For each code, whether it was created (<see langword="true"/>) or updated.</returns>
|
||||
internal static async Task<Dictionary<string, bool>> ImportAsync(IUnitOfWork uow, IReadOnlyList<ImportedAccount> accounts, bool update, CancellationToken cancellationToken)
|
||||
{
|
||||
var repository = uow.Repository<GlAccount, long>();
|
||||
var existing = (await repository.ListAsync(Query.For<GlAccount>(), cancellationToken).ConfigureAwait(false)).Items.ToDictionary(a => a.Code, StringComparer.OrdinalIgnoreCase);
|
||||
var result = new Dictionary<string, bool>(StringComparer.OrdinalIgnoreCase);
|
||||
foreach (var imported in accounts.OrderBy(a => a.Level).ThenBy(a => a.Code, StringComparer.Ordinal))
|
||||
{
|
||||
if (existing.TryGetValue(imported.Code, out var account))
|
||||
{
|
||||
if (!update)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
account.Description = LedgerStore.Trim(imported.Description, 100)!;
|
||||
account.Nature = imported.Nature;
|
||||
account.Type = imported.Type;
|
||||
account.StatementLine = LedgerStore.Trim(imported.StatementLine, 20) ?? account.StatementLine;
|
||||
account.Reclassification = LedgerStore.Trim(imported.Reclassification, 20) ?? account.Reclassification;
|
||||
account.VatRelevant = imported.VatRelevant;
|
||||
account.SubLedger = imported.SubLedger;
|
||||
account.ClosesAutomatically = imported.ClosesAutomatically;
|
||||
account.Disabled = imported.Disabled;
|
||||
await repository.UpdateAsync(account, cancellationToken).ConfigureAwait(false);
|
||||
result[imported.Code] = false;
|
||||
continue;
|
||||
}
|
||||
|
||||
account = new GlAccount
|
||||
{
|
||||
Code = imported.Code,
|
||||
Description = LedgerStore.Trim(imported.Description, 100)!,
|
||||
Level = imported.Level,
|
||||
ParentId = imported.ParentCode is { } parent && existing.TryGetValue(parent, out var found) ? found.Id : null,
|
||||
Nature = imported.Nature,
|
||||
Type = imported.Type,
|
||||
StatementLine = LedgerStore.Trim(imported.StatementLine, 20),
|
||||
Reclassification = LedgerStore.Trim(imported.Reclassification, 20),
|
||||
SubLedger = imported.SubLedger,
|
||||
VatRelevant = imported.VatRelevant,
|
||||
ClosesAutomatically = imported.ClosesAutomatically,
|
||||
Disabled = imported.Disabled,
|
||||
Postable = imported.Postable,
|
||||
};
|
||||
account.Id = await repository.InsertAsync(account, cancellationToken).ConfigureAwait(false);
|
||||
existing[account.Code] = account;
|
||||
result[imported.Code] = true;
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
internal static async Task<bool> UsedAsync(IUnitOfWork uow, long accountId, CancellationToken cancellationToken) =>
|
||||
await uow.Repository<GlEntryLine, long>().CountAsync(Query.For<GlEntryLine>().Where(l => l.AccountId == accountId), cancellationToken).ConfigureAwait(false) > 0;
|
||||
|
||||
private static GlAccount Clone(GlAccount a) => new()
|
||||
{
|
||||
Id = a.Id,
|
||||
Code = a.Code,
|
||||
Level = a.Level,
|
||||
ParentId = a.ParentId,
|
||||
Postable = a.Postable,
|
||||
IsDemo = a.IsDemo,
|
||||
RowVersion = a.RowVersion,
|
||||
CreatedAt = a.CreatedAt,
|
||||
CreatedBy = a.CreatedBy,
|
||||
UpdatedAt = a.UpdatedAt,
|
||||
UpdatedBy = a.UpdatedBy,
|
||||
};
|
||||
}
|
||||