Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e53b14a3c5 | ||
|
|
b323d70f83 | ||
|
|
caa33a2cee | ||
|
|
3dbbaba86e | ||
|
|
c8241a414e | ||
|
|
3401271483 | ||
|
|
a9eda510f2 | ||
|
|
321aae7e81 | ||
|
|
07555de700 | ||
|
|
9bcf8c1082 | ||
|
|
34e196424f | ||
|
|
25f8a7ad30 | ||
|
|
49d2bb166b | ||
|
|
8079d3da69 | ||
|
|
f7c9cf6da8 |
No files matched your search
@@ -7,6 +7,91 @@ un'immagine `gitea.encke-hake.ts.net/balbosoft/khaemhat:X.Y.Z`.
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
## [0.4.0] - 2026-11-12
|
||||
|
||||
M4 — Tabelle, anagrafiche, articoli. Il pacchetto fiscale italiano, il profilo e le tabelle dell'azienda con i dati
|
||||
di base (province, comuni e CAP compresi), clienti, fornitori e contatti, articoli e listini, i codici automatici,
|
||||
l'import/export guidato e i dati di esempio: le prime maschere gestionali vere.
|
||||
|
||||
### Added
|
||||
- Pacchetto fiscale (ADR 0025): `IFiscalPack` con codici IVA, motore delle imposte e calendario fiscale, più funzioni
|
||||
facoltative per paese; `FiscalPackCatalog` sceglie il pacchetto dal paese dell'azienda. Il pacchetto italiano
|
||||
(`IT 2026.2`) porta nature IVA N1-N7, codici IVA di base, code list FatturaPA (specifiche **1.9.1**: TD, MP, TP,
|
||||
RF, ritenute, casse previdenziali), castelletto IVA con arrotondamento sul totale per aliquota, regola del bollo,
|
||||
scadenze IVA mensili e trimestrali con slittamenti di agosto e dei festivi, ritenute, regole di base dei cespiti e
|
||||
codici tributo F24.
|
||||
- Controlli degli identificativi: IBAN (mod 97 e lunghezza per paese), codici a barre EAN/GTIN, e-mail; partita IVA
|
||||
italiana, codice fiscale con calcolo, lettura dei dati e omocodia, codice destinatario SDI per azienda, PA, privato
|
||||
ed estero; `ViesClient` per la verifica delle partite IVA comunitarie (esito *valida*, *non valida* o *servizio
|
||||
non disponibile*).
|
||||
- Tabelle azienda (ADR 0026): 26 tabelle codificate (codici IVA, modalità e condizioni di pagamento con le rate,
|
||||
banche, valute, tipi documento, numeratori, listini, sconti, agenti, depositi, causali di magazzino, unità di misura,
|
||||
vettori, porto, trasporto, causali di trasporto, aspetto dei beni, rese, nazioni, province, comuni, categorie,
|
||||
centri di costo, commesse) con un'unica maschera a `/tabelle/<tabella>`: elenco con filtro attive/disattivate,
|
||||
dettaglio con errori e avvisi, disattivazione al posto dell'eliminazione per le righe usate, export e import CSV
|
||||
tutto o niente, storico e cache condivisa fra istanze. Indice delle tabelle a `/tabelle` e voci nel menu.
|
||||
- Profilo azienda a schede (dati societari, fiscale e SDI, banche, stampa, esercizi, trasmittente e intermediario)
|
||||
con i controlli del pacchetto fiscale; esercizi e mesi con blocco e sblocco; cambi BCE giornalieri (attività di
|
||||
sistema) e cambi manuali.
|
||||
- Dati di base aggiunti alla creazione dell'azienda e a ogni avvio, solo per i codici mancanti: paesi, valute, unità
|
||||
di misura, codici IVA, pagamenti, tipi documento, numeratori, causali, trasporti, deposito, listino ed esercizio in
|
||||
corso. Versione salvata nelle impostazioni dell'azienda (`IT 2026.3`).
|
||||
- Province e comuni dall'elenco ISTAT dei codici dei comuni al 26/02/2026 (ADR 0028, CC BY 4.0): 110 province e
|
||||
7.894 comuni con codice catastale, provincia, regione e codice ISTAT, nei dati di base del pacchetto italiano
|
||||
(`IT 2026.3`), con i CAP di GeoNames (CC BY 4.0) per 7.750 comuni; i mancanti si completano nella tabella
|
||||
*Comuni*. `tools/Khaemhat.PlacesTool` rigenera i due elenchi dai file scaricati.
|
||||
- `scripts/seed.sh --base [--company CODICE]`, incluso nell'immagine in `/app/scripts/`.
|
||||
- Codici automatici (ADR 0027): maschere per clienti, fornitori, lead, articoli, cespiti, opportunità, ticket,
|
||||
contratti e interventi con `{seq:0000}`, `{anno}` e `{categoria}`, anteprima del prossimo codice, codice manuale
|
||||
ammesso o no, progressivi in `code_sequences` assegnati nella transazione del salvataggio (nessun doppione, nessun
|
||||
numero perso se il salvataggio fallisce, codici già presenti saltati).
|
||||
- Compilazione automatica: comune, provincia e regione dal CAP e CAP dal comune, codice fiscale, verifica VIES, ABI,
|
||||
CAB, banca e BIC dall'IBAN, data di consegna sul calendario lavorativo; ogni opzione si spegne nelle preferenze, e
|
||||
il job dei cambi BCE salta le aziende che l'hanno spento. Pagina *Preferenze azienda* (`/tabelle/preferenze`).
|
||||
- Anagrafiche (ADR 0029): clienti, fornitori, prospect e lead in un solo archivio, con tre radar
|
||||
(`/anagrafiche/clienti`, `/fornitori`, `/contatti`) con ricerca, filtri rapidi, disattivazione e riattivazione di
|
||||
più righe, e la scheda a otto schede: dati principali, indirizzi, contatti, condizioni di vendita e di acquisto,
|
||||
fiscale e SDI (fatturazione elettronica, regime IVA, ritenute e casse, dichiarazione d'intento), banche, note e
|
||||
allegati, storico. Controlli del pacchetto fiscale su partita IVA, codice fiscale, codice destinatario e paese, con
|
||||
avvisi che non bloccano (P.IVA doppia, privato senza codice fiscale); codice destinatario proposto per privati ed
|
||||
esteri; verifica VIES al salvataggio e su richiesta; calcolo del codice fiscale; CAP e comune compilati a vicenda.
|
||||
*Converti in cliente* per prospect e lead (nuovo codice, il vecchio resta come codice precedente) e per i fornitori
|
||||
(diventano anche clienti con lo stesso codice). Un'anagrafica usata da altri dati si disattiva invece di cancellarsi.
|
||||
- Dati di esempio delle anagrafiche con `KHAEMHAT_SEED_DEMO=true`: 3 agenti, 12 clienti di ogni tipo soggetto,
|
||||
5 fornitori, 2 prospect e 2 lead, con numeri inventati ma formalmente validi.
|
||||
- Articoli (ADR 0030): radar `/anagrafiche/articoli` con ricerca anche per codice a barre, filtri per tipo,
|
||||
categoria, magazzino e stato, disattivazione e riattivazione; scheda con dati principali, UM alternative, codici
|
||||
alternativi, listini e prezzi netti dei clienti, fornitori con il fornitore abituale, sostitutivi, note e allegati,
|
||||
storico. Codice dalla maschera per categoria, verifica EAN con duplicati bloccati o segnalati secondo le
|
||||
preferenze, NC8, solo le merci a magazzino; costi visibili solo con `items.cost.read` e conservati per chi non li
|
||||
vede; un articolo usato si disattiva invece di cancellarsi.
|
||||
- Listini (ADR 0030): prezzi con data di validità e storico, listino base, listini derivati con ricarico e
|
||||
arrotondamento, griglia `/anagrafiche/listini` articoli x listini con modifica in cella, prezzi netti di un
|
||||
cliente, margine e aggiornamento massivo con anteprima; ricerca del prezzo per i documenti (netto, listino del
|
||||
documento o del cliente, base, articolo) con la fonte e gli sconti del cliente a cascata.
|
||||
- Scheda *Articoli e codici* delle anagrafiche: i codici con cui un cliente o un fornitore chiama i tuoi articoli,
|
||||
trovati dalla ricerca nei suoi documenti.
|
||||
- 120 articoli di esempio con listini *Pubblico* e *Rivenditori*, prezzi dell'anno precedente, fornitori, UM e
|
||||
codici alternativi, sostitutivi e prezzi netti di un cliente; `scripts/seed.sh --demo [--scale N]` carica i dati
|
||||
di esempio da riga di comando e moltiplica il catalogo per le prove di prestazione.
|
||||
- Import/export guidato (ADR 0031) in *Amministrazione → Import / export dati*: CSV (separatore e codifica dedotti),
|
||||
XLSX (lettore interno, primo foglio) e JSON per clienti, fornitori, articoli e prezzi di listino e netti cliente;
|
||||
mappatura automatica delle colonne con alias, validazione riga per riga con le regole della scheda, esiti *nuovo*,
|
||||
*aggiorna*, *avviso*, *errore*, opzioni per codici esistenti o mancanti, VIES e comune da CAP, report errori CSV,
|
||||
esito nel log. Export con le stesse colonne dell'import e modelli vuoti. Giacenze iniziali e piano dei conti (tracciato
|
||||
`codice;descrizione;livello;padre;natura;tipo;voce_cee;riclassifica;flag` e `khaemhat-coa.json`) si verificano
|
||||
già, la scrittura arriva con M6 e M7.
|
||||
|
||||
### Changed
|
||||
- Tabella *Listini*: nuovi campi *Listino base* (uno solo) e *Derivato da*; la migrazione marca come base il listino
|
||||
`BASE` esistente.
|
||||
- Il componente dei passi verticali mette il dettaglio di ogni passo su una riga propria.
|
||||
|
||||
### Known issues
|
||||
- L'azienda demo creata da `KHAEMHAT_SEED_DEMO` ha il profilo vuoto (indirizzo, partita IVA): va compilato prima dei
|
||||
documenti (M5).
|
||||
- Mancano le banche ABI/CAB nei dati di base: non c'è ancora una fonte con licenza compatibile (#45).
|
||||
|
||||
## [0.3.0] - 2026-11-11
|
||||
|
||||
M3 — Framework UI. La shell dell'applicazione, la libreria di componenti `Kh*` con griglie, radar e pagine record, la
|
||||
|
||||
@@ -88,6 +88,11 @@ fermandosi solo per blocchi reali (SDK mancante, credenziali, PNG o dati che sol
|
||||
inglese che dicono *cosa cambia e perché*. Il push su Gitea e le pull request seguono le indicazioni dell'utente;
|
||||
il tag `vX.Y.Z` si crea alla chiusura di ogni milestone (§20).
|
||||
|
||||
**E7 — Versioni 0.x fino al via dell'utente** (sostituisce la colonna versione di §20 per M13 e M14; deciso
|
||||
dall'utente il 2026-11-12). Finché il prodotto è in sviluppo le versioni restano **0.x**: ogni milestone chiude con
|
||||
`v0.<n>.0` (M13 `v0.13.0`, M14 `v0.14.0` e seguenti). La **1.0.0 non si crea** (tag, immagine, release, CHANGELOG)
|
||||
finché l'utente non lo dice esplicitamente. L'icona versionata `icon-v1.0` resta il modello grafico.
|
||||
|
||||
## 4. Vincoli non negoziabili (sintesi di SPEC §1 — leggere l'originale)
|
||||
|
||||
1. C# 14 su .NET 10; JavaScript solo come interop minimo in `wwwroot/js`, senza framework né bundler.
|
||||
|
||||
@@ -43,6 +43,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Khaemhat.LicenseTool", "too
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Khaemhat.DataModelTool", "tools\Khaemhat.DataModelTool\Khaemhat.DataModelTool.csproj", "{7CA26565-5E1A-46AA-A2F7-C38FBADF0E3F}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Khaemhat.PlacesTool", "tools\Khaemhat.PlacesTool\Khaemhat.PlacesTool.csproj", "{04C6CC82-F19E-437A-BDFE-7A6F66E29D2E}"
|
||||
EndProject
|
||||
Global
|
||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||
Debug|Any CPU = Debug|Any CPU
|
||||
@@ -257,6 +259,18 @@ Global
|
||||
{7CA26565-5E1A-46AA-A2F7-C38FBADF0E3F}.Release|x64.Build.0 = Release|Any CPU
|
||||
{7CA26565-5E1A-46AA-A2F7-C38FBADF0E3F}.Release|x86.ActiveCfg = Release|Any CPU
|
||||
{7CA26565-5E1A-46AA-A2F7-C38FBADF0E3F}.Release|x86.Build.0 = Release|Any CPU
|
||||
{04C6CC82-F19E-437A-BDFE-7A6F66E29D2E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{04C6CC82-F19E-437A-BDFE-7A6F66E29D2E}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{04C6CC82-F19E-437A-BDFE-7A6F66E29D2E}.Debug|x64.ActiveCfg = Debug|Any CPU
|
||||
{04C6CC82-F19E-437A-BDFE-7A6F66E29D2E}.Debug|x64.Build.0 = Debug|Any CPU
|
||||
{04C6CC82-F19E-437A-BDFE-7A6F66E29D2E}.Debug|x86.ActiveCfg = Debug|Any CPU
|
||||
{04C6CC82-F19E-437A-BDFE-7A6F66E29D2E}.Debug|x86.Build.0 = Debug|Any CPU
|
||||
{04C6CC82-F19E-437A-BDFE-7A6F66E29D2E}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{04C6CC82-F19E-437A-BDFE-7A6F66E29D2E}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{04C6CC82-F19E-437A-BDFE-7A6F66E29D2E}.Release|x64.ActiveCfg = Release|Any CPU
|
||||
{04C6CC82-F19E-437A-BDFE-7A6F66E29D2E}.Release|x64.Build.0 = Release|Any CPU
|
||||
{04C6CC82-F19E-437A-BDFE-7A6F66E29D2E}.Release|x86.ActiveCfg = Release|Any CPU
|
||||
{04C6CC82-F19E-437A-BDFE-7A6F66E29D2E}.Release|x86.Build.0 = Release|Any CPU
|
||||
EndGlobalSection
|
||||
GlobalSection(SolutionProperties) = preSolution
|
||||
HideSolutionNode = FALSE
|
||||
@@ -279,5 +293,6 @@ Global
|
||||
{FDCAC352-BB40-4B5E-948A-2CDAA48B9E6A} = {0AB3BF05-4346-4AA6-1389-037BE0695223}
|
||||
{4317FFD0-9473-43FD-8543-F80EF9BA812A} = {07C2787E-EAC7-C090-1BA3-A61EC2A24D84}
|
||||
{7CA26565-5E1A-46AA-A2F7-C38FBADF0E3F} = {07C2787E-EAC7-C090-1BA3-A61EC2A24D84}
|
||||
{04C6CC82-F19E-437A-BDFE-7A6F66E29D2E} = {07C2787E-EAC7-C090-1BA3-A61EC2A24D84}
|
||||
EndGlobalSection
|
||||
EndGlobal
|
||||
@@ -65,8 +65,8 @@ ENV ASPNETCORE_ENVIRONMENT=Production \
|
||||
WORKDIR /app
|
||||
COPY --from=build /app ./
|
||||
COPY docker/entrypoint.sh /app/entrypoint.sh
|
||||
COPY scripts/restore-system.sh /app/scripts/restore-system.sh
|
||||
RUN chmod 0755 /app/entrypoint.sh /app/scripts/restore-system.sh \
|
||||
COPY scripts/restore-system.sh scripts/seed.sh /app/scripts/
|
||||
RUN chmod 0755 /app/entrypoint.sh /app/scripts/restore-system.sh /app/scripts/seed.sh \
|
||||
&& install -d -o app -g app -m 0750 /data
|
||||
|
||||
LABEL org.opencontainers.image.title="Khaemhat" \
|
||||
|
||||
@@ -75,6 +75,7 @@ client degli aggiornamenti è `GiteaPackagesClient`.
|
||||
| `Khaemhat.Web` | host ASP.NET Core 10, Blazor Interactive Server, Minimal API, MCP, autenticazione | M0 → M13 |
|
||||
| `tools/Khaemhat.LicenseTool` | CLI per chiavi ed emissione licenze (chiave privata mai nel repository; non distribuito) | M2 |
|
||||
| `tools/Khaemhat.DataModelTool` | rigenera la sezione generata di `docs/DATA-MODEL.md` dalle migrazioni (non distribuito, ADR 0018) | M1 |
|
||||
| `tools/Khaemhat.PlacesTool` | rigenera province e comuni del pacchetto italiano dall'elenco ISTAT e dai CAP GeoNames (non distribuito, ADR 0028) | M4 |
|
||||
| `tests/*` | `Core`, `Data`, `Infrastructure`, `Fiscal.Italy`, `Application`, `Web` (MSTest) | ogni milestone |
|
||||
|
||||
## 3. Regole di dipendenza
|
||||
@@ -380,7 +381,7 @@ Khaemhat/
|
||||
│ └── Khaemhat.Web/ Program.cs Configuration/ Auth/ Api/ Mcp/ Help/ Components/
|
||||
│ (App, Routes, Layout/, Ui/, Pages/<Modulo>/, Shared/) Localization/ wwwroot/
|
||||
├── tests/ Core, Data, Infrastructure, Fiscal.Italy, Application, Web
|
||||
├── tools/Khaemhat.LicenseTool/
|
||||
├── tools/ Khaemhat.LicenseTool, Khaemhat.DataModelTool, Khaemhat.PlacesTool
|
||||
└── docs/
|
||||
├── SPEC.md ARCHITECTURE.md DATA-MODEL.md MODULES.md API.md MCP.md
|
||||
├── DEPLOY.md DEVELOPMENT.md SECURITY.md STATUS.md
|
||||
|
||||
@@ -219,7 +219,8 @@ Regole (SPEC §16.6, E1):
|
||||
VERSION` (`/p:Version`) insieme a `GIT_SHA` (`/p:SourceRevisionId`, mostrato come `+sha`).
|
||||
- Dove compare (SPEC §16.5): barra superiore (`major.minor`), barra di stato (completa), *Stato sistema*,
|
||||
`manifest.webmanifest`, etichette OCI, icona versionata.
|
||||
- Milestone: `v0.0.1` (M0) … `v0.12.0` (M12), `v1.0.0` (M13), `v1.1.0`+ (M14) — SPEC §20.
|
||||
- Milestone: `v0.0.1` (M0) … `v0.12.0` (M12), `v0.13.0` (M13), `v0.14.0`+ (M14). La `1.0.0` si crea solo quando
|
||||
l'utente lo decide (emendamento E7 in `CLAUDE.md`, che modifica SPEC §20).
|
||||
- Le migrazioni non si riscrivono mai dopo un rilascio: una correzione è una migrazione nuova.
|
||||
|
||||
## 8. Endpoint di salute
|
||||
|
||||
@@ -34,8 +34,10 @@ Se manca l'SDK 10 ci si ferma e lo si chiede al titolare (SPEC §23). Su Windows
|
||||
| `scripts/gen-datamodel.sh [--check]` | rigenera la sezione generata di `docs/DATA-MODEL.md` dalle migrazioni; `--check` verifica soltanto |
|
||||
| `KHAEMHAT_PERF=1 scripts/test.sh --filter TestCategory=Performance` | misure di riferimento dello strato dati con 100.000 righe (`docs/DATA-MODEL.md` §6.1) |
|
||||
|
||||
Gli stub `seed.sh` (M4) e `restore-system.sh` (M12, incluso nell'immagine, ADR 0017) spiegano l'uso previsto ed
|
||||
escono con errore finché la loro milestone non li completa.
|
||||
`scripts/seed.sh --base [--company CODICE]` aggiunge i dati di base mancanti (ADR 0026) con le variabili `KHAEMHAT_*`
|
||||
già impostate (ad esempio quelle di `run-dev.sh`); è incluso nell'immagine in `/app/scripts/`. `--demo` arriva con
|
||||
anagrafiche e articoli. Lo stub `restore-system.sh` (M12, incluso nell'immagine, ADR 0017) spiega l'uso previsto ed
|
||||
esce con errore finché la sua milestone non lo completa.
|
||||
|
||||
#### Test sui due motori
|
||||
|
||||
|
||||
@@ -2,19 +2,19 @@
|
||||
|
||||
> Punto di ripresa per ogni sessione. Aggiornare a fine sessione.
|
||||
|
||||
**Ultimo aggiornamento:** 2026-11-11
|
||||
**Milestone corrente:** M3 — Framework UI, completa nel ramo `feat/25-interfaccia` e in attesa del merge in `main`
|
||||
(pull request di chiusura, issue #36). Dopo il merge: tag `v0.3.0`, immagine e release.
|
||||
**Prossimo passo:** M4 — Tabelle, anagrafiche, articoli (issue #37-#46). #35 (PNG ad alta risoluzione) resta aperta
|
||||
e non blocca.
|
||||
Da recuperare: misure di riferimento su PostgreSQL in `docs/DATA-MODEL.md` §6.1; indicatore di robustezza della
|
||||
password (mockup 003); schede *Layout salvati* (M4) e *Notifiche* (con le e-mail, M5) del profilo; rinomina e
|
||||
**Ultimo aggiornamento:** 2026-11-12
|
||||
**Milestone corrente:** M4 — Tabelle, anagrafiche, articoli: chiusa sul ramo `feat/37-tabelle-anagrafiche` (#46),
|
||||
in attesa del merge in `main` con l'approvazione del titolare; poi tag `v0.4.0`, immagine e release.
|
||||
**Prossimo passo:** dopo il merge, M5 — Motore documenti e Vendite (#47-#54). #35 (PNG ad alta risoluzione) resta
|
||||
aperta e non blocca; #45 resta aperta solo per le banche ABI/CAB (manca una fonte con licenza compatibile).
|
||||
Da recuperare: profilo dell'azienda demo (indirizzo, partita IVA) prima dei documenti di M5; misure di riferimento su PostgreSQL in `docs/DATA-MODEL.md` §6.1; indicatore di robustezza della
|
||||
password (mockup 003); schede *Layout salvati* e *Notifiche* (con le e-mail, M5) del profilo; rinomina e
|
||||
filtro predefinito nei radar.
|
||||
|
||||
## Fatto
|
||||
|
||||
- Specifica normativa in `docs/SPEC.md`; `CLAUDE.md` con emendamenti E1-E6.
|
||||
- ADR 0001-0024.
|
||||
- Specifica normativa in `docs/SPEC.md`; `CLAUDE.md` con emendamenti E1-E7.
|
||||
- ADR 0001-0031.
|
||||
- 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`,
|
||||
@@ -40,7 +40,7 @@ filtro predefinito nei radar.
|
||||
job di sistema; storico dei record; aziende con stati e contesto (`X-Company`); header di sicurezza; ADR 0019.
|
||||
Test: 180 verdi in locale, più 21 di PostgreSQL saltati senza Docker (girano in CI). La chiave privata delle licenze è fuori dal
|
||||
repository (`Khaemhat-private/khaemhat-license.khkey`) e va conservata dal titolare.
|
||||
- **M3 (completa, `v0.3.0` dopo il merge):** shell con barra superiore, menu comprimibile con sottomenu a comparsa,
|
||||
- **M3 (chiusa, `v0.3.0`, PR #119):** shell con barra superiore, menu comprimibile con sottomenu a comparsa,
|
||||
schede tenute in vita, barra di stato, scorciatoie con varianti `Alt`; testi in `Resources/it-IT/*.json` con test
|
||||
anti-testo-letterale; preferenze utente e *Il mio profilo* (aspetto, pagina iniziale, dati personali, password e
|
||||
2FA, sessioni, scorciatoie); libreria `Kh*` con campi all'italiana, toolbar a icone, intestazione documento e basi
|
||||
@@ -50,6 +50,14 @@ filtro predefinito nei radar.
|
||||
cestino e storico; anteprima di stampa A4; catalogo dei componenti e documento di prova per gli sviluppatori;
|
||||
primi screenshot reali in `docs/wiki/img/`; ADR 0020-0024. Test: 368 verdi in locale, 21 di PostgreSQL saltati;
|
||||
immagine costruita in locale e avviata da zero con SQLite.
|
||||
- **M4 (chiusa, `v0.4.0`):** pacchetto fiscale `IT 2026.3` (codici IVA, nature, code list FatturaPA, motore IVA,
|
||||
calendario, ritenute, F24; ADR 0025); validatori e `ViesClient`; 26 tabelle azienda con un'unica maschera, profilo
|
||||
azienda, esercizi e cambi BCE (ADR 0026); dati di base con province e comuni ISTAT e CAP GeoNames (ADR 0028) e
|
||||
`scripts/seed.sh --base|--demo`; codici automatici e compilazione automatica (ADR 0027); clienti, fornitori e
|
||||
contatti con radar, scheda, controlli e VIES (ADR 0029); articoli e listini con prezzi a validità, listini derivati e
|
||||
aggiornamento massivo (ADR 0030); import/export guidato CSV/XLSX/JSON con tracciato del piano dei conti (ADR 0031);
|
||||
21 anagrafiche e 120 articoli di esempio; screenshot reali nella wiki. Test: 631 verdi in locale, 21 di PostgreSQL
|
||||
saltati; immagine costruita in locale e avviata da zero con SQLite e dati di esempio.
|
||||
- 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,
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
# ADR 0025 - Pacchetto fiscale con parti obbligatorie e funzioni facoltative
|
||||
|
||||
- **Stato:** accettata
|
||||
- **Data:** 2026-11-11
|
||||
- **Modifica:** SPEC §1.10, §3, §21 (Fiscal e Validatori); ADR 0007; milestone M4, issue #37 e #40
|
||||
|
||||
## Contesto
|
||||
|
||||
ADR 0007 isola la fiscalità in `Khaemhat.Fiscal.Abstractions` (interfacce) e `Khaemhat.Fiscal.Italy`
|
||||
(implementazione). SPEC §21 elenca una dozzina di interfacce (`ITaxEngine`, `IEInvoiceFormat`, `IWithholdingRules`,
|
||||
`IIntrastatExporter`…), ma non dice come il pacchetto le espone né cosa succede a quelle che arrivano con milestone
|
||||
successive (FatturaPA in M9, bilancio CEE e Intrastat in M10). Inoltre non tutti i paesi hanno tutte le funzioni:
|
||||
un paese fuori dall'UE non ha Intrastat, non ovunque esistono le ritenute d'acconto.
|
||||
|
||||
## Decisione
|
||||
|
||||
1. **Tre parti obbligatorie** come proprietà di `IFiscalPack`: `TaxCodes` (`ITaxCodeCatalog`: nature, codici IVA di
|
||||
base, regole del codice IVA), `TaxEngine` (`ITaxEngine`: arrotondamenti, castelletto, bollo) e `Calendar`
|
||||
(`IFiscalCalendar`: periodi, scadenze, festivi). Ogni paese ha imposte e scadenze.
|
||||
2. **Funzioni facoltative** chieste per tipo: `GetFeature<T>()` restituisce `null` se il paese (o la versione) non
|
||||
la offre; `Require<T>()` lancia `FiscalFeatureNotAvailableException` con paese e funzione. In 0.4.0 il pacchetto
|
||||
italiano offre `IEInvoiceFormat` (versione delle specifiche e code list FatturaPA), `IWithholdingRules`,
|
||||
`IFixedAssetRules` e `ITaxPaymentFormExporter` (codici tributo F24); `IFinancialStatementsSchema`,
|
||||
`IChartOfAccountsTemplate` e `IIntrastatExporter` sono definite ma arrivano con la milestone che le usa.
|
||||
3. **Le interfacce crescono con le milestone.** Ognuna contiene oggi solo ciò che serve e si può verificare
|
||||
(code list, regole, costanti); scrittori e lettori di file si aggiungono quando arriva la loro maschera.
|
||||
4. **Problemi come codici.** Le regole restituiscono `FiscalProblem` (campo, codice stabile come
|
||||
`fiscal.tax.nature-required`, errore o avviso); l'interfaccia traduce il codice con le risorse.
|
||||
5. **Risoluzione per paese.** `FiscalPackCatalog` raccoglie i pacchetti registrati e li trova per
|
||||
`company_profile.country` (senza distinzione di maiuscole). La composizione in `Hosting/KhaemhatServices.cs` è
|
||||
l'unico file fuori dal pacchetto che nomina `Khaemhat.Fiscal.Italy`: lo verifica `FiscalPackIsolationTests`, che
|
||||
controlla anche che le astrazioni non contengano nomi italiani.
|
||||
6. **Identificativi italiani nel pacchetto.** SPEC §21 mette `ItalianVatNumberValidator`, `FiscalCodeValidator`,
|
||||
`FiscalCodeCalculator` e `SdiRecipientCodeValidator` in `Khaemhat.Core`; il vincolo non negoziabile di SPEC §1.10
|
||||
("tutto ciò che è italiano sta in `Fiscal.Italy`") prevale: stanno nel pacchetto italiano dietro la funzione
|
||||
`ITaxIdentifierRules`, e la banca da IBAN dietro `IBankDirectory`. In `Core` restano i controlli internazionali:
|
||||
`IbanValidator` (mod 97 e lunghezza per paese), `EanValidator` (EAN-8, UPC-A, EAN-13, GTIN-14), `EmailValidator`.
|
||||
Il controllo VIES è `ViesClient` in `Infrastructure` (servizio REST della Commissione europea): un servizio che
|
||||
non risponde dà *non disponibile*, mai *non valida*.
|
||||
7. **Versione delle specifiche.** `FatturaPaCodeLists.SpecVersion` è **1.9.1** (pubblicata il 31 marzo 2026, in
|
||||
vigore dal 15 maggio 2026; non cambia le code list della 1.9, che aveva introdotto TD29 e ridefinito TD20). Va
|
||||
ricontrollata sul sito dell'Agenzia delle Entrate a ogni rilascio.
|
||||
|
||||
## Conseguenze
|
||||
|
||||
- Un modulo che usa una funzione facoltativa decide cosa mostrare quando manca (per esempio nascondere Intrastat),
|
||||
invece di fallire alla prima chiamata.
|
||||
- Codici IVA di base, nature e code list del seed (#45) vengono dal pacchetto: c'è un'unica fonte.
|
||||
- La regola del bollo considera le nature N1, N2.x, N3.5, N3.6, N4 e N5; esportazioni, cessioni intracomunitarie,
|
||||
San Marino, operazioni assimilate, inversione contabile e N7 non contano. È da rivedere con i documenti di
|
||||
vendita (M5) se la normativa cambia.
|
||||
@@ -0,0 +1,53 @@
|
||||
# ADR 0026 - Tabelle azienda generiche e dati di base solo in aggiunta
|
||||
|
||||
- **Stato:** accettata
|
||||
- **Data:** 2026-11-11
|
||||
- **Modifica:** SPEC §4 (`scripts/seed.sh`), §11.1, §14; ADR 0025; milestone M4, issue #38, #39 e #45
|
||||
|
||||
## Contesto
|
||||
|
||||
SPEC §11.1 elenca una ventina di tabelle azienda (codici IVA, pagamenti, depositi, vettori, numeratori, categorie…),
|
||||
ognuna con elenco, dettaglio, import ed export CSV. SPEC §14 chiede che le tabelle di base si carichino alla creazione
|
||||
dell'azienda e si aggiornino a ogni versione "senza toccare le righe modificate dall'azienda", ma non dice come
|
||||
riconoscere una riga modificata. Province, comuni con CAP e la tabella ABI/CAB delle banche sono elenchi pubblici
|
||||
grandi (8.000 comuni, decine di migliaia di sportelli) che non sono nel repository e hanno licenze da verificare.
|
||||
|
||||
## Decisione
|
||||
|
||||
1. **Un servizio per tutte le tabelle codificate.** Ogni tabella è un'entità `CodedEntity` (codice, descrizione,
|
||||
disattivata) descritta in `TableCatalog`: le regole comuni (codice unico, una sola riga predefinita, eliminazione
|
||||
rifiutata se la riga è usata e proposta di disattivarla, storico, cache invalidata fra istanze, CSV tutto o niente)
|
||||
stanno in `TableService`. Le regole proprie di una tabella sono funzioni del catalogo; quelle italiane (natura
|
||||
IVA, codici SDI) arrivano dal pacchetto fiscale (ADR 0025).
|
||||
2. **Una maschera generica.** L'interfaccia descrive ogni tabella in `TableScreens` (campi, tipo, lookup, code list
|
||||
del pacchetto) e la mostra con un unico editor `KhTableEditor<T>` all'indirizzo `/tabelle/<slug>`. Profilo
|
||||
azienda, esercizi e cambi hanno pagine proprie perché non sono elenchi di codici.
|
||||
3. **Dati di base solo in aggiunta.** Il caricamento inserisce **solo i codici che mancano** e non modifica né
|
||||
cancella righe esistenti, anche se identiche al pacchetto: una riga presente è dell'azienda. Non serve quindi
|
||||
distinguere righe "modificate" da righe "originali". La versione caricata è salvata nelle impostazioni
|
||||
dell'azienda (`seed.base.version`, ad esempio `IT 2026.2`). Correggere una riga di base già presente è un'azione
|
||||
esplicita dell'utente, non dell'aggiornamento.
|
||||
4. **Origine delle righe.** Righe fiscali (codici IVA, modalità e condizioni di pagamento, tipi documento) dal
|
||||
pacchetto del paese tramite `IBaseTablesTemplate`; paesi ISO da un CSV incorporato; valute BCE, unità di misura,
|
||||
trasporti, causali, deposito principale, listino base, numeratori ed esercizio corrente dal seeder di base.
|
||||
5. **Comuni.** Il **codice** di un comune è il suo codice catastale (4 caratteri, quello del codice fiscale): non
|
||||
serve una colonna in più.
|
||||
6. **Elenchi pubblici caricati a parte.** Province, comuni con CAP e banche ABI/CAB non sono nel seed di 0.4.0:
|
||||
arriveranno come file di dati con origine e licenza indicate (ISTAT, CC BY 4.0, per province e comuni) dopo il
|
||||
via dell'utente al download. Fino ad allora le tabelle si riempiono a mano o con l'import CSV.
|
||||
*Aggiornato dall'ADR 0028:* province e comuni ISTAT, con i CAP di GeoNames, sono nei dati di base dalla
|
||||
versione `IT 2026.3`; le banche restano fuori.
|
||||
7. **Riga di comando.** `scripts/seed.sh --base [--company CODICE]` esegue la sequenza di avvio senza servire pagine
|
||||
(migrazioni, prima azienda) e aggiunge i dati di base a un'azienda o a tutte quelle attive. Nel container lo
|
||||
script è in `/app/scripts/` e passa da `entrypoint.sh` con il verbo `seed`; in sviluppo usa `dotnet run`.
|
||||
`--demo` e `--scale` arrivano con anagrafiche e articoli.
|
||||
|
||||
## Conseguenze
|
||||
|
||||
- Un aggiornamento delle tabelle di base non può mai rovinare una configurazione aziendale; il rovescio è che una
|
||||
correzione a un codice già presente (ad esempio un riferimento normativo cambiato) va comunicata nel `CHANGELOG`
|
||||
e fatta dall'utente, o con una migrazione mirata quando è obbligatoria.
|
||||
- Aggiungere una tabella costa un'entità, una mappa, una voce in `TableCatalog` e una in `TableScreens`, più i testi:
|
||||
i test controllano che ogni schermata abbia le chiavi di testo e ogni codice di errore la sua traduzione.
|
||||
- Il pulsante *Aggiorna da tabelle base* delle maschere e la pagina di amministrazione (mockup 089) usano lo
|
||||
stesso `SeedRunner`.
|
||||
@@ -0,0 +1,49 @@
|
||||
# ADR 0027 - Codici automatici con sequenze per chiave e compilazione a opzioni
|
||||
|
||||
- **Stato:** accettata
|
||||
- **Data:** 2026-11-11
|
||||
- **Modifica:** SPEC §11.12 (codici automatici, compilazione automatica); ADR 0025, 0026; milestone M4, issue #43
|
||||
|
||||
## Contesto
|
||||
|
||||
SPEC §11.12 chiede maschere di codice per archivio (`C{seq:000000}`, `{categoria}-{seq:0000}`, `L{anno}-{seq:0000}`…),
|
||||
progressivo globale o per categoria/anno, codice manuale ammesso o no, anteprima del prossimo codice e sequenze in
|
||||
`code_sequences` con assegnazione atomica. Non dice dove stanno le regole, come si chiamano le sequenze, cosa succede
|
||||
se il codice successivo è già stato scritto a mano o se la maschera cambia. Per la compilazione automatica elenca le
|
||||
opzioni senza dire chi le applica, e la banca dall'IBAN dipende da un elenco ABI che non è ancora nel repository
|
||||
(ADR 0026).
|
||||
|
||||
## Decisione
|
||||
|
||||
1. **Regole nelle impostazioni dell'azienda.** La maschera e il codice manuale di ogni archivio stanno in
|
||||
`company_settings` (`codes.<archivio>.mask`, `codes.<archivio>.manual`, `codes.items.unique-barcode`); un archivio
|
||||
senza impostazioni usa la maschera di SPEC. Gli archivi sono un elenco fisso in `CodeRuleService.Definitions`, con
|
||||
il modulo di licenza e la lunghezza massima del codice.
|
||||
2. **Una sequenza per chiave.** `code_sequences` ha una riga per chiave: il nome dell'archivio, più l'anno se la
|
||||
maschera contiene `{anno}`, più la categoria se contiene `{categoria}` (`customers`, `leads:2026`, `items:VALV`).
|
||||
La maschera non fa parte della chiave: **cambiare maschera continua lo stesso progressivo** e non riscrive i codici
|
||||
già assegnati.
|
||||
3. **Assegnazione nella transazione del salvataggio.** `CodeRuleService.AssignAsync` prende un lock applicativo sulla
|
||||
chiave (`AcquireLockAsync`, vuoto su SQLite dove le scritture sono già in fila), incrementa la sequenza e la scrive
|
||||
nella stessa unità di lavoro del record: se il salvataggio fallisce il numero torna libero, e due salvataggi
|
||||
contemporanei non ottengono mai lo stesso codice. Un codice già presente nella tabella (scritto a mano) viene
|
||||
saltato; dopo 1.000 salti il salvataggio è rifiutato.
|
||||
4. **Maschere controllate.** Letterali `A-Z 0-9 - _ / .` in maiuscolo, esattamente un `{seq}`, segnaposto
|
||||
`{anno}`/`{year}` e `{categoria}`/`{category}`, lunghezza minima entro quella della tabella. Gli errori sono codici
|
||||
(`codes.mask.*`) tradotti dall'interfaccia.
|
||||
5. **Compilazione a opzioni.** `AutoFillService` raccoglie le funzioni (comune da CAP e viceversa, codice fiscale dal
|
||||
pacchetto fiscale, VIES, banca da IBAN, data di consegna sul calendario del pacchetto) e le opzioni accese o spente
|
||||
(`autofill.<opzione>`); le maschere chiedono `IsOnAsync` prima di compilare. Il job dei cambi BCE salta le aziende
|
||||
che hanno spento l'opzione. Le opzioni sulle righe dei documenti e sui conti si applicano con i documenti (M5).
|
||||
6. **Banca da IBAN senza elenco ABI.** `IBankDirectory.ReadIban` restituisce sempre ABI e CAB di un IBAN italiano;
|
||||
nome e BIC arrivano dall'elenco quando c'è, altrimenti da un conto dell'azienda presso la stessa banca.
|
||||
7. **Modulo.** SPEC mette codici automatici e preferenze nel modulo AUTO, ma servono a ogni azienda (mockup 074, M4):
|
||||
stanno nel modulo CORE come le tabelle; le maschere degli archivi di CRM, Servizi e Cespiti si preparano anche
|
||||
senza il modulo.
|
||||
|
||||
## Conseguenze
|
||||
|
||||
- Le anagrafiche (#41) e gli articoli (#42) chiamano `AssignAsync` quando il codice è vuoto e `CheckManual` quando è
|
||||
scritto; gli import li trattano allo stesso modo.
|
||||
- Una sequenza per categoria nasce al primo articolo della categoria; rinominare il codice di una categoria fa
|
||||
ripartire il suo progressivo, ma i codici già assegnati restano e quelli ripetuti vengono saltati.
|
||||
@@ -0,0 +1,53 @@
|
||||
# ADR 0028 - Province e comuni dall'elenco ISTAT e CAP da GeoNames nel pacchetto fiscale
|
||||
|
||||
- **Stato:** accettata
|
||||
- **Data:** 2026-11-12
|
||||
- **Modifica:** ADR 0026 punto 6; SPEC §11.1, §11.12, §14; milestone M4, issue #45
|
||||
|
||||
## Contesto
|
||||
|
||||
L'ADR 0026 rimandava province, comuni con CAP e banche ABI/CAB a file di dati con origine e licenza verificate,
|
||||
caricati dopo il via dell'utente. Il via è arrivato il 2026-11-12 per due fonti:
|
||||
|
||||
- l'**elenco dei codici dei comuni dell'ISTAT** (*Codici statistici delle unità amministrative territoriali*),
|
||||
pubblicato con licenza **CC BY 4.0** (note legali ISTAT). Il file CSV allo stesso indirizzo è fermo al gennaio 2024
|
||||
e ha ancora le 107 province precedenti al riordino della Sardegna; il file xlsx è aggiornato al **26/02/2026** e ha
|
||||
le **110 province** e i **7.894 comuni** in vigore;
|
||||
- il repository **comuni-json** per i CAP. La sua licenza non è MIT come si era ipotizzato: i comuni vengono
|
||||
dall'ISTAT (CC BY), ma per i CAP l'autore dichiara che le fonti non indicano una licenza e che al repository
|
||||
**non si applica nessuna licenza**. I dati sono fermi al 01/01/2020, prima delle fusioni di comuni successive.
|
||||
|
||||
## Decisione
|
||||
|
||||
1. **Province e comuni nel pacchetto fiscale.** Sono dati italiani, quindi stanno in `Khaemhat.Fiscal.Italy`
|
||||
(`Data/province.csv`, `Data/comuni.csv`, risorse incorporate) dietro una nuova funzione facoltativa del pacchetto,
|
||||
`IPlaceDirectory` (province, comuni, origine). `BaseTablesSeeder` li aggiunge come il resto dei dati di base: solo
|
||||
i codici mancanti, mai modificando una riga già presente.
|
||||
2. **Formato ridotto.** Dal foglio ISTAT si tengono, per le province, sigla, denominazione e regione; per i comuni,
|
||||
codice catastale (il **codice** del comune, ADR 0026), denominazione in italiano, sigla della provincia, regione e
|
||||
codice ISTAT a 6 cifre. I file si rigenerano dal foglio ISTAT con lo stesso schema; ogni aggiornamento porta una
|
||||
nuova versione dei dati del pacchetto (da `IT 2026.2` a `IT 2026.3`).
|
||||
3. **Attribuzione.** L'origine (ISTAT, data dell'elenco, CC BY 4.0; GeoNames per i CAP) è scritta in
|
||||
`ItalianPlaces.ListSource`, nella wiki *Dati di base e di esempio* e in questo ADR.
|
||||
4. **Niente CAP da comuni-json.** Un file senza licenza non entra in un repository pubblico né nell'immagine
|
||||
distribuita, e i CAP del 2020 sarebbero comunque incompleti.
|
||||
5. **CAP da GeoNames.** Con un secondo via dell'utente (2026-11-12) i CAP vengono dall'elenco dei codici postali
|
||||
italiani di **GeoNames** (`IT.zip`, CC BY 4.0, attribuzione a www.geonames.org). GeoNames elenca località, non
|
||||
comuni: una riga si assegna a un comune quando nome (senza accenti, apostrofi e trattini, parte italiana dei nomi
|
||||
bilingui) e sigla della provincia coincidono con un solo comune; in Sardegna, dove le sigle sono cambiate, basta
|
||||
il nome entro la regione. Le frazioni con nome proprio restano fuori. Risultato: **7.750 comuni su 7.894** hanno i
|
||||
CAP (un CAP, una lista o intervalli come `10121-10156`); i 144 senza sono in gran parte comuni rinominati o nati da
|
||||
fusioni (ad esempio Sanremo, che GeoNames chiama *San Remo*) e si completano a mano o con l'**Importa CSV**.
|
||||
6. **Strumento di rigenerazione.** `tools/Khaemhat.PlacesTool` (non distribuito, solo framework) legge il foglio ISTAT
|
||||
e `IT.zip` e riscrive `Data/province.csv` e `Data/comuni.csv`; i file scaricati restano fuori dal repository.
|
||||
7. **Banche ABI/CAB** restano fuori finché non c'è una fonte aperta con licenza chiara (ADR 0026, ADR 0027 punto 6).
|
||||
|
||||
## Conseguenze
|
||||
|
||||
- Un'azienda nuova ha subito province, comuni e CAP: il calcolo del codice fiscale, la scelta del comune e la
|
||||
compilazione dal CAP funzionano senza caricare nulla. Le aziende esistenti li ricevono al primo avvio con la
|
||||
versione `IT 2026.3`, o con *Aggiorna tabelle di base*.
|
||||
- Il caricamento di base aggiunge circa 8.000 righe alla creazione dell'azienda: su SQLite resta sotto i due secondi;
|
||||
su PostgreSQL va misurato insieme alle altre misure di riferimento (`docs/DATA-MODEL.md` §6.1).
|
||||
- Un comune soppresso per fusione resta nella tabella di chi lo aveva già: va disattivato a mano. Le variazioni
|
||||
vanno annotate nel `CHANGELOG` quando si aggiorna l'elenco.
|
||||
@@ -0,0 +1,65 @@
|
||||
# ADR 0029 - Anagrafiche: un archivio per clienti, fornitori, prospect e lead
|
||||
|
||||
- **Stato:** accettata
|
||||
- **Data:** 2026-11-12
|
||||
- **Modifica:** SPEC §9 (modello dati delle anagrafiche), §11.2, §11.12, §14; milestone M4, issue #41
|
||||
|
||||
## Contesto
|
||||
|
||||
SPEC §11.2 descrive clienti, fornitori, prospect e lead con radar (mockup 012-013), scheda a gruppi (014-016),
|
||||
condizioni commerciali, dati fiscali e SDI, banche, contatti e indirizzi. §9 elenca le tabelle `parties` e i
|
||||
dettagli, ma lascia aperti alcuni punti: come si rappresenta un soggetto che è sia cliente sia fornitore, che codice
|
||||
riceve un prospect, quando si verifica il VIES, come si cancella un'anagrafica usata, come sono fatti i dati di
|
||||
esempio prima che esistano gli articoli e i documenti.
|
||||
|
||||
## Decisione
|
||||
|
||||
1. **Un archivio, quattro tipi.** `parties` ha un `kind` (*Customer*, *Supplier*, *Prospect*, *Lead*) e un
|
||||
`subject_type` (*Company*, *Person*, *PublicAdministration*, *EuCompany*, *NonEuCompany*, *FlatRate*) che decide i
|
||||
controlli e i valori proposti. Un soggetto che è sia cliente sia fornitore è un **cliente** con
|
||||
`is_also_supplier`: compare in entrambi i radar con lo stesso codice cliente. Un fornitore che diventa cliente
|
||||
(azione *Converti in cliente*) diventa quindi `Customer` con `is_also_supplier = true` e tiene il suo codice.
|
||||
2. **Tre radar.** `/anagrafiche/clienti` (tipo *Customer*), `/anagrafiche/fornitori` (*Supplier* più i clienti che
|
||||
sono anche fornitori), `/anagrafiche/contatti` (*Prospect* e *Lead*, con il filtro rapido del tipo).
|
||||
3. **Codici.** Clienti e fornitori usano le maschere `customers` e `suppliers`; prospect e lead la maschera `leads`
|
||||
(`L{anno}-{seq:0000}`, ADR 0027). Alla conversione in cliente un prospect o un lead riceve il codice cliente e il
|
||||
vecchio resta in `previous_code`, così i riferimenti esterni (e-mail, appunti) si ritrovano con la ricerca.
|
||||
4. **Dettagli in tabelle proprie.** Indirizzi, contatti e conti sono liste (`party_addresses`, `party_contacts`,
|
||||
`party_bank_accounts`, al più un predefinito per tipo); condizioni di vendita, di acquisto e dati fiscali sono
|
||||
tabelle 1:1 (`party_sales_terms`, `party_purchase_terms`, `party_fiscal`) create insieme all'anagrafica. Il
|
||||
salvataggio riscrive la scheda intera in una transazione; lo storico registra testata e dettagli. La cancellazione
|
||||
dei dettagli è a cascata.
|
||||
5. **Controlli dal pacchetto fiscale.** Partita IVA, codice fiscale, codice destinatario e PEC passano da
|
||||
`ITaxIdentifierRules` (ADR 0025). Errori bloccanti: ragione sociale, P.IVA per un'impresa, identificativo per una
|
||||
PA, codice fiscale non valido, codice duplicato, paese incoerente con il tipo soggetto, dichiarazione d'intento
|
||||
senza numero o plafond. **Avvisi**, che non bloccano: P.IVA già usata da un'altra anagrafica (filiali, sedi
|
||||
distinte), privato senza codice fiscale. Per un cliente privato o estero, o per un'impresa con sola PEC, il codice
|
||||
destinatario mancante si compila con il valore del formato (`0000000`, `XXXXXXX`).
|
||||
6. **VIES al salvataggio.** Per un'impresa UE la verifica parte dopo il commit, solo se la P.IVA o il paese sono
|
||||
cambiati o non è mai stata verificata, e solo se la compilazione automatica *Vies* è accesa. L'esito (*valida*,
|
||||
*non valida*, *non verificata*) e la data restano sull'anagrafica; un VIES irraggiungibile non impedisce di
|
||||
salvare. L'azione *Verifica VIES* della scheda ripete la verifica. Le date sono `DateTime` in UTC, come nel
|
||||
resto del modello.
|
||||
7. **Cancellare o disattivare.** *Elimina* prova a cancellare; se il database rifiuta per riferimenti (documenti dalle
|
||||
prossime milestone), l'anagrafica viene **disattivata** e l'utente lo legge in un messaggio. Il radar disattiva e
|
||||
riattiva più righe insieme; le disattivate sono escluse per filtro iniziale.
|
||||
8. **Dati di esempio senza documenti.** `DemoPartiesSeeder` (seeder *Demo*, solo se le anagrafiche sono vuote) crea
|
||||
3 agenti e 21 anagrafiche con `is_demo`: 12 clienti che coprono tutti i tipi soggetto (PA con split payment,
|
||||
cliente bloccato, disattivato, anche fornitore, con dichiarazione d'intento), 5 fornitori (ritenuta, ENASARCO, UE),
|
||||
2 prospect e 2 lead. Partite IVA, codici fiscali e IBAN sono **numeri inventati ma formalmente validi** (cifra di
|
||||
controllo, mod 97), scritti come costanti e controllati da un test; nessuno appartiene a un soggetto reale per
|
||||
scelta, ma la coincidenza non si può escludere e per questo non si verificano sul VIES. Il volume completo della
|
||||
SPEC (40 clienti, 15 fornitori, documenti) arriva in M9 con `seed --demo`.
|
||||
9. **Rinviati.** `party_item_codes` (codici articolo del cliente o del fornitore) arriva con gli articoli (#42);
|
||||
fatturato, scaduto, fido usato e *Scheda 360°* con vendite (M5) e scadenzario (M9); il flag utente *vede solo i
|
||||
propri clienti* con i filtri per riga sui permessi, non ancora previsti in una milestone. Gli agenti di esempio non hanno `is_demo` perché la tabella
|
||||
degli agenti (ADR 0026) non ha la colonna: si rimuovono a mano.
|
||||
|
||||
## Conseguenze
|
||||
|
||||
- Una sola tabella e una sola query per i tre radar; le condizioni commerciali si leggono con un join 1:1.
|
||||
- Il passaggio fornitore → cliente non cambia codice né documenti; il passaggio prospect → cliente cambia codice e
|
||||
lascia traccia in `previous_code` e nello storico.
|
||||
- I controlli fiscali italiani restano nel pacchetto; un altro paese porterà le sue regole senza toccare il servizio.
|
||||
- I dati di esempio non hanno numeri reali e restano validi per i controlli, quindi le prove automatiche li usano come
|
||||
casi realistici (ogni anagrafica di esempio supera `ValidateAsync`).
|
||||
@@ -0,0 +1,67 @@
|
||||
# ADR 0030 - Articoli e listini: prezzi con validità, listini derivati, ricerca del prezzo
|
||||
|
||||
- **Stato:** accettata
|
||||
- **Data:** 2026-11-12
|
||||
- **Modifica:** SPEC §9 (modello dati degli articoli), §11.2, §11.3, §14; milestone M4, issue #42
|
||||
|
||||
## Contesto
|
||||
|
||||
SPEC §11.2 descrive la scheda articolo (mockup 017) con UM alternative, codici alternativi, listini, fornitori,
|
||||
sostitutivi, giacenze e movimenti, e la griglia dei listini (mockup 018) con modifica in cella e aggiornamento
|
||||
massivo. §11.3 fissa l'ordine di ricerca del prezzo di una riga (netto cliente-articolo, listino del cliente o del
|
||||
documento, listino base, prezzo dell'articolo) e dice che i listini hanno validità, possono essere derivati e hanno
|
||||
regole di arrotondamento. Restavano aperti: dove stanno i prezzi netti dei clienti, come convivono prezzi vecchi e
|
||||
nuovi, quale listino è "il base", come si calcola un listino derivato, che cosa vede chi non può vedere i costi, che
|
||||
cosa si fa delle giacenze prima del magazzino (M6).
|
||||
|
||||
## Decisione
|
||||
|
||||
1. **Una tabella di prezzi.** `item_prices` tiene sia i prezzi di listino (`price_list_id`) sia i **prezzi netti**
|
||||
di un cliente (`party_id`): una riga ha esattamente uno dei due. Ogni riga ha un `valid_from`; il prezzo in vigore
|
||||
a una data è quello con l'**inizio più recente non successivo** alla data (una riga senza data vale sempre).
|
||||
Scrivere un prezzo con una data nuova aggiunge una riga, così i documenti già fatti e quelli datati prima
|
||||
ritrovano il prezzo di allora; scriverlo con la stessa data cambia la riga, e "nessun prezzo" la toglie. Un prezzo
|
||||
uguale a quello già in vigore non si riscrive.
|
||||
2. **Listino base.** `price_lists.is_base` marca il listino base (al più uno, regola della tabella); in mancanza
|
||||
vale quello con codice `BASE`, che i dati di base creano già marcato. La migrazione marca il `BASE` esistente.
|
||||
3. **Listini derivati.** Un listino con `base_price_list_id` senza un proprio prezzo per l'articolo prende il prezzo
|
||||
del listino di partenza alla stessa data, applica `markup_percent` (anche negativo) e arrotonda a `rounding_step`
|
||||
(al centesimo se zero). Il prezzo scritto nel listino derivato vince su quello calcolato. La derivazione si segue
|
||||
per al più cinque livelli. Il calcolo è in `PriceBook`, che lavora in memoria sui prezzi letti una volta.
|
||||
4. **Ricerca del prezzo** (`PriceListService.QuoteAsync`, usata dai documenti da M5): netto del cliente, poi il
|
||||
listino del documento o del cliente se valido alla data, poi il listino base, poi `items.price`. La risposta dice
|
||||
la **fonte** (`PriceSource`), che la riga del documento conserva. Gli sconti 1 e 2 del cliente si propongono come
|
||||
formula a cascata (`10+5`), **mai su un prezzo netto**.
|
||||
5. **Griglia dei listini.** Legge e scrive tutti i prezzi a **una data di validità** scelta in alto (oggi di
|
||||
default). Le celle modificate e quelle calcolate dall'aggiornamento massivo restano in sospeso, evidenziate, finché
|
||||
non si salva; l'anteprima dell'aggiornamento massivo (`PreviewAsync`) non scrive nulla. Le celle dei listini
|
||||
derivati senza prezzo proprio sono in corsivo.
|
||||
6. **Costi.** Costo standard, ultimo costo e costo medio si vedono solo con `items.cost.read`; per gli altri il
|
||||
servizio li restituisce vuoti e al salvataggio conserva quelli in archivio. Ultimo costo e costo medio non si
|
||||
scrivono dalla scheda: li aggiornano i carichi di magazzino (M6); fino ad allora li valorizzano solo i dati di
|
||||
esempio. Il margine è sul prezzo: (prezzo - costo) / prezzo.
|
||||
7. **Tipi e magazzino.** Solo le merci possono essere *gestite a magazzino*; servizi, spese, righe descrittive e
|
||||
cespiti non lo sono mai (il servizio lo corregge). Giacenze, impegni, movimenti e proposta di riordino arrivano
|
||||
con il magazzino (M6): la scheda li annuncia, i campi di riordino si compilano già.
|
||||
8. **Codici.** Il codice segue la maschera `items` (`{categoria}-{seq:0000}`, ADR 0027); se la maschera usa la
|
||||
categoria, la categoria è obbligatoria. Il codice a barre principale e quelli delle UM alternative hanno la
|
||||
verifica EAN; un codice a barre già usato da un altro articolo è un avviso, o un errore se le preferenze chiedono
|
||||
codici a barre univoci. La ricerca degli articoli trova esattamente anche i **codici alternativi** e, nei
|
||||
documenti di un'anagrafica, i **codici che quell'anagrafica usa** (`party_item_codes`).
|
||||
9. **Codici dell'anagrafica.** `party_item_codes` si gestisce nella scheda *Articoli e codici* dell'anagrafica e si
|
||||
salva con essa (un codice non si ripete per la stessa anagrafica); i controlli sono di `ItemService`.
|
||||
10. **Cancellazione.** Un articolo usato (sostitutivo di un altro, in documenti da M5) si disattiva invece di
|
||||
cancellarsi, come le anagrafiche (ADR 0029). Un cliente con prezzi netti non si cancella.
|
||||
11. **Dati di esempio.** `DemoItemsSeeder` crea 120 articoli fittizi di un grossista termoidraulico (SPEC §14) in dieci
|
||||
categorie, due listini derivati dal base (*Pubblico* +45% arrotondato a 0,10, *Rivenditori* -10%), un prezzo
|
||||
dell'anno precedente per lo storico, prezzi netti e codici di Rossi Impianti, fornitori abituali, UM alternative,
|
||||
codici alternativi e sostitutivi. I codici a barre hanno prefisso 200, riservato all'uso interno. Il comando
|
||||
`seed --demo [--scale N]` esegue prima i dati di base e poi quelli di esempio, ripetendo il catalogo N volte.
|
||||
|
||||
## Conseguenze
|
||||
|
||||
- I documenti (M5) chiamano `PriceListService.QuoteAsync` dentro la propria unità di lavoro e salvano prezzo e fonte;
|
||||
la stessa logica serve l'API (`items`, `price-lists`) e il tool MCP `search_items`.
|
||||
- Cambiare un prezzo non tocca i documenti esistenti; per correggere un prezzo sbagliato si riscrive con la stessa
|
||||
data, per un aumento si usa una data nuova.
|
||||
- Il magazzino (M6) aggiornerà `last_cost` e `average_cost` e aggiungerà le schede *Giacenze* e *Movimenti*.
|
||||
@@ -0,0 +1,69 @@
|
||||
# ADR 0031 - Import e export guidato: entità, tracciati, controlli come da scheda
|
||||
|
||||
- **Stato:** accettata
|
||||
- **Data:** 2026-11-12
|
||||
- **Modifica:** SPEC §11.7, §12.12, mockup 077; milestone M4, issue #44
|
||||
|
||||
## Contesto
|
||||
|
||||
SPEC §12.12 chiede una procedura guidata di import/export (CSV, XLSX, JSON) per anagrafiche, articoli, listini,
|
||||
giacenze iniziali, piano dei conti, saldi e partite di apertura, con mappatura delle colonne, validazione riga per
|
||||
riga, report degli errori e un tracciato proprio del piano dei conti (`codice;descrizione;livello;padre;natura;tipo;
|
||||
voce_cee;riclassifica;flag` e `khaemhat-coa.json`). Restavano aperti: dove sta la procedura, quali entità esistono già
|
||||
in M4, come si controllano le righe, che cosa succede ai codici esistenti o mancanti, i valori ammessi di `natura`,
|
||||
`tipo` e `flag`, come si legge un XLSX senza librerie esterne, chi può esportare.
|
||||
|
||||
## Decisione
|
||||
|
||||
1. **Dove.** Pagina `/amministrazione/import-export` (voce *Import / export dati* sotto *Amministrazione*, visibile
|
||||
agli account di istanza), consegnata in M4 prima del resto dell'area (M13). Una persona dell'azienda la apre se ha
|
||||
il permesso di scrittura o di export di almeno un'entità.
|
||||
2. **Entità.** `IImportTarget` descrive un'entità: chiave, modulo di licenza, permesso di import e di export, colonne
|
||||
(con alias per l'abbinamento automatico), verifica, scrittura ed export. In M4: `clienti`, `fornitori`,
|
||||
`articoli`, `listini` (prezzi di listino e netti cliente), `giacenze-iniziali`, `piano-dei-conti`. Le ultime due
|
||||
**si verificano soltanto** finché non esistono i movimenti di magazzino (M6) e la contabilità (M7): la procedura
|
||||
prepara il file in anticipo, la scrittura arriva con il modulo. Saldi e partite di apertura arrivano con M7 e M9.
|
||||
3. **Le righe passano dalla scheda.** Clienti, fornitori e articoli si leggono per codice (o si creano con i valori
|
||||
proposti dalla scheda), si riempiono con le celle **non vuote** della riga e si controllano e salvano con
|
||||
`PartyService` e `ItemService`: stesse regole, stessi codici di errore, stesso storico. Una cella vuota lascia il
|
||||
valore che c'è. I codici di altre tabelle (categoria, pagamento, listino, agente, UM, IVA, deposito) devono
|
||||
esistere. I prezzi si scrivono con `PriceListService` in una sola transazione (stessa voce e stessa data:
|
||||
sostituisce; data nuova: aggiunge, come la griglia dei listini, ADR 0030).
|
||||
4. **Opzioni.** *Se il codice esiste*: aggiorna (predefinito) o salta la riga (avviso). *Codice mancante*: genera con
|
||||
le regole dei codici automatici (ADR 0027) o errore. Un codice scritto per un record nuovo rispetta la regola
|
||||
(*codice manuale ammesso*). Un codice ripetuto nel file è un errore dalla seconda riga; un codice di un'anagrafica di
|
||||
altro tipo è un errore. *Verifica P.IVA su VIES* chiama VIES durante l'import (spento: nessuna chiamata, qualunque
|
||||
sia l'opzione automatica dell'azienda). *Completa comune da CAP* propone comune e provincia da un CAP con un solo
|
||||
comune, o il CAP da un comune con un solo CAP, come avviso.
|
||||
5. **Esiti.** Ogni riga ha *OK*, *avviso* (importabile) o *errore* (esclusa), con colonna, codice del testo e valore.
|
||||
Si importano solo le righe senza errori; le altre finiscono nel **report errori** (CSV con riga, codice, colonna,
|
||||
esito, messaggio). L'esito dell'import va nel log, sezione *Sistema*.
|
||||
6. **Valori.** Numeri all'italiana (`1.234,56`) o con il punto decimale (`1234.56`, come li scrivono XLSX e JSON);
|
||||
date `gg/mm/aaaa`, ISO, `aaaammgg` o numero seriale del foglio; sì/no come `sì`, `x`, `1`, `VERO`, `true` e i
|
||||
contrari; le parole di una scelta senza badare a maiuscole, accenti e punteggiatura.
|
||||
7. **Piano dei conti.** Codice di 1-3 parti separate da punto (mastro, conto, sottoconto); `livello` è il numero di
|
||||
parti; `padre` è il codice senza l'ultima parte e deve essere nel file; la `natura` (`attivo`, `passivo`, `costo`,
|
||||
`ricavo`, `ordine`) si eredita dal padre e non può essere diversa; `tipo` è `generico`, `clienti`, `fornitori`,
|
||||
`banca`, `cassa`, `iva`, `erario` (nuovo `AccountType` in `Khaemhat.Core.Accounting`); `flag` è un insieme di lettere:
|
||||
`M` movimentabile (solo conti senza sottoconti), `I` rilevante IVA, `P` con partitario, `C` chiusura automatica,
|
||||
`X` disattivato. `khaemhat-coa.json` è un oggetto `{format, version, accounts, statementLines, journalTemplates,
|
||||
mappings}`: `accounts` ha le stesse colonne, le altre sezioni si contano e si importano in M7. Il controllo è puro
|
||||
(`ChartOfAccountsImportValidator`) perché M7 scriva esattamente ciò che accetta.
|
||||
8. **File.** CSV in UTF-8 (con o senza BOM) o, se non è UTF-8 valido, Windows-1252; separatore `;`, `,` o tabulazione
|
||||
dedotto dall'intestazione; l'apostrofo che l'export mette davanti al testo che inizia con `=`, `+`, `-`, `@` si
|
||||
toglie. XLSX: primo foglio letto da `XlsxReader` (System.IO.Compression e XmlReader, DTD vietate, stringhe
|
||||
condivise, celle in linea, numeri formattati come data restituiti come data). JSON: elenco di oggetti. Al più
|
||||
50.000 righe e 25 MB.
|
||||
9. **Export e modelli.** L'export scrive le stesse colonne dell'import in CSV (`;`, UTF-8 con BOM, numeri e date
|
||||
all'italiana), XLSX o JSON, così il file si corregge e si reimporta; richiede il permesso di export dell'entità e
|
||||
il flag utente *Può esportare dati*. Il **modello** è il file con le sole intestazioni (in JSON un oggetto con i
|
||||
valori vuoti).
|
||||
|
||||
## Conseguenze
|
||||
|
||||
- L'import non ha regole proprie: ogni regola nuova di una scheda vale subito anche per i file.
|
||||
- Un file di un altro gestionale con codici propri richiede che la regola dei codici ammetta il codice manuale.
|
||||
- M6 e M7 aggiungono la scrittura di giacenze e piano dei conti senza cambiare tracciati né controlli; M7 e M9
|
||||
aggiungono saldi e partite come nuove entità.
|
||||
- Le righe si scrivono una alla volta (anagrafiche e articoli): un errore a metà non annulla le righe già scritte,
|
||||
che il report indica come create o aggiornate.
|
||||
@@ -1,7 +1,7 @@
|
||||
# Anagrafiche
|
||||
|
||||
> **Stato:** bozza · **Ultima revisione:** 2026-11-10 · **Versione software:** non ancora rilasciata (milestone M4)
|
||||
> **Modulo di licenza:** CORE · **Permessi principali:** famiglia `parties.*` (`read`, `write`, `delete`, `export`; codici esatti definiti in sviluppo) · **Specifica:** SPEC §11.2, §11.12, §22
|
||||
> **Stato:** completa · **Ultima revisione:** 2026-11-12 · **Versione software:** 0.4.0 (milestone M4)
|
||||
> **Modulo di licenza:** CORE · **Permessi principali:** `parties.party.read` (consultare), `parties.party.write` (inserire, modificare, disattivare, convertire), `parties.party.delete` (eliminare) · **Specifica:** SPEC §11.2, §11.12, §22 · **Decisioni:** ADR 0029
|
||||
|
||||
Le **anagrafiche** sono l'archivio unico delle controparti dell'azienda: **clienti**, **fornitori**, **prospect** e
|
||||
**lead**. Un soggetto è registrato una volta sola; il suo *tipo* (cliente, fornitore…) dice come viene usato. Dalla
|
||||
@@ -10,8 +10,9 @@ codici che il cliente o il fornitore usa per i tuoi articoli.
|
||||
|
||||
## Dove si trova
|
||||
|
||||
Menu **Anagrafiche** → **Clienti**, **Fornitori**, **Contatti** (prospect e lead), **Categorie**. Nello stesso menu ci
|
||||
sono anche *Articoli* e *Listini* (vedi [Articoli e listini](Articoli-e-listini)).
|
||||
Menu **Anagrafiche** → **Clienti** (`/anagrafiche/clienti`), **Fornitori** (`/anagrafiche/fornitori`), **Contatti**
|
||||
(`/anagrafiche/contatti`, prospect e lead). Le categorie sono una tabella azienda (vedi [Tabelle azienda](Tabelle-azienda)).
|
||||
Nello stesso menu arriveranno *Articoli* e *Listini* (vedi [Articoli e listini](Articoli-e-listini)).
|
||||
|
||||
## Tipi di anagrafica
|
||||
|
||||
@@ -19,13 +20,15 @@ sono anche *Articoli* e *Listini* (vedi [Articoli e listini](Articoli-e-listini)
|
||||
|---|---|---|
|
||||
| **Cliente** | intestatario di preventivi, ordini, DDT e fatture di vendita | `C{seq:000000}` → `C000124` |
|
||||
| **Fornitore** | intestatario di ordini fornitore, DDT di carico, fatture di acquisto | `F{seq:000000}` → `F000032` |
|
||||
| **Prospect** | potenziale cliente già qualificato, senza documenti fiscali | assegnato alla conversione in cliente |
|
||||
| **Prospect** | potenziale cliente già qualificato, senza documenti fiscali | come i lead; alla conversione riceve il codice cliente |
|
||||
| **Lead** | contatto commerciale da qualificare (gestito con il CRM) | `L{anno}-{seq:0000}` → `L2026-0001` |
|
||||
|
||||
Lo stesso soggetto può essere sia cliente sia fornitore.
|
||||
Lo stesso soggetto può essere sia cliente sia fornitore: è un **cliente** con la casella *È anche fornitore* e compare
|
||||
in entrambi gli elenchi con lo stesso codice.
|
||||
|
||||
Il **tipo soggetto** (*azienda*, *privato*, *pubblica amministrazione*, *UE*, *extra-UE*, *forfettario*) determina
|
||||
i controlli e i valori proposti: codice destinatario SDI, split payment, bollo, partita IVA estera.
|
||||
Il **tipo soggetto** (*impresa italiana*, *privato*, *pubblica amministrazione*, *impresa UE*, *impresa extra-UE*,
|
||||
*forfettario*) determina i controlli e i valori proposti: codice destinatario SDI, split payment, partita IVA estera,
|
||||
paese della sede.
|
||||
|
||||
## Radar dei clienti
|
||||
|
||||
@@ -35,55 +38,68 @@ i controlli e i valori proposti: codice destinatario SDI, split payment, bollo,
|
||||

|
||||
*Mockup 012 — lo stesso radar con il menu espanso (anteprima ridotta).*
|
||||
|
||||
Il radar elenca le anagrafiche con le colonne **Codice**, **Ragione sociale**, **P.IVA / C.F.**, **Città**,
|
||||
**Pagamento**, **Listino**, **Agente**, **Fatturato** dell'anno, **Scaduto** (in rosso se presente) e **Stato**. Lo
|
||||
stato è un badge: *Attivo*, *Disabilitato*, *PA · split*, *UE*, *Extra-UE*, *Privato*, *Fido superato*.
|
||||

|
||||
*Khaemhat 0.4.0 — il radar dei clienti di esempio con i filtri Soggetto, Agente e Stato e lo stato di ogni anagrafica (impresa UE, PA con split payment, privato, bloccato, anche fornitore). Fatturato e scaduto arrivano con vendite e scadenzario.*
|
||||
|
||||
- Filtri: ricerca libera, **Tipo**, **Agente**, **Stato**, più filtri aggiunti come chip (ad esempio *Scaduto > 0*,
|
||||
*Provincia: CN, TO, AT*).
|
||||
- Il piede mostra i totali della selezione (ad esempio *1.284 clienti · 12 selezionati · fatturato visibile*).
|
||||
- Tasti: `F9` radar, `Invio` apri, `Spazio` seleziona. Con più righe selezionate si possono usare le azioni
|
||||
multiple (stampa, e-mail, esporta, **Disabilita**).
|
||||
Il radar elenca le anagrafiche con le colonne **Codice**, **Ragione sociale**, **P.IVA / C.F.**, **Città** (con la
|
||||
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).
|
||||
|
||||
- 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
|
||||
anagrafiche attive.
|
||||
- Tasti: `F9` radar, `Invio` o doppio clic apre la scheda, `Spazio` seleziona. Con più righe selezionate si usano
|
||||
**Disattiva** e **Riattiva**; l'esportazione CSV/XLSX è quella di tutti i radar.
|
||||
|
||||
## La scheda anagrafica
|
||||
|
||||

|
||||
*Mockup 014 — scheda cliente: azioni Scheda 360°, Nuovo documento, VIES, Attività CRM; intestazione con identità, condizioni e fatturato; scheda Dati principali a gruppi (anteprima ridotta).*
|
||||
|
||||
**Toolbar**: comandi standard a icone (vedi [Interfaccia e scorciatoie](Interfaccia-e-scorciatoie)) e le azioni
|
||||
contestuali **Scheda 360°** (visione completa: documenti, partite, attività CRM), **Nuovo documento**, **VIES**
|
||||
(verifica della partita IVA comunitaria), **Attività CRM**.
|
||||

|
||||
*Khaemhat 0.4.0 — la scheda di un cliente di esempio: intestazione con condizioni e agente, schede con i contatori e gruppi Identità, Sede legale, Recapiti, Classificazione e consensi.*
|
||||
|
||||
**Intestazione** in tre blocchi: a sinistra tipo (*Cliente*), codice e nome, stato (*Attivo*), uso del fido, data
|
||||
di inizio rapporto, agente; al centro ragione sociale con P.IVA, indirizzo, contatti e i chip delle condizioni
|
||||
(pagamento, listino e sconto, codice SDI, dichiarazione d'intento, scaduto); a destra il **fatturato** dell'anno con
|
||||
anno precedente, aperto e fido.
|
||||
**Toolbar**: comandi standard a icone (vedi [Interfaccia e scorciatoie](Interfaccia-e-scorciatoie)) e le azioni
|
||||
contestuali **Verifica VIES** (partita IVA comunitaria) e, per prospect, lead e fornitori, **Converti in cliente**;
|
||||
nel menu `…` **Disattiva** o **Riattiva**. *Scheda 360°*, *Nuovo documento* e *Attività CRM* arrivano con vendite e
|
||||
CRM.
|
||||
|
||||
**Intestazione**: tipo, codice e nome, stato, data di inizio rapporto e agente; i chip delle condizioni (pagamento,
|
||||
listino, agente, esito VIES, split payment). Il blocco del **fatturato** arriva con le vendite (M5).
|
||||
|
||||
**Schede**:
|
||||
|
||||
| Scheda | Contenuto |
|
||||
|---|---|
|
||||
| **Dati principali** | gruppi *Identità*, *Sede legale*, *Classificazione e note* |
|
||||
| **Indirizzi** | destinazioni diverse (cantieri, sedi di consegna, indirizzo di fatturazione) |
|
||||
| **Contatti** | persone di riferimento con ruolo, telefono, e-mail |
|
||||
| **Condizioni commerciali** | condizioni di vendita (clienti) o di acquisto (fornitori) |
|
||||
| **Fiscale e SDI** | fatturazione elettronica, regime IVA, ritenute, dichiarazione d'intento, identificativi |
|
||||
| **Banche** | conti correnti della controparte (IBAN) |
|
||||
| **Articoli e codici** | codici con cui la controparte identifica i tuoi articoli |
|
||||
| **Dati principali** | gruppi *Identità*, *Dati di nascita* (privati), *Sede legale*, *Recapiti*, *Classificazione e consensi* |
|
||||
| **Indirizzi** | destinazioni diverse (destinazione merce, fatturazione, cantiere o sede operativa), una predefinita per tipo |
|
||||
| **Contatti** | persone di riferimento con ruolo, telefono, cellulare, e-mail; un contatto principale |
|
||||
| **Condizioni** | condizioni di vendita (clienti), di acquisto (fornitori, e clienti che sono anche fornitori), conti contabili |
|
||||
| **Fiscale e SDI** | fatturazione elettronica, regime IVA, ritenute e casse, dichiarazione d'intento, identificativi |
|
||||
| **Banche** | conti correnti della controparte (IBAN), uno predefinito |
|
||||
| **Articoli e codici** | i codici con cui il cliente o il fornitore identifica i tuoi articoli: codice, articolo (ricerca F4), descrizione; nei documenti di quell'anagrafica la ricerca degli articoli trova anche questi codici (vedi [Articoli e listini](Articoli-e-listini)) |
|
||||
| **Note e allegati** | note libere e file allegati all'anagrafica |
|
||||
| **CRM** | lead, opportunità e attività collegate (con modulo CRM) |
|
||||
| **Storico** | modifiche registrate: chi, quando, cosa |
|
||||
|
||||
Una scheda con errori mostra il numero degli errori nell'etichetta; le liste mostrano quante righe contengono. La
|
||||
scheda *CRM* arriva con il modulo CRM. Nella scheda *Articoli e codici* lo stesso codice non si ripete per la stessa
|
||||
anagrafica.
|
||||
|
||||
### Dati principali
|
||||
|
||||
| Gruppo | Campi |
|
||||
|---|---|
|
||||
| **Identità** | Codice (automatico), Tipo, Tipo soggetto, **Ragione sociale** *, Denominazione fiscale, **Partita IVA** *, Codice fiscale, REA, Categoria |
|
||||
| **Sede legale** | Indirizzo, N., CAP, Comune, Provincia, Paese, Telefono, E-mail, PEC, Sito |
|
||||
| **Classificazione e note** | Agente, Lingua, Valuta, Attivo, Privacy accettata, Marketing, Note |
|
||||
| **Identità** | Codice (automatico), Codice precedente, Tipo, Tipo soggetto, **Ragione sociale** *, Denominazione per i documenti, **Partita IVA** *, Codice fiscale, REA, Categoria |
|
||||
| **Dati di nascita** | Data, Sesso, Comune di nascita (codice catastale) |
|
||||
| **Sede legale** | Indirizzo, Civico, CAP, Comune, Provincia, Paese |
|
||||
| **Recapiti** | Telefono, Cellulare, E-mail, PEC, Sito web |
|
||||
| **Classificazione e consensi** | Agente, Lingua, Valuta, In anagrafica dal, Informativa privacy accettata, Consenso al marketing |
|
||||
|
||||
Per i privati si inseriscono nome e cognome al posto della ragione sociale. Digitando il **CAP** Khaemhat propone
|
||||
comune, provincia e regione; il **codice fiscale** di una persona fisica può essere calcolato dai dati anagrafici.
|
||||
Per i privati si inseriscono cognome e nome al posto della ragione sociale. Digitando il **CAP** Khaemhat propone
|
||||
comune e provincia (se il CAP è di più comuni li elenca e si sceglie); digitando il comune propone il CAP. Il
|
||||
**codice fiscale** di un privato si calcola con il pulsante accanto al campo da cognome, nome e dati di nascita.
|
||||
|
||||
### Fiscale e SDI
|
||||
|
||||
@@ -93,7 +109,8 @@ comune, provincia e regione; il **codice fiscale** di una persona fisica può es
|
||||
| Gruppo | Campi |
|
||||
|---|---|
|
||||
| **Fatturazione elettronica** | **Codice destinatario** *, PEC destinatario, tipo destinatario, formato (FPR12 privati / FPA12 PA), riferimento amministrazione, *Allega PDF di cortesia*, *Invia copia via e-mail all'emissione* |
|
||||
| **Regime IVA e ritenute** | *Split payment* (art. 17-ter), *Reverse charge* predefinito, codice IVA predefinito, esigibilità, *Soggetto a ritenuta*, cassa previdenza, bollo (a carico del cliente o dell'azienda), regime |
|
||||
| **Regime IVA** | *Scissione dei pagamenti* (art. 17-ter), *Inversione contabile*, codice IVA abituale, esigibilità (I, D, S), bollo a carico del cliente |
|
||||
| **Ritenute e casse** | *Ritenuta d'acconto* con aliquota e causale, cassa previdenziale con aliquota, *ENASARCO* |
|
||||
| **Dichiarazione d'intento** (esportatore abituale) | Attiva, Numero, Data, Protocollo AdE, Codice IVA (non imponibile art. 8 c.1 lett. c, natura N3.5), **Plafond**, **Utilizzato**, **Residuo**, Validità |
|
||||
| **Identificativi** | GLN, EORI, nostro codice presso il cliente |
|
||||
|
||||
@@ -101,21 +118,22 @@ comune, provincia e regione; il **codice fiscale** di una persona fisica può es
|
||||
|
||||
| Controparte | Valore |
|
||||
|---|---|
|
||||
| Azienda italiana (B2B) | 7 caratteri, comunicati dal cliente (in alternativa la PEC) |
|
||||
| Azienda italiana (B2B) | 7 caratteri, comunicati dal cliente; con la sola PEC si usa `0000000` (proposto) |
|
||||
| Pubblica amministrazione | **codice IPA** dell'ufficio, 6 caratteri |
|
||||
| Estero (UE ed extra-UE) | `XXXXXXX` |
|
||||
| Privato | `0000000` |
|
||||
| Estero (UE ed extra-UE) | `XXXXXXX` (proposto se vuoto) |
|
||||
| Privato | `0000000` (proposto se vuoto) |
|
||||
|
||||
**Dichiarazione d'intento**: quando il cliente è esportatore abituale, le fatture usano il codice IVA non
|
||||
imponibile collegato e riportano numero e protocollo della dichiarazione; l'utilizzato si aggiorna con le fatture e
|
||||
il residuo avvisa quando il plafond sta per esaurirsi (il mockup mostra un avviso all'80% e un blocco al 100%; le
|
||||
soglie definitive saranno fissate in sviluppo). Il registro completo delle dichiarazioni ricevute ed emesse è nel
|
||||
soglie si fissano con la fatturazione, M5). Una dichiarazione attiva richiede numero e plafond. Il registro completo delle dichiarazioni ricevute ed emesse è nel
|
||||
modulo Fatturazione elettronica (vedi [Fatturazione elettronica](Fatturazione-elettronica)).
|
||||
|
||||
### Condizioni di vendita (clienti)
|
||||
|
||||
Listino, sconti, pagamento, banca d'appoggio per le RiBa, agente, vettore, porto, deposito, **fido** e **blocco**,
|
||||
raggruppamento dei DDT in fattura differita, giorno di fatturazione, invio dei documenti per e-mail o PEC. Queste
|
||||
Listino, due sconti, pagamento, nostra banca d'appoggio per le RiBa, vettore, porto, deposito, **fido** e **ordini
|
||||
bloccati**, raggruppamento dei DDT in fattura differita, giorno di fatturazione, invio dei documenti per e-mail o PEC
|
||||
con l'indirizzo dedicato. Queste
|
||||
condizioni vengono proposte automaticamente nei documenti del cliente (vedi [Vendite](Vendite)).
|
||||
|
||||
Il **fido** è l'esposizione massima ammessa: quando viene superato, o se il cliente ha scaduto, gli ordini
|
||||
@@ -128,13 +146,12 @@ segnalano il blocco, superabile solo da chi ha il permesso di forzarlo.
|
||||
|
||||
| Gruppo | Campi |
|
||||
|---|---|
|
||||
| **Condizioni di acquisto** | Pagamento, Valuta, **Lead time** (giorni), **Minimo d'ordine**, Sconto %, Porto, Registro IVA acquisti, Conto di costo predefinito |
|
||||
| **Ritenute e contributi** | *Professionista (ritenuta d'acconto)*, aliquota ritenuta, causale, cassa previdenza, *Agente ENASARCO*, *Regime forfettario* (niente IVA, bollo), *Reverse charge* (es. subappalto edile) |
|
||||
| **Banca e contatti** | IBAN, BIC, referente, e-mail per gli ordini |
|
||||
| **Condizioni di acquisto** | Pagamento, **Tempo di consegna** (giorni), **Ordine minimo**, Sconto %, Porto, Registro IVA, Conto di costo, E-mail per gli ordini |
|
||||
| **Ritenute e casse** (scheda *Fiscale e SDI*) | *Ritenuta d'acconto* con aliquota e causale, cassa previdenziale, *ENASARCO*; il tipo soggetto *Forfettario* per chi non applica l'IVA |
|
||||
| **Banche** e **Contatti** | IBAN, BIC, banca, ABI e CAB; referenti |
|
||||
|
||||
L'intestazione del fornitore mostra il totale **acquisti** dell'anno, l'aperto, lo scaduto e gli ordini aperti; tra
|
||||
le schede *Articoli forniti* elenca gli articoli che il fornitore ti vende. Il lead time viene usato per calcolare
|
||||
le date di consegna previste negli ordini fornitore.
|
||||
Il tempo di consegna servirà a calcolare le date previste negli ordini fornitore. Il totale **acquisti**, l'aperto,
|
||||
lo scaduto e gli *Articoli forniti* del mockup arrivano con acquisti e articoli.
|
||||
|
||||
## Come si usa
|
||||
|
||||
@@ -142,41 +159,54 @@ le date di consegna previste negli ordini fornitore.
|
||||
|
||||
1. **Anagrafiche → Clienti**, premi **Nuovo cliente** (o `Ctrl+N`).
|
||||
2. Scegli il **tipo soggetto**. Il codice viene assegnato automaticamente al salvataggio (vedi più sotto).
|
||||
3. Inserisci ragione sociale e partita IVA: al salvataggio Khaemhat controlla la partita IVA e, se è comunitaria,
|
||||
3. Inserisci ragione sociale e partita IVA: al salvataggio Khaemhat controlla la partita IVA e, per un'impresa UE,
|
||||
la verifica sul servizio **VIES** (l'esito resta salvato con la data).
|
||||
4. Compila la sede legale partendo dal CAP.
|
||||
5. In **Fiscale e SDI** inserisci il codice destinatario o la PEC.
|
||||
6. In **Condizioni commerciali** imposta pagamento, listino, agente e fido.
|
||||
7. **Salva** (`Ctrl+S`).
|
||||
6. In **Condizioni** imposta pagamento, listino e fido; l'agente è nei dati principali.
|
||||
7. **Salva** (`Ctrl+S`). Gli errori portano alla scheda del primo campo da correggere; gli **avvisi** (ad esempio
|
||||
una partita IVA già usata da un'altra anagrafica, che va bene per filiali e sedi distinte) non bloccano e compaiono
|
||||
in un messaggio dopo il salvataggio.
|
||||
|
||||
Un lead si crea da **Contatti → Nuovo lead**, un prospect da **Contatti → Nuovo prospect**.
|
||||
|
||||
### Convertire un lead o un prospect in cliente
|
||||
|
||||
Dalla scheda del lead o del prospect usa l'azione di conversione: il soggetto diventa **cliente**, riceve il codice
|
||||
cliente secondo la maschera automatica e mantiene la propria storia (attività, opportunità). Con il modulo CRM la
|
||||
conversione si avvia anche dalla maschera dei lead (vedi [CRM](CRM)).
|
||||
Dalla scheda del lead o del prospect usa **Converti in cliente**: il soggetto diventa **cliente**, riceve il codice
|
||||
cliente secondo la maschera automatica e conserva il vecchio come **codice precedente** (si trova ancora con la
|
||||
ricerca), insieme a storico e allegati. Con il modulo CRM la conversione si avvierà anche dalla maschera dei lead
|
||||
(vedi [CRM](CRM)).
|
||||
|
||||
Su un **fornitore** la stessa azione lo rende anche cliente: il codice non cambia e l'anagrafica compare in entrambi
|
||||
gli elenchi.
|
||||
|
||||
### Disabilitare invece di cancellare
|
||||
|
||||
Un'anagrafica che compare in almeno un documento **non si cancella**: si **disabilita** (azione **Disabilita** nel
|
||||
radar o nella scheda). Un'anagrafica disabilitata non viene più proposta nei nuovi documenti né nelle ricerche
|
||||
predefinite, ma resta consultabile con i suoi documenti. Si può cancellare solo un'anagrafica mai usata.
|
||||
Un'anagrafica che compare in almeno un documento **non si cancella**: si **disattiva** (azione **Disattiva** nel
|
||||
radar o nel menu della scheda). Un'anagrafica disattivata non viene più proposta nei nuovi documenti né nelle
|
||||
ricerche predefinite, ma resta consultabile con i suoi documenti. Se si prova a eliminare un'anagrafica usata,
|
||||
Khaemhat la disattiva e lo dice. Si cancella davvero solo un'anagrafica mai usata.
|
||||
|
||||
## Validazioni
|
||||
|
||||
| Dato | Controllo |
|
||||
|---|---|
|
||||
| **Partita IVA italiana** | 11 cifre con cifra di controllo |
|
||||
| **Ragione sociale** | obbligatoria (per i privati cognome e nome) |
|
||||
| **Partita IVA italiana** | 11 cifre con cifra di controllo; obbligatoria per un'impresa; un doppione è un avviso |
|
||||
| **Partita IVA UE** | verifica sul servizio VIES della Commissione europea; esito e data salvati |
|
||||
| **Codice fiscale** | 16 caratteri con carattere di controllo (11 cifre per le società); calcolabile dai dati anagrafici |
|
||||
| **Codice fiscale** | 16 caratteri con carattere di controllo (11 cifre per le società); per un privato senza codice fiscale un avviso |
|
||||
| **Pubblica amministrazione** | serve il codice fiscale o la partita IVA |
|
||||
| **Paese** | nella tabella dei paesi; un'impresa UE ha sede in un altro paese dell'Unione, impresa italiana, privato, PA e forfettario nel paese dell'azienda |
|
||||
| **IBAN** | struttura e controllo modulo 97 |
|
||||
| **Codice destinatario** | 7 caratteri; 6 per la PA (codice IPA); `XXXXXXX` estero; `0000000` privato |
|
||||
| **E-mail / PEC** | formato dell'indirizzo |
|
||||
| **Codice** | unico fra tutte le anagrafiche |
|
||||
|
||||
## Codici automatici
|
||||
|
||||
Il codice di clienti, fornitori e lead è assegnato automaticamente secondo le maschere impostate in
|
||||
Il codice di clienti, fornitori, prospect e lead è assegnato automaticamente secondo le maschere impostate in
|
||||
*Tabelle azienda → Preferenze e codici automatici* (vedi [Tabelle azienda](Tabelle-azienda)): `C{seq:000000}` per i
|
||||
clienti, `F{seq:000000}` per i fornitori, `L{anno}-{seq:0000}` per i lead. La maschera mostra l'anteprima del
|
||||
clienti, `F{seq:000000}` per i fornitori, `L{anno}-{seq:0000}` per prospect e lead. La maschera mostra l'anteprima del
|
||||
prossimo codice; un'impostazione decide se è ammesso scrivere un **codice manuale**. Il progressivo è assegnato in
|
||||
modo atomico: due utenti che salvano insieme non ottengono mai lo stesso codice.
|
||||
|
||||
@@ -184,25 +214,31 @@ modo atomico: due utenti che salvano insieme non ottengono mai lo stesso codice.
|
||||
|
||||
| Quando | Khaemhat propone |
|
||||
|---|---|
|
||||
| inserisci il CAP | comune, provincia e regione |
|
||||
| inserisci i dati anagrafici di una persona | il codice fiscale |
|
||||
| inserisci il CAP | comune e provincia (scelta fra più comuni) |
|
||||
| inserisci il comune | CAP e provincia |
|
||||
| premi *Calcola* accanto al codice fiscale di un privato | il codice fiscale |
|
||||
| salvi una P.IVA UE | la verifica VIES |
|
||||
| inserisci un IBAN | banca e BIC (tabella ABI) |
|
||||
| crei un documento per il cliente | destinazione, listino, pagamento, agente |
|
||||
| inserisci un IBAN | ABI, CAB e banca (dalla tabella delle banche, quando caricata) |
|
||||
| lasci vuoto il codice destinatario di un privato o di un estero | `0000000` o `XXXXXXX` |
|
||||
| crei un documento per il cliente | destinazione, listino, pagamento, agente (con le vendite, M5) |
|
||||
|
||||
Le singole compilazioni si attivano o disattivano in *Tabelle azienda → Preferenze e codici automatici*.
|
||||
|
||||
## Permessi e licenza
|
||||
|
||||
Le anagrafiche fanno parte del modulo **CORE**. Il flag utente *vede solo i propri clienti* limita un agente ai
|
||||
clienti a lui assegnati. Le schede *CRM* e *Scheda 360°* mostrano i dati CRM solo con il modulo **CRM** attivo; il
|
||||
Le anagrafiche fanno parte del modulo **CORE**: `parties.party.read` per consultare, `parties.party.write` per
|
||||
inserire, modificare, disattivare e convertire, `parties.party.delete` per eliminare. Il flag utente *vede solo i
|
||||
propri clienti*, che limiterà un agente ai clienti assegnati, non è ancora attivo. Le schede *CRM* e *Scheda 360°* mostrano i dati CRM solo con il modulo **CRM** attivo; il
|
||||
registro delle dichiarazioni d'intento richiede **EINV**. Ogni modifica è registrata nello **Storico**.
|
||||
|
||||
## Domande frequenti
|
||||
|
||||
- **Non riesco a cancellare un cliente.** Ha documenti collegati: disabilitalo.
|
||||
- **La verifica VIES non risponde.** Il servizio europeo può essere temporaneamente non disponibile: salva
|
||||
comunque e ripeti la verifica con l'azione **VIES** più tardi.
|
||||
comunque e ripeti la verifica con l'azione **Verifica VIES** più tardi.
|
||||
- **Ho convertito un prospect e il vecchio codice è sparito.** È nel campo *Codice precedente* e la ricerca lo trova.
|
||||
- **Un fornitore compare anche fra i clienti.** È un cliente con *È anche fornitore*: un solo soggetto, un solo
|
||||
codice.
|
||||
- **Un cliente privato non ha codice destinatario.** È corretto: si usa `0000000` e la fattura resta disponibile
|
||||
nell'area riservata del cliente sul sito dell'Agenzia delle Entrate; consegnagli comunque una copia di cortesia.
|
||||
|
||||
|
||||
@@ -1,153 +1,212 @@
|
||||
# Articoli e listini
|
||||
|
||||
> **Stato:** bozza · **Ultima revisione:** 2026-11-10 · **Versione software:** non ancora rilasciata (milestone M4)
|
||||
> **Modulo di licenza:** CORE · **Permessi principali:** famiglia `items.*` (es. `items.cost.read` per vedere i costi) · **Specifica:** SPEC §11.2, §11.3 (prezzi), §11.6
|
||||
> **Stato:** completa · **Ultima revisione:** 2026-11-12 · **Versione software:** 0.4.0 (milestone M4; giacenze e costi dai movimenti con il magazzino, 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 di solo testo e cespiti.
|
||||
Nella scheda articolo stanno codici, unità di misura, IVA, conti contabili, prezzi e costi, i parametri di
|
||||
**riordino** e le **giacenze** per deposito in tempo reale. I **listini** raccolgono i prezzi di vendita per gruppi di
|
||||
clienti e si aggiornano anche in modo massivo.
|
||||
L'**articolo** descrive ciò che l'azienda vende o compra: merci, servizi, spese, righe descrittive e cespiti. Nella
|
||||
scheda articolo stanno codici, unità di misura, IVA, conti, prezzi e costi e i parametri di **riordino**. I
|
||||
**listini** raccolgono i prezzi di vendita per gruppi di clienti, con una data di validità, e si aggiornano anche in
|
||||
modo massivo.
|
||||
|
||||
## Dove si trova
|
||||
|
||||
Menu **Anagrafiche → Articoli** e **Anagrafiche → Listini**; le categorie articolo sono in **Anagrafiche →
|
||||
Categorie**.
|
||||
Menu **Anagrafiche → Articoli** e **Anagrafiche → Listini**. Le **categorie articolo**, le **intestazioni dei
|
||||
listini** e le **unità di misura** sono tabelle dell'azienda (vedi [Tabelle azienda](Tabelle-azienda)).
|
||||
|
||||
## L'elenco degli articoli
|
||||
|
||||
L'elenco è una griglia con ricerca per codice, descrizione, codice a barre (anche alternativo) e marca, e le colonne
|
||||
codice, descrizione, tipo, categoria, UM, **prezzo base**, **costo medio** (solo con il permesso di vedere i costi),
|
||||
magazzino e stato. I filtri rapidi scelgono tipo, categoria, articoli a magazzino e **attivi / disattivati**. Dalla
|
||||
toolbar si disattivano e riattivano gli articoli selezionati e si apre la griglia dei listini.
|
||||
|
||||

|
||||
*Khaemhat 0.4.0 — il radar dei 120 articoli di esempio con categoria, UM, marca, tipo, costo medio e prezzo base.*
|
||||
|
||||
## La scheda articolo
|
||||
|
||||

|
||||
*Mockup 017 — scheda articolo: azioni Movimenti, Etichette, Proposta riordino; intestazione con disponibilità e costo medio; gruppi Identità, Codici UM e fisco, Prezzi e costi, Riordino; giacenze per deposito (anteprima ridotta).*
|
||||
*Mockup 017 — scheda articolo: intestazione con prezzo e costo medio; gruppi Identità, Codici UM e fisco, Prezzi e costi, Riordino; giacenze per deposito (anteprima ridotta).*
|
||||
|
||||
**Toolbar**: comandi standard e le azioni contestuali **Movimenti** (movimenti di magazzino dell'articolo),
|
||||
**Etichette** (stampa etichette), **Proposta riordino**.
|
||||

|
||||
*Khaemhat 0.4.0 — la scheda di un articolo di esempio con prezzo base, costo medio e margine nell'intestazione e le schede UM, codici alternativi, listini, fornitori e sostitutivi.*
|
||||
|
||||
**Intestazione**: a sinistra codice, avvisi (ad esempio *Sotto punto di riordino*), EAN e categoria; al centro
|
||||
descrizione, UM, marca, peso, nomenclatura NC8, aliquota IVA e chip con prezzi di listino, disponibilità
|
||||
(*Disp. · Imp. · Ord.*), fornitore abituale, scorta minima e punto di riordino; a destra il **costo medio** con
|
||||
ultimo costo, costo standard e margine.
|
||||
**Intestazione**: codice, descrizione, tipo e categoria; a destra il **prezzo base in vigore oggi** con costo medio,
|
||||
ultimo costo, costo standard e **margine** (i costi solo con il permesso `items.cost.read`).
|
||||
|
||||
**Schede**: *Dati principali*, *UM alternative*, *Codici alternativi*, *Listini*, *Fornitori*, *Sostitutivi*,
|
||||
*Movimenti*, *Immagini e allegati*.
|
||||
**Schede**:
|
||||
|
||||
| Scheda | Contenuto |
|
||||
|---|---|
|
||||
| **Dati principali** | i gruppi *Identità*, *Unità, codici e IVA*, *Prezzi e costi*, *Magazzino e riordino*, *Contabilità* |
|
||||
| **UM alternative** | unità diverse da quella base con il **fattore** (una scatola da 10 pezzi ha fattore 10) e l'EAN della confezione |
|
||||
| **Codici alternativi** | codici a barre dei produttori e codici dei vecchi gestionali: la ricerca li trova esattamente |
|
||||
| **Listini** | i prezzi in vigore oggi in ogni listino, i prezzi di listino scritti con la loro data e i **prezzi netti dei clienti** |
|
||||
| **Fornitori** | chi fornisce l'articolo, con codice e prezzo del fornitore, giorni di consegna, minimo d'ordine e il **fornitore abituale** |
|
||||
| **Sostitutivi** | articoli equivalenti da proporre quando quello richiesto manca |
|
||||
| **Note e allegati** | note libere e file (immagini, schede tecniche) |
|
||||
| **Storico** | modifiche registrate: chi, quando, cosa |
|
||||
|
||||
Una scheda con errori mostra il numero degli errori nell'etichetta, come nelle [Anagrafiche](Anagrafiche).
|
||||
|
||||
### Campi principali
|
||||
|
||||
| Gruppo | Campi |
|
||||
|---|---|
|
||||
| **Identità** | Codice (automatico), Tipo, Categoria, **Descrizione** *, Descrizione estesa, Marca, Produttore |
|
||||
| **Codici, UM e fisco** | UM base, EAN (con verifica della cifra di controllo), NC8 (Intrastat), IVA vendita, IVA acquisto, Peso netto, Conto ricavo, Conto costo |
|
||||
| **Prezzi e costi** | prezzi dei listini principali (es. base, pubblico IVA inclusa, rivenditori), Costo standard, Ultimo costo, Medio ponderato (gli ultimi due calcolati) |
|
||||
| **Riordino** | Gestito a magazzino, Deposito, **Scorta minima**, **Punto di riordino**, **Lotto di riordino**, Fornitore abituale |
|
||||
| **Giacenze per deposito (tempo reale)** | per ogni deposito: Giacenza, Impegnato, Ordinato, Disponibile, Valore, con riga di totale |
|
||||
| **Unità, codici e IVA** | UM base, codice a barre (EAN, con verifica della cifra di controllo), nomenclatura **NC8** (otto cifre, per Intrastat), IVA vendita, IVA acquisto, Peso netto e lordo |
|
||||
| **Prezzi e costi** | Prezzo dell'articolo (vale solo se nessun listino ha un prezzo), Costo standard, Ultimo costo, Costo medio |
|
||||
| **Magazzino e riordino** | Gestito a magazzino, Deposito, **Scorta minima**, **Punto di riordino**, **Lotto di riordino** |
|
||||
| **Contabilità** | Conto ricavo, Conto costo |
|
||||
|
||||
### Tipi di articolo
|
||||
|
||||
| Tipo | Uso | Magazzino |
|
||||
|---|---|---|
|
||||
| **Merce** | beni venduti o acquistati | sì, se *Gestito a magazzino* |
|
||||
| **Servizio** | prestazioni (es. installazione, assistenza a ore) | no |
|
||||
| **Servizio** | prestazioni (installazione, assistenza a ore) | no |
|
||||
| **Spesa** | spese accessorie in fattura (trasporto, incasso) | no |
|
||||
| **Testo** | righe descrittive ricorrenti | no |
|
||||
| **Cespite** | beni strumentali (collegati al registro cespiti con il modulo Cespiti) | da definire in sviluppo |
|
||||
| **Descrittivo** | righe di solo testo ricorrenti | no |
|
||||
| **Cespite** | beni strumentali (registro cespiti con il modulo Cespiti) | no |
|
||||
|
||||
### Unità di misura e codici
|
||||
Solo le merci possono essere gestite a magazzino: per gli altri tipi l'opzione è spenta e Khaemhat la corregge al
|
||||
salvataggio.
|
||||
|
||||
- **UM base** (ad esempio `PZ`, `MT`, `H`, `NR`) dalla tabella delle unità di misura, con il codice usato nell'XML
|
||||
SDI; le **UM alternative** hanno un fattore di conversione (ad esempio confezione da 10 pezzi).
|
||||
- **Codici alternativi**: altri codici a barre (EAN) e codici interni; nella ricerca F4 un articolo si trova anche
|
||||
per EAN e per il **codice che il cliente usa** per quell'articolo (impostato nella scheda *Articoli e codici* del
|
||||
cliente, vedi [Anagrafiche](Anagrafiche)).
|
||||
- **Fornitori**: chi fornisce l'articolo, con codice e prezzo del fornitore; uno è il **fornitore abituale** usato
|
||||
dalla proposta di riordino.
|
||||
- **Sostitutivi**: articoli equivalenti proposti quando quello richiesto non è disponibile.
|
||||
### Costi
|
||||
|
||||
### Prezzi e 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)).
|
||||
- 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.
|
||||
|
||||
- I **prezzi di vendita** stanno nei listini (vedi sotto); la scheda mostra quelli dei listini principali.
|
||||
- **Costo standard**: valore impostato a mano.
|
||||
- **Ultimo costo** e **costo medio ponderato**: aggiornati dai carichi di magazzino (DDT di carico, fatture di
|
||||
acquisto). Il costo medio è il criterio di valorizzazione del magazzino (vedi [Magazzino](Magazzino)).
|
||||
- Il **margine** è mostrato solo a chi ha il permesso di vedere costi e margini.
|
||||
### Giacenze e riordino
|
||||
|
||||
### Riordino e giacenze
|
||||
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** attivo l'articolo partecipa ai movimenti, alle giacenze e alla **proposta di riordino**:
|
||||
quando la disponibilità scende sotto il **punto di riordino** l'articolo viene proposto per un ordine al fornitore
|
||||
abituale, in multipli del **lotto**. La griglia *Giacenze per deposito* mostra:
|
||||
### Controlli al salvataggio
|
||||
|
||||
| Colonna | Significato |
|
||||
|---|---|
|
||||
| **Giacenza** | quantità fisicamente presente |
|
||||
| **Impegnato** | quantità riservata da ordini clienti confermati |
|
||||
| **Ordinato** | quantità in arrivo da ordini fornitore |
|
||||
| **Disponibile** | giacenza - impegnato |
|
||||
| **Valore** | giacenza x costo medio |
|
||||
- Descrizione obbligatoria; categoria obbligatoria se la maschera del codice la usa.
|
||||
- Codice a barre con cifra di controllo corretta (EAN-8, EAN-13, UPC). Un codice a barre già usato da un altro
|
||||
articolo blocca il salvataggio se nelle preferenze è attivo *Blocca duplicati per EAN* (impostazione di
|
||||
partenza), altrimenti è solo un avviso.
|
||||
- NC8 di otto cifre; quantità, pesi, prezzi e costi non negativi; fattori delle UM maggiori di zero.
|
||||
- Nelle schede di dettaglio: la stessa UM, lo stesso codice alternativo, lo stesso fornitore o sostitutivo non si
|
||||
ripetono; un articolo non è sostitutivo di sé stesso; un prezzo netto vale per un cliente.
|
||||
|
||||
### Disattivare ed eliminare
|
||||
|
||||
**Disattiva** toglie l'articolo dalle ricerche dei documenti nuovi senza perdere nulla. **Elimina** cancella
|
||||
l'articolo solo se nessun altro dato lo usa (ad esempio se è sostitutivo di un altro articolo, e da M5 se compare
|
||||
nei documenti); altrimenti Khaemhat lo **disattiva** al posto dell'eliminazione e lo dice.
|
||||
|
||||
## Codici articolo
|
||||
|
||||
Il codice segue la maschera `{categoria}-{seq:0000}` con progressivo **per categoria** (categoria `VALV` →
|
||||
`VALV-0013`). Maschera, codice manuale e blocco dei duplicati per EAN si impostano in *Tabelle azienda →
|
||||
Preferenze e codici automatici* (vedi [Tabelle azienda](Tabelle-azienda)). Il codice si assegna al primo
|
||||
salvataggio.
|
||||
|
||||
I **codici che un cliente o un fornitore usa** per i tuoi articoli si scrivono nella scheda *Articoli e codici*
|
||||
dell'anagrafica (vedi [Anagrafiche](Anagrafiche)): nei documenti di quel cliente la ricerca F4 trova l'articolo
|
||||
anche con il suo codice.
|
||||
|
||||
## Listini
|
||||
|
||||

|
||||
*Mockup 018 — griglia listino x articolo: costo medio, LIST01 Base, LIST02 Pubblico, LIST03 Rivenditori, prezzi netti di un cliente e margine; cella modificata evidenziata e scheda con pallino di modifica.*
|
||||
*Mockup 018 — griglia listino x articolo: costo medio, listini base, pubblico e rivenditori, prezzi netti di un cliente e margine; cella modificata evidenziata.*
|
||||
|
||||
La maschera **Listini** è una **griglia articoli x listini**: per ogni articolo (codice, descrizione, UM, costo
|
||||
medio) una colonna per ciascun listino, più eventuali colonne di **prezzi netti per cliente** e il **margine**.
|
||||

|
||||
*Khaemhat 0.4.0 — la griglia articoli x listini sui 120 articoli di esempio: listino base, Pubblico e Rivenditori derivati (in corsivo i prezzi calcolati), costo medio e margine.*
|
||||
|
||||
- Filtri: ricerca, **Categoria**, **Listino**, **Validità** (la data a cui leggere i prezzi, ad esempio *Oggi*),
|
||||
chip *Mostra margine*.
|
||||
- I prezzi si modificano direttamente nelle celle; le modifiche restano evidenziate e la scheda mostra il pallino
|
||||
arancione finché non salvi. Il piede riporta il numero di articoli, le modifiche non salvate e la data di validità
|
||||
dei nuovi prezzi.
|
||||
- Azioni: **Aggiornamento massivo**, **Nuovo listino**; icone per salvare, annullare, stampare, esportare,
|
||||
applicare una variazione percentuale, ripristinare, duplicare.
|
||||
Un **listino** ha codice, descrizione, valuta, *IVA inclusa*, validità e, se è derivato, il listino da cui
|
||||
**deriva**, il **ricarico %** (anche negativo, come uno sconto) e il **passo di arrotondamento**. Le intestazioni si
|
||||
gestiscono nella tabella *Listini* dell'azienda; uno solo è il **listino base** (in partenza `BASE`).
|
||||
|
||||
Ogni listino ha una **validità** (i prezzi nuovi valgono da una data, i vecchi restano per i documenti precedenti),
|
||||
può essere **derivato** da un altro listino (ad esempio pubblico = base + 40%) e ha le proprie regole di
|
||||
**arrotondamento**.
|
||||
### La griglia dei listini
|
||||
|
||||
**Anagrafiche → Listini** è una griglia **articoli x listini**: per ogni articolo codice, descrizione, UM, costo
|
||||
medio (con il permesso) e una colonna per ciascun listino attivo.
|
||||
|
||||
- In alto: ricerca, **Listino** (tutti o uno solo), **Validità** (la data a cui leggere e scrivere i prezzi, oggi
|
||||
in partenza), **Prezzi netti di** un cliente (aggiunge la colonna dei suoi prezzi netti) e **Mostra margine**.
|
||||
- I prezzi si scrivono nelle celle (vuoto toglie il prezzo a quella data). Le celle cambiate restano **evidenziate
|
||||
da salvare**; il piede riporta articoli, modifiche non salvate e data di validità dei nuovi prezzi. **Salva**
|
||||
scrive tutto insieme, **Annulla modifiche** torna ai prezzi salvati.
|
||||
- Le celle in *corsivo* sono **calcolate** da un listino derivato che non ha un prezzo proprio per l'articolo: il
|
||||
suggerimento dice da quale listino. Scrivere un prezzo nella cella lo rende proprio di quel listino.
|
||||
- Con modifiche non salvate non si cambiano validità o cliente: prima salva o annulla.
|
||||
- **Nuovo listino** apre la tabella dei listini.
|
||||
|
||||
### Validità dei prezzi
|
||||
|
||||
Ogni prezzo vale **dalla sua data** fino al prezzo successivo dello stesso listino (o dello stesso cliente).
|
||||
Scrivere un prezzo con una data nuova **aggiunge** un prezzo e lascia quello vecchio ai documenti datati prima;
|
||||
scriverlo con la stessa data lo corregge. I documenti già fatti conservano sempre il prezzo di allora.
|
||||
|
||||
### Listini derivati
|
||||
|
||||
Un listino derivato senza un proprio prezzo per un articolo prende il prezzo del listino di partenza alla stessa
|
||||
data, applica il ricarico e arrotonda al passo (al centesimo se il passo è zero). Esempio dei dati di esempio:
|
||||
*Pubblico* = base + 45% arrotondato a 0,10; *Rivenditori* = base - 10%. Un prezzo scritto nel listino derivato vince
|
||||
su quello calcolato.
|
||||
|
||||
### Aggiornamento massivo
|
||||
|
||||
1. Premi **Aggiornamento massivo**.
|
||||
2. Scegli **che cosa** aggiornare: un listino, una categoria o le righe selezionate.
|
||||
3. Scegli la **variazione**: percentuale (anche negativa) oppure a partire da un altro listino.
|
||||
4. Scegli l'**arrotondamento**: a 0,10, 0,50 o 1,00, per eccesso o per difetto.
|
||||
5. Indica la **data di validità** dei nuovi prezzi.
|
||||
6. Controlla le righe aggiornate (restano evidenziate) e **Salva**.
|
||||
2. Scegli il **listino da aggiornare** e da dove **calcolare**: i prezzi attuali dello stesso listino o un altro
|
||||
listino.
|
||||
3. Scrivi la **variazione %** (anche negativa).
|
||||
4. Scegli l'**arrotondamento** (0,01, 0,10, 0,50, 1,00) e il **verso** (al più vicino, per eccesso, per difetto).
|
||||
5. Indica la data da cui valgono i nuovi prezzi (**Valido dal**).
|
||||
6. Scegli gli **articoli**: tutti, quelli di una categoria o solo i selezionati.
|
||||
7. Premi **Calcola i prezzi**: le celle calcolate restano evidenziate; controllale e **Salva**.
|
||||
|
||||
L'aggiornamento listini è disponibile anche come procedura pianificabile (vedi [Automazioni](Automazioni)).
|
||||
Il calcolo non scrive nulla finché non salvi; gli articoli il cui prezzo non cambia sono esclusi.
|
||||
|
||||
## Come viene scelto il prezzo in un documento
|
||||
|
||||
Quando inserisci un articolo in una riga di vendita, Khaemhat cerca il prezzo in quest'ordine e si ferma al primo
|
||||
che trova:
|
||||
Quando inserisci un articolo in una riga di vendita (da M5), Khaemhat cerca il prezzo valido alla data del documento
|
||||
in quest'ordine e si ferma al primo che trova:
|
||||
|
||||
| Ordine | Fonte | Esempio |
|
||||
|---|---|---|
|
||||
| 1 | **prezzo netto cliente-articolo** | prezzo concordato con Rossi Impianti per quella valvola |
|
||||
| 2 | **listino del cliente** | il cliente usa LIST03 Rivenditori |
|
||||
| 3 | **listino base** | LIST01 Base |
|
||||
| 4 | **prezzo dell'articolo** | prezzo indicato nella scheda |
|
||||
| 2 | **listino del documento o del cliente** | il cliente usa il listino *Rivenditori* |
|
||||
| 3 | **listino base** | *Base* |
|
||||
| 4 | **prezzo dell'articolo** | prezzo scritto nella scheda |
|
||||
|
||||
La riga ricorda **da dove viene il prezzo** (la fonte), così è sempre possibile capire perché è stato proposto
|
||||
quel valore. Sul prezzo si applicano poi gli sconti del cliente e della riga (anche a cascata, come `5+2`). Se è
|
||||
attiva la compilazione automatica *Ultimo prezzo praticato al cliente*, Khaemhat lo mostra come riferimento.
|
||||
|
||||
## Codici automatici
|
||||
|
||||
Il codice articolo segue la maschera `{categoria}-{seq:0000}` con progressivo **per categoria** (ad esempio
|
||||
categoria `VALV` → `VALV-0013`); la maschera, l'eventuale codice manuale e il blocco dei **duplicati per EAN** si
|
||||
impostano in *Tabelle azienda → Preferenze e codici automatici* (vedi [Tabelle azienda](Tabelle-azienda)).
|
||||
La riga ricorda **da dove viene il prezzo** (la fonte). Sul prezzo di listino si propongono gli sconti del cliente a
|
||||
cascata (come `10+5`); su un **prezzo netto** non si applicano sconti.
|
||||
|
||||
## Permessi e licenza
|
||||
|
||||
Articoli e listini sono nel modulo **CORE**. I costi e i margini sono visibili solo agli utenti con il permesso
|
||||
`items.cost.read` (flag *vede costi e margini*). Il collegamento ai cespiti richiede il modulo **ASSET**; i conti
|
||||
contabili sono usati con il modulo **ACCT**.
|
||||
Articoli e listini sono nel modulo **CORE**. Per scrivere i prezzi nella griglia serve `items.item.write`; i costi
|
||||
e i margini richiedono `items.cost.read` (il ruolo *Magazzino* gestisce gli articoli ma non vede i costi). Il
|
||||
collegamento ai cespiti richiede il modulo **ASSET**; i conti contabili sono usati con il modulo **ACCT**.
|
||||
|
||||
## Dati di esempio
|
||||
|
||||
I dati di esempio (vedi [Dati di base e di esempio](Dati-di-base-e-esempio)) creano 120 articoli fittizi di un
|
||||
grossista termoidraulico in dieci categorie (valvolame, raccorderia, tubi, caldaie, sanitari, consumabili, pompe,
|
||||
utensili, servizi, spese), i listini *Pubblico* e *Rivenditori* derivati dal base, prezzi dell'anno precedente per
|
||||
lo storico, fornitori abituali, UM alternative, codici alternativi, sostitutivi e i prezzi netti e i codici di
|
||||
Rossi Impianti. I codici a barre di esempio iniziano con `200`, prefisso riservato all'uso interno.
|
||||
|
||||
## Domande frequenti
|
||||
|
||||
- **Ho cambiato un prezzo di listino ma la fattura di ieri non cambia.** È corretto: i documenti conservano il
|
||||
prezzo con cui sono stati fatti; la validità del listino vale per i documenti nuovi.
|
||||
- **Perché il prezzo proposto non è quello del listino?** Probabilmente esiste un prezzo netto per quel cliente:
|
||||
la fonte del prezzo è indicata nella riga.
|
||||
- **Un articolo di servizio non compare nelle giacenze.** I servizi e le spese non sono gestiti a magazzino.
|
||||
prezzo con cui sono stati fatti; i prezzi nuovi valgono dalla loro data.
|
||||
- **Ho scritto un prezzo con la data sbagliata.** Imposta quella data in *Validità*, svuota la cella e salva: il
|
||||
prezzo a quella data viene tolto.
|
||||
- **Perché il prezzo proposto non è quello del listino?** Probabilmente esiste un prezzo netto per quel cliente: la
|
||||
fonte del prezzo è indicata nella riga.
|
||||
- **Non vedo il costo medio.** Serve il permesso di vedere costi e margini (`items.cost.read`).
|
||||
- **Un servizio non si può mettere a magazzino.** È voluto: solo le merci vanno a magazzino.
|
||||
|
||||
## Pagine correlate
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Changelog
|
||||
|
||||
> **Stato:** completa per 0.3.0 · **Ultima revisione:** 2026-11-11
|
||||
> **Stato:** completa per 0.4.0 · **Ultima revisione:** 2026-11-12
|
||||
|
||||
Le novità di ogni versione sono nel file
|
||||
[`CHANGELOG.md`](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/src/branch/main/CHANGELOG.md) del repository
|
||||
@@ -11,6 +11,7 @@ Le novità di ogni versione sono nel file
|
||||
|
||||
| Versione | Data | Contenuto |
|
||||
|---|---|---|
|
||||
| 0.4.0 | 2026-11-12 | M4 — Tabelle, anagrafiche, articoli: pacchetto fiscale italiano, profilo azienda, esercizi e cambi, 26 tabelle azienda con province, comuni e CAP, clienti, fornitori e contatti con controlli e VIES, articoli e listini con prezzi a validità, codici automatici, import/export guidato (anche del piano dei conti, per ora solo verifica) e dati di esempio. |
|
||||
| 0.3.0 | 2026-11-11 | M3 — Framework UI: la finestra di Khaemhat con menu, schede e barra di stato, la dashboard a widget, *Il mio profilo* con temi e colori, ricerca globale, aiuto in app, notifiche, componenti per maschere e liste, allegati e anteprima di stampa (provati su un documento di prova, le maschere gestionali arrivano da 0.4.0). |
|
||||
| 0.2.0 | 2026-11-11 | M2 — Sistema e sicurezza: avvio da variabili d'ambiente, super utente e prima azienda, accesso con password e verifica in due passaggi, utenti, ruoli e permessi, licenze e moduli con codici di prova, log per sezioni, attività programmate. |
|
||||
| 0.1.0 | 2026-11-11 | M1 — Strato dati: accesso ai database SQLite e PostgreSQL, migrazioni dello schema, registro delle aziende, cifratura dei dati riservati. Nessuna funzione visibile nell'interfaccia. |
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Dati di base e di esempio
|
||||
|
||||
> **Stato:** bozza · **Ultima revisione:** 2026-11-10 · **Versione software:** non ancora rilasciata (milestone M4; dati di esempio completi in M9)
|
||||
> **Stato:** completa per M4 · **Ultima revisione:** 2026-11-12 · **Versione software:** 0.4.0 (dati di esempio di documenti e contabilità con i moduli, completi in M9)
|
||||
> **Modulo di licenza:** CORE · **Livello richiesto:** amministratore (rimozione dati di esempio: super utente) · **Specifica:** SPEC §6, §12.11, §14
|
||||
|
||||
## A cosa serve
|
||||
@@ -21,26 +21,26 @@ alto a destra, es. *Database: khaemhat_demo*).
|
||||
|
||||
*Mockup 089 — riepilogo di tabelle di base, dati di esempio, documenti reali e utenti demo con i pulsanti **Aggiorna
|
||||
tabelle di base**, **Carica dati di esempio**, **Rimuovi dati di esempio**, **Anteprima differenze**; a destra le
|
||||
ultime migrazioni; sotto, i **pacchetti di dati di base** della versione `IT 2026.2` con contenuto, righe e stato
|
||||
ultime migrazioni; sotto, i **pacchetti di dati di base** della versione `IT 2026.3` con contenuto, righe e stato
|
||||
(anteprima ridotta)*
|
||||
|
||||
Il riepilogo mostra:
|
||||
|
||||
| Voce | Esempio |
|
||||
|---|---|
|
||||
| **Tabelle di base** | versione del pacchetto (`IT 2026.2`), righe, data dell'ultimo aggiornamento |
|
||||
| **Tabelle di base** | versione del pacchetto (`IT 2026.3`), righe, data dell'ultimo aggiornamento |
|
||||
| **Dati di esempio** | *presenti* con i conteggi (clienti, fornitori, articoli, documenti, registrazioni, cespiti, lead) oppure *assenti* |
|
||||
| **Documenti reali** | numero di documenti non dimostrativi (0 in un'azienda demo) |
|
||||
| **Utenti demo** | utenti dimostrativi e relativa password |
|
||||
|
||||
## Le tabelle di base
|
||||
|
||||
Sono raccolte in **pacchetti** con una **versione** (oggi `IT 2026.2`, salvata nelle impostazioni dell'azienda).
|
||||
Sono raccolte in **pacchetti** con una **versione** (oggi `IT 2026.3`, salvata nelle impostazioni dell'azienda).
|
||||
Il pacchetto italiano fa parte del pacchetto fiscale Italia (vedi [Fiscalità italiana](Fiscalita-italiana)).
|
||||
|
||||
| Pacchetto | Contenuto |
|
||||
|---|---|
|
||||
| **Paesi e comuni** | paesi ISO, province, comuni con CAP e codice catastale |
|
||||
| **Paesi e comuni** | paesi ISO, province, comuni con codice catastale, codice ISTAT e CAP |
|
||||
| **Valute e unità di misura** | valute, unità di misura |
|
||||
| **Codici IVA e nature** | aliquote 22, 10, 5, 4; esenti (ESE10 N4); non imponibili (NI8 N3.1, NI41 N3.2, NI71 N3.3, NI8C N3.5); fuori campo (FC7 N2.1, altre N2.2); escluse (ESC15 N1); reverse charge (RC17 N6.x); split payment; non soggette; indetraibili 50% e 100%; forfettari |
|
||||
| **Modalità e condizioni di pagamento** | modalità `MP01`-`MP23`, condizioni di pagamento |
|
||||
@@ -56,6 +56,32 @@ Il pacchetto italiano fa parte del pacchetto fiscale Italia (vedi [Fiscalità it
|
||||
| **CRM** | pipeline e fasi, modelli e-mail |
|
||||
| **Sistema** | ruoli predefiniti, regole di automazione predefinite, attività programmate di sistema |
|
||||
|
||||
### Cosa c'è oggi
|
||||
|
||||
Dalla versione 0.4.0 il caricamento di base contiene: paesi ISO con appartenenza all'UE, le 30 valute dei cambi BCE,
|
||||
unità di misura, codici IVA e nature, modalità `MP01`-`MP23` e condizioni di pagamento con le rate, tipi documento
|
||||
con codice TD, numeratori, causali di magazzino, deposito principale, porti, trasporto a cura, causali di trasporto,
|
||||
aspetto dei beni, rese, categorie, listino base e l'esercizio dell'anno in corso con i suoi mesi. Le righe fiscali
|
||||
vengono dal pacchetto del paese dell'azienda.
|
||||
|
||||
**Province e comuni** (dalla versione `IT 2026.3`) vengono dall'elenco ISTAT dei codici dei comuni aggiornato al
|
||||
26/02/2026: 110 province con sigla e regione, 7.894 comuni con codice catastale, provincia, regione e codice ISTAT.
|
||||
Il **codice** di un comune è il suo codice catastale (es. `H501` per Roma), lo stesso del codice fiscale.
|
||||
I **CAP** vengono dall'elenco dei codici postali di GeoNames e ci sono per 7.750 comuni: un CAP, una lista o un
|
||||
intervallo come `10121-10156` per le città con più CAP.
|
||||
|
||||
> Fonti: ISTAT, *Codici statistici delle unità amministrative territoriali*, e GeoNames
|
||||
> ([www.geonames.org](https://www.geonames.org)), entrambi con licenza
|
||||
> [CC BY 4.0](https://creativecommons.org/licenses/by/4.0/deed.it).
|
||||
|
||||
Ai comuni rinominati o nati da fusioni recenti (ad esempio Sanremo) il CAP può mancare: si completa a mano nella
|
||||
tabella *Comuni* o con l'**Importa CSV** (colonne `Code` e `PostalCodes`, più CAP separati da virgola). La
|
||||
compilazione dal CAP propone solo i comuni che hanno il CAP scritto. Le **banche ABI/CAB** non sono ancora incluse: banca e BIC dall'IBAN vengono da un conto
|
||||
dell'azienda presso la stessa banca. Un comune soppresso per fusione resta nella tabella finché non lo disattivi.
|
||||
|
||||
Le altre voci dell'elenco (piano dei conti, causali contabili, registri IVA, cespiti, codici tributo, CRM) arrivano con i
|
||||
moduli che le usano.
|
||||
|
||||
### Aggiorna tabelle di base
|
||||
|
||||
Ogni nuova versione di Khaemhat può portare un pacchetto aggiornato (nuovi codici IVA, nuovi tipi documento SDI,
|
||||
@@ -64,8 +90,12 @@ nuovi codici tributo…).
|
||||
1. Premi **Anteprima differenze** per vedere cosa cambierebbe.
|
||||
2. Premi **Aggiorna tabelle di base**.
|
||||
|
||||
L'aggiornamento è **idempotente** (rieseguirlo non duplica nulla) e **aggiunge solo i codici mancanti senza
|
||||
toccare le righe che l'azienda ha modificato**.
|
||||
L'aggiornamento è **idempotente** (rieseguirlo non duplica nulla) e **aggiunge solo i codici mancanti**: una riga
|
||||
già presente non viene mai modificata né cancellata, anche se l'azienda non l'ha mai toccata. Se una nuova versione
|
||||
corregge un codice esistente (ad esempio un riferimento normativo), il [CHANGELOG](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/src/branch/main/CHANGELOG.md)
|
||||
lo segnala e la correzione si fa nella tabella. La versione caricata è salvata nelle impostazioni dell'azienda.
|
||||
|
||||
Lo stesso aggiornamento si avvia dal menu `…` di ogni tabella con **Aggiorna da tabelle base**.
|
||||
|
||||
Le tabelle di base si caricano anche automaticamente alla creazione di un'azienda, se la variabile
|
||||
`KHAEMHAT_SEED_BASE` non è `false` (predefinito `true`).
|
||||
@@ -94,6 +124,16 @@ reale. Contiene:
|
||||
| Log | voci di log di esempio in tutte le sezioni |
|
||||
|
||||
Tutte le righe dimostrative sono marcate come tali (`is_demo`), così si possono rimuovere senza toccare il resto.
|
||||
|
||||
**Oggi (M4)** i dati di esempio contengono 3 agenti e **21 anagrafiche**: 12 clienti che coprono tutti i tipi
|
||||
soggetto (fra cui un comune con split payment, un cliente bloccato, uno disattivato, uno che è anche fornitore e
|
||||
uno con dichiarazione d'intento), 5 fornitori (professionista con ritenuta, agente ENASARCO, fornitore UE),
|
||||
2 prospect e 2 lead. Partite IVA, codici fiscali e IBAN sono numeri inventati ma formalmente validi, perché passino
|
||||
i controlli; non si verificano sul VIES (ADR 0029). Gli agenti di esempio non sono marcati e si rimuovono a mano.
|
||||
Ci sono poi **120 articoli** in dieci categorie con i listini *Pubblico* e *Rivenditori* derivati dal base, prezzi
|
||||
dell'anno precedente, fornitori abituali, UM e codici alternativi, sostitutivi e i prezzi netti e i codici di un
|
||||
cliente (ADR 0030, vedi [Articoli e listini](Articoli-e-listini)). I codici a barre di esempio iniziano con `200`,
|
||||
prefisso riservato all'uso interno. Il resto della tabella arriva con le milestone dei rispettivi moduli.
|
||||
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.
|
||||
|
||||
@@ -125,14 +165,29 @@ esempio.
|
||||
|
||||
## Da riga di comando
|
||||
|
||||
Lo script `scripts/seed.sh` esegue le stesse operazioni fuori dall'interfaccia (utile in sviluppo):
|
||||
Lo script `scripts/seed.sh` aggiunge le tabelle di base e i dati di esempio fuori dall'interfaccia. Esegue la sequenza di avvio
|
||||
(migrazioni, prima azienda) senza servire pagine, poi lavora su un'azienda o su tutte quelle attive e stampa le righe
|
||||
aggiunte per tabella. Usa le stesse variabili `KHAEMHAT_*` del servizio.
|
||||
|
||||
Nel container (lo script è in `/app/scripts/`):
|
||||
|
||||
```
|
||||
scripts/seed.sh --base
|
||||
scripts/seed.sh --demo [--scale N] [--company CODICE]
|
||||
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
|
||||
```
|
||||
|
||||
`--scale N` moltiplica i volumi dei dati di esempio (usato per le prove di prestazione).
|
||||
In sviluppo, dalla cartella del repository: `scripts/seed.sh --base|--demo [--scale N] [--company CODICE]`.
|
||||
|
||||
| Opzione | Effetto |
|
||||
|---|---|
|
||||
| `--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 |
|
||||
| `--company CODICE` | lavora solo su quell'azienda invece che su tutte quelle attive |
|
||||
|
||||
I dati di esempio si caricano anche al primo avvio con `KHAEMHAT_SEED_DEMO=true`.
|
||||
|
||||
## Migrazioni
|
||||
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
# Fiscalità italiana
|
||||
|
||||
> **Stato:** bozza · **Ultima revisione:** 2026-11-10 · **Versione software:** non ancora rilasciata (milestone M4-M10)
|
||||
> **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
|
||||
|
||||
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.
|
||||
|
||||
Tutte queste tabelle sono **caricate dai dati di base** (pacchetto dati, per esempio `IT 2026.2`) e si aggiornano da
|
||||
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.
|
||||
@@ -58,6 +58,9 @@ caso di dubbio fa fede il testo mostrato dal programma, non questa pagina.
|
||||
| TD28 | Acquisti da San Marino con IVA (fattura cartacea) | acquisti |
|
||||
| TD29 | Comunicazione per omessa o irregolare fatturazione | regolarizzazione (introdotto con le specifiche v1.9) |
|
||||
|
||||
Versione delle specifiche tecniche seguita: **1.9.1** (pubblicata dall'Agenzia il 31 marzo 2026, in vigore dal
|
||||
15 maggio 2026; non cambia le code list della 1.9, che ha introdotto TD29 e ridefinito TD20).
|
||||
|
||||
Formati di trasmissione: **FPR12** (verso privati), **FPA12** (verso pubbliche amministrazioni), **FSM10** (fattura
|
||||
semplificata). Nome del file: `IT<partita IVA>_<progressivo>.xml`.
|
||||
|
||||
@@ -70,7 +73,7 @@ codice IVA sulla riga del documento la natura viene compilata da sola.
|
||||
|---|---|---|
|
||||
| N1 | Escluse ex art. 15 DPR 633/72 | `ESC15` |
|
||||
| N2.1 | Non soggette ad IVA ai sensi degli artt. da 7 a 7-septies DPR 633/72 | `FC7` |
|
||||
| N2.2 | Non soggette - altri casi | fuori campo altre (anche fatture da forfettari) |
|
||||
| N2.2 | Non soggette - altri casi | `NS`, `FORF` (operazioni in regime forfettario) |
|
||||
| N3.1 | Non imponibili - esportazioni | `NI8` |
|
||||
| N3.2 | Non imponibili - cessioni intracomunitarie | `NI41` |
|
||||
| N3.3 | Non imponibili - cessioni verso San Marino | `NI71` |
|
||||
@@ -79,11 +82,25 @@ codice IVA sulla riga del documento la natura viene compilata da sola.
|
||||
| N3.6 | Non imponibili - altre operazioni che non concorrono alla formazione del plafond | — |
|
||||
| N4 | Esenti | `ESE10` |
|
||||
| N5 | Regime del margine / IVA non esposta in fattura | — (regime del margine previsto in fase 2) |
|
||||
| N6.1 … N6.9 | Inversione contabile (reverse charge): rottami (N6.1), oro e argento (N6.2), subappalto edile (N6.3), cessione di fabbricati (N6.4), telefoni cellulari (N6.5), prodotti elettronici (N6.6), prestazioni comparto edile e connessi (N6.7), settore energetico (N6.8), altri casi (N6.9) | `RC17` (varianti per sotto-codice) |
|
||||
| N6.1 … N6.9 | Inversione contabile (reverse charge): rottami (N6.1), oro e argento (N6.2), subappalto edile (N6.3), cessione di fabbricati (N6.4), telefoni cellulari (N6.5), prodotti elettronici (N6.6), prestazioni comparto edile e connessi (N6.7), settore energetico (N6.8), altri casi (N6.9) | `RC74` (N6.1), `RC17O` (N6.2), `RC17A` (N6.3), `RC17F` (N6.4), `RC17B` (N6.5), `RC17C` (N6.6), `RC17E` (N6.7), `RC17N` (N6.8), `RC17` (N6.9) |
|
||||
| N7 | IVA assolta in altro stato UE | — |
|
||||
|
||||
Altri codici IVA di base: aliquote **22**, **10**, **5**, **4**; **SPLIT** (scissione dei pagamenti), **NS**,
|
||||
**indetraibili 50% e 100%**, codici per **forfettari**.
|
||||
Altri codici IVA di base: aliquote **22**, **10**, **5**, **4**; **22SP** e **10SP** (scissione dei pagamenti,
|
||||
esigibilità S); **22I50** e **22I100** (IVA 22% indetraibile al 50% e al 100%).
|
||||
|
||||
I codici N2, N3 e N6 senza sotto-codice non sono più accettati dallo SDI: Khaemhat li riconosce nei documenti vecchi
|
||||
ma non li lascia scegliere su un codice IVA nuovo.
|
||||
|
||||
**Controlli sul codice IVA.** Salvando un codice IVA Khaemhat verifica che:
|
||||
|
||||
- un'aliquota maggiore di zero non abbia natura e un'aliquota zero ce l'abbia;
|
||||
- la natura esista e sia ancora valida;
|
||||
- la scissione dei pagamenti abbia un'aliquota;
|
||||
- l'inversione contabile (N6.x) abbia esigibilità immediata;
|
||||
- la percentuale di indetraibilità sia fra 0 e 100.
|
||||
|
||||
Sono solo **avvisi** (il codice si salva) un'aliquota diversa da 4, 5, 10 e 22 (per esempio le percentuali di
|
||||
compensazione agricole) e la mancanza del riferimento normativo, che va stampato in fattura quando c'è la natura.
|
||||
|
||||
**Esigibilità** (campo del codice IVA): **I** immediata, **D** differita, **S** scissione dei pagamenti (split
|
||||
payment).
|
||||
@@ -181,12 +198,13 @@ Khaemhat propone il codice tributo e prepara i **dati F24** da passare a interme
|
||||
| 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 | interessi calcolati in automatico |
|
||||
| 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 |
|
||||
| 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** | applicato in automatico; addebito al cliente o a carico azienda |
|
||||
| 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 |
|
||||
| Fattura differita (TD24) | emissione entro il 15 del mese successivo a quello delle consegne documentate da DDT | procedura **Fatturazione differita** |
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Khaemhat
|
||||
|
||||
> **Stato:** bozza · **Ultima revisione:** 2026-11-10 · **Versione software:** 0.0.1 (M0, pagina "in costruzione"; sviluppo in corso)
|
||||
> **Stato:** bozza · **Ultima revisione:** 2026-11-12 · **Versione software:** 0.4.0 (M4; sviluppo in corso)
|
||||
|
||||

|
||||
|
||||
@@ -12,8 +12,8 @@ Docker** e gestisce più aziende sulla stessa installazione.
|
||||
Il nome viene da uno scriba dell'antico Egitto che sovrintendeva ai granai del regno: vedi
|
||||
[Origine del nome](Origine-del-nome).
|
||||
|
||||
> Il software è **in fase di progettazione**: questa wiki descrive ciò che verrà costruito, milestone dopo
|
||||
> milestone. Ogni pagina indica nel riquadro iniziale lo stato (*bozza* finché la funzione non è consegnata) e la
|
||||
> Il software è **in sviluppo** (versioni 0.x): questa wiki descrive ciò che è già consegnato e ciò che verrà
|
||||
> costruito, milestone dopo milestone. Ogni pagina indica nel riquadro iniziale lo stato (*bozza* finché la funzione non è consegnata) e la
|
||||
> milestone in cui arriva. Vedi la [Roadmap](Roadmap).
|
||||
|
||||
## Per iniziare
|
||||
|
||||
@@ -1,103 +1,169 @@
|
||||
# Import/Export
|
||||
|
||||
> **Stato:** bozza · **Ultima revisione:** 2026-11-10 · **Versione software:** non ancora rilasciata (milestone M4; saldi e partite di apertura in M12)
|
||||
> **Modulo di licenza:** CORE (piano dei conti, saldi e partite: ACCT/FIN) · **Livello richiesto:** amministratore · **Specifica:** SPEC §11.7, §12.12
|
||||
> **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)
|
||||
> **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
|
||||
|
||||
La procedura guidata di **Import/Export** porta in Khaemhat i dati che arrivano da un altro gestionale o da un
|
||||
foglio di calcolo e li esporta in formati aperti. È lo strumento per l'**avviamento** di un'azienda: anagrafiche,
|
||||
articoli, listini, giacenze iniziali, piano dei conti, saldi iniziali e partite aperte.
|
||||
articoli, prezzi, giacenze iniziali e piano dei conti.
|
||||
|
||||
## Dove si trova
|
||||
|
||||
**Amministrazione → Import/Export** (titolo: *Import / export dati*). Ogni importazione si apre in una scheda
|
||||
propria (es. *Import clienti*).
|
||||
**Amministrazione → Import / export dati** (indirizzo `/amministrazione/import-export`). Il tasto **F1** apre questa
|
||||
pagina.
|
||||
|
||||
## Schermata
|
||||
|
||||

|
||||
|
||||
*Mockup 077 — a sinistra i quattro passi della procedura guidata (Origine, Mappatura colonne, Validazione,
|
||||
Importazione) e le opzioni; a destra l'**Anteprima e validazione** con l'esito riga per riga; in alto **Scarica report
|
||||
errori** e **Importa N righe** (anteprima ridotta)*
|
||||
Importazione), le opzioni e il riquadro **Esporta e modelli**; a destra la mappatura o l'**Anteprima e validazione**
|
||||
con l'esito riga per riga; in alto **Scarica report errori** e **Importa N righe***
|
||||
|
||||

|
||||
*Khaemhat 0.4.0 — il passo Mappatura colonne con un CSV di clienti: le dieci colonne si abbinano da sole, anche *P.IVA*, *Città* e *Prov*.*
|
||||
|
||||

|
||||
*Khaemhat 0.4.0 — l'anteprima dello stesso file: un comune dedotto dal CAP (avviso), un cliente nuovo e tre righe escluse (partita IVA mancante ed e-mail non valida, codice ripetuto, pagamento inesistente).*
|
||||
|
||||
## Formati
|
||||
|
||||
| Formato | Uso |
|
||||
| Formato | Lettura | Scrittura (export e modelli) |
|
||||
|---|---|---|
|
||||
| **CSV** (`.csv`, `.txt`) | separatore `;`, `,` o tabulazione (dedotto dalla riga di intestazione); UTF-8 con o senza BOM, altrimenti Windows-1252 | `;`, UTF-8 con BOM, numeri con la virgola, date `gg/mm/aaaa`, sì/no come `VERO`/`FALSO` |
|
||||
| **XLSX** | il primo foglio, intestazioni nella prima riga | un foglio con le intestazioni bloccate |
|
||||
| **JSON** | un elenco di oggetti con le colonne come chiavi; per il piano dei conti anche `khaemhat-coa.json` | lo stesso elenco (numeri e sì/no come valori JSON) |
|
||||
|
||||
La prima riga contiene sempre le **intestazioni**. Le righe vuote si saltano. Al massimo **50.000 righe** e **25 MB**
|
||||
per file.
|
||||
|
||||
**Valori accettati in tutte le colonne:**
|
||||
|
||||
- **numeri** all'italiana (`1.234,56`, `€ 12,5`, `22 %`) o con il punto decimale (`1234.56`, come li scrivono Excel e
|
||||
JSON);
|
||||
- **date** `gg/mm/aaaa` (anche `g/m/aa`, `gg-mm-aaaa`, `gg.mm.aaaa`), `aaaa-mm-gg`, `aaaammgg` o il numero di serie
|
||||
di una cella data di Excel;
|
||||
- **sì/no** come `sì`, `si`, `x`, `1`, `VERO`, `true` oppure `no`, `0`, `FALSO`, `false`;
|
||||
- le **parole di una scelta** (es. `tipo_soggetto`) senza badare a maiuscole, accenti, spazi e punteggiatura
|
||||
(`Extra UE` = `extra-ue`, `P.A.` = `pa`).
|
||||
|
||||
## Entità e colonne
|
||||
|
||||
Le intestazioni si abbinano da sole quando sono uguali ai nomi qui sotto o a un nome simile (es. `P.IVA`,
|
||||
`Partita IVA`, `piva` → `partita_iva`; `Città` → `comune`). Le colonne con **\*** servono per un record nuovo.
|
||||
|
||||
### Clienti e fornitori
|
||||
|
||||
`codice`, `ragione_sociale`, `nome`, `cognome`, `tipo_soggetto`, `partita_iva`, `codice_fiscale`, `rea`, `indirizzo`,
|
||||
`civico`, `cap`, `comune`, `provincia`, `nazione`, `telefono`, `email`, `pec`, `sito`, `codice_destinatario`,
|
||||
`categoria`; per i **clienti** anche `agente`, `pagamento`, `listino`, `sconto1`, `sconto2`, `fido`, `iban`, `note`;
|
||||
per i **fornitori** `pagamento`, `iban`, `note`.
|
||||
|
||||
| Colonna | Valori |
|
||||
|---|---|
|
||||
| **CSV** | testo con separatore `;` e codifica UTF-8 (formato più comune per gli scambi) |
|
||||
| **XLSX** | foglio Excel con le stesse colonne del CSV |
|
||||
| **JSON** | scambio completo fra installazioni Khaemhat (es. piano dei conti con voci di bilancio e causali) |
|
||||
| `tipo_soggetto` | `impresa`, `privato`, `pa`, `ue`, `extra-ue`, `forfettario` (vuoto: impresa; con solo cognome e nome: privato) |
|
||||
| `nazione` | codice ISO a due lettere (`IT`, `DE`...) |
|
||||
| `categoria`, `agente`, `pagamento`, `listino` | il **codice** della tabella (vedi [Tabelle azienda](Tabelle-azienda)) |
|
||||
| `iban` | aggiunge il conto se non c'è già (il primo diventa predefinito) |
|
||||
|
||||
## Entità importabili
|
||||
Ragione sociale (o cognome e nome per un privato), partita IVA e gli altri controlli sono quelli della scheda (vedi
|
||||
[Anagrafiche](Anagrafiche)).
|
||||
|
||||
| Entità | Note |
|
||||
### Articoli
|
||||
|
||||
`codice`, `descrizione`\*, `descrizione_estesa`, `tipo`, `categoria`, `um`, `iva_vendite`, `iva_acquisti`, `ean`,
|
||||
`nc8`, `marca`, `produttore`, `peso_netto`, `peso_lordo`, `a_magazzino`, `magazzino`, `scorta_minima`,
|
||||
`punto_riordino`, `lotto_riordino`, `prezzo`, `costo_standard`, `conto_ricavo`, `conto_costo`, `note`.
|
||||
|
||||
| Colonna | Valori |
|
||||
|---|---|
|
||||
| **Anagrafiche** (clienti, fornitori) | verifica partita IVA (VIES per i soggetti UE), comune da CAP |
|
||||
| **Articoli** | |
|
||||
| **Listini** | |
|
||||
| **Giacenze iniziali** | quantità di apertura per deposito |
|
||||
| **Piano dei conti** | tracciato descritto sotto; verifica della coerenza gerarchica |
|
||||
| **Saldi iniziali** | saldi di apertura dei conti |
|
||||
| **Partite di apertura** | crediti e debiti aperti verso clienti e fornitori, con scadenze |
|
||||
| `tipo` | `merce`, `servizio`, `spesa`, `descrittivo`, `cespite` (vuoto: merce) |
|
||||
| `categoria`, `um`, `iva_vendite`, `iva_acquisti`, `magazzino` | il **codice** della tabella (`PZ`, `22`, il codice del deposito) |
|
||||
| `a_magazzino` | sì/no; un articolo che non è merce non è mai a magazzino |
|
||||
| `prezzo` | il prezzo dell'articolo; i prezzi di listino si importano con l'entità *Prezzi* |
|
||||
|
||||
Le colonne disponibili per ogni entità corrispondono ai campi della relativa scheda (vedi [Anagrafiche](Anagrafiche),
|
||||
[Articoli e listini](Articoli-e-listini), [Magazzino](Magazzino), [Contabilità](Contabilita),
|
||||
[Scadenzario](Scadenzario)); i tracciati completi saranno pubblicati con i rispettivi moduli.
|
||||
Il codice generato usa la regola degli articoli, di solito `{categoria}-{seq:0000}`: in quel caso la categoria è
|
||||
obbligatoria. Unità alternative, codici alternativi, fornitori e sostitutivi restano quelli della scheda (vedi
|
||||
[Articoli e listini](Articoli-e-listini)).
|
||||
|
||||
### Prezzi di listino e netti cliente
|
||||
|
||||
`articolo`\*, `listino`, `cliente`, `prezzo`\*, `valido_dal`. Ogni riga ha **il listino oppure il cliente** (prezzo
|
||||
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)
|
||||
|
||||
`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).
|
||||
|
||||
### Piano dei conti (solo verifica fino a M7)
|
||||
|
||||
Vedi il tracciato più sotto.
|
||||
|
||||
## Come si importa
|
||||
|
||||
### 1. Origine
|
||||
|
||||
1. Scegli l'**Entità** (es. *Clienti*).
|
||||
2. Carica il file. Khaemhat riconosce numero di righe, codifica e separatore (es. *clienti.csv · 1.284 righe ·
|
||||
UTF-8 · separatore ;*).
|
||||
3. Imposta le opzioni:
|
||||
1. Scegli l'**Entità**.
|
||||
2. Imposta le opzioni:
|
||||
|
||||
| Opzione | Valori |
|
||||
|---|---|
|
||||
| **Se il codice esiste** | *Aggiorna* il record esistente oppure lo salta (valori esatti definiti in sviluppo) |
|
||||
| **Codici mancanti** | *Genera automatici* secondo le regole dei codici automatici (vedi [Tabelle azienda](Tabelle-azienda)) |
|
||||
| **Verifica P.IVA (VIES per UE)** | controlla le partite IVA |
|
||||
| **Compila comune da CAP** | completa comune e provincia dal CAP |
|
||||
| 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 |
|
||||
| **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 |
|
||||
|
||||
3. Scegli il **file**. Il passo mostra nome, righe e dimensione (es. *clienti_2026.csv · 1.284 righe · 37 KB*).
|
||||
|
||||
Un codice scritto nel file per un record nuovo deve essere ammesso dalla regola dei codici (**codice manuale**): per
|
||||
mantenere i codici del gestionale precedente lascia attiva quell'opzione nella regola. Un codice già presente in una
|
||||
riga precedente del file è un errore; il codice di un'anagrafica di altro tipo (un fornitore fra i clienti) anche.
|
||||
|
||||
### 2. Mappatura colonne
|
||||
|
||||
Khaemhat abbina le colonne del file ai campi dell'entità (es. *12 di 14 colonne abbinate*). Controlla gli
|
||||
abbinamenti proposti, correggi quelli sbagliati e indica le colonne da ignorare.
|
||||
Khaemhat abbina le colonne del file ai campi dell'entità (es. *14 di 16 colonne abbinate*) e mostra per ognuna il
|
||||
valore della prima riga. Correggi gli abbinamenti con l'elenco **Campo**; scegli *Ignora* per le colonne da
|
||||
tralasciare. Un campo va su una sola colonna. Un avviso elenca i campi obbligatori non abbinati. Premi **Verifica le
|
||||
righe**.
|
||||
|
||||
### 3. Validazione
|
||||
|
||||
Ogni riga viene controllata come se fosse inserita a mano. L'**Anteprima e validazione** mostra le prime righe con
|
||||
l'**Esito**:
|
||||
Ogni riga viene controllata come se fosse inserita a mano nella scheda. L'**Anteprima e validazione** mostra fino a
|
||||
500 righe con l'**Esito** e il motivo accanto; le celle con un problema sono evidenziate.
|
||||
|
||||
| Esito | Significato | Esempio |
|
||||
|---|---|---|
|
||||
| **OK** | riga importabile | |
|
||||
| **Avviso** | riga importabile con una correzione proposta | *CAP mancante: proposto 12100* |
|
||||
| **Errore** | riga non importabile | *P.IVA non valida* |
|
||||
| **Nuovo** / **Aggiorna** | riga importabile | |
|
||||
| **Avviso** | riga importabile con una correzione proposta o una nota | *Comune: dedotto dal CAP (Forlì)* |
|
||||
| **Errore** | riga esclusa | *Partita IVA non valida*, *Il codice XX non esiste* |
|
||||
|
||||
Il filtro **Tutte / Solo problemi** mostra solo le righe con avvisi o errori. **Scarica report errori** scarica
|
||||
l'elenco delle righe problematiche con il motivo: correggile nel file di origine e reimportale.
|
||||
Il filtro **Tutte / Solo problemi** mostra solo le righe con avvisi o errori. **Scarica report errori** scarica un CSV
|
||||
con riga, codice, colonna, esito e messaggio: correggi il file di origine e reimportalo. **Mappatura** torna al passo
|
||||
precedente.
|
||||
|
||||
### 4. Importazione
|
||||
|
||||
Il riepilogo indica quante righe verranno **create** e quante **aggiornate**. Premi **Importa N righe**: le righe con
|
||||
errori vengono escluse, le altre importate. L'esito finisce nel [Log](Log) e ogni record creato ha il suo storico.
|
||||
**Importa N righe** chiede conferma e scrive le righe senza errori, una alla volta come un salvataggio della scheda
|
||||
(i prezzi tutti insieme). Il riepilogo indica creati, aggiornati, saltati e righe con errori; ogni record ha il suo
|
||||
storico e l'esito finisce nel [Log](Log) (sezione *Sistema*). **Nuova importazione** ricomincia.
|
||||
|
||||
**Consiglio:** prova l'importazione su un'azienda clonata (vedi [Istanza e database](Istanza-e-database)) prima di
|
||||
farla sull'azienda reale, soprattutto per saldi e partite di apertura.
|
||||
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 è già **precaricato** con le tabelle di base; l'importazione serve a chi vuole
|
||||
usare il piano del proprio commercialista o del gestionale precedente.
|
||||
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.
|
||||
|
||||
### CSV e XLSX
|
||||
|
||||
Separatore `;`, una riga per conto, con le colonne:
|
||||
Una riga per conto, con le colonne:
|
||||
|
||||
```
|
||||
codice;descrizione;livello;padre;natura;tipo;voce_cee;riclassifica;flag
|
||||
@@ -105,54 +171,78 @@ codice;descrizione;livello;padre;natura;tipo;voce_cee;riclassifica;flag
|
||||
|
||||
| Colonna | Contenuto |
|
||||
|---|---|
|
||||
| `codice` | codice gerarchico nella forma `MM.CC.SSS` (mastro, conto, sottoconto) |
|
||||
| `descrizione` | descrizione del conto |
|
||||
| `livello` | livello nella gerarchia (mastro, conto, sottoconto) |
|
||||
| `padre` | codice del conto padre (vuoto per i mastri) |
|
||||
| `natura` | natura del conto (es. patrimoniale/economico; valori ammessi definiti in sviluppo) |
|
||||
| `tipo` | tipo del conto (valori ammessi definiti in sviluppo) |
|
||||
| `codice`\* | da 1 a 3 parti separate da punto: mastro, conto, sottoconto (`01`, `01.10`, `01.10.001`) |
|
||||
| `descrizione`\* | descrizione del conto |
|
||||
| `livello` | 1, 2 o 3: il numero di parti del codice (se indicato deve corrispondere) |
|
||||
| `padre` | il codice senza l'ultima parte (se indicato deve corrispondere); deve essere nel file |
|
||||
| `natura` | `attivo`, `passivo`, `costo`, `ricavo`, `ordine`; obbligatoria sui mastri, ereditata dai sottoconti e uguale a quella del padre |
|
||||
| `tipo` | `generico` (vuoto), `clienti`, `fornitori`, `banca`, `cassa`, `iva`, `erario` |
|
||||
| `voce_cee` | voce dello schema di bilancio CEE (artt. 2424/2425 c.c.) |
|
||||
| `riclassifica` | voce del bilancio riclassificato |
|
||||
| `flag` | indicatori del conto (partitario clienti/fornitori, rilevante IVA, chiusura automatica, movimentabile, attivo; codifica definita in sviluppo) |
|
||||
| `flag` | lettere: `M` movimentabile, `I` rilevante IVA, `P` con partitario clienti/fornitori, `C` chiusura automatica, `X` disattivato |
|
||||
|
||||
Esempio di righe (valori indicativi):
|
||||
Esempio:
|
||||
|
||||
```
|
||||
codice;descrizione;livello;padre;natura;tipo;voce_cee;riclassifica;flag
|
||||
01;Immobilizzazioni;1;;…;…;;;
|
||||
01.01;Immobilizzazioni immateriali;2;01;…;…;…;…;
|
||||
01.01.001;Software;3;01.01;…;…;…;…;…
|
||||
01;Attivo;1;;attivo;;;;
|
||||
01.10;Crediti verso clienti;2;01;;;;;
|
||||
01.10.001;Clienti Italia;3;01.10;;clienti;CII1;;MP
|
||||
01.20;Disponibilità liquide;2;01;;;;;
|
||||
01.20.001;Banca;3;01.20;;banca;CIV1;;M
|
||||
```
|
||||
|
||||
Il file **XLSX** usa le stesse colonne, nella prima riga del primo foglio.
|
||||
|
||||
### JSON (`khaemhat-coa.json`)
|
||||
|
||||
Per l'export e l'import **completo** fra installazioni Khaemhat: contiene **conti**, **voci di bilancio**, **causali
|
||||
contabili** e **mappature**. È il formato da usare per copiare il piano dei conti da un'azienda all'altra.
|
||||
Per lo scambio **completo** fra installazioni Khaemhat:
|
||||
|
||||
### Controlli in importazione
|
||||
```json
|
||||
{
|
||||
"format": "khaemhat-coa",
|
||||
"version": 1,
|
||||
"accounts": [ { "codice": "01", "descrizione": "Attivo", "natura": "attivo" } ],
|
||||
"statementLines": [],
|
||||
"journalTemplates": [],
|
||||
"mappings": []
|
||||
}
|
||||
```
|
||||
|
||||
- **Coerenza gerarchica**: ogni conto deve avere un padre esistente e un livello coerente con il codice.
|
||||
- Gli altri controlli (ad esempio codici duplicati o voci CEE inesistenti) seguono le regole del piano dei conti e
|
||||
saranno precisati in sviluppo.
|
||||
`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).
|
||||
|
||||
## Export
|
||||
### Controlli
|
||||
|
||||
I dati si esportano negli stessi formati:
|
||||
- codice di 1-3 parti, livello e padre coerenti con il codice, padre presente nel file;
|
||||
- natura indicata sui mastri e uguale a quella del padre;
|
||||
- **solo i conti senza sottoconti** sono movimentabili (`M` su un conto con sottoconti è un errore; un sottoconto
|
||||
senza `M` è un avviso);
|
||||
- lettere di `flag` sconosciute e codici ripetuti sono errori.
|
||||
|
||||
- dalla procedura guidata, per le entità sopra elencate (l'obiettivo è che un file esportato si possa reimportare
|
||||
con lo stesso tracciato; dettagli definiti in sviluppo);
|
||||
- dalle griglie e dai report (CSV/XLSX/PDF), dal pulsante **Genera file/esporta**;
|
||||
- il piano dei conti completo in `khaemhat-coa.json`.
|
||||
## Export e modelli
|
||||
|
||||
Gli export richiedono il flag utente **Può esportare dati** (vedi [Utenti e permessi](Utenti-e-permessi)).
|
||||
Il riquadro **Esporta e modelli** usa l'entità scelta in alto:
|
||||
|
||||
- **Formato**: CSV, XLSX o JSON;
|
||||
- **Scarica modello**: il file con le sole intestazioni (in JSON un oggetto con i valori vuoti; per il piano dei conti
|
||||
l'oggetto `khaemhat-coa`);
|
||||
- **Esporta**: tutti i record con le **stesse colonne dell'import**, così il file si corregge e si reimporta
|
||||
(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).
|
||||
|
||||
## Domande frequenti
|
||||
|
||||
- **Il file ha la virgola come separatore.** Usa il separatore `;` (standard per i CSV in italiano, dove la virgola è
|
||||
il separatore decimale) oppure salva in XLSX.
|
||||
- **Le lettere accentate appaiono sbagliate.** Salva il CSV in UTF-8.
|
||||
- **Il file ha la virgola come separatore.** Va bene: il separatore si deduce dalla riga di intestazione.
|
||||
- **Le lettere accentate appaiono sbagliate.** Khaemhat legge UTF-8 e, in alternativa, Windows-1252 (il CSV di Excel
|
||||
per l'Italia); con altre codifiche salva in UTF-8 o in XLSX.
|
||||
- **Il codice del vecchio gestionale viene rifiutato.** La regola dei codici di quell'archivio non ammette il codice
|
||||
manuale: abilitalo in *Preferenze azienda → Codici automatici* (`/tabelle/preferenze`), oppure scegli *Genera automatico* e togli la colonna.
|
||||
- **Ho importato con errori: devo rifare tutto?** No: correggi solo le righe del report e reimportale; con *Aggiorna*
|
||||
le righe già importate si aggiornano senza doppioni.
|
||||
- **Posso importare documenti (fatture, DDT) da un altro gestionale?** Non con questa procedura: le fatture
|
||||
elettroniche di acquisto si importano dall'XML SDI (vedi [Acquisti](Acquisti) e
|
||||
[Fatturazione elettronica](Fatturazione-elettronica)).
|
||||
@@ -160,4 +250,4 @@ Gli export richiedono il flag utente **Può esportare dati** (vedi [Utenti e per
|
||||
## Pagine correlate
|
||||
|
||||
[Dati di base e di esempio](Dati-di-base-e-esempio) · [Contabilità](Contabilita) · [Anagrafiche](Anagrafiche) ·
|
||||
[Articoli e listini](Articoli-e-listini) · [Scadenzario](Scadenzario) · [Tabelle azienda](Tabelle-azienda) · [Primi passi](Primi-passi)
|
||||
[Articoli e listini](Articoli-e-listini) · [Magazzino](Magazzino) · [Tabelle azienda](Tabelle-azienda) · [Primi passi](Primi-passi)
|
||||
@@ -1,6 +1,6 @@
|
||||
# Roadmap
|
||||
|
||||
> **Stato:** bozza · **Ultima revisione:** 2026-11-11 · **Specifica:** SPEC §20
|
||||
> **Stato:** bozza · **Ultima revisione:** 2026-11-12 · **Specifica:** SPEC §20
|
||||
|
||||
Khaemhat si costruisce in **15 milestone**. Ogni milestone si chiude con un tag di versione, un'immagine Docker nel
|
||||
registro pacchetti di Gitea e la wiki delle funzioni consegnate portata da *bozza* a *completa*.
|
||||
@@ -10,7 +10,10 @@ Il lavoro di dettaglio è nelle issue di Gitea, raggruppate per
|
||||
[progetti](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/projects) *Khaemhat 1.0 — Sviluppo* e
|
||||
*Khaemhat 1.1+ — Fase 2*.
|
||||
|
||||
**Completate:** M0 (0.0.1), M1 (0.1.0), M2 (0.2.0), M3 (0.3.0). **In corso:** M4.
|
||||
Finché il prodotto è in sviluppo le versioni restano **0.x**, anche dopo M13: la **1.0.0** sarà pubblicata solo
|
||||
quando verrà deciso esplicitamente.
|
||||
|
||||
**Completate:** M0 (0.0.1), M1 (0.1.0), M2 (0.2.0), M3 (0.3.0), M4 (0.4.0). **In corso:** M5.
|
||||
|
||||
| # | Milestone | Contenuto principale | Versione |
|
||||
|---|---|---|---|
|
||||
@@ -27,8 +30,8 @@ Il lavoro di dettaglio è nelle issue di Gitea, raggruppate per
|
||||
| M10 | Cespiti, Intrastat, chiusura, bilancio | Registro cespiti, Intrastat, dichiarazioni d'intento, ratei e risconti, chiusura e apertura, bilancio CEE | 0.10.0 |
|
||||
| M11 | CRM | Lead, pipeline, opportunità, attività e agenda, campagne, ticket, scheda 360° | 0.11.0 |
|
||||
| M12 | Amministrazione, automazioni, API | Gestione database, backup e ripristino (anche S3 e WebDAV), attività programmate, impostazioni, stato sistema e aggiornamenti, API REST, MCP, webhook, regole e procedure | 0.12.0 |
|
||||
| M13 | Consolidamento e rilascio | Sicurezza, prestazioni, accessibilità, wiki completa, PWA, prova su Unraid | **1.0.0** |
|
||||
| M14 | Fase 2 | Servizi (contratti e interventi), canali e-commerce, EN 16931/Peppol, XBRL, regime del margine, ventilazione, IVA per cassa completa, SFTP | 1.1.0+ |
|
||||
| M13 | Consolidamento e rilascio | Sicurezza, prestazioni, accessibilità, wiki completa, PWA, prova su Unraid | 0.13.0 |
|
||||
| M14 | Fase 2 | Servizi (contratti e interventi), canali e-commerce, EN 16931/Peppol, XBRL, regime del margine, ventilazione, IVA per cassa completa, SFTP | 0.14.0+ |
|
||||
|
||||
## Stato attuale
|
||||
|
||||
|
||||
@@ -63,7 +63,7 @@ Il riquadro **Versione** riporta:
|
||||
| **Motore DB** | PostgreSQL 17 · minima 16 |
|
||||
| **Cache** | Redis (opzionale) o memoria |
|
||||
| **Fuso orario** | `Europe/Rome` |
|
||||
| **Pacchetto fiscale** | Italia · dati `IT 2026.2` |
|
||||
| **Pacchetto fiscale** | Italia · dati `IT 2026.3` |
|
||||
| **Istanza** | nome host e numero di aziende |
|
||||
|
||||
La stessa versione compare nella barra superiore (solo `major.minor`), nella barra di stato (completa) e
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
# Tabelle azienda
|
||||
|
||||
> **Stato:** bozza · **Ultima revisione:** 2026-11-10 · **Versione software:** non ancora rilasciata (milestone M4)
|
||||
> **Modulo di licenza:** CORE · **Permessi principali:** famiglia `company.*` (codici esatti definiti in sviluppo) · **Specifica:** SPEC §11.1, §11.12 (codici automatici, compilazione, preferenze), §14
|
||||
> **Stato:** completa · **Ultima revisione:** 2026-11-12 · **Versione software:** 0.4.0 (milestone M4)
|
||||
> **Modulo di licenza:** CORE · **Permessi principali:** `company.settings.read` (consultare), `company.settings.write` (modificare) · **Specifica:** SPEC §11.1, §11.12 (codici automatici, compilazione, preferenze), §14
|
||||
|
||||
Le **tabelle azienda** sono i dati di configurazione su cui si appoggia tutto il resto: il **profilo dell'azienda**,
|
||||
gli **esercizi e i periodi**, i **codici IVA**, i pagamenti, le banche, i depositi, i numeratori dei documenti, i
|
||||
@@ -10,20 +10,50 @@ dati di base italiani (vedi [Dati di base e di esempio](Dati-di-base-e-esempio))
|
||||
|
||||
## Dove si trova
|
||||
|
||||
Menu **Tabelle azienda** → *Profilo azienda*, *Codici IVA*, *Pagamenti*, *Numeratori*, *Depositi*, *Valute*,
|
||||
*Trasporti*, *Preferenze e codici automatici*; le altre tabelle sono raggiungibili dallo stesso menu e dalla ricerca
|
||||
globale (`Ctrl+K`). Esercizi e periodi sono in *Tabelle azienda → Esercizi*.
|
||||
Menu **Tabelle azienda**: la voce principale apre l'indice di tutte le tabelle (`/tabelle`), raggruppate in
|
||||
*Azienda*, *Fisco, pagamenti e banche*, *Vendite e documenti*, *Magazzino e trasporto*, *Geografia* e *Classificazioni*. Sotto la voce
|
||||
ci sono le scorciatoie per *Profilo azienda*, *Esercizi*, *Preferenze e codici automatici*, *Codici IVA*, *Pagamenti*, *Numeratori*, *Depositi*,
|
||||
*Valute* e *Cambi*. Ogni tabella ha un indirizzo proprio, ad esempio `/tabelle/codici-iva`, ed è raggiungibile anche
|
||||
dalla ricerca globale (`Ctrl+K`). *Preferenze e codici automatici* è a `/tabelle/preferenze`.
|
||||
|
||||
Ogni tabella ha la propria maschera, costruita come il radar dei clienti e la maschera dei codici IVA: elenco con
|
||||
ricerca e filtri, dettaglio sotto o in scheda, **import ed export CSV**.
|
||||

|
||||
*Khaemhat 0.4.0 — l'indice delle tabelle azienda per gruppi, con il sottomenu delle voci più usate.*
|
||||
|
||||
## Come si usa una tabella
|
||||
|
||||
Tutte le tabelle codificate hanno la stessa maschera:
|
||||
|
||||
- **Elenco** con ricerca, filtro rapido *Attive / Disattivate / Tutte* (all'apertura si vedono solo le attive) e
|
||||
colonne principali; un clic sceglie la riga, doppio clic o `Invio` la apre.
|
||||
- **Dettaglio** sotto l'elenco: *Codice*, *Descrizione*, *Disattivata* e i campi propri della tabella. Gli errori
|
||||
compaiono accanto al campo e nel riepilogo; gli **avvisi** (ad esempio un codice IVA senza riferimento normativo)
|
||||
non bloccano il salvataggio.
|
||||
- **Barra comandi**: *Nuovo*, *Salva* (`Ctrl+S`), *Annulla modifiche*, *Elimina*. Una riga usata altrove non si può
|
||||
eliminare: Khaemhat propone di **disattivarla**, così resta nei documenti già fatti ma non si propone più.
|
||||
- Menu `…`: **Esporta CSV**, **Importa CSV** e **Aggiorna da tabelle base**.
|
||||
- Uscendo con modifiche non salvate viene chiesta conferma.
|
||||
|
||||
**Importa CSV** (file fino a 20 MB, separatore `;`, `,` o tabulazione, prima riga con i nomi delle colonne come nell'export): le
|
||||
righe con un codice già presente vengono aggiornate, le altre aggiunte. È **tutto o niente**: se una riga ha un
|
||||
errore non viene importato nulla e la finestra elenca riga, campo e motivo.
|
||||
|
||||
**Aggiorna da tabelle base** aggiunge i codici di base mancanti senza modificare le righe che ci sono già (vedi
|
||||
[Dati di base e di esempio](Dati-di-base-e-esempio)).
|
||||
|
||||
Le **condizioni di pagamento** hanno anche le **rate**: giorni, fine mese, giorno fisso e percentuale; la somma delle
|
||||
percentuali deve fare 100 e le rate si salvano tutte insieme.
|
||||
|
||||
## Profilo azienda
|
||||
|
||||

|
||||
*Mockup 075 — profilo azienda: schede Dati societari, Fiscale e SDI, Banche, Logo e stampe, Esercizi e periodicità, Trasmittente/intermediario (anteprima ridotta).*
|
||||
|
||||
Indirizzo: `/tabelle/profilo-azienda`. Al salvataggio partita IVA, codice fiscale, codice destinatario e regime
|
||||
fiscale sono controllati dal pacchetto fiscale del paese; se un errore è in un'altra scheda, Khaemhat si sposta
|
||||
sulla scheda del primo errore. Il logo per le stampe arriva con i modelli di stampa dei documenti.
|
||||
|
||||
Il profilo è una scheda unica (una sola per azienda). In alto a destra un badge indica la versione del **pacchetto
|
||||
fiscale** in uso (es. *IT 2026.2*).
|
||||
fiscale** in uso (es. *IT 2026.3*).
|
||||
|
||||
| Scheda / gruppo | Campi |
|
||||
|---|---|
|
||||
@@ -49,6 +79,10 @@ sblocca.
|
||||
**Periodi** (mesi o trimestri secondo la periodicità IVA): stato *aperto*, *liquidato* o *bloccato*, esito della
|
||||
liquidazione IVA (*provvisoria*, *confermata*), registrazioni, interruttore **Blocco**.
|
||||
|
||||
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).
|
||||
|
||||
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
|
||||
periodo (vedi [IVA](IVA)) e la chiusura dell'esercizio lo rende di sola lettura (vedi [Contabilità](Contabilita)).
|
||||
@@ -58,8 +92,8 @@ periodo (vedi [IVA](IVA)) e la chiusura dell'esercizio lo rende di sola lettura
|
||||
| Tabella | Contenuto |
|
||||
|---|---|
|
||||
| **Paesi** | codici ISO 3166-1, appartenenza all'UE, codice SDI per l'estero (`XXXXXXX`) |
|
||||
| **Province** e **Comuni** | CAP e codice catastale: servono per la compilazione da CAP e per il calcolo del codice fiscale |
|
||||
| **Valute** e **Cambi** | valute con i cambi giornalieri della BCE |
|
||||
| **Province** e **Comuni** | Sigla, regione, codice catastale (il codice del comune), codice ISTAT e CAP: servono per la compilazione da CAP e per il calcolo del codice fiscale. Province, comuni e CAP arrivano con i dati di base (elenco ISTAT, CAP da GeoNames); i pochi CAP mancanti si completano a mano o con l'Importa CSV, vedi [Dati di base e di esempio](Dati-di-base-e-esempio) |
|
||||
| **Valute** e **Cambi** | valute con i cambi giornalieri della BCE; in *Cambi* (`/tabelle/cambi`) si vedono i cambi per data e origine e si inserisce un cambio manuale |
|
||||
| **Unità di misura** | codici interni e codice usato nell'XML SDI |
|
||||
| **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) |
|
||||
@@ -77,8 +111,8 @@ periodo (vedi [IVA](IVA)) e la chiusura dell'esercizio lo rende di sola lettura
|
||||
| **Depositi** | magazzini, anche mobili (es. furgone) |
|
||||
| **Categorie articolo** | su tre livelli |
|
||||
| **Categorie controparte** | classificazione di clienti e fornitori |
|
||||
| **Listini** | intestazioni dei listini (i prezzi sono in [Articoli e listini](Articoli-e-listini)) |
|
||||
| **Politiche di sconto** | regole di sconto riutilizzabili (struttura definita in sviluppo) |
|
||||
| **Listini** | intestazioni dei listini: valuta, IVA inclusa, validità, **Listino base** (uno solo, in partenza `BASE`), **Derivato da** con ricarico % e arrotondamento (i prezzi sono in [Articoli e listini](Articoli-e-listini)) |
|
||||
| **Politiche di sconto** | sconti in cascata con un codice, come formula (`10+5`), da richiamare nelle condizioni |
|
||||
| **Tipi documento** | catalogo dei documenti con numeratore, causale di magazzino, causale contabile, registro IVA, codice TD, modello di stampa |
|
||||
| **Centri di costo** | per l'analisi dei costi e dei ricavi |
|
||||
| **Commesse** | progetti o cantieri a cui imputare costi e ricavi |
|
||||
@@ -88,6 +122,9 @@ periodo (vedi [IVA](IVA)) e la chiusura dell'esercizio lo rende di sola lettura
|
||||

|
||||
*Mockup 076 — elenco dei codici IVA con aliquota, tipo, natura SDI, esigibilità, indetraibilità e conti, con il dettaglio del codice RC17 (anteprima ridotta).*
|
||||
|
||||

|
||||
*Khaemhat 0.4.0 — l'elenco dei codici IVA di base con il dettaglio del codice 22SP (scissione dei pagamenti).*
|
||||
|
||||
Ogni codice IVA ha: **codice**, **descrizione**, **aliquota**, **tipo** (IVA, esente, non imponibile, fuori campo,
|
||||
escluso, reverse charge), **natura SDI** per le operazioni senza imposta, **riferimento normativo** (stampato in
|
||||
fattura e riportato nell'XML), **esigibilità** (`I` immediata, `D` differita, `S` scissione dei pagamenti),
|
||||
@@ -112,19 +149,26 @@ sotto-codice scelto in riga), `SPLIT` (split payment), indetraibili 50% e 100%,
|
||||
|
||||
## Numeratori
|
||||
|
||||
Ogni **tipo documento** usa un numeratore per **sezionale** e **anno**, con un **formato** che di predefinito è
|
||||
`{prefix}/{anno}/{number:D6}`, ad esempio `FT/2026/000419`. Il numero è assegnato in modo atomico **alla conferma**;
|
||||
per fatture, note di credito e registrazioni contabili definitive **non sono ammessi buchi** nella numerazione. Il
|
||||
protocollo IVA degli acquisti ha il proprio formato (es. `ACQ/{anno}/…`) e i progressivi si azzerano a ogni
|
||||
esercizio (impostazione *Reset progressivi*).
|
||||
Ogni **tipo documento** usa un numeratore per **sezionale** e **anno**, con un **formato** composto dai segnaposto
|
||||
`{prefix}`, `{year}`, `{section}` e `{number}` (con `{number:D6}` il numero ha sei cifre con gli zeri davanti). Il
|
||||
formato deve contenere `{number}`. Esempi dei numeratori di base: fatture `{number}/{year}` (`419/2026`), ordini
|
||||
clienti `OC-{year}-{number:D4}` (`OC-2026-0042`), autofatture `{number}/AF/{year}` nel sezionale `AF`.
|
||||
|
||||
Il numero è assegnato in modo atomico **alla conferma** del documento (da M5); per fatture, note di credito,
|
||||
protocollo acquisti e registrazioni contabili **non sono ammessi buchi** nella numerazione (opzione *Ammessi buchi di numerazione*
|
||||
spenta). I numeratori sono per anno: il caricamento di base crea quelli dell'anno in corso.
|
||||
|
||||
## Preferenze e codici automatici
|
||||
|
||||

|
||||
*Mockup 074 — Preferenze azienda: maschere dei codici automatici per anagrafiche, articoli e cespiti, CRM e servizi, documenti e contabilità; elenco delle compilazioni automatiche (anteprima ridotta).*
|
||||
|
||||
La maschera **Preferenze azienda** ha le schede *Codici automatici*, *Compilazione automatica*, *Arrotondamenti e
|
||||
controlli*, *Default documenti*, *Modelli e-mail*, *Testi di stampa*.
|
||||

|
||||
*Khaemhat 0.4.0 — le maschere dei codici automatici con l'anteprima del prossimo codice; le maschere dei moduli non attivi restano pronte.*
|
||||
|
||||
La maschera **Preferenze azienda** (`/tabelle/preferenze`) ha le schede *Codici automatici* e *Compilazione
|
||||
automatica*; le schede *Arrotondamenti e controlli*, *Default documenti*, *Modelli e-mail* e *Testi di stampa*
|
||||
arrivano con i documenti e le e-mail. **Salva** registra le due schede insieme.
|
||||
|
||||
### Codici automatici
|
||||
|
||||
@@ -142,40 +186,58 @@ Per ogni archivio si imposta una **maschera**; sotto il campo compare l'anteprim
|
||||
| Contratti di servizio | `SVC-{seq:0000}` | `SVC-0001` |
|
||||
| Interventi | `MAN-{anno}-{seq:0000}` | `MAN-2026-0001` |
|
||||
|
||||
Segnaposto: `{seq:0000}` progressivo con il numero di cifre indicato, `{anno}` anno corrente, `{categoria}` codice
|
||||
della categoria. Il progressivo può essere **globale** o **per categoria / per anno**. Opzioni: *Consenti codice
|
||||
manuale* (l'utente può scrivere un codice diverso), *Blocca duplicati per EAN* (articoli). I progressivi sono
|
||||
assegnati in modo atomico: due salvataggi contemporanei non ottengono mai lo stesso codice.
|
||||
Segnaposto: `{seq:0000}` progressivo con tante cifre quanti sono gli zeri (`{seq}` senza zeri davanti), `{anno}`
|
||||
anno della registrazione, `{categoria}` codice della categoria (solo articoli). Il resto della maschera si scrive
|
||||
così com'è: lettere, cifre e `- _ / .`. Il progressivo è **globale**, riparte **ogni anno** se la maschera
|
||||
contiene `{anno}` e va **per categoria** se contiene `{categoria}`. Una maschera sbagliata (senza progressivo, con
|
||||
segnaposto sconosciuti o con codici più lunghi della tabella) viene segnalata sotto il campo e non si salva.
|
||||
|
||||
Opzioni: *Consenti codice manuale* per ogni riquadro (l'utente può scrivere un codice diverso; spento, il campo
|
||||
codice resta vuoto e il codice arriva al salvataggio), *Blocca duplicati per EAN* (articoli). Le maschere dei moduli
|
||||
non attivi (CRM, Servizi, Cespiti) si possono preparare: valgono quando il modulo viene attivato.
|
||||
|
||||
I progressivi sono assegnati **al salvataggio** dentro la stessa transazione: due salvataggi contemporanei non
|
||||
ottengono mai lo stesso codice, e un salvataggio non riuscito non consuma il numero. Se il codice successivo esiste
|
||||
già (perché scritto a mano), Khaemhat passa al numero dopo. **Cambiare la maschera non riscrive i codici già
|
||||
assegnati** e non azzera il progressivo: da `C{seq:000000}` a `CL{seq:0000}` dopo `C000123` il codice successivo è
|
||||
`CL0124`.
|
||||
|
||||
Il riquadro *Documenti e contabilità* rimanda ai [numeratori](#numeratori): fatture, protocollo e registrazioni non
|
||||
usano maschere ma numeratori per anno e sezionale.
|
||||
|
||||
### Compilazione automatica
|
||||
|
||||
| Opzione | Effetto |
|
||||
|---|---|
|
||||
| Comune, provincia e regione dal CAP | compila l'indirizzo partendo dal CAP |
|
||||
| Codice fiscale dai dati anagrafici | calcola il codice fiscale delle persone fisiche |
|
||||
| Verifica P.IVA UE (VIES) al salvataggio | interroga il servizio VIES e salva l'esito |
|
||||
| Banca e BIC dall'IBAN | ricava la banca dalla tabella ABI |
|
||||
| Cambi BCE giornalieri | scarica i cambi ogni giorno |
|
||||
| Descrizione articolo nelle righe | copia la descrizione dell'articolo nella riga del documento |
|
||||
| Ultimo prezzo praticato al cliente | lo mostra come riferimento |
|
||||
| Proponi ultimo documento simile | parte dal documento precedente dello stesso cliente |
|
||||
| Date consegna = data + lead time | calcola la consegna prevista |
|
||||
| Conti contabili da articolo, categoria, causale | propone conti di ricavo e costo |
|
||||
Ogni opzione si accende o spegne con un interruttore; spenta, i campi restano da scrivere a mano.
|
||||
|
||||
Oltre a queste, i documenti ricevono sempre destinazione, listino, pagamento e agente dal cliente e causale e
|
||||
deposito dal tipo documento.
|
||||
| Opzione | Effetto | Predefinita |
|
||||
|---|---|---|
|
||||
| Comune, provincia e regione dal CAP | scrivendo il CAP propone il comune (o i comuni) con provincia e regione; scrivendo il comune propone CAP e provincia | accesa |
|
||||
| Codice fiscale dai dati anagrafici | calcola il codice fiscale delle persone fisiche da cognome, nome, data, sesso e comune di nascita | accesa |
|
||||
| Verifica P.IVA UE (VIES) al salvataggio | interroga il servizio VIES e salva l'esito (*valida*, *non valida*, *servizio non disponibile*) | accesa |
|
||||
| Banca e BIC dall'IBAN | legge ABI e CAB dall'IBAN; banca e BIC vengono dall'elenco ABI o, finché l'elenco non è caricato, da un conto dell'azienda presso la stessa banca | accesa |
|
||||
| Cambi BCE giornalieri | l'attività di sistema scarica i cambi nei giorni lavorativi; spenta, l'azienda usa solo cambi manuali | accesa |
|
||||
| Descrizione articolo nelle righe | copia la descrizione dell'articolo nella riga del documento | accesa |
|
||||
| Ultimo prezzo praticato al cliente | lo mostra come riferimento | accesa |
|
||||
| Proponi ultimo documento simile | parte dal documento precedente dello stesso tipo e cliente | spenta |
|
||||
| Data di consegna = data + lead time | aggiunge il tempo di approvvigionamento e sposta la data al primo giorno lavorativo | accesa |
|
||||
| Conti contabili da articolo, categoria e causale | propone conti di ricavo e costo | accesa |
|
||||
|
||||
Le opzioni sulle righe e sui conti agiscono con i documenti e la contabilità (da M5). Oltre a queste, i documenti
|
||||
ricevono sempre destinazione, listino, pagamento e agente dal cliente e causale e deposito dal tipo documento.
|
||||
|
||||
### Altre preferenze aziendali
|
||||
|
||||
| Scheda | Contenuto |
|
||||
|---|---|
|
||||
| **Arrotondamenti e controlli** | arrotondamenti di prezzi e totali, controlli bloccanti o di avviso (fido, scaduto, date) |
|
||||
| **Default documenti** | sezionali, depositi, causali e condizioni proposti per tipo documento |
|
||||
| **Modelli e-mail** | testi per l'invio di documenti, solleciti, notifiche |
|
||||
| **Testi di stampa** | diciture e note in calce ai documenti |
|
||||
In 0.4.0 le preferenze azienda hanno le schede *Codici automatici* e *Compilazione automatica*. Arriveranno con i
|
||||
moduli che le usano:
|
||||
|
||||
La periodicità IVA e le numerazioni fanno parte delle preferenze aziendali e si impostano nel profilo e nei
|
||||
numeratori. Il dettaglio di ogni opzione sarà completato in sviluppo.
|
||||
| Scheda | Contenuto | Con |
|
||||
|---|---|---|
|
||||
| **Arrotondamenti e controlli** | arrotondamenti di prezzi e totali, controlli bloccanti o di avviso (fido, scaduto, date) | documenti (M5) |
|
||||
| **Default documenti** | sezionali, depositi, causali e condizioni proposti per tipo documento | documenti (M5) |
|
||||
| **Modelli e-mail** | testi per l'invio di documenti, solleciti, notifiche | e-mail (M5) |
|
||||
| **Testi di stampa** | diciture e note in calce ai documenti | stampe (M5) |
|
||||
|
||||
La periodicità IVA e le numerazioni si impostano nel profilo azienda e nei numeratori.
|
||||
|
||||
## Permessi e licenza
|
||||
|
||||
@@ -188,8 +250,9 @@ con i rispettivi moduli attivi. La conferma della liquidazione e la chiusura del
|
||||
modificare i codici predefiniti usati in documenti già emessi.
|
||||
- **Non riesco a inserire un documento con data di agosto.** Il periodo è bloccato o liquidato: chiedi a chi gestisce
|
||||
la contabilità.
|
||||
- **Posso cambiare la maschera dei codici clienti a metà anno?** I codici già assegnati non vengono riscritti: la
|
||||
nuova maschera vale per i codici successivi (il comportamento in caso di conflitti sarà definito in sviluppo).
|
||||
- **Posso cambiare la maschera dei codici clienti a metà anno?** Sì: i codici già assegnati non vengono riscritti,
|
||||
la nuova maschera vale per i codici successivi e continua lo stesso progressivo; un codice che esiste già viene
|
||||
saltato.
|
||||
|
||||
## Pagine correlate
|
||||
|
||||
|
||||
|
After Width: | Height: | Size: 119 KiB |
|
After Width: | Height: | Size: 115 KiB |
|
After Width: | Height: | Size: 150 KiB |
|
After Width: | Height: | Size: 134 KiB |
|
After Width: | Height: | Size: 127 KiB |
|
After Width: | Height: | Size: 115 KiB |
|
After Width: | Height: | Size: 140 KiB |
|
After Width: | Height: | Size: 119 KiB |
|
After Width: | Height: | Size: 117 KiB |
|
After Width: | Height: | Size: 111 KiB |
@@ -1,9 +1,17 @@
|
||||
#!/usr/bin/env bash
|
||||
# Loads base tables and demo data into a company database (SPEC §15).
|
||||
# scripts/seed.sh --base | --demo [--scale N] [--company CODE]
|
||||
# Stub: completed in milestone M4 (SPEC §20). Until then it explains what it will do and exits with an error.
|
||||
# Adds the missing base tables to the company databases (SPEC §14, ADR 0026), and with --demo the demo data to the
|
||||
# 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]
|
||||
# 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).
|
||||
set -euo pipefail
|
||||
|
||||
echo "seed.sh: non ancora disponibile, arriva con la milestone M4." >&2
|
||||
echo "Uso previsto: scripts/seed.sh --base | --demo [--scale N] [--company CODE]" >&2
|
||||
exit 1
|
||||
if [[ -f /app/Khaemhat.Web.dll ]]; then
|
||||
# The entrypoint prepares the user and waits for the database, then runs "dotnet Khaemhat.Web.dll seed ...".
|
||||
exec /app/entrypoint.sh seed "$@"
|
||||
fi
|
||||
|
||||
root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
|
||||
exec dotnet run --project "$root/src/Khaemhat.Web" -- seed "$@"
|
||||
@@ -0,0 +1,332 @@
|
||||
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;
|
||||
|
||||
/// <summary>An account of the chart read from a file.</summary>
|
||||
/// <param name="Code">The code, parts separated by points (<c>01.02.003</c>).</param>
|
||||
/// <param name="Description">The description.</param>
|
||||
/// <param name="Level">The level, 1 to 3: the number of parts of the code.</param>
|
||||
/// <param name="ParentCode">The code without its last part.</param>
|
||||
/// <param name="Nature">The nature.</param>
|
||||
/// <param name="Type">The use.</param>
|
||||
/// <param name="Postable">Postings go on it (only leaves).</param>
|
||||
/// <param name="VatRelevant">Relevant for VAT.</param>
|
||||
/// <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>
|
||||
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);
|
||||
|
||||
/// <summary>
|
||||
/// The checks of a chart of accounts from a file (SPEC §12.12, ADR 0031): codes of one to three parts separated by
|
||||
/// points, each account under the account whose code is its own without the last part, with the same nature; only
|
||||
/// leaves are postable. Pure, so that M7 writes what this checks.
|
||||
/// </summary>
|
||||
public static class ChartOfAccountsImportValidator
|
||||
{
|
||||
/// <summary>The words of <c>natura</c>, in the order of <see cref="AccountNature"/>.</summary>
|
||||
public static readonly IReadOnlyList<string> NatureWords = ["attivo", "passivo", "costo", "ricavo", "ordine"];
|
||||
|
||||
/// <summary>The words of <c>tipo</c>, in the order of <see cref="AccountType"/>.</summary>
|
||||
public static readonly IReadOnlyList<string> TypeWords = ["generico", "clienti", "fornitori", "banca", "cassa", "iva", "erario"];
|
||||
|
||||
/// <summary>The flag letters: postable, VAT relevant, sub-ledger, automatic closing, disabled.</summary>
|
||||
public const string FlagLetters = "MIPCX";
|
||||
|
||||
/// <summary>The deepest level.</summary>
|
||||
public const int MaxLevel = 3;
|
||||
|
||||
/// <summary>The columns of the chart.</summary>
|
||||
public static IReadOnlyList<ImportField> Fields { get; } =
|
||||
[
|
||||
new("codice", ImportFieldKind.Code, Required: true, Aliases: ["conto", "codice_conto", "cod_conto"]),
|
||||
new("descrizione", Required: true, Aliases: ["descr", "denominazione"]),
|
||||
new("livello", ImportFieldKind.Number, Aliases: ["liv"]),
|
||||
new("padre", ImportFieldKind.Code, Aliases: ["conto_padre", "mastro"]),
|
||||
new("natura", ImportFieldKind.Choice, Aliases: ["sezione"], Choices: NatureWords),
|
||||
new("tipo", ImportFieldKind.Choice, Aliases: ["tipo_conto"], Choices: TypeWords),
|
||||
new("voce_cee", Aliases: ["cee", "voce_bilancio"]),
|
||||
new("riclassifica", Aliases: ["riclassificazione"]),
|
||||
new("flag", Aliases: ["flags", "attributi"]),
|
||||
];
|
||||
|
||||
/// <summary>Checks the rows of a chart.</summary>
|
||||
/// <param name="rows">The rows.</param>
|
||||
/// <returns>A result per row, and the accounts without errors.</returns>
|
||||
public static (IReadOnlyList<ImportRowResult> Results, IReadOnlyList<ImportedAccount> Accounts) Check(IReadOnlyList<ImportRow> rows)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(rows);
|
||||
|
||||
// First pass: every code with its nature as written, to check parents wherever they are in the file.
|
||||
var natures = new Dictionary<string, AccountNature?>(StringComparer.OrdinalIgnoreCase);
|
||||
foreach (var row in rows)
|
||||
{
|
||||
if (row["codice"] is { } code)
|
||||
{
|
||||
natures.TryAdd(code, Choice(row["natura"], NatureWords) is { } n ? (AccountNature)n : null);
|
||||
}
|
||||
}
|
||||
|
||||
var parents = natures.Keys.Select(ParentOf).Where(p => p is not null).ToHashSet(StringComparer.OrdinalIgnoreCase);
|
||||
var seen = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
|
||||
var results = new List<ImportRowResult>(rows.Count);
|
||||
var accounts = new List<ImportedAccount>();
|
||||
foreach (var row in rows)
|
||||
{
|
||||
var messages = new List<ImportMessage>();
|
||||
var cells = new CellReader(row, messages);
|
||||
var code = row["codice"];
|
||||
messages.AddRange(Fields.Where(f => f.Required && !cells.Has(f.Key)).Select(f => new ImportMessage(f.Key, ImportErrors.Required)));
|
||||
if (code is null)
|
||||
{
|
||||
results.Add(new(row.Line, row["descrizione"] ?? string.Empty, ImportAction.Skip, messages));
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!seen.Add(code))
|
||||
{
|
||||
results.Add(new(row.Line, code, ImportAction.Skip, [new("codice", ImportErrors.CodeRepeated, Value: code)]));
|
||||
continue;
|
||||
}
|
||||
|
||||
var parts = code.Split('.');
|
||||
var level = parts.Length;
|
||||
if (level > MaxLevel || parts.Any(p => p.Length == 0 || !p.All(char.IsAsciiLetterOrDigit)))
|
||||
{
|
||||
messages.Add(new("codice", ImportErrors.AccountLevel, Value: code));
|
||||
}
|
||||
else if (cells.Number("livello") is { } written && written != level)
|
||||
{
|
||||
messages.Add(new("livello", ImportErrors.AccountLevel, Value: level.ToString(System.Globalization.CultureInfo.InvariantCulture)));
|
||||
}
|
||||
|
||||
var parent = ParentOf(code);
|
||||
if (row["padre"] is { } named && !string.Equals(named, parent, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
messages.Add(new("padre", ImportErrors.AccountParent, Value: parent ?? string.Empty));
|
||||
}
|
||||
else if (parent is not null && !natures.ContainsKey(parent))
|
||||
{
|
||||
messages.Add(new("padre", ImportErrors.AccountParent, Value: parent));
|
||||
}
|
||||
|
||||
var nature = NatureOf(code, natures);
|
||||
if (nature is null)
|
||||
{
|
||||
messages.Add(new("natura", cells.Has("natura") ? ImportErrors.Choice : ImportErrors.Required, Value: cells.Has("natura") ? string.Join(", ", NatureWords) : null));
|
||||
}
|
||||
else if (parent is not null && natures.ContainsKey(parent) && NatureOf(parent, natures) is { } parentNature && parentNature != nature)
|
||||
{
|
||||
messages.Add(new("natura", ImportErrors.AccountNature, Value: NatureWords[(int)parentNature]));
|
||||
}
|
||||
|
||||
var type = cells.Choice(Fields[5]) is { } t ? (AccountType)t : AccountType.Generic;
|
||||
var flags = (row["flag"] ?? string.Empty).ToUpperInvariant().Where(c => !char.IsWhiteSpace(c) && c is not ',' and not ';').ToList();
|
||||
if (flags.FirstOrDefault(c => !FlagLetters.Contains(c, StringComparison.Ordinal)) is var bad && bad != default)
|
||||
{
|
||||
messages.Add(new("flag", ImportErrors.AccountFlag, Value: bad.ToString()));
|
||||
}
|
||||
|
||||
var postable = flags.Contains('M');
|
||||
var leaf = !parents.Contains(code);
|
||||
if (postable && !leaf)
|
||||
{
|
||||
messages.Add(new("flag", ImportErrors.AccountPostable));
|
||||
}
|
||||
else if (!postable && leaf && level > 1)
|
||||
{
|
||||
messages.Add(new("flag", ImportErrors.AccountLeaf, IsWarning: true));
|
||||
}
|
||||
|
||||
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')));
|
||||
}
|
||||
|
||||
results.Add(new(row.Line, code, messages.Any(m => !m.IsWarning) ? ImportAction.Skip : ImportAction.Create, messages));
|
||||
}
|
||||
|
||||
return (results, accounts);
|
||||
}
|
||||
|
||||
/// <summary>The code without its last part, or <see langword="null"/> for a first level account.</summary>
|
||||
/// <param name="code">The code.</param>
|
||||
/// <returns>The parent code.</returns>
|
||||
public static string? ParentOf(string code)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(code);
|
||||
var point = code.LastIndexOf('.');
|
||||
return point <= 0 ? null : code[..point];
|
||||
}
|
||||
|
||||
// The nature written on the account, else the one of the nearest ancestor that has one.
|
||||
private static AccountNature? NatureOf(string code, Dictionary<string, AccountNature?> natures)
|
||||
{
|
||||
for (var current = code; current is not null; current = ParentOf(current))
|
||||
{
|
||||
if (natures.TryGetValue(current, out var nature) && nature is not null)
|
||||
{
|
||||
return nature;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private static int? Choice(string? text, IReadOnlyList<string> words) => text is null ? null : ImportValues.Choice(text, words) is var i and >= 0 ? i : null;
|
||||
}
|
||||
|
||||
/// <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.
|
||||
/// </summary>
|
||||
/// <param name="permissions">Checks the permission.</param>
|
||||
public sealed class ChartOfAccountsImportTarget(PermissionService permissions) : IImportTarget
|
||||
{
|
||||
/// <summary>The permission to change the chart of accounts.</summary>
|
||||
public const string WritePermission = "ledger.account.write";
|
||||
|
||||
/// <inheritdoc />
|
||||
public string Key => "piano-dei-conti";
|
||||
|
||||
/// <inheritdoc />
|
||||
public string ModuleCode => ModuleCodes.Accounting;
|
||||
|
||||
/// <inheritdoc />
|
||||
public string Permission => WritePermission;
|
||||
|
||||
/// <inheritdoc />
|
||||
public string ExportPermission => "ledger.account.read";
|
||||
|
||||
/// <inheritdoc />
|
||||
public bool CanApply => false;
|
||||
|
||||
/// <inheritdoc />
|
||||
public bool CanExport => false;
|
||||
|
||||
/// <inheritdoc />
|
||||
public IReadOnlyList<ImportField> Fields => ChartOfAccountsImportValidator.Fields;
|
||||
|
||||
/// <inheritdoc />
|
||||
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);
|
||||
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)
|
||||
{
|
||||
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 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));
|
||||
}
|
||||
|
||||
return 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?>>>([]);
|
||||
}
|
||||
@@ -0,0 +1,255 @@
|
||||
using System.Globalization;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using Khaemhat.Infrastructure.Files;
|
||||
|
||||
namespace Khaemhat.Application.ImportExport;
|
||||
|
||||
/// <summary>A file the import cannot use; <see cref="Code"/> is one of the <c>import.file.*</c> codes.</summary>
|
||||
public sealed class ImportFileException : Exception
|
||||
{
|
||||
/// <summary>Creates the exception.</summary>
|
||||
public ImportFileException()
|
||||
{
|
||||
Code = ImportErrors.FileUnreadable;
|
||||
}
|
||||
|
||||
/// <summary>Creates the exception.</summary>
|
||||
/// <param name="message">What went wrong.</param>
|
||||
public ImportFileException(string message)
|
||||
: base(message)
|
||||
{
|
||||
Code = ImportErrors.FileUnreadable;
|
||||
}
|
||||
|
||||
/// <summary>Creates the exception.</summary>
|
||||
/// <param name="message">What went wrong.</param>
|
||||
/// <param name="innerException">The cause.</param>
|
||||
public ImportFileException(string message, Exception innerException)
|
||||
: base(message, innerException)
|
||||
{
|
||||
Code = ImportErrors.FileUnreadable;
|
||||
}
|
||||
|
||||
/// <summary>Creates the exception with a code.</summary>
|
||||
/// <param name="code">The text code.</param>
|
||||
/// <param name="message">What went wrong.</param>
|
||||
/// <param name="innerException">The cause.</param>
|
||||
public ImportFileException(string code, string message, Exception? innerException)
|
||||
: base(message, innerException)
|
||||
{
|
||||
Code = code;
|
||||
}
|
||||
|
||||
/// <summary>The text code.</summary>
|
||||
public string Code { get; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reads the files of the guided import (SPEC §12.12): CSV (UTF-8 with or without byte order mark, else Windows-1252;
|
||||
/// separator <c>;</c>, <c>,</c> or tab guessed from the header), XLSX (first sheet) and JSON (an array of objects, or the
|
||||
/// object of <c>khaemhat-coa.json</c> with its <c>accounts</c>). The first row holds the headers.
|
||||
/// </summary>
|
||||
public static class ImportFileReader
|
||||
{
|
||||
/// <summary>The most data rows an import takes.</summary>
|
||||
public const int MaxRows = 50_000;
|
||||
|
||||
/// <summary>The format name written in <c>khaemhat-coa.json</c>.</summary>
|
||||
public const string ChartFormat = "khaemhat-coa";
|
||||
|
||||
private static readonly UTF8Encoding StrictUtf8 = new(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true);
|
||||
|
||||
/// <summary>The format of a file from its name.</summary>
|
||||
/// <param name="fileName">The name.</param>
|
||||
/// <returns>The format, or <see langword="null"/> when not supported.</returns>
|
||||
public static TransferFormat? FormatOf(string? fileName) => Path.GetExtension(fileName ?? string.Empty).ToUpperInvariant() switch
|
||||
{
|
||||
".CSV" or ".TXT" => TransferFormat.Csv,
|
||||
".XLSX" => TransferFormat.Xlsx,
|
||||
".JSON" => TransferFormat.Json,
|
||||
_ => null,
|
||||
};
|
||||
|
||||
/// <summary>Reads a file.</summary>
|
||||
/// <param name="fileName">The name, which gives the format.</param>
|
||||
/// <param name="content">The content.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The file with headers and rows.</returns>
|
||||
/// <exception cref="ImportFileException">The format is not supported, or the file is empty, damaged or too large.</exception>
|
||||
public static async Task<ImportFile> ReadAsync(string fileName, Stream content, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(fileName);
|
||||
ArgumentNullException.ThrowIfNull(content);
|
||||
var format = FormatOf(fileName) ?? throw new ImportFileException(ImportErrors.FileFormat, "Not CSV, XLSX or JSON: " + fileName, null);
|
||||
using var buffer = new MemoryStream();
|
||||
await content.CopyToAsync(buffer, cancellationToken).ConfigureAwait(false);
|
||||
buffer.Position = 0;
|
||||
return format switch
|
||||
{
|
||||
TransferFormat.Xlsx => await ReadXlsxAsync(fileName, buffer, cancellationToken).ConfigureAwait(false),
|
||||
TransferFormat.Json => ReadJson(fileName, buffer.ToArray()),
|
||||
_ => ReadCsv(fileName, buffer.ToArray()),
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>Reads CSV bytes.</summary>
|
||||
/// <param name="fileName">The name.</param>
|
||||
/// <param name="bytes">The content.</param>
|
||||
/// <returns>The file.</returns>
|
||||
/// <exception cref="ImportFileException">Empty or too large.</exception>
|
||||
public static ImportFile ReadCsv(string fileName, byte[] bytes)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(bytes);
|
||||
string text;
|
||||
string encoding;
|
||||
var start = bytes.Length >= 3 && bytes[0] == 0xEF && bytes[1] == 0xBB && bytes[2] == 0xBF ? 3 : 0;
|
||||
try
|
||||
{
|
||||
text = StrictUtf8.GetString(bytes, start, bytes.Length - start);
|
||||
encoding = "UTF-8";
|
||||
}
|
||||
catch (DecoderFallbackException)
|
||||
{
|
||||
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
|
||||
text = Encoding.GetEncoding(1252).GetString(bytes);
|
||||
encoding = "Windows-1252";
|
||||
}
|
||||
|
||||
var separator = Guess(text);
|
||||
var lines = CsvReader.Parse(text, separator);
|
||||
return Build(fileName, TransferFormat.Csv, encoding, separator, lines, null);
|
||||
}
|
||||
|
||||
private static async Task<ImportFile> ReadXlsxAsync(string fileName, Stream content, CancellationToken cancellationToken)
|
||||
{
|
||||
try
|
||||
{
|
||||
var rows = await XlsxReader.ReadAsync(content, cancellationToken).ConfigureAwait(false);
|
||||
return Build(fileName, TransferFormat.Xlsx, null, null, rows, null);
|
||||
}
|
||||
catch (XlsxReadException ex)
|
||||
{
|
||||
throw new ImportFileException(ImportErrors.FileUnreadable, ex.Message, ex);
|
||||
}
|
||||
}
|
||||
|
||||
private static ImportFile ReadJson(string fileName, byte[] bytes)
|
||||
{
|
||||
JsonDocument document;
|
||||
try
|
||||
{
|
||||
document = JsonDocument.Parse(bytes, new JsonDocumentOptions { MaxDepth = 16, AllowTrailingCommas = true, CommentHandling = JsonCommentHandling.Skip });
|
||||
}
|
||||
catch (JsonException ex)
|
||||
{
|
||||
throw new ImportFileException(ImportErrors.FileUnreadable, ex.Message, ex);
|
||||
}
|
||||
|
||||
using (document)
|
||||
{
|
||||
var root = document.RootElement;
|
||||
Dictionary<string, int>? sections = null;
|
||||
JsonElement records;
|
||||
if (root.ValueKind == JsonValueKind.Array)
|
||||
{
|
||||
records = root;
|
||||
}
|
||||
else if (root.ValueKind == JsonValueKind.Object && root.TryGetProperty("accounts", out var accounts) && accounts.ValueKind == JsonValueKind.Array)
|
||||
{
|
||||
records = accounts;
|
||||
sections = new Dictionary<string, int>(StringComparer.Ordinal);
|
||||
foreach (var property in root.EnumerateObject())
|
||||
{
|
||||
if (property.Name != "accounts" && property.Value.ValueKind == JsonValueKind.Array)
|
||||
{
|
||||
sections[property.Name] = property.Value.GetArrayLength();
|
||||
}
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
throw new ImportFileException(ImportErrors.FileUnreadable, "Neither an array of objects nor a chart of accounts.", null);
|
||||
}
|
||||
|
||||
var headers = new List<string>();
|
||||
var index = new Dictionary<string, int>(StringComparer.Ordinal);
|
||||
var objects = new List<Dictionary<string, string>>();
|
||||
foreach (var element in records.EnumerateArray())
|
||||
{
|
||||
if (element.ValueKind != JsonValueKind.Object)
|
||||
{
|
||||
throw new ImportFileException(ImportErrors.FileUnreadable, "An entry is not an object.", null);
|
||||
}
|
||||
|
||||
var values = new Dictionary<string, string>(StringComparer.Ordinal);
|
||||
foreach (var property in element.EnumerateObject())
|
||||
{
|
||||
if (index.TryAdd(property.Name, headers.Count))
|
||||
{
|
||||
headers.Add(property.Name);
|
||||
}
|
||||
|
||||
values[property.Name] = Cell(property.Value);
|
||||
}
|
||||
|
||||
objects.Add(values);
|
||||
}
|
||||
|
||||
var rows = new List<IReadOnlyList<string>> { headers };
|
||||
rows.AddRange(objects.Select(o => (IReadOnlyList<string>)[.. headers.Select(h => o.GetValueOrDefault(h, string.Empty))]));
|
||||
return Build(fileName, TransferFormat.Json, "UTF-8", null, rows, sections);
|
||||
}
|
||||
}
|
||||
|
||||
private static string Cell(JsonElement value) => value.ValueKind switch
|
||||
{
|
||||
JsonValueKind.String => value.GetString() ?? string.Empty,
|
||||
JsonValueKind.Number => value.GetRawText(),
|
||||
JsonValueKind.True => "true",
|
||||
JsonValueKind.False => "false",
|
||||
JsonValueKind.Null or JsonValueKind.Undefined => string.Empty,
|
||||
_ => value.GetRawText(),
|
||||
};
|
||||
|
||||
private static ImportFile Build(string fileName, TransferFormat format, string? encoding, char? separator, IReadOnlyList<IReadOnlyList<string>> lines,
|
||||
IReadOnlyDictionary<string, int>? sections)
|
||||
{
|
||||
if (lines.Count == 0 || lines[0].All(string.IsNullOrWhiteSpace))
|
||||
{
|
||||
throw new ImportFileException(ImportErrors.FileEmpty, "No header.", null);
|
||||
}
|
||||
|
||||
if (lines.Count - 1 > MaxRows)
|
||||
{
|
||||
throw new ImportFileException(ImportErrors.FileTooLarge, "More than " + MaxRows.ToString(CultureInfo.InvariantCulture) + " rows.", null);
|
||||
}
|
||||
|
||||
var headers = lines[0].Select((h, i) => string.IsNullOrWhiteSpace(h) ? "colonna_" + (i + 1).ToString(CultureInfo.InvariantCulture) : h.Trim()).ToList();
|
||||
var rows = new List<IReadOnlyList<string>>(lines.Count - 1);
|
||||
foreach (var line in lines.Skip(1))
|
||||
{
|
||||
if (line.All(string.IsNullOrWhiteSpace))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
rows.Add([.. Enumerable.Range(0, headers.Count).Select(i => i < line.Count ? Unprotect(line[i]) : string.Empty)]);
|
||||
}
|
||||
|
||||
return new ImportFile(Path.GetFileName(fileName), format, encoding, separator, headers, rows, sections);
|
||||
}
|
||||
|
||||
// The apostrophe the export puts before text that a spreadsheet would read as a formula (CsvWriter).
|
||||
private static string Unprotect(string cell) =>
|
||||
cell.Length > 1 && cell[0] == '\'' && cell[1] is '=' or '+' or '-' or '@' ? cell[1..].Trim() : cell.Trim();
|
||||
|
||||
private static char Guess(string text)
|
||||
{
|
||||
var end = text.IndexOfAny(['\r', '\n']);
|
||||
var first = end < 0 ? text : text[..end];
|
||||
return Separators.OrderByDescending(s => first.Count(c => c == s)).First();
|
||||
}
|
||||
|
||||
private static readonly char[] Separators = [';', ',', '\t'];
|
||||
}
|
||||
@@ -0,0 +1,197 @@
|
||||
using Khaemhat.Application.Security;
|
||||
|
||||
namespace Khaemhat.Application.ImportExport;
|
||||
|
||||
/// <summary>The formats of the guided import and export (SPEC §12.12).</summary>
|
||||
public enum TransferFormat
|
||||
{
|
||||
/// <summary>Text with <c>;</c>, UTF-8 (other separators and Windows-1252 are recognized when reading).</summary>
|
||||
Csv = 0,
|
||||
|
||||
/// <summary>Excel workbook, first sheet, headers in the first row.</summary>
|
||||
Xlsx = 1,
|
||||
|
||||
/// <summary>JSON: an array of objects keyed by column, or the object of <c>khaemhat-coa.json</c>.</summary>
|
||||
Json = 2,
|
||||
}
|
||||
|
||||
/// <summary>The kind of value of a column, for reading and writing it.</summary>
|
||||
public enum ImportFieldKind
|
||||
{
|
||||
/// <summary>Free text.</summary>
|
||||
Text = 0,
|
||||
|
||||
/// <summary>A code of another archive or table.</summary>
|
||||
Code = 1,
|
||||
|
||||
/// <summary>A decimal number (Italian or invariant notation).</summary>
|
||||
Number = 2,
|
||||
|
||||
/// <summary>A date (<c>dd/MM/yyyy</c>, ISO or a spreadsheet serial).</summary>
|
||||
Date = 3,
|
||||
|
||||
/// <summary>Yes or no.</summary>
|
||||
Boolean = 4,
|
||||
|
||||
/// <summary>One of a list of words.</summary>
|
||||
Choice = 5,
|
||||
}
|
||||
|
||||
/// <summary>A column an entity accepts.</summary>
|
||||
/// <param name="Key">The column name used in files and templates (<c>partita_iva</c>).</param>
|
||||
/// <param name="Kind">The kind of value.</param>
|
||||
/// <param name="Required">Whether a new record needs it.</param>
|
||||
/// <param name="Aliases">Other headers recognized by the automatic mapping, already normalized.</param>
|
||||
/// <param name="Choices">The words accepted for <see cref="ImportFieldKind.Choice"/>.</param>
|
||||
public sealed record ImportField(string Key, ImportFieldKind Kind = ImportFieldKind.Text, bool Required = false, IReadOnlyList<string>? Aliases = null,
|
||||
IReadOnlyList<string>? Choices = null);
|
||||
|
||||
/// <summary>A file read for the import.</summary>
|
||||
/// <param name="Name">The file name.</param>
|
||||
/// <param name="Format">The format.</param>
|
||||
/// <param name="Encoding">The text encoding (CSV), such as <c>UTF-8</c>.</param>
|
||||
/// <param name="Separator">The separator (CSV).</param>
|
||||
/// <param name="Headers">The headers of the columns.</param>
|
||||
/// <param name="Rows">The rows under the headers, each as long as the headers.</param>
|
||||
/// <param name="Sections">For <c>khaemhat-coa.json</c>: the other sections with their number of entries.</param>
|
||||
public sealed record ImportFile(string Name, TransferFormat Format, string? Encoding, char? Separator, IReadOnlyList<string> Headers,
|
||||
IReadOnlyList<IReadOnlyList<string>> Rows, IReadOnlyDictionary<string, int>? Sections = null)
|
||||
{
|
||||
/// <summary>The number of data rows.</summary>
|
||||
public int Count => Rows.Count;
|
||||
}
|
||||
|
||||
/// <summary>What happens to a row whose code is already in the archive.</summary>
|
||||
public enum ExistingCodeAction
|
||||
{
|
||||
/// <summary>The record is updated with the non empty cells of the row.</summary>
|
||||
Update = 0,
|
||||
|
||||
/// <summary>The row is skipped.</summary>
|
||||
Skip = 1,
|
||||
}
|
||||
|
||||
/// <summary>What happens to a row without a code.</summary>
|
||||
public enum MissingCodeAction
|
||||
{
|
||||
/// <summary>The code comes from the automatic code rules.</summary>
|
||||
Generate = 0,
|
||||
|
||||
/// <summary>The row is an error.</summary>
|
||||
Refuse = 1,
|
||||
}
|
||||
|
||||
/// <summary>The options of an import (mockup 077, step 1).</summary>
|
||||
public sealed record ImportOptions
|
||||
{
|
||||
/// <summary>Rows whose code exists.</summary>
|
||||
public ExistingCodeAction Existing { get; init; } = ExistingCodeAction.Update;
|
||||
|
||||
/// <summary>Rows without a code.</summary>
|
||||
public MissingCodeAction Missing { get; init; } = MissingCodeAction.Generate;
|
||||
|
||||
/// <summary>Check the VAT numbers of EU parties on VIES while importing.</summary>
|
||||
public bool VerifyVat { get; init; }
|
||||
|
||||
/// <summary>Fill the city from the postal code (and the postal code from the city) when one is missing.</summary>
|
||||
public bool FillFromPostalCode { get; init; } = true;
|
||||
}
|
||||
|
||||
/// <summary>Who imports, where and how: what a target needs besides the rows.</summary>
|
||||
/// <param name="Actor">Who imports.</param>
|
||||
/// <param name="CompanyCode">The company.</param>
|
||||
/// <param name="Options">The options.</param>
|
||||
public sealed record ImportContext(Actor Actor, string CompanyCode, ImportOptions Options);
|
||||
|
||||
/// <summary>A row of the file with the cells of the mapped columns by field key.</summary>
|
||||
/// <param name="Line">The line in the file, counting the header as line 1.</param>
|
||||
/// <param name="Values">The trimmed cells by field key; empty cells are left out.</param>
|
||||
public sealed record ImportRow(int Line, IReadOnlyDictionary<string, string> Values)
|
||||
{
|
||||
/// <summary>The cell of a field, or <see langword="null"/> when empty or not mapped.</summary>
|
||||
/// <param name="key">The field.</param>
|
||||
/// <returns>The text.</returns>
|
||||
public string? this[string key] => Values.TryGetValue(key, out var value) ? value : null;
|
||||
}
|
||||
|
||||
/// <summary>The outcome of a row in the preview (mockup 077: OK, avviso, errore).</summary>
|
||||
public enum ImportOutcome
|
||||
{
|
||||
/// <summary>Importable.</summary>
|
||||
Ok = 0,
|
||||
|
||||
/// <summary>Importable, with a correction proposed or a remark.</summary>
|
||||
Warning = 1,
|
||||
|
||||
/// <summary>Not importable.</summary>
|
||||
Error = 2,
|
||||
}
|
||||
|
||||
/// <summary>What the import does with a row.</summary>
|
||||
public enum ImportAction
|
||||
{
|
||||
/// <summary>A new record.</summary>
|
||||
Create = 0,
|
||||
|
||||
/// <summary>An existing record changes.</summary>
|
||||
Update = 1,
|
||||
|
||||
/// <summary>Nothing (existing code to skip, or an error).</summary>
|
||||
Skip = 2,
|
||||
}
|
||||
|
||||
/// <summary>A remark on a row: a text code with the field it concerns.</summary>
|
||||
/// <param name="Field">The field key, or empty for the whole row.</param>
|
||||
/// <param name="Code">The text code (an error code of the services or <c>import.*</c>).</param>
|
||||
/// <param name="IsWarning">A warning instead of an error.</param>
|
||||
/// <param name="Value">A value to show in the text (<c>{0}</c>), such as the code not found or the city proposed.</param>
|
||||
public sealed record ImportMessage(string Field, string Code, bool IsWarning = false, string? Value = null);
|
||||
|
||||
/// <summary>The check of a row.</summary>
|
||||
/// <param name="Line">The line in the file.</param>
|
||||
/// <param name="Key">The code or description that identifies the row in the preview.</param>
|
||||
/// <param name="Action">What the import will do.</param>
|
||||
/// <param name="Messages">The remarks.</param>
|
||||
public sealed record ImportRowResult(int Line, string Key, ImportAction Action, IReadOnlyList<ImportMessage> Messages)
|
||||
{
|
||||
/// <summary>The outcome from the remarks.</summary>
|
||||
public ImportOutcome Outcome =>
|
||||
Messages.Any(m => !m.IsWarning) ? ImportOutcome.Error : Messages.Count > 0 ? ImportOutcome.Warning : ImportOutcome.Ok;
|
||||
}
|
||||
|
||||
/// <summary>The preview of an import (mockup 077, steps 3 and 4).</summary>
|
||||
/// <param name="Target">The entity.</param>
|
||||
/// <param name="Rows">The checked rows, in file order.</param>
|
||||
/// <param name="CanApply">Whether the entity can be written now (opening stock and chart of accounts only check, until M6 and M7).</param>
|
||||
public sealed record ImportPreview(string Target, IReadOnlyList<ImportRowResult> Rows, bool CanApply)
|
||||
{
|
||||
/// <summary>Rows that will create a record.</summary>
|
||||
public int Creates => Rows.Count(r => r.Outcome != ImportOutcome.Error && r.Action == ImportAction.Create);
|
||||
|
||||
/// <summary>Rows that will update a record.</summary>
|
||||
public int Updates => Rows.Count(r => r.Outcome != ImportOutcome.Error && r.Action == ImportAction.Update);
|
||||
|
||||
/// <summary>Rows skipped on purpose.</summary>
|
||||
public int Skips => Rows.Count(r => r.Outcome != ImportOutcome.Error && r.Action == ImportAction.Skip);
|
||||
|
||||
/// <summary>Rows with errors.</summary>
|
||||
public int Errors => Rows.Count(r => r.Outcome == ImportOutcome.Error);
|
||||
|
||||
/// <summary>Rows with warnings only.</summary>
|
||||
public int Warnings => Rows.Count(r => r.Outcome == ImportOutcome.Warning);
|
||||
|
||||
/// <summary>Rows the import writes.</summary>
|
||||
public int Importable => Creates + Updates;
|
||||
}
|
||||
|
||||
/// <summary>The result of an import.</summary>
|
||||
/// <param name="Target">The entity.</param>
|
||||
/// <param name="Created">Records created.</param>
|
||||
/// <param name="Updated">Records updated.</param>
|
||||
/// <param name="Skipped">Rows skipped on purpose.</param>
|
||||
/// <param name="Rows">Every row with its final outcome; rows refused while writing carry their errors.</param>
|
||||
public sealed record ImportReport(string Target, int Created, int Updated, int Skipped, IReadOnlyList<ImportRowResult> Rows)
|
||||
{
|
||||
/// <summary>Rows not imported because of errors.</summary>
|
||||
public int Failed => Rows.Count(r => r.Outcome == ImportOutcome.Error);
|
||||
}
|
||||
@@ -0,0 +1,375 @@
|
||||
using System.Text.Json;
|
||||
using Khaemhat.Application.Licensing;
|
||||
using Khaemhat.Application.Security;
|
||||
using Khaemhat.Core.Logging;
|
||||
using Khaemhat.Infrastructure.Files;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace Khaemhat.Application.ImportExport;
|
||||
|
||||
/// <summary>
|
||||
/// The guided import and export (SPEC §11.7, §12.12, mockup 077, ADR 0031): the entities the licence allows, the
|
||||
/// automatic mapping of the columns, the preview that checks every row as if typed in its record, the import of the
|
||||
/// rows without errors, the error report, the export with the same columns and the empty templates.
|
||||
/// </summary>
|
||||
public sealed partial class ImportService
|
||||
{
|
||||
private static readonly JsonWriterOptions JsonOptions = new() { Indented = true };
|
||||
|
||||
private readonly IReadOnlyList<IImportTarget> _targets;
|
||||
private readonly ILicenseGate _license;
|
||||
private readonly PermissionService _permissions;
|
||||
private readonly ILogger<ImportService> _logger;
|
||||
|
||||
/// <summary>Creates the service.</summary>
|
||||
/// <param name="targets">The entities.</param>
|
||||
/// <param name="license">The licence.</param>
|
||||
/// <param name="permissions">The permissions and the user flags.</param>
|
||||
/// <param name="logger">The log.</param>
|
||||
public ImportService(IEnumerable<IImportTarget> targets, ILicenseGate license, PermissionService permissions, ILogger<ImportService> logger)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(targets);
|
||||
ArgumentNullException.ThrowIfNull(license);
|
||||
ArgumentNullException.ThrowIfNull(permissions);
|
||||
ArgumentNullException.ThrowIfNull(logger);
|
||||
_targets = [.. targets];
|
||||
_license = license;
|
||||
_permissions = permissions;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
/// <summary>The entities whose module is licensed, in the order of the screen.</summary>
|
||||
public IReadOnlyList<IImportTarget> Targets => [.. _targets.Where(t => _license.IsModuleActive(t.ModuleCode))];
|
||||
|
||||
/// <summary>A licensed entity by key.</summary>
|
||||
/// <param name="key">The key.</param>
|
||||
/// <returns>The entity.</returns>
|
||||
/// <exception cref="ImportFileException">Unknown or not licensed (<see cref="ImportErrors.TargetUnknown"/>).</exception>
|
||||
public IImportTarget Target(string key) =>
|
||||
Targets.FirstOrDefault(t => string.Equals(t.Key, key, StringComparison.OrdinalIgnoreCase))
|
||||
?? throw new ImportFileException(ImportErrors.TargetUnknown, "Unknown import: " + key, null);
|
||||
|
||||
/// <summary>
|
||||
/// The field of each column of a file, by name or alias ignoring case, accents and punctuation; a field goes to one
|
||||
/// column only.
|
||||
/// </summary>
|
||||
/// <param name="target">The entity.</param>
|
||||
/// <param name="headers">The headers.</param>
|
||||
/// <returns>The field key per column, or <see langword="null"/> for columns to ignore.</returns>
|
||||
public static IReadOnlyList<string?> SuggestMapping(IImportTarget target, IReadOnlyList<string> headers)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(target);
|
||||
ArgumentNullException.ThrowIfNull(headers);
|
||||
var taken = new HashSet<string>(StringComparer.Ordinal);
|
||||
var mapping = new string?[headers.Count];
|
||||
for (var pass = 0; pass < 2; pass++)
|
||||
{
|
||||
for (var i = 0; i < headers.Count; i++)
|
||||
{
|
||||
if (mapping[i] is not null)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var header = ImportValues.Normalize(headers[i]);
|
||||
var field = target.Fields.FirstOrDefault(f => !taken.Contains(f.Key)
|
||||
&& (pass == 0 ? f.Key == header : (f.Aliases ?? []).Any(a => ImportValues.Normalize(a) == header)));
|
||||
if (field is not null)
|
||||
{
|
||||
mapping[i] = field.Key;
|
||||
taken.Add(field.Key);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return mapping;
|
||||
}
|
||||
|
||||
/// <summary>The rows of a file with the cells of the mapped columns.</summary>
|
||||
/// <param name="file">The file.</param>
|
||||
/// <param name="mapping">The field key per column, or <see langword="null"/>.</param>
|
||||
/// <returns>The rows, line numbers counting the header as line 1.</returns>
|
||||
public static IReadOnlyList<ImportRow> Rows(ImportFile file, IReadOnlyList<string?> mapping)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(file);
|
||||
ArgumentNullException.ThrowIfNull(mapping);
|
||||
var rows = new List<ImportRow>(file.Count);
|
||||
for (var r = 0; r < file.Count; r++)
|
||||
{
|
||||
var values = new Dictionary<string, string>(StringComparer.Ordinal);
|
||||
var cells = file.Rows[r];
|
||||
for (var c = 0; c < mapping.Count && c < cells.Count; c++)
|
||||
{
|
||||
if (mapping[c] is { } key && !string.IsNullOrWhiteSpace(cells[c]))
|
||||
{
|
||||
values.TryAdd(key, cells[c].Trim());
|
||||
}
|
||||
}
|
||||
|
||||
rows.Add(new ImportRow(r + 2, values));
|
||||
}
|
||||
|
||||
return rows;
|
||||
}
|
||||
|
||||
/// <summary>Checks a file without writing (steps 2 and 3 of the screen).</summary>
|
||||
/// <param name="actor">Who imports.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="targetKey">The entity.</param>
|
||||
/// <param name="file">The file.</param>
|
||||
/// <param name="mapping">The field per column.</param>
|
||||
/// <param name="options">The options.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The preview.</returns>
|
||||
public async Task<ImportPreview> PreviewAsync(Actor actor, string companyCode, string targetKey, ImportFile file, IReadOnlyList<string?> mapping, ImportOptions options,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
var target = Target(targetKey);
|
||||
var context = new ImportContext(actor, companyCode, options ?? new ImportOptions());
|
||||
var rows = await target.CheckAsync(context, Rows(file, mapping), cancellationToken).ConfigureAwait(false);
|
||||
return new ImportPreview(target.Key, rows, target.CanApply);
|
||||
}
|
||||
|
||||
/// <summary>Imports the rows without errors (step 4); rows with errors are left out and reported.</summary>
|
||||
/// <param name="actor">Who imports.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="targetKey">The entity.</param>
|
||||
/// <param name="file">The file.</param>
|
||||
/// <param name="mapping">The field per column.</param>
|
||||
/// <param name="options">The options.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>What was done.</returns>
|
||||
/// <exception cref="ImportFileException">The entity is only checked for now (<see cref="ImportErrors.CheckOnly"/>).</exception>
|
||||
public async Task<ImportReport> ImportAsync(Actor actor, string companyCode, string targetKey, ImportFile file, IReadOnlyList<string?> mapping, ImportOptions options,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(actor);
|
||||
ArgumentNullException.ThrowIfNull(file);
|
||||
var target = Target(targetKey);
|
||||
if (!target.CanApply)
|
||||
{
|
||||
throw new ImportFileException(ImportErrors.CheckOnly, "Only checked for now: " + target.Key, null);
|
||||
}
|
||||
|
||||
var context = new ImportContext(actor, companyCode, options ?? new ImportOptions());
|
||||
var rows = await target.ApplyAsync(context, Rows(file, mapping), cancellationToken).ConfigureAwait(false);
|
||||
var report = new ImportReport(
|
||||
target.Key,
|
||||
rows.Count(r => r.Outcome != ImportOutcome.Error && r.Action == ImportAction.Create),
|
||||
rows.Count(r => r.Outcome != ImportOutcome.Error && r.Action == ImportAction.Update),
|
||||
rows.Count(r => r.Outcome != ImportOutcome.Error && r.Action == ImportAction.Skip),
|
||||
rows);
|
||||
using (_logger.BeginScope(LogSections.Scope(LogSection.System)))
|
||||
{
|
||||
LogImported(_logger, target.Key, file.Name, companyCode, actor.UserName, report.Created, report.Updated, report.Skipped, report.Failed);
|
||||
}
|
||||
|
||||
return report;
|
||||
}
|
||||
|
||||
/// <summary>Writes the rows with errors and warnings as CSV (button <i>Scarica report errori</i>).</summary>
|
||||
/// <param name="rows">The checked rows.</param>
|
||||
/// <param name="text">The text of a remark, in the language of the user.</param>
|
||||
/// <param name="labels">The headers: line, key, column, outcome, message.</param>
|
||||
/// <param name="output">Where to write.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>A task.</returns>
|
||||
public static async Task WriteErrorReportAsync(IReadOnlyList<ImportRowResult> rows, Func<ImportRowResult, ImportMessage, (string Outcome, string Message)> text,
|
||||
IReadOnlyList<string> labels, Stream output, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(rows);
|
||||
ArgumentNullException.ThrowIfNull(text);
|
||||
ArgumentNullException.ThrowIfNull(labels);
|
||||
await using var csv = new CsvWriter(output, CsvOptions.Italian, leaveOpen: true);
|
||||
await csv.WriteRowAsync(labels, cancellationToken).ConfigureAwait(false);
|
||||
foreach (var row in rows)
|
||||
{
|
||||
foreach (var message in row.Messages)
|
||||
{
|
||||
var (outcome, line) = text(row, message);
|
||||
await csv.WriteRowAsync([row.Line, row.Key, message.Field, outcome, line], cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
await csv.FlushAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>Exports an entity with the columns of its import, so that the file can be imported again.</summary>
|
||||
/// <param name="actor">Who exports: needs the export permission of the entity and the <i>can export</i> flag.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="targetKey">The entity.</param>
|
||||
/// <param name="format">The format.</param>
|
||||
/// <param name="output">Where to write.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The number of records written.</returns>
|
||||
/// <exception cref="AccessDeniedException">The user cannot export.</exception>
|
||||
public async Task<int> ExportAsync(Actor actor, string companyCode, string targetKey, TransferFormat format, Stream output, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(actor);
|
||||
var target = Target(targetKey);
|
||||
if (!(await _permissions.GetAsync(actor, cancellationToken).ConfigureAwait(false)).Flags.CanExport)
|
||||
{
|
||||
throw new AccessDeniedException(SecurityErrors.PermissionDenied, "The user cannot export.");
|
||||
}
|
||||
|
||||
var rows = target.CanExport
|
||||
? await target.ExportAsync(new ImportContext(actor, companyCode, new ImportOptions()), cancellationToken).ConfigureAwait(false)
|
||||
: [];
|
||||
await WriteAsync(target, format, rows, output, cancellationToken).ConfigureAwait(false);
|
||||
using (_logger.BeginScope(LogSections.Scope(LogSection.System)))
|
||||
{
|
||||
LogExported(_logger, target.Key, format, companyCode, actor.UserName, rows.Count);
|
||||
}
|
||||
|
||||
return rows.Count;
|
||||
}
|
||||
|
||||
/// <summary>Writes the empty template of an entity: the headers only (for JSON, one object with empty values).</summary>
|
||||
/// <param name="target">The entity.</param>
|
||||
/// <param name="format">The format.</param>
|
||||
/// <param name="output">Where to write.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>A task.</returns>
|
||||
public static Task WriteTemplateAsync(IImportTarget target, TransferFormat format, Stream output, CancellationToken cancellationToken = default) =>
|
||||
WriteAsync(target, format, [], output, cancellationToken);
|
||||
|
||||
/// <summary>The name of an export or template file (<c>clienti-2026-11-12.csv</c>, <c>modello-clienti.xlsx</c>).</summary>
|
||||
/// <param name="targetKey">The entity.</param>
|
||||
/// <param name="format">The format.</param>
|
||||
/// <param name="date">The day of an export, or <see langword="null"/> for a template.</param>
|
||||
/// <returns>The file name.</returns>
|
||||
public static string FileName(string targetKey, TransferFormat format, DateOnly? date)
|
||||
{
|
||||
var extension = format switch
|
||||
{
|
||||
TransferFormat.Xlsx => ".xlsx",
|
||||
TransferFormat.Json => ".json",
|
||||
_ => ".csv",
|
||||
};
|
||||
return date is { } day
|
||||
? targetKey + "-" + day.ToString("yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture) + extension
|
||||
: "modello-" + targetKey + extension;
|
||||
}
|
||||
|
||||
/// <summary>The media type of a format.</summary>
|
||||
/// <param name="format">The format.</param>
|
||||
/// <returns>The media type.</returns>
|
||||
public static string MediaType(TransferFormat format) => format switch
|
||||
{
|
||||
TransferFormat.Xlsx => XlsxWriter.MediaType,
|
||||
TransferFormat.Json => "application/json",
|
||||
_ => "text/csv",
|
||||
};
|
||||
|
||||
private static async Task WriteAsync(IImportTarget target, TransferFormat format, IReadOnlyList<IReadOnlyList<object?>> rows, Stream output, CancellationToken cancellationToken)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(target);
|
||||
ArgumentNullException.ThrowIfNull(output);
|
||||
var headers = target.Fields.Select(f => f.Key).ToList();
|
||||
switch (format)
|
||||
{
|
||||
case TransferFormat.Xlsx:
|
||||
await using (var xlsx = await XlsxWriter.CreateAsync(output, leaveOpen: true, cancellationToken: cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
await xlsx.StartSheetAsync(target.Key, [.. target.Fields.Select(Column)], cancellationToken).ConfigureAwait(false);
|
||||
foreach (var row in rows)
|
||||
{
|
||||
await xlsx.WriteRowAsync(row, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
await xlsx.CompleteAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
break;
|
||||
case TransferFormat.Json:
|
||||
await WriteJsonAsync(target, headers, rows, output, cancellationToken).ConfigureAwait(false);
|
||||
break;
|
||||
default:
|
||||
await using (var csv = new CsvWriter(output, CsvOptions.Italian, leaveOpen: true))
|
||||
{
|
||||
await csv.WriteRowAsync(headers, cancellationToken).ConfigureAwait(false);
|
||||
foreach (var row in rows)
|
||||
{
|
||||
await csv.WriteRowAsync(row, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
await csv.FlushAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
private static XlsxColumn Column(ImportField field) => new(field.Key, field.Kind switch
|
||||
{
|
||||
ImportFieldKind.Text => 28,
|
||||
ImportFieldKind.Number or ImportFieldKind.Date => 14,
|
||||
_ => 16,
|
||||
});
|
||||
|
||||
private static async Task WriteJsonAsync(IImportTarget target, List<string> headers, IReadOnlyList<IReadOnlyList<object?>> rows, Stream output,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
await using var json = new Utf8JsonWriter(output, JsonOptions);
|
||||
var chart = target is ChartOfAccountsImportTarget;
|
||||
if (chart)
|
||||
{
|
||||
json.WriteStartObject();
|
||||
json.WriteString("format", ImportFileReader.ChartFormat);
|
||||
json.WriteNumber("version", 1);
|
||||
json.WritePropertyName("accounts");
|
||||
}
|
||||
|
||||
json.WriteStartArray();
|
||||
IEnumerable<IReadOnlyList<object?>> objects = rows.Count > 0 ? rows : [new object?[headers.Count]];
|
||||
foreach (var row in objects)
|
||||
{
|
||||
json.WriteStartObject();
|
||||
for (var i = 0; i < headers.Count; i++)
|
||||
{
|
||||
var value = i < row.Count ? row[i] : null;
|
||||
switch (value)
|
||||
{
|
||||
case null:
|
||||
json.WriteString(headers[i], string.Empty);
|
||||
break;
|
||||
case decimal number:
|
||||
json.WriteNumber(headers[i], number);
|
||||
break;
|
||||
case bool flag:
|
||||
json.WriteBoolean(headers[i], flag);
|
||||
break;
|
||||
case DateOnly day:
|
||||
json.WriteString(headers[i], day.ToString("yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture));
|
||||
break;
|
||||
default:
|
||||
json.WriteString(headers[i], Convert.ToString(value, System.Globalization.CultureInfo.InvariantCulture));
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
json.WriteEndObject();
|
||||
}
|
||||
|
||||
json.WriteEndArray();
|
||||
if (chart)
|
||||
{
|
||||
foreach (var section in new[] { "statementLines", "journalTemplates", "mappings" })
|
||||
{
|
||||
json.WriteStartArray(section);
|
||||
json.WriteEndArray();
|
||||
}
|
||||
|
||||
json.WriteEndObject();
|
||||
}
|
||||
|
||||
await json.FlushAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
[LoggerMessage(EventId = 7101, Level = LogLevel.Information,
|
||||
Message = "Import {Target} from {File} in {Company} by {User}: {Created} created, {Updated} updated, {Skipped} skipped, {Failed} with errors")]
|
||||
private static partial void LogImported(ILogger logger, string target, string file, string company, string user, int created, int updated, int skipped, int failed);
|
||||
|
||||
[LoggerMessage(EventId = 7102, Level = LogLevel.Information, Message = "Export {Target} as {Format} from {Company} by {User}: {Count} records")]
|
||||
private static partial void LogExported(ILogger logger, string target, TransferFormat format, string company, string user, int count);
|
||||
}
|
||||
@@ -0,0 +1,442 @@
|
||||
using Khaemhat.Application.Security;
|
||||
using Khaemhat.Application.Tables;
|
||||
using Khaemhat.Core.Tables;
|
||||
using Khaemhat.Data;
|
||||
using Khaemhat.Data.Querying;
|
||||
|
||||
namespace Khaemhat.Application.ImportExport;
|
||||
|
||||
/// <summary>
|
||||
/// An entity of the guided import and export (SPEC §12.12): its columns, the check of the rows as if typed in its
|
||||
/// record, the writing through its own service, and the export with the same columns so that a file exported can be
|
||||
/// imported again.
|
||||
/// </summary>
|
||||
public interface IImportTarget
|
||||
{
|
||||
/// <summary>The key in addresses and texts (<c>clienti</c>, <c>piano-dei-conti</c>).</summary>
|
||||
string Key { get; }
|
||||
|
||||
/// <summary>The licence module the entity belongs to.</summary>
|
||||
string ModuleCode { get; }
|
||||
|
||||
/// <summary>The permission to import it (the write permission of its record).</summary>
|
||||
string Permission { get; }
|
||||
|
||||
/// <summary>The permission to export it (besides the <i>can export</i> flag of the user).</summary>
|
||||
string ExportPermission { get; }
|
||||
|
||||
/// <summary>Whether rows can be written now; otherwise the file is only checked (opening stock until M6, chart of accounts until M7).</summary>
|
||||
bool CanApply { get; }
|
||||
|
||||
/// <summary>Whether there are records to export now.</summary>
|
||||
bool CanExport { get; }
|
||||
|
||||
/// <summary>The columns, in the order of templates and exports.</summary>
|
||||
IReadOnlyList<ImportField> Fields { get; }
|
||||
|
||||
/// <summary>Checks the rows without writing.</summary>
|
||||
/// <param name="context">Who, where, how.</param>
|
||||
/// <param name="rows">The rows.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>A result per row, in order.</returns>
|
||||
Task<IReadOnlyList<ImportRowResult>> CheckAsync(ImportContext context, IReadOnlyList<ImportRow> rows, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>Writes the rows without errors, each like a save of its record.</summary>
|
||||
/// <param name="context">Who, where, how.</param>
|
||||
/// <param name="rows">The rows.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>A result per row, in order, with what was done.</returns>
|
||||
Task<IReadOnlyList<ImportRowResult>> ApplyAsync(ImportContext context, IReadOnlyList<ImportRow> rows, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>The records as rows of cells in the order of <see cref="Fields"/>.</summary>
|
||||
/// <param name="context">Who, where.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The rows.</returns>
|
||||
Task<IReadOnlyList<IReadOnlyList<object?>>> ExportAsync(ImportContext context, CancellationToken cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>Reads the cells of a row as values, adding a remark for every cell that is not what its field wants.</summary>
|
||||
/// <param name="row">The row.</param>
|
||||
/// <param name="messages">Where the remarks go.</param>
|
||||
public sealed class CellReader(ImportRow row, List<ImportMessage> messages)
|
||||
{
|
||||
/// <summary>The row.</summary>
|
||||
public ImportRow Row => row;
|
||||
|
||||
/// <summary>The remarks so far.</summary>
|
||||
public List<ImportMessage> Messages => messages;
|
||||
|
||||
/// <summary>Whether the cell has a value.</summary>
|
||||
/// <param name="key">The field.</param>
|
||||
/// <returns><see langword="true"/> when not empty.</returns>
|
||||
public bool Has(string key) => row[key] is not null;
|
||||
|
||||
/// <summary>The text of a cell.</summary>
|
||||
/// <param name="key">The field.</param>
|
||||
/// <returns>The text, or <see langword="null"/>.</returns>
|
||||
public string? Text(string key) => row[key];
|
||||
|
||||
/// <summary>A number.</summary>
|
||||
/// <param name="key">The field.</param>
|
||||
/// <returns>The number, or <see langword="null"/> when empty or wrong (with a remark).</returns>
|
||||
public decimal? Number(string key)
|
||||
{
|
||||
if (row[key] is not { } text)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
if (ImportValues.TryNumber(text, out var value))
|
||||
{
|
||||
return value;
|
||||
}
|
||||
|
||||
messages.Add(new(key, ImportErrors.Number, Value: text));
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>A date.</summary>
|
||||
/// <param name="key">The field.</param>
|
||||
/// <returns>The date, or <see langword="null"/> when empty or wrong (with a remark).</returns>
|
||||
public DateOnly? Date(string key)
|
||||
{
|
||||
if (row[key] is not { } text)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
if (ImportValues.TryDate(text, out var value))
|
||||
{
|
||||
return value;
|
||||
}
|
||||
|
||||
messages.Add(new(key, ImportErrors.Date, Value: text));
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>Yes or no.</summary>
|
||||
/// <param name="key">The field.</param>
|
||||
/// <returns>The value, or <see langword="null"/> when empty or wrong (with a remark).</returns>
|
||||
public bool? Boolean(string key)
|
||||
{
|
||||
if (row[key] is not { } text)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
if (ImportValues.TryBoolean(text, out var value))
|
||||
{
|
||||
return value;
|
||||
}
|
||||
|
||||
messages.Add(new(key, ImportErrors.Boolean, Value: text));
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>One of the words of a field.</summary>
|
||||
/// <param name="field">The field with its choices.</param>
|
||||
/// <returns>The position of the word, or <see langword="null"/> when empty or unknown (with a remark).</returns>
|
||||
public int? Choice(ImportField field)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(field);
|
||||
if (row[field.Key] is not { } text)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var choices = field.Choices ?? [];
|
||||
var index = ImportValues.Choice(text, choices);
|
||||
if (index >= 0)
|
||||
{
|
||||
return index;
|
||||
}
|
||||
|
||||
messages.Add(new(field.Key, ImportErrors.Choice, Value: string.Join(", ", choices)));
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>The id of a code of another archive or table.</summary>
|
||||
/// <param name="key">The field.</param>
|
||||
/// <param name="index">The codes.</param>
|
||||
/// <returns>The id, or <see langword="null"/> when empty or unknown (with a remark).</returns>
|
||||
public long? Code(string key, CodeIndex index)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(index);
|
||||
if (row[key] is not { } code)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
if (index.Find(code) is { } id)
|
||||
{
|
||||
return id;
|
||||
}
|
||||
|
||||
messages.Add(new(key, ImportErrors.CodeUnknown, Value: code));
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The ids of the records of an archive or table by code, ignoring case.</summary>
|
||||
public sealed class CodeIndex
|
||||
{
|
||||
private readonly Dictionary<string, long> _ids = new(StringComparer.OrdinalIgnoreCase);
|
||||
private readonly Dictionary<long, string> _codes = [];
|
||||
|
||||
/// <summary>Creates an index.</summary>
|
||||
/// <param name="entries">The codes with their ids.</param>
|
||||
public CodeIndex(IEnumerable<(string Code, long Id)> entries)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(entries);
|
||||
foreach (var (code, id) in entries)
|
||||
{
|
||||
_ids.TryAdd(code, id);
|
||||
_codes[id] = code;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The number of codes.</summary>
|
||||
public int Count => _ids.Count;
|
||||
|
||||
/// <summary>Loads the codes of a table of the company.</summary>
|
||||
/// <typeparam name="T">The table.</typeparam>
|
||||
/// <param name="uow">The unit of work.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The index.</returns>
|
||||
public static async Task<CodeIndex> LoadAsync<T>(IUnitOfWork uow, CancellationToken cancellationToken)
|
||||
where T : CodedEntity, new()
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(uow);
|
||||
var rows = await uow.Repository<T, long>().ListAsync(Query.For<T>(), cancellationToken).ConfigureAwait(false);
|
||||
return new CodeIndex(rows.Items.Select(r => (r.Code, r.Id)));
|
||||
}
|
||||
|
||||
/// <summary>The id of a code.</summary>
|
||||
/// <param name="code">The code.</param>
|
||||
/// <returns>The id, or <see langword="null"/>.</returns>
|
||||
public long? Find(string? code) => code is not null && _ids.TryGetValue(code.Trim(), out var id) ? id : null;
|
||||
|
||||
/// <summary>The code of an id.</summary>
|
||||
/// <param name="id">The id.</param>
|
||||
/// <returns>The code, or <see langword="null"/>.</returns>
|
||||
public string? CodeOf(long? id) => id is { } key && _codes.TryGetValue(key, out var code) ? code : null;
|
||||
|
||||
/// <summary>Adds a code written meanwhile.</summary>
|
||||
/// <param name="code">The code.</param>
|
||||
/// <param name="id">The id.</param>
|
||||
public void Add(string code, long id)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(code);
|
||||
_ids[code] = id;
|
||||
_codes[id] = code;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The common steps of the entities written as records (parties, items): each row becomes a record, new or read by its
|
||||
/// code, checked by the service of the record and saved by it, so the import obeys the same rules as the screen.
|
||||
/// </summary>
|
||||
/// <typeparam name="TRecord">The record.</typeparam>
|
||||
/// <typeparam name="TState">What is loaded once per check or import (codes of tables and archives).</typeparam>
|
||||
public abstract class RecordImportTarget<TRecord, TState> : IImportTarget
|
||||
where TRecord : class
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public abstract string Key { get; }
|
||||
|
||||
/// <inheritdoc />
|
||||
public abstract string ModuleCode { get; }
|
||||
|
||||
/// <inheritdoc />
|
||||
public abstract string Permission { get; }
|
||||
|
||||
/// <inheritdoc />
|
||||
public abstract string ExportPermission { get; }
|
||||
|
||||
/// <inheritdoc />
|
||||
public bool CanApply => true;
|
||||
|
||||
/// <inheritdoc />
|
||||
public bool CanExport => true;
|
||||
|
||||
/// <inheritdoc />
|
||||
public abstract IReadOnlyList<ImportField> Fields { get; }
|
||||
|
||||
/// <summary>The column with the code of the record.</summary>
|
||||
protected virtual string CodeField => "codice";
|
||||
|
||||
/// <inheritdoc />
|
||||
public Task<IReadOnlyList<ImportRowResult>> CheckAsync(ImportContext context, IReadOnlyList<ImportRow> rows, CancellationToken cancellationToken) =>
|
||||
RunAsync(context, rows, write: false, cancellationToken);
|
||||
|
||||
/// <inheritdoc />
|
||||
public Task<IReadOnlyList<ImportRowResult>> ApplyAsync(ImportContext context, IReadOnlyList<ImportRow> rows, CancellationToken cancellationToken) =>
|
||||
RunAsync(context, rows, write: true, cancellationToken);
|
||||
|
||||
/// <inheritdoc />
|
||||
public abstract Task<IReadOnlyList<IReadOnlyList<object?>>> ExportAsync(ImportContext context, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>Loads what every row needs, checking a permission.</summary>
|
||||
/// <param name="context">Who, where, how.</param>
|
||||
/// <param name="permission">The permission demanded (to import or to export).</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The state.</returns>
|
||||
protected abstract Task<TState> LoadAsync(ImportContext context, string permission, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>The id of an existing record with a code, or <see langword="null"/>; a remark refuses the code (another kind).</summary>
|
||||
/// <param name="state">The state.</param>
|
||||
/// <param name="code">The code.</param>
|
||||
/// <param name="messages">Where remarks go.</param>
|
||||
/// <returns>The id.</returns>
|
||||
protected abstract long? Existing(TState state, string code, List<ImportMessage> messages);
|
||||
|
||||
/// <summary>A new record, or an existing one read by id.</summary>
|
||||
/// <param name="context">Who, where.</param>
|
||||
/// <param name="id">The id, or <see langword="null"/> for a new record.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The record.</returns>
|
||||
protected abstract Task<TRecord?> OpenAsync(ImportContext context, long? id, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>Copies the cells of a row into the record; a code given for a new record is set too.</summary>
|
||||
/// <param name="context">Who, where, how.</param>
|
||||
/// <param name="state">The state.</param>
|
||||
/// <param name="record">The record.</param>
|
||||
/// <param name="cells">The row with its remarks.</param>
|
||||
/// <param name="isNew">Whether the record is new.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>A task.</returns>
|
||||
protected abstract Task FillAsync(ImportContext context, TState state, TRecord record, CellReader cells, bool isNew, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>Checks a record with the rules of its service.</summary>
|
||||
/// <param name="context">Who, where.</param>
|
||||
/// <param name="record">The record.</param>
|
||||
/// <param name="isNew">Whether the record is new (its code is checked against the code rules).</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The problems.</returns>
|
||||
protected abstract Task<IReadOnlyList<TableProblem>> ValidateAsync(ImportContext context, TRecord record, bool isNew, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>Saves a record with its service.</summary>
|
||||
/// <param name="context">Who, where, how.</param>
|
||||
/// <param name="record">The record.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The code and id given by the save.</returns>
|
||||
protected abstract Task<(string Code, long Id)> SaveAsync(ImportContext context, TRecord record, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>What identifies the row in the preview (code, else description).</summary>
|
||||
/// <param name="row">The row.</param>
|
||||
/// <returns>The text.</returns>
|
||||
protected abstract string Label(ImportRow row);
|
||||
|
||||
/// <summary>Records a code saved, so that later rows find it.</summary>
|
||||
/// <param name="state">The state.</param>
|
||||
/// <param name="code">The code.</param>
|
||||
/// <param name="id">The id.</param>
|
||||
protected abstract void Remember(TState state, string code, long id);
|
||||
|
||||
/// <summary>The column of a field of the service (<c>VatNumber</c>, <c>Fiscal.RecipientCode</c>); empty for the row.</summary>
|
||||
/// <param name="serviceField">The field named by the service.</param>
|
||||
/// <returns>The column key.</returns>
|
||||
protected abstract string ColumnOf(string serviceField);
|
||||
|
||||
private async Task<IReadOnlyList<ImportRowResult>> RunAsync(ImportContext context, IReadOnlyList<ImportRow> rows, bool write, CancellationToken cancellationToken)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(context);
|
||||
ArgumentNullException.ThrowIfNull(rows);
|
||||
var state = await LoadAsync(context, Permission, cancellationToken).ConfigureAwait(false);
|
||||
var seen = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
|
||||
var results = new List<ImportRowResult>(rows.Count);
|
||||
foreach (var row in rows)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
var messages = new List<ImportMessage>();
|
||||
var cells = new CellReader(row, messages);
|
||||
var code = row[CodeField];
|
||||
long? id = null;
|
||||
if (code is not null)
|
||||
{
|
||||
if (!seen.Add(code))
|
||||
{
|
||||
messages.Add(new(CodeField, ImportErrors.CodeRepeated, Value: code));
|
||||
results.Add(new(row.Line, Label(row), ImportAction.Skip, messages));
|
||||
continue;
|
||||
}
|
||||
|
||||
id = Existing(state, code, messages);
|
||||
if (messages.Count > 0)
|
||||
{
|
||||
results.Add(new(row.Line, Label(row), ImportAction.Skip, messages));
|
||||
continue;
|
||||
}
|
||||
|
||||
if (id is not null && context.Options.Existing == ExistingCodeAction.Skip)
|
||||
{
|
||||
results.Add(new(row.Line, Label(row), ImportAction.Skip, [new(CodeField, ImportErrors.CodeExists, IsWarning: true, Value: code)]));
|
||||
continue;
|
||||
}
|
||||
}
|
||||
else if (context.Options.Missing == MissingCodeAction.Refuse)
|
||||
{
|
||||
messages.Add(new(CodeField, ImportErrors.CodeMissing));
|
||||
results.Add(new(row.Line, Label(row), ImportAction.Skip, messages));
|
||||
continue;
|
||||
}
|
||||
|
||||
var isNew = id is null;
|
||||
var action = isNew ? ImportAction.Create : ImportAction.Update;
|
||||
var record = await OpenAsync(context, id, cancellationToken).ConfigureAwait(false);
|
||||
if (record is null)
|
||||
{
|
||||
messages.Add(new(CodeField, ImportErrors.WriteFailed, Value: code));
|
||||
results.Add(new(row.Line, Label(row), ImportAction.Skip, messages));
|
||||
continue;
|
||||
}
|
||||
|
||||
await FillAsync(context, state, record, cells, isNew, cancellationToken).ConfigureAwait(false);
|
||||
if (isNew)
|
||||
{
|
||||
messages.AddRange(Fields.Where(f => f.Required && !cells.Has(f.Key) && messages.All(m => m.Field != f.Key))
|
||||
.Select(f => new ImportMessage(f.Key, ImportErrors.Required)));
|
||||
}
|
||||
|
||||
if (messages.All(m => m.IsWarning))
|
||||
{
|
||||
messages.AddRange((await ValidateAsync(context, record, isNew, cancellationToken).ConfigureAwait(false))
|
||||
.Select(p => new ImportMessage(ColumnOf(p.Field), p.Code, p.IsWarning)));
|
||||
}
|
||||
|
||||
if (write && messages.All(m => m.IsWarning))
|
||||
{
|
||||
try
|
||||
{
|
||||
var (savedCode, savedId) = await SaveAsync(context, record, cancellationToken).ConfigureAwait(false);
|
||||
Remember(state, savedCode, savedId);
|
||||
}
|
||||
catch (ValidationFailedException ex)
|
||||
{
|
||||
messages.AddRange(ex.Errors.Select(TableErrors.Split).Select(e => new ImportMessage(ColumnOf(e.Field), e.Code)));
|
||||
}
|
||||
catch (Core.Common.ConcurrencyException)
|
||||
{
|
||||
messages.Add(new(string.Empty, ImportErrors.WriteFailed));
|
||||
}
|
||||
}
|
||||
|
||||
results.Add(new(row.Line, Label(row), messages.Any(m => !m.IsWarning) ? ImportAction.Skip : action, messages));
|
||||
}
|
||||
|
||||
return results;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Splits the <c>Field:code</c> errors of <see cref="ValidationFailedException"/>.</summary>
|
||||
internal static class TableErrors
|
||||
{
|
||||
/// <summary>Splits an error.</summary>
|
||||
/// <param name="error">The error.</param>
|
||||
/// <returns>The field (empty for the record) and the code.</returns>
|
||||
public static (string Field, string Code) Split(string error)
|
||||
{
|
||||
var colon = error.LastIndexOf(':');
|
||||
return colon < 0 ? (string.Empty, error) : (error[..colon], error[(colon + 1)..]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,274 @@
|
||||
using System.Globalization;
|
||||
using System.Text;
|
||||
|
||||
namespace Khaemhat.Application.ImportExport;
|
||||
|
||||
/// <summary>The text codes of the import remarks (<c>import.*</c>), shown by the screen with the field and the value.</summary>
|
||||
public static class ImportErrors
|
||||
{
|
||||
/// <summary>The file is not CSV, XLSX or JSON.</summary>
|
||||
public const string FileFormat = "import.file.format";
|
||||
|
||||
/// <summary>The file has no header or no rows.</summary>
|
||||
public const string FileEmpty = "import.file.empty";
|
||||
|
||||
/// <summary>The file cannot be read (damaged spreadsheet, invalid JSON).</summary>
|
||||
public const string FileUnreadable = "import.file.unreadable";
|
||||
|
||||
/// <summary>The file has more rows than an import takes.</summary>
|
||||
public const string FileTooLarge = "import.file.too-large";
|
||||
|
||||
/// <summary>The entity is unknown or not licensed.</summary>
|
||||
public const string TargetUnknown = "import.target.unknown";
|
||||
|
||||
/// <summary>The entity is only checked for now (opening stock until M6, chart of accounts until M7).</summary>
|
||||
public const string CheckOnly = "import.target.check-only";
|
||||
|
||||
/// <summary>A required column of a new record is empty or not mapped.</summary>
|
||||
public const string Required = "import.value.required";
|
||||
|
||||
/// <summary>Not a number.</summary>
|
||||
public const string Number = "import.value.number";
|
||||
|
||||
/// <summary>Not a date.</summary>
|
||||
public const string Date = "import.value.date";
|
||||
|
||||
/// <summary>Not yes or no.</summary>
|
||||
public const string Boolean = "import.value.boolean";
|
||||
|
||||
/// <summary>Not one of the words accepted (<c>{0}</c> lists them).</summary>
|
||||
public const string Choice = "import.value.choice";
|
||||
|
||||
/// <summary>A code of another archive or table that does not exist (<c>{0}</c>).</summary>
|
||||
public const string CodeUnknown = "import.value.code-unknown";
|
||||
|
||||
/// <summary>The row has no code and the options do not generate it.</summary>
|
||||
public const string CodeMissing = "import.code.missing";
|
||||
|
||||
/// <summary>The same code is on an earlier row of the file.</summary>
|
||||
public const string CodeRepeated = "import.code.repeated";
|
||||
|
||||
/// <summary>The code exists and the options skip existing codes (a remark, not an error).</summary>
|
||||
public const string CodeExists = "import.code.exists";
|
||||
|
||||
/// <summary>The code belongs to a party of another kind (a supplier among the customers).</summary>
|
||||
public const string OtherKind = "import.party.other-kind";
|
||||
|
||||
/// <summary>The city was filled from the postal code (<c>{0}</c>).</summary>
|
||||
public const string CityFilled = "import.filled.city";
|
||||
|
||||
/// <summary>The postal code was filled from the city (<c>{0}</c>).</summary>
|
||||
public const string PostalCodeFilled = "import.filled.postal-code";
|
||||
|
||||
/// <summary>A price row names both a list and a customer, or neither.</summary>
|
||||
public const string PriceTarget = "import.price.target";
|
||||
|
||||
/// <summary>Opening stock of an item that is not stocked goods.</summary>
|
||||
public const string NotStocked = "import.stock.not-stocked";
|
||||
|
||||
/// <summary>The quantity must be more than zero.</summary>
|
||||
public const string Positive = "import.value.positive";
|
||||
|
||||
/// <summary>The record could not be written (someone changed it meanwhile, or an unexpected rule).</summary>
|
||||
public const string WriteFailed = "import.write.failed";
|
||||
|
||||
/// <summary>The level of an account is not 1 to 3, or not the number of parts of its code.</summary>
|
||||
public const string AccountLevel = "import.coa.level";
|
||||
|
||||
/// <summary>The parent of an account is not the code without its last part, or is not in the file (<c>{0}</c>).</summary>
|
||||
public const string AccountParent = "import.coa.parent";
|
||||
|
||||
/// <summary>An account has a nature other than its parent's.</summary>
|
||||
public const string AccountNature = "import.coa.nature";
|
||||
|
||||
/// <summary>An account with sub-accounts is marked as postable.</summary>
|
||||
public const string AccountPostable = "import.coa.postable";
|
||||
|
||||
/// <summary>A leaf account is not marked as postable (a remark).</summary>
|
||||
public const string AccountLeaf = "import.coa.leaf";
|
||||
|
||||
/// <summary>A flag letter is not M, I, P, C or X (<c>{0}</c>).</summary>
|
||||
public const string AccountFlag = "import.coa.flag";
|
||||
}
|
||||
|
||||
/// <summary>The cells of the import as values, and the values of the export as cells.</summary>
|
||||
public static class ImportValues
|
||||
{
|
||||
private static readonly CultureInfo Italian = CultureInfo.GetCultureInfo("it-IT");
|
||||
|
||||
private static readonly string[] DateFormats =
|
||||
["dd/MM/yyyy", "d/M/yyyy", "dd/MM/yy", "d/M/yy", "dd-MM-yyyy", "d-M-yyyy", "dd.MM.yyyy", "yyyy-MM-dd", "yyyy/MM/dd", "yyyyMMdd", "yyyy-MM-ddTHH:mm:ss"];
|
||||
|
||||
private static readonly HashSet<string> Yes = new(StringComparer.Ordinal) { "si", "s", "yes", "y", "x", "1", "true", "vero", "v" };
|
||||
|
||||
private static readonly HashSet<string> No = new(StringComparer.Ordinal) { "no", "n", "0", "false", "falso", "f", "-" };
|
||||
|
||||
private static readonly DateTime Epoch = new(1899, 12, 30, 0, 0, 0, DateTimeKind.Unspecified);
|
||||
|
||||
/// <summary>
|
||||
/// A header or a word as compared by the mapping and the choices: lower case, no accents, every run of other
|
||||
/// characters as one underscore (<c>Partita IVA</c> and <c>partita-iva</c> both give <c>partita_iva</c>).
|
||||
/// </summary>
|
||||
/// <param name="text">The text.</param>
|
||||
/// <returns>The normalized text.</returns>
|
||||
public static string Normalize(string? text)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(text))
|
||||
{
|
||||
return string.Empty;
|
||||
}
|
||||
|
||||
var builder = new StringBuilder(text.Length);
|
||||
var underscore = false;
|
||||
foreach (var c in text.Trim().Normalize(NormalizationForm.FormD))
|
||||
{
|
||||
if (CharUnicodeInfo.GetUnicodeCategory(c) == UnicodeCategory.NonSpacingMark)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
if (char.IsAsciiLetterOrDigit(c))
|
||||
{
|
||||
if (underscore && builder.Length > 0)
|
||||
{
|
||||
builder.Append('_');
|
||||
}
|
||||
|
||||
builder.Append(char.ToLowerInvariant(c));
|
||||
underscore = false;
|
||||
}
|
||||
else
|
||||
{
|
||||
underscore = true;
|
||||
}
|
||||
}
|
||||
|
||||
return builder.ToString();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reads a number written the Italian way (<c>1.234,56</c>, <c>€ 12,5</c>) or the machine way (<c>1234.56</c>):
|
||||
/// with both marks the last one is the decimal one; a single point alone is the decimal mark (as spreadsheets and JSON
|
||||
/// write it), several points alone group thousands; percent signs, currency signs and spaces are ignored.
|
||||
/// </summary>
|
||||
/// <param name="text">The cell.</param>
|
||||
/// <param name="value">The number.</param>
|
||||
/// <returns><see langword="true"/> when the cell is a number.</returns>
|
||||
public static bool TryNumber(string? text, out decimal value)
|
||||
{
|
||||
value = 0;
|
||||
if (string.IsNullOrWhiteSpace(text))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var clean = new StringBuilder(text.Length);
|
||||
foreach (var c in text)
|
||||
{
|
||||
if (char.IsAsciiDigit(c) || c is ',' or '.' or '-' or '+' or 'e' or 'E')
|
||||
{
|
||||
clean.Append(c);
|
||||
}
|
||||
else if (!char.IsWhiteSpace(c) && c is not ('€' or '%' or '\'' or ' ' or ' '))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
var s = clean.ToString();
|
||||
var comma = s.LastIndexOf(',');
|
||||
var point = s.LastIndexOf('.');
|
||||
if (comma >= 0 && point >= 0)
|
||||
{
|
||||
s = comma > point ? s.Replace(".", string.Empty, StringComparison.Ordinal).Replace(',', '.') : s.Replace(",", string.Empty, StringComparison.Ordinal);
|
||||
}
|
||||
else if (comma >= 0)
|
||||
{
|
||||
s = s.Count(c => c == ',') > 1 ? s.Replace(",", string.Empty, StringComparison.Ordinal) : s.Replace(',', '.');
|
||||
}
|
||||
else if (point >= 0 && s.Count(c => c == '.') > 1)
|
||||
{
|
||||
s = s.Replace(".", string.Empty, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
return decimal.TryParse(s, NumberStyles.Float, CultureInfo.InvariantCulture, out value);
|
||||
}
|
||||
|
||||
/// <summary>Reads a date: <c>dd/MM/yyyy</c> and its variants, ISO, or a spreadsheet serial number.</summary>
|
||||
/// <param name="text">The cell.</param>
|
||||
/// <param name="value">The date.</param>
|
||||
/// <returns><see langword="true"/> when the cell is a date.</returns>
|
||||
public static bool TryDate(string? text, out DateOnly value)
|
||||
{
|
||||
value = default;
|
||||
if (string.IsNullOrWhiteSpace(text))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var s = text.Trim();
|
||||
if (s.Length > 10 && s[10] is ' ' or 'T')
|
||||
{
|
||||
s = s[..10];
|
||||
}
|
||||
|
||||
if (DateTime.TryParseExact(s, DateFormats, CultureInfo.InvariantCulture, DateTimeStyles.None, out var day))
|
||||
{
|
||||
value = DateOnly.FromDateTime(day);
|
||||
return true;
|
||||
}
|
||||
|
||||
if (s.All(char.IsAsciiDigit) && s.Length <= 5 && int.TryParse(s, NumberStyles.None, CultureInfo.InvariantCulture, out var serial) && serial > 0)
|
||||
{
|
||||
value = DateOnly.FromDateTime(Epoch.AddDays(serial));
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>Reads yes or no: <c>sì</c>, <c>x</c>, <c>1</c>, <c>VERO</c>, <c>true</c>... and <c>no</c>, <c>0</c>, <c>FALSO</c>...</summary>
|
||||
/// <param name="text">The cell.</param>
|
||||
/// <param name="value">The value.</param>
|
||||
/// <returns><see langword="true"/> when the cell is yes or no.</returns>
|
||||
public static bool TryBoolean(string? text, out bool value)
|
||||
{
|
||||
var word = Normalize(text);
|
||||
value = Yes.Contains(word);
|
||||
return value || No.Contains(word);
|
||||
}
|
||||
|
||||
/// <summary>Finds a word among the choices of a field, ignoring case, accents, spaces and punctuation (<c>P.A.</c> is <c>pa</c>).</summary>
|
||||
/// <param name="text">The cell.</param>
|
||||
/// <param name="choices">The words accepted, in the order of the values they stand for.</param>
|
||||
/// <returns>The position of the word, or -1.</returns>
|
||||
public static int Choice(string? text, IReadOnlyList<string> choices)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(choices);
|
||||
var word = Normalize(text).Replace("_", string.Empty, StringComparison.Ordinal);
|
||||
for (var i = 0; i < choices.Count; i++)
|
||||
{
|
||||
if (Normalize(choices[i]).Replace("_", string.Empty, StringComparison.Ordinal) == word)
|
||||
{
|
||||
return i;
|
||||
}
|
||||
}
|
||||
|
||||
return -1;
|
||||
}
|
||||
|
||||
/// <summary>A number for a text cell of the export, the Italian way without thousands marks (<c>1234,5</c>).</summary>
|
||||
/// <param name="value">The number.</param>
|
||||
/// <returns>The text, or <see langword="null"/>.</returns>
|
||||
public static string? Text(decimal? value) => value?.ToString("0.############", Italian);
|
||||
|
||||
/// <summary>A date for a text cell of the export (<c>dd/MM/yyyy</c>).</summary>
|
||||
/// <param name="value">The date.</param>
|
||||
/// <returns>The text, or <see langword="null"/>.</returns>
|
||||
public static string? Text(DateOnly? value) => value?.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture);
|
||||
|
||||
/// <summary>Yes or no for a text cell of the export.</summary>
|
||||
/// <param name="value">The value.</param>
|
||||
/// <returns><c>sì</c> or <c>no</c>.</returns>
|
||||
public static string Text(bool value) => value ? "sì" : "no";
|
||||
}
|
||||
@@ -0,0 +1,274 @@
|
||||
using Khaemhat.Application.Items;
|
||||
using Khaemhat.Application.Modules;
|
||||
using Khaemhat.Application.Querying;
|
||||
using Khaemhat.Application.Security;
|
||||
using Khaemhat.Application.Tables;
|
||||
using Khaemhat.Core.Items;
|
||||
using Khaemhat.Core.Tables;
|
||||
using Khaemhat.Data;
|
||||
using Khaemhat.Data.Querying;
|
||||
|
||||
namespace Khaemhat.Application.ImportExport;
|
||||
|
||||
/// <summary>
|
||||
/// The items (SPEC §12.12): each row is an item read by its code, or a new one with the values proposed by the record,
|
||||
/// filled with the cells of the row, checked and saved by <see cref="ItemService"/>. Empty cells keep the values of an
|
||||
/// existing item; units, bar codes, prices and suppliers of the record are left as they are.
|
||||
/// </summary>
|
||||
/// <param name="items">The items.</param>
|
||||
/// <param name="codes">The automatic codes.</param>
|
||||
/// <param name="factory">Opens the company databases (codes of the tables).</param>
|
||||
/// <param name="permissions">Checks the permission to import.</param>
|
||||
public sealed class ItemsImportTarget(ItemService items, CodeRuleService codes, IUnitOfWorkFactory factory, PermissionService permissions)
|
||||
: RecordImportTarget<ItemRecord, ItemsImportTarget.State>
|
||||
{
|
||||
/// <summary>The words of <c>tipo</c>, in the order of <see cref="ItemKind"/>.</summary>
|
||||
public static readonly IReadOnlyList<string> KindWords = ["merce", "servizio", "spesa", "descrittivo", "cespite"];
|
||||
|
||||
private static readonly ImportField[] ItemFields =
|
||||
[
|
||||
new("codice", ImportFieldKind.Code, Aliases: ["cod", "codice_articolo", "cod_articolo", "sku", "code"]),
|
||||
new("descrizione", Required: true, Aliases: ["descr", "description", "nome"]),
|
||||
new("descrizione_estesa", Aliases: ["descrizione_lunga", "note_descrizione"]),
|
||||
new("tipo", ImportFieldKind.Choice, Aliases: ["tipologia", "tipo_articolo"], Choices: KindWords),
|
||||
new("categoria", ImportFieldKind.Code, Aliases: ["famiglia", "categoria_merceologica"]),
|
||||
new("um", ImportFieldKind.Code, Aliases: ["unita_misura", "unita_di_misura", "u_m"]),
|
||||
new("iva_vendite", ImportFieldKind.Code, Aliases: ["iva", "aliquota_iva", "codice_iva"]),
|
||||
new("iva_acquisti", ImportFieldKind.Code),
|
||||
new("ean", Aliases: ["barcode", "codice_a_barre", "ean13", "gtin"]),
|
||||
new("nc8", Aliases: ["nomenclatura", "codice_doganale", "taric"]),
|
||||
new("marca", Aliases: ["brand"]),
|
||||
new("produttore", Aliases: ["fabbricante", "manufacturer"]),
|
||||
new("peso_netto", ImportFieldKind.Number),
|
||||
new("peso_lordo", ImportFieldKind.Number, Aliases: ["peso"]),
|
||||
new("a_magazzino", ImportFieldKind.Boolean, Aliases: ["gestito_a_magazzino", "movimenta_magazzino"]),
|
||||
new("magazzino", ImportFieldKind.Code, Aliases: ["deposito"]),
|
||||
new("scorta_minima", ImportFieldKind.Number, Aliases: ["scorta"]),
|
||||
new("punto_riordino", ImportFieldKind.Number),
|
||||
new("lotto_riordino", ImportFieldKind.Number),
|
||||
new("prezzo", ImportFieldKind.Number, Aliases: ["prezzo_vendita", "prezzo_base", "price"]),
|
||||
new("costo_standard", ImportFieldKind.Number, Aliases: ["costo"]),
|
||||
new("conto_ricavo", Aliases: ["conto_ricavi"]),
|
||||
new("conto_costo", Aliases: ["conto_costi"]),
|
||||
new("note", Aliases: ["annotazioni", "notes"]),
|
||||
];
|
||||
|
||||
private static readonly Dictionary<string, string> Columns = new(StringComparer.Ordinal)
|
||||
{
|
||||
["Code"] = "codice",
|
||||
["Description"] = "descrizione",
|
||||
["ExtendedDescription"] = "descrizione_estesa",
|
||||
["Kind"] = "tipo",
|
||||
["CategoryId"] = "categoria",
|
||||
["UnitOfMeasureId"] = "um",
|
||||
["SalesTaxCodeId"] = "iva_vendite",
|
||||
["PurchaseTaxCodeId"] = "iva_acquisti",
|
||||
["Barcode"] = "ean",
|
||||
["CustomsCode"] = "nc8",
|
||||
["Brand"] = "marca",
|
||||
["Manufacturer"] = "produttore",
|
||||
["NetWeight"] = "peso_netto",
|
||||
["GrossWeight"] = "peso_lordo",
|
||||
["Stocked"] = "a_magazzino",
|
||||
["WarehouseId"] = "magazzino",
|
||||
["MinimumStock"] = "scorta_minima",
|
||||
["ReorderPoint"] = "punto_riordino",
|
||||
["ReorderLot"] = "lotto_riordino",
|
||||
["Price"] = "prezzo",
|
||||
["StandardCost"] = "costo_standard",
|
||||
["RevenueAccountCode"] = "conto_ricavo",
|
||||
["CostAccountCode"] = "conto_costo",
|
||||
["Notes"] = "note",
|
||||
};
|
||||
|
||||
/// <inheritdoc />
|
||||
public override string Key => "articoli";
|
||||
|
||||
/// <inheritdoc />
|
||||
public override string ModuleCode => ModuleCodes.Core;
|
||||
|
||||
/// <inheritdoc />
|
||||
public override string Permission => ItemService.WritePermission;
|
||||
|
||||
/// <inheritdoc />
|
||||
public override string ExportPermission => ItemService.ReadPermission;
|
||||
|
||||
/// <inheritdoc />
|
||||
public override IReadOnlyList<ImportField> Fields => ItemFields;
|
||||
|
||||
/// <inheritdoc />
|
||||
public override async Task<IReadOnlyList<IReadOnlyList<object?>>> ExportAsync(ImportContext context, CancellationToken cancellationToken)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(context);
|
||||
var state = await LoadAsync(context, ExportPermission, cancellationToken).ConfigureAwait(false);
|
||||
var rows = new List<IReadOnlyList<object?>>();
|
||||
var offset = 0;
|
||||
while (true)
|
||||
{
|
||||
var page = await items.ListAsync(context.Actor, context.CompanyCode, new ListQuery { Offset = offset, Limit = 500, Sort = [new ListSort("code")] }, cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
foreach (var row in page.Items)
|
||||
{
|
||||
if (await items.GetAsync(context.Actor, context.CompanyCode, row.Id, cancellationToken).ConfigureAwait(false) is { } record)
|
||||
{
|
||||
rows.Add(Cells(state, record.Item));
|
||||
}
|
||||
}
|
||||
|
||||
offset += page.Items.Count;
|
||||
if (page.Items.Count == 0 || offset >= page.Total)
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return rows;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override async Task<State> LoadAsync(ImportContext context, string permission, CancellationToken cancellationToken)
|
||||
{
|
||||
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 all = (await uow.Repository<Item, long>().ListAsync(Query.For<Item>(), cancellationToken).ConfigureAwait(false)).Items;
|
||||
return new State
|
||||
{
|
||||
Items = new CodeIndex(all.Select(i => (i.Code, i.Id))),
|
||||
Categories = await CodeIndex.LoadAsync<ItemCategory>(uow, cancellationToken).ConfigureAwait(false),
|
||||
Units = await CodeIndex.LoadAsync<UnitOfMeasure>(uow, cancellationToken).ConfigureAwait(false),
|
||||
TaxCodes = await CodeIndex.LoadAsync<TaxCode>(uow, cancellationToken).ConfigureAwait(false),
|
||||
Warehouses = await CodeIndex.LoadAsync<Warehouse>(uow, cancellationToken).ConfigureAwait(false),
|
||||
};
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override long? Existing(State state, string code, List<ImportMessage> messages)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(state);
|
||||
return state.Items.Find(code);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override async Task<ItemRecord?> OpenAsync(ImportContext context, long? id, CancellationToken cancellationToken) =>
|
||||
id is { } key
|
||||
? await items.GetAsync(context.Actor, context.CompanyCode, key, cancellationToken).ConfigureAwait(false)
|
||||
: await items.NewAsync(context.Actor, context.CompanyCode, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override Task FillAsync(ImportContext context, State state, ItemRecord record, CellReader cells, bool isNew, CancellationToken cancellationToken)
|
||||
{
|
||||
var item = record.Item;
|
||||
if (isNew && cells.Text("codice") is { } code)
|
||||
{
|
||||
item.Code = code;
|
||||
}
|
||||
|
||||
if (cells.Choice(ItemFields[3]) is { } kind)
|
||||
{
|
||||
item.Kind = (ItemKind)kind;
|
||||
if (isNew && item.Kind != ItemKind.Goods)
|
||||
{
|
||||
item.Stocked = false;
|
||||
}
|
||||
}
|
||||
|
||||
Set(cells, "descrizione", v => item.Description = v);
|
||||
Set(cells, "descrizione_estesa", v => item.ExtendedDescription = v);
|
||||
Set(cells, "ean", v => item.Barcode = v);
|
||||
Set(cells, "nc8", v => item.CustomsCode = v);
|
||||
Set(cells, "marca", v => item.Brand = v);
|
||||
Set(cells, "produttore", v => item.Manufacturer = v);
|
||||
Set(cells, "conto_ricavo", v => item.RevenueAccountCode = v);
|
||||
Set(cells, "conto_costo", v => item.CostAccountCode = v);
|
||||
Set(cells, "note", v => item.Notes = v);
|
||||
item.CategoryId = cells.Code("categoria", state.Categories) ?? item.CategoryId;
|
||||
item.UnitOfMeasureId = cells.Code("um", state.Units) ?? item.UnitOfMeasureId;
|
||||
item.SalesTaxCodeId = cells.Code("iva_vendite", state.TaxCodes) ?? item.SalesTaxCodeId;
|
||||
item.PurchaseTaxCodeId = cells.Code("iva_acquisti", state.TaxCodes) ?? item.PurchaseTaxCodeId;
|
||||
item.WarehouseId = cells.Code("magazzino", state.Warehouses) ?? item.WarehouseId;
|
||||
item.Stocked = cells.Boolean("a_magazzino") ?? item.Stocked;
|
||||
item.NetWeight = cells.Number("peso_netto") ?? item.NetWeight;
|
||||
item.GrossWeight = cells.Number("peso_lordo") ?? item.GrossWeight;
|
||||
item.MinimumStock = cells.Number("scorta_minima") ?? item.MinimumStock;
|
||||
item.ReorderPoint = cells.Number("punto_riordino") ?? item.ReorderPoint;
|
||||
item.ReorderLot = cells.Number("lotto_riordino") ?? item.ReorderLot;
|
||||
item.Price = cells.Number("prezzo") ?? item.Price;
|
||||
item.StandardCost = cells.Number("costo_standard") ?? item.StandardCost;
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override async Task<IReadOnlyList<TableProblem>> ValidateAsync(ImportContext context, ItemRecord record, bool isNew, CancellationToken cancellationToken)
|
||||
{
|
||||
var problems = (await items.ValidateAsync(context.Actor, context.CompanyCode, record, cancellationToken).ConfigureAwait(false)).ToList();
|
||||
if (isNew && record.Item.Code.Length > 0)
|
||||
{
|
||||
var rule = await codes.RuleAsync(context.CompanyCode, ItemService.CodeRule, cancellationToken).ConfigureAwait(false);
|
||||
if (CodeRuleService.CheckManual(rule, record.Item.Code) is { } manual)
|
||||
{
|
||||
problems.Add(new(nameof(Item.Code), manual));
|
||||
}
|
||||
}
|
||||
|
||||
return problems;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override async Task<(string Code, long Id)> SaveAsync(ImportContext context, ItemRecord record, CancellationToken cancellationToken)
|
||||
{
|
||||
var saved = await items.SaveAsync(context.Actor, context.CompanyCode, record, cancellationToken).ConfigureAwait(false);
|
||||
return (saved.Item.Code, saved.Item.Id);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override string Label(ImportRow row)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(row);
|
||||
return row["codice"] ?? row["descrizione"] ?? string.Empty;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void Remember(State state, string code, long id)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(state);
|
||||
state.Items.Add(code, id);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override string ColumnOf(string serviceField) => Columns.GetValueOrDefault(serviceField ?? string.Empty, string.Empty);
|
||||
|
||||
private static void Set(CellReader cells, string key, Action<string> set)
|
||||
{
|
||||
if (cells.Text(key) is { } value)
|
||||
{
|
||||
set(value);
|
||||
}
|
||||
}
|
||||
|
||||
private static object?[] Cells(State state, Item item) =>
|
||||
[
|
||||
item.Code, item.Description, item.ExtendedDescription, KindWords[(int)item.Kind], state.Categories.CodeOf(item.CategoryId), state.Units.CodeOf(item.UnitOfMeasureId),
|
||||
state.TaxCodes.CodeOf(item.SalesTaxCodeId), state.TaxCodes.CodeOf(item.PurchaseTaxCodeId), item.Barcode, item.CustomsCode, item.Brand, item.Manufacturer,
|
||||
item.NetWeight, item.GrossWeight, item.Stocked, state.Warehouses.CodeOf(item.WarehouseId), item.MinimumStock, item.ReorderPoint, item.ReorderLot, item.Price,
|
||||
item.StandardCost, item.RevenueAccountCode, item.CostAccountCode, item.Notes,
|
||||
];
|
||||
|
||||
/// <summary>What a check or an import of items loads once.</summary>
|
||||
public sealed class State
|
||||
{
|
||||
/// <summary>The items.</summary>
|
||||
public required CodeIndex Items { get; init; }
|
||||
|
||||
/// <summary>The categories.</summary>
|
||||
public required CodeIndex Categories { get; init; }
|
||||
|
||||
/// <summary>The units of measure.</summary>
|
||||
public required CodeIndex Units { get; init; }
|
||||
|
||||
/// <summary>The VAT codes.</summary>
|
||||
public required CodeIndex TaxCodes { get; init; }
|
||||
|
||||
/// <summary>The warehouses.</summary>
|
||||
public required CodeIndex Warehouses { get; init; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,429 @@
|
||||
using System.Globalization;
|
||||
using Khaemhat.Application.Parties;
|
||||
using Khaemhat.Application.Querying;
|
||||
using Khaemhat.Application.Tables;
|
||||
using Khaemhat.Application.Modules;
|
||||
using Khaemhat.Application.Security;
|
||||
using Khaemhat.Core.Parties;
|
||||
using Khaemhat.Core.Tables;
|
||||
using Khaemhat.Data;
|
||||
using Khaemhat.Data.Querying;
|
||||
|
||||
namespace Khaemhat.Application.ImportExport;
|
||||
|
||||
/// <summary>
|
||||
/// The customers or the suppliers (SPEC §12.12): each row is a party read by its code, or a new one, filled with the
|
||||
/// cells of the row, checked and saved by <see cref="PartyService"/>, so the import obeys the rules of the record
|
||||
/// (fiscal checks, automatic codes, duplicates). Empty cells keep the values of an existing party.
|
||||
/// </summary>
|
||||
/// <param name="kind">Customers or suppliers.</param>
|
||||
/// <param name="parties">The parties.</param>
|
||||
/// <param name="codes">The automatic codes.</param>
|
||||
/// <param name="autoFill">The places by postal code.</param>
|
||||
/// <param name="factory">Opens the company databases (codes of the tables).</param>
|
||||
/// <param name="permissions">Checks the permission to import.</param>
|
||||
public sealed class PartiesImportTarget(
|
||||
PartyKind kind, PartyService parties, CodeRuleService codes, AutoFillService autoFill, IUnitOfWorkFactory factory, PermissionService permissions)
|
||||
: RecordImportTarget<PartyRecord, PartiesImportTarget.State>
|
||||
{
|
||||
/// <summary>The words of <c>tipo_soggetto</c>, in the order of <see cref="SubjectType"/>.</summary>
|
||||
public static readonly IReadOnlyList<string> SubjectWords = ["impresa", "privato", "pa", "ue", "extra-ue", "forfettario"];
|
||||
|
||||
private static readonly ImportField[] Common =
|
||||
[
|
||||
new("codice", ImportFieldKind.Code, Aliases: ["cod", "codice_cliente", "codice_fornitore", "code"]),
|
||||
new("ragione_sociale", Aliases: ["denominazione", "nome_ditta", "ragione", "rag_sociale", "name"]),
|
||||
new("nome", Aliases: ["first_name"]),
|
||||
new("cognome", Aliases: ["last_name"]),
|
||||
new("tipo_soggetto", ImportFieldKind.Choice, Aliases: ["tipo", "soggetto"], Choices: SubjectWords),
|
||||
new("partita_iva", Aliases: ["p_iva", "piva", "partitaiva", "vat", "vat_number"]),
|
||||
new("codice_fiscale", Aliases: ["cf", "c_f", "cod_fiscale", "codicefiscale"]),
|
||||
new("rea", Aliases: ["numero_rea"]),
|
||||
new("indirizzo", Aliases: ["via", "address"]),
|
||||
new("civico", Aliases: ["numero_civico", "n_civico"]),
|
||||
new("cap", Aliases: ["c_a_p", "codice_postale", "postal_code"]),
|
||||
new("comune", Aliases: ["citta", "localita", "city"]),
|
||||
new("provincia", Aliases: ["prov", "pr", "sigla_provincia"]),
|
||||
new("nazione", Aliases: ["paese", "stato", "country", "codice_nazione"]),
|
||||
new("telefono", Aliases: ["tel", "phone"]),
|
||||
new("email", Aliases: ["e_mail", "mail"]),
|
||||
new("pec", Aliases: ["email_pec", "posta_certificata"]),
|
||||
new("sito", Aliases: ["sito_web", "web", "website"]),
|
||||
new("codice_destinatario", Aliases: ["codice_sdi", "sdi", "codice_univoco"]),
|
||||
new("categoria", ImportFieldKind.Code),
|
||||
];
|
||||
|
||||
private static readonly ImportField[] CustomerFields =
|
||||
[
|
||||
.. Common,
|
||||
new("agente", ImportFieldKind.Code, Aliases: ["venditore"]),
|
||||
new("pagamento", ImportFieldKind.Code, Aliases: ["condizioni_pagamento", "cod_pagamento"]),
|
||||
new("listino", ImportFieldKind.Code),
|
||||
new("sconto1", ImportFieldKind.Number, Aliases: ["sconto", "sconto_1"]),
|
||||
new("sconto2", ImportFieldKind.Number, Aliases: ["sconto_2"]),
|
||||
new("fido", ImportFieldKind.Number, Aliases: ["limite_fido", "fido_massimo"]),
|
||||
new("iban", Aliases: ["codice_iban"]),
|
||||
new("note", Aliases: ["annotazioni", "notes"]),
|
||||
];
|
||||
|
||||
private static readonly ImportField[] SupplierFields =
|
||||
[
|
||||
.. Common,
|
||||
new("pagamento", ImportFieldKind.Code, Aliases: ["condizioni_pagamento", "cod_pagamento"]),
|
||||
new("iban", Aliases: ["codice_iban"]),
|
||||
new("note", Aliases: ["annotazioni", "notes"]),
|
||||
];
|
||||
|
||||
private static readonly Dictionary<string, string> Columns = new(StringComparer.Ordinal)
|
||||
{
|
||||
["Code"] = "codice",
|
||||
["Name"] = "ragione_sociale",
|
||||
["FirstName"] = "nome",
|
||||
["LastName"] = "cognome",
|
||||
["SubjectType"] = "tipo_soggetto",
|
||||
["VatNumber"] = "partita_iva",
|
||||
["TaxCode"] = "codice_fiscale",
|
||||
["Rea"] = "rea",
|
||||
["Address"] = "indirizzo",
|
||||
["StreetNumber"] = "civico",
|
||||
["PostalCode"] = "cap",
|
||||
["City"] = "comune",
|
||||
["Province"] = "provincia",
|
||||
["CountryCode"] = "nazione",
|
||||
["Phone"] = "telefono",
|
||||
["Email"] = "email",
|
||||
["Pec"] = "pec",
|
||||
["Website"] = "sito",
|
||||
["CategoryId"] = "categoria",
|
||||
["SalespersonId"] = "agente",
|
||||
["Notes"] = "note",
|
||||
["Fiscal.RecipientCode"] = "codice_destinatario",
|
||||
["Sales.PaymentTermId"] = "pagamento",
|
||||
["Purchase.PaymentTermId"] = "pagamento",
|
||||
["Sales.PriceListId"] = "listino",
|
||||
["Sales.Discount1"] = "sconto1",
|
||||
["Sales.Discount2"] = "sconto2",
|
||||
["Sales.CreditLimit"] = "fido",
|
||||
};
|
||||
|
||||
/// <inheritdoc />
|
||||
public override string Key => kind == PartyKind.Supplier ? "fornitori" : "clienti";
|
||||
|
||||
/// <inheritdoc />
|
||||
public override string ModuleCode => ModuleCodes.Core;
|
||||
|
||||
/// <inheritdoc />
|
||||
public override string Permission => PartyService.WritePermission;
|
||||
|
||||
/// <inheritdoc />
|
||||
public override string ExportPermission => "parties.party.export";
|
||||
|
||||
/// <inheritdoc />
|
||||
public override IReadOnlyList<ImportField> Fields => kind == PartyKind.Supplier ? SupplierFields : CustomerFields;
|
||||
|
||||
private bool IsCustomer => kind != PartyKind.Supplier;
|
||||
|
||||
/// <inheritdoc />
|
||||
public override async Task<IReadOnlyList<IReadOnlyList<object?>>> ExportAsync(ImportContext context, CancellationToken cancellationToken)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(context);
|
||||
var state = await LoadAsync(context, ExportPermission, cancellationToken).ConfigureAwait(false);
|
||||
var archive = IsCustomer ? PartyArchive.Customers : PartyArchive.Suppliers;
|
||||
var rows = new List<IReadOnlyList<object?>>();
|
||||
var offset = 0;
|
||||
while (true)
|
||||
{
|
||||
var page = await parties.ListAsync(context.Actor, context.CompanyCode, archive, new ListQuery { Offset = offset, Limit = 500, Sort = [new ListSort("code")] },
|
||||
cancellationToken).ConfigureAwait(false);
|
||||
foreach (var row in page.Items.Where(r => r.Kind == kind))
|
||||
{
|
||||
if (await parties.GetAsync(context.Actor, context.CompanyCode, row.Id, cancellationToken).ConfigureAwait(false) is { } record)
|
||||
{
|
||||
rows.Add(Cells(state, record));
|
||||
}
|
||||
}
|
||||
|
||||
offset += page.Items.Count;
|
||||
if (page.Items.Count == 0 || offset >= page.Total)
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return rows;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override async Task<State> LoadAsync(ImportContext context, string permission, CancellationToken cancellationToken)
|
||||
{
|
||||
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 all = (await uow.Repository<Party, long>().ListAsync(Query.For<Party>(), cancellationToken).ConfigureAwait(false)).Items;
|
||||
return new State
|
||||
{
|
||||
Kinds = all.GroupBy(p => p.Code, StringComparer.OrdinalIgnoreCase).ToDictionary(g => g.Key, g => (g.First().Id, g.First().Kind), StringComparer.OrdinalIgnoreCase),
|
||||
Categories = await CodeIndex.LoadAsync<PartyCategory>(uow, cancellationToken).ConfigureAwait(false),
|
||||
Salespeople = await CodeIndex.LoadAsync<Salesperson>(uow, cancellationToken).ConfigureAwait(false),
|
||||
PaymentTerms = await CodeIndex.LoadAsync<PaymentTerm>(uow, cancellationToken).ConfigureAwait(false),
|
||||
PriceLists = await CodeIndex.LoadAsync<PriceList>(uow, cancellationToken).ConfigureAwait(false),
|
||||
};
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override long? Existing(State state, string code, List<ImportMessage> messages)
|
||||
{
|
||||
if (!state.Kinds.TryGetValue(code, out var found))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
if (found.Kind != kind)
|
||||
{
|
||||
messages.Add(new("codice", ImportErrors.OtherKind, Value: code));
|
||||
return null;
|
||||
}
|
||||
|
||||
return found.Id;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override Task<PartyRecord?> OpenAsync(ImportContext context, long? id, CancellationToken cancellationToken) =>
|
||||
id is { } key
|
||||
? parties.GetAsync(context.Actor, context.CompanyCode, key, cancellationToken)
|
||||
: NewAsync(context, cancellationToken);
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override async Task FillAsync(ImportContext context, State state, PartyRecord record, CellReader cells, bool isNew, CancellationToken cancellationToken)
|
||||
{
|
||||
var party = record.Party;
|
||||
if (isNew && cells.Text("codice") is { } code)
|
||||
{
|
||||
party.Code = code;
|
||||
}
|
||||
|
||||
if (cells.Choice(Fields.First(f => f.Key == "tipo_soggetto")) is { } subject)
|
||||
{
|
||||
party.SubjectType = (SubjectType)subject;
|
||||
}
|
||||
else if (isNew && !cells.Has("tipo_soggetto") && !cells.Has("ragione_sociale") && cells.Has("cognome"))
|
||||
{
|
||||
party.SubjectType = SubjectType.Person;
|
||||
}
|
||||
|
||||
Set(cells, "ragione_sociale", v => party.Name = v);
|
||||
Set(cells, "nome", v => party.FirstName = v);
|
||||
Set(cells, "cognome", v => party.LastName = v);
|
||||
if (party.SubjectType == SubjectType.Person && !cells.Has("ragione_sociale") && (cells.Has("nome") || cells.Has("cognome")))
|
||||
{
|
||||
party.Name = string.Empty;
|
||||
}
|
||||
|
||||
Set(cells, "partita_iva", v => party.VatNumber = v);
|
||||
Set(cells, "codice_fiscale", v => party.TaxCode = v.ToUpperInvariant());
|
||||
Set(cells, "rea", v => party.Rea = v);
|
||||
Set(cells, "indirizzo", v => party.Address = v);
|
||||
Set(cells, "civico", v => party.StreetNumber = v);
|
||||
Set(cells, "cap", v => party.PostalCode = v);
|
||||
Set(cells, "comune", v => party.City = v);
|
||||
Set(cells, "provincia", v => party.Province = v.ToUpperInvariant());
|
||||
Set(cells, "nazione", v => party.CountryCode = v.ToUpperInvariant());
|
||||
Set(cells, "telefono", v => party.Phone = v);
|
||||
Set(cells, "email", v => party.Email = v);
|
||||
Set(cells, "pec", v => party.Pec = v);
|
||||
Set(cells, "sito", v => party.Website = v);
|
||||
Set(cells, "codice_destinatario", v => record.Fiscal.RecipientCode = v.ToUpperInvariant());
|
||||
Set(cells, "note", v => party.Notes = v);
|
||||
if (cells.Code("categoria", state.Categories) is { } category)
|
||||
{
|
||||
party.CategoryId = category;
|
||||
}
|
||||
|
||||
if (cells.Code("pagamento", state.PaymentTerms) is { } payment)
|
||||
{
|
||||
if (IsCustomer)
|
||||
{
|
||||
record.Sales.PaymentTermId = payment;
|
||||
}
|
||||
else
|
||||
{
|
||||
record.Purchase.PaymentTermId = payment;
|
||||
}
|
||||
}
|
||||
|
||||
if (IsCustomer)
|
||||
{
|
||||
if (cells.Code("agente", state.Salespeople) is { } salesperson)
|
||||
{
|
||||
party.SalespersonId = salesperson;
|
||||
}
|
||||
|
||||
if (cells.Code("listino", state.PriceLists) is { } list)
|
||||
{
|
||||
record.Sales.PriceListId = list;
|
||||
}
|
||||
|
||||
record.Sales.Discount1 = cells.Number("sconto1") ?? record.Sales.Discount1;
|
||||
record.Sales.Discount2 = cells.Number("sconto2") ?? record.Sales.Discount2;
|
||||
record.Sales.CreditLimit = cells.Number("fido") ?? record.Sales.CreditLimit;
|
||||
}
|
||||
|
||||
if (cells.Text("iban") is { } text)
|
||||
{
|
||||
var iban = string.Concat(text.Where(c => !char.IsWhiteSpace(c))).ToUpperInvariant();
|
||||
if (!record.BankAccounts.Any(b => string.Equals(b.Iban, iban, StringComparison.OrdinalIgnoreCase)))
|
||||
{
|
||||
record.BankAccounts.Add(new PartyBankAccount { Iban = iban, IsDefault = !record.BankAccounts.Any(b => b.IsDefault) });
|
||||
}
|
||||
}
|
||||
|
||||
if (context.Options.FillFromPostalCode && (cells.Has("cap") || cells.Has("comune")))
|
||||
{
|
||||
await FillPlaceAsync(context, state, party, cells, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override async Task<IReadOnlyList<TableProblem>> ValidateAsync(ImportContext context, PartyRecord record, bool isNew, CancellationToken cancellationToken)
|
||||
{
|
||||
var problems = (await parties.ValidateAsync(context.Actor, context.CompanyCode, record, cancellationToken).ConfigureAwait(false)).ToList();
|
||||
if (isNew && record.Party.Code.Length > 0 && CodeRuleService.CheckManual(await RuleAsync(context, cancellationToken).ConfigureAwait(false), record.Party.Code) is { } manual)
|
||||
{
|
||||
problems.Add(new(nameof(Party.Code), manual));
|
||||
}
|
||||
|
||||
return problems;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override async Task<(string Code, long Id)> SaveAsync(ImportContext context, PartyRecord record, CancellationToken cancellationToken)
|
||||
{
|
||||
var saved = await parties.SaveAsync(context.Actor, context.CompanyCode, record, context.Options.VerifyVat, cancellationToken).ConfigureAwait(false);
|
||||
return (saved.Party.Code, saved.Party.Id);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override string Label(ImportRow row)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(row);
|
||||
return row["codice"] ?? row["ragione_sociale"] ?? string.Join(' ', new[] { row["cognome"], row["nome"] }.Where(n => n is not null));
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void Remember(State state, string code, long id)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(state);
|
||||
state.Kinds[code] = (id, kind);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override string ColumnOf(string serviceField)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(serviceField);
|
||||
if (Columns.TryGetValue(serviceField, out var column))
|
||||
{
|
||||
return column;
|
||||
}
|
||||
|
||||
return serviceField.StartsWith("BankAccounts.", StringComparison.Ordinal) ? "iban" : string.Empty;
|
||||
}
|
||||
|
||||
private static void Set(CellReader cells, string key, Action<string> set)
|
||||
{
|
||||
if (cells.Text(key) is { } value)
|
||||
{
|
||||
set(value);
|
||||
}
|
||||
}
|
||||
|
||||
private object?[] Cells(State state, PartyRecord record)
|
||||
{
|
||||
var p = record.Party;
|
||||
var common = new object?[]
|
||||
{
|
||||
p.Code, p.SubjectType == SubjectType.Person ? null : p.Name, p.FirstName, p.LastName, SubjectWords[(int)p.SubjectType], p.VatNumber, p.TaxCode, p.Rea,
|
||||
p.Address, p.StreetNumber, p.PostalCode, p.City, p.Province, p.CountryCode, p.Phone, p.Email, p.Pec, p.Website, record.Fiscal.RecipientCode,
|
||||
state.Categories.CodeOf(p.CategoryId),
|
||||
};
|
||||
var iban = record.BankAccounts.OrderByDescending(b => b.IsDefault).FirstOrDefault()?.Iban;
|
||||
return IsCustomer
|
||||
?
|
||||
[
|
||||
.. common, state.Salespeople.CodeOf(p.SalespersonId), state.PaymentTerms.CodeOf(record.Sales.PaymentTermId), state.PriceLists.CodeOf(record.Sales.PriceListId),
|
||||
record.Sales.Discount1, record.Sales.Discount2, record.Sales.CreditLimit, iban, p.Notes,
|
||||
]
|
||||
: [.. common, state.PaymentTerms.CodeOf(record.Purchase.PaymentTermId), iban, p.Notes];
|
||||
}
|
||||
|
||||
private async Task<PartyRecord?> NewAsync(ImportContext context, CancellationToken cancellationToken) =>
|
||||
await parties.NewAsync(context.Actor, context.CompanyCode, kind, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
private async Task<CodeRule> RuleAsync(ImportContext context, CancellationToken cancellationToken) =>
|
||||
await codes.RuleAsync(context.CompanyCode, PartyService.CodeRuleOf(kind), cancellationToken).ConfigureAwait(false);
|
||||
|
||||
// City from the postal code and postal code from the city, only for Italian addresses and only when one place fits.
|
||||
private async Task FillPlaceAsync(ImportContext context, State state, Party party, CellReader cells, CancellationToken cancellationToken)
|
||||
{
|
||||
if (!string.Equals(party.CountryCode, "IT", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (party.PostalCode is { } cap && string.IsNullOrWhiteSpace(party.City))
|
||||
{
|
||||
if (!state.ByPostalCode.TryGetValue(cap, out var places))
|
||||
{
|
||||
places = await autoFill.PlacesByPostalCodeAsync(context.Actor, context.CompanyCode, cap, cancellationToken).ConfigureAwait(false);
|
||||
state.ByPostalCode[cap] = places;
|
||||
}
|
||||
|
||||
if (places.Count == 1)
|
||||
{
|
||||
party.City = places[0].Name;
|
||||
party.Province ??= places[0].ProvinceCode;
|
||||
cells.Messages.Add(new("comune", ImportErrors.CityFilled, IsWarning: true, Value: places[0].Name));
|
||||
}
|
||||
}
|
||||
else if (party.City is { } city && string.IsNullOrWhiteSpace(party.PostalCode))
|
||||
{
|
||||
var key = city.ToUpper(CultureInfo.InvariantCulture);
|
||||
if (!state.ByName.TryGetValue(key, out var places))
|
||||
{
|
||||
places = await autoFill.PlacesByNameAsync(context.Actor, context.CompanyCode, city, cancellationToken).ConfigureAwait(false);
|
||||
state.ByName[key] = places;
|
||||
}
|
||||
|
||||
var exact = places.Where(p => string.Equals(p.Name, city, StringComparison.OrdinalIgnoreCase)).ToList();
|
||||
if (exact.Count == 1 && exact[0].PostalCode is { } postalCode)
|
||||
{
|
||||
party.PostalCode = postalCode;
|
||||
party.Province ??= exact[0].ProvinceCode;
|
||||
cells.Messages.Add(new("cap", ImportErrors.PostalCodeFilled, IsWarning: true, Value: postalCode));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>What a check or an import of parties loads once.</summary>
|
||||
public sealed class State
|
||||
{
|
||||
/// <summary>The id and kind of every party by code.</summary>
|
||||
public required Dictionary<string, (long Id, PartyKind Kind)> Kinds { get; init; }
|
||||
|
||||
/// <summary>The categories.</summary>
|
||||
public required CodeIndex Categories { get; init; }
|
||||
|
||||
/// <summary>The salespeople.</summary>
|
||||
public required CodeIndex Salespeople { get; init; }
|
||||
|
||||
/// <summary>The payment terms.</summary>
|
||||
public required CodeIndex PaymentTerms { get; init; }
|
||||
|
||||
/// <summary>The price lists.</summary>
|
||||
public required CodeIndex PriceLists { get; init; }
|
||||
|
||||
/// <summary>Places found by postal code.</summary>
|
||||
public Dictionary<string, IReadOnlyList<PlaceSuggestion>> ByPostalCode { get; } = new(StringComparer.Ordinal);
|
||||
|
||||
/// <summary>Places found by name.</summary>
|
||||
public Dictionary<string, IReadOnlyList<PlaceSuggestion>> ByName { get; } = new(StringComparer.Ordinal);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,187 @@
|
||||
using Khaemhat.Application.Items;
|
||||
using Khaemhat.Application.Modules;
|
||||
using Khaemhat.Application.Security;
|
||||
using Khaemhat.Application.Tables;
|
||||
using Khaemhat.Core.Items;
|
||||
using Khaemhat.Core.Parties;
|
||||
using Khaemhat.Core.Tables;
|
||||
using Khaemhat.Data;
|
||||
using Khaemhat.Data.Querying;
|
||||
|
||||
namespace Khaemhat.Application.ImportExport;
|
||||
|
||||
/// <summary>
|
||||
/// The prices of the lists and the net prices of the customers (SPEC §12.12): each row is the price of an item in a list
|
||||
/// or for a customer, valid from a day; the same item, list or customer and day replaces the price, another day adds a
|
||||
/// dated price as the price grid does. All rows are written by <see cref="PriceListService"/> in one transaction.
|
||||
/// </summary>
|
||||
/// <param name="prices">The price lists.</param>
|
||||
/// <param name="factory">Opens the company databases.</param>
|
||||
/// <param name="permissions">Checks the permission.</param>
|
||||
public sealed class PricesImportTarget(PriceListService prices, IUnitOfWorkFactory factory, PermissionService permissions) : IImportTarget
|
||||
{
|
||||
private static readonly ImportField[] PriceFields =
|
||||
[
|
||||
new("articolo", ImportFieldKind.Code, Required: true, Aliases: ["codice_articolo", "codice", "cod_articolo", "sku"]),
|
||||
new("listino", ImportFieldKind.Code, Aliases: ["codice_listino", "cod_listino"]),
|
||||
new("cliente", ImportFieldKind.Code, Aliases: ["codice_cliente", "cod_cliente"]),
|
||||
new("prezzo", ImportFieldKind.Number, Required: true, Aliases: ["prezzo_netto", "price"]),
|
||||
new("valido_dal", ImportFieldKind.Date, Aliases: ["validita", "data_inizio", "dal", "decorrenza"]),
|
||||
];
|
||||
|
||||
/// <inheritdoc />
|
||||
public string Key => "listini";
|
||||
|
||||
/// <inheritdoc />
|
||||
public string ModuleCode => ModuleCodes.Core;
|
||||
|
||||
/// <inheritdoc />
|
||||
public string Permission => ItemService.WritePermission;
|
||||
|
||||
/// <inheritdoc />
|
||||
public string ExportPermission => ItemService.ReadPermission;
|
||||
|
||||
/// <inheritdoc />
|
||||
public bool CanApply => true;
|
||||
|
||||
/// <inheritdoc />
|
||||
public bool CanExport => true;
|
||||
|
||||
/// <inheritdoc />
|
||||
public IReadOnlyList<ImportField> Fields => PriceFields;
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<IReadOnlyList<ImportRowResult>> CheckAsync(ImportContext context, IReadOnlyList<ImportRow> rows, CancellationToken cancellationToken) =>
|
||||
(await PlanAsync(context, rows, cancellationToken).ConfigureAwait(false)).Results;
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<IReadOnlyList<ImportRowResult>> ApplyAsync(ImportContext context, IReadOnlyList<ImportRow> rows, CancellationToken cancellationToken)
|
||||
{
|
||||
var plan = await PlanAsync(context, rows, cancellationToken).ConfigureAwait(false);
|
||||
if (plan.Edits.Count == 0)
|
||||
{
|
||||
return plan.Results;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
await prices.SaveAsync(context.Actor, context.CompanyCode, [.. plan.Edits.Select(e => e.Edit)], cancellationToken).ConfigureAwait(false);
|
||||
return plan.Results;
|
||||
}
|
||||
catch (ValidationFailedException ex)
|
||||
{
|
||||
// The rows were checked already: an error here is a change made meanwhile; it goes on its row and nothing is written.
|
||||
var results = plan.Results.ToList();
|
||||
foreach (var (index, code) in ex.Errors.Select(TableErrors.Split))
|
||||
{
|
||||
var position = int.TryParse(index, out var i) && i >= 0 && i < plan.Edits.Count ? plan.Edits[i].Result : -1;
|
||||
if (position >= 0)
|
||||
{
|
||||
var row = results[position];
|
||||
results[position] = row with { Action = ImportAction.Skip, Messages = [.. row.Messages, new ImportMessage("prezzo", code)] };
|
||||
}
|
||||
}
|
||||
|
||||
return [.. results.Select(r => r.Outcome == ImportOutcome.Error ? r : r with { Action = ImportAction.Skip, Messages = [.. r.Messages, new ImportMessage(string.Empty, ImportErrors.WriteFailed)] })];
|
||||
}
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<IReadOnlyList<IReadOnlyList<object?>>> ExportAsync(ImportContext context, CancellationToken cancellationToken)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(context);
|
||||
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 items = new CodeIndex((await uow.Repository<Item, long>().ListAsync(Query.For<Item>(), cancellationToken).ConfigureAwait(false)).Items.Select(i => (i.Code, i.Id)));
|
||||
var parties = new CodeIndex((await uow.Repository<Party, long>().ListAsync(Query.For<Party>(), cancellationToken).ConfigureAwait(false)).Items.Select(p => (p.Code, p.Id)));
|
||||
var lists = await CodeIndex.LoadAsync<PriceList>(uow, cancellationToken).ConfigureAwait(false);
|
||||
var rows = (await uow.Repository<ItemPrice, long>().ListAsync(Query.For<ItemPrice>(), cancellationToken).ConfigureAwait(false)).Items;
|
||||
return
|
||||
[
|
||||
.. rows.Select(p => (IReadOnlyList<object?>)[items.CodeOf(p.ItemId), lists.CodeOf(p.PriceListId), parties.CodeOf(p.PartyId), p.Price, p.ValidFrom])
|
||||
.OrderBy(r => (string?)r[0], StringComparer.OrdinalIgnoreCase)
|
||||
.ThenBy(r => (string?)r[1] ?? "~" + (string?)r[2], StringComparer.OrdinalIgnoreCase)
|
||||
.ThenBy(r => (DateOnly?)r[4]),
|
||||
];
|
||||
}
|
||||
|
||||
private async Task<Plan> PlanAsync(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 = new CodeIndex((await uow.Repository<Item, long>().ListAsync(Query.For<Item>(), cancellationToken).ConfigureAwait(false)).Items.Select(i => (i.Code, i.Id)));
|
||||
var allParties = (await uow.Repository<Party, long>().ListAsync(Query.For<Party>(), cancellationToken).ConfigureAwait(false)).Items;
|
||||
var customers = new CodeIndex(allParties.Where(p => p.IsCustomer).Select(p => (p.Code, p.Id)));
|
||||
var others = new HashSet<string>(allParties.Where(p => !p.IsCustomer).Select(p => p.Code), StringComparer.OrdinalIgnoreCase);
|
||||
var lists = await CodeIndex.LoadAsync<PriceList>(uow, cancellationToken).ConfigureAwait(false);
|
||||
var existing = (await uow.Repository<ItemPrice, long>().ListAsync(Query.For<ItemPrice>(), cancellationToken).ConfigureAwait(false)).Items
|
||||
.Select(p => (p.ItemId, p.PriceListId, p.PartyId, p.ValidFrom)).ToHashSet();
|
||||
|
||||
var seen = new HashSet<(long, long?, long?, DateOnly?)>();
|
||||
var results = new List<ImportRowResult>(rows.Count);
|
||||
var edits = new List<(PriceEdit Edit, int Result)>();
|
||||
foreach (var row in rows)
|
||||
{
|
||||
var messages = new List<ImportMessage>();
|
||||
var cells = new CellReader(row, messages);
|
||||
var item = cells.Code("articolo", items);
|
||||
long? list = null;
|
||||
long? party = null;
|
||||
if (cells.Has("listino") == cells.Has("cliente"))
|
||||
{
|
||||
messages.Add(new(cells.Has("listino") ? "cliente" : "listino", ImportErrors.PriceTarget));
|
||||
}
|
||||
else if (cells.Has("listino"))
|
||||
{
|
||||
list = cells.Code("listino", lists);
|
||||
}
|
||||
else if (row["cliente"] is { } customer && others.Contains(customer))
|
||||
{
|
||||
messages.Add(new("cliente", ImportErrors.OtherKind, Value: customer));
|
||||
}
|
||||
else
|
||||
{
|
||||
party = cells.Code("cliente", customers);
|
||||
}
|
||||
|
||||
var price = cells.Number("prezzo");
|
||||
if (price < 0)
|
||||
{
|
||||
messages.Add(new("prezzo", ItemService.NotNegative));
|
||||
}
|
||||
|
||||
var from = cells.Date("valido_dal");
|
||||
messages.AddRange(PriceFields.Where(f => f.Required && !cells.Has(f.Key)).Select(f => new ImportMessage(f.Key, ImportErrors.Required)));
|
||||
var label = row["articolo"] ?? string.Empty;
|
||||
if (messages.Any(m => !m.IsWarning) || item is not { } itemId || price is not { } value)
|
||||
{
|
||||
results.Add(new(row.Line, label, ImportAction.Skip, messages));
|
||||
continue;
|
||||
}
|
||||
|
||||
var key = (itemId, list, party, from);
|
||||
if (!seen.Add(key))
|
||||
{
|
||||
messages.Add(new("articolo", ImportErrors.CodeRepeated, Value: label));
|
||||
results.Add(new(row.Line, label, ImportAction.Skip, messages));
|
||||
continue;
|
||||
}
|
||||
|
||||
var update = existing.Contains(key);
|
||||
if (update && context.Options.Existing == ExistingCodeAction.Skip)
|
||||
{
|
||||
results.Add(new(row.Line, label, ImportAction.Skip, [new("articolo", ImportErrors.CodeExists, IsWarning: true, Value: label)]));
|
||||
continue;
|
||||
}
|
||||
|
||||
edits.Add((new PriceEdit(itemId, list, party, value, from), results.Count));
|
||||
results.Add(new(row.Line, label, update ? ImportAction.Update : ImportAction.Create, messages));
|
||||
}
|
||||
|
||||
return new Plan(results, edits);
|
||||
}
|
||||
|
||||
private sealed record Plan(IReadOnlyList<ImportRowResult> Results, IReadOnlyList<(PriceEdit Edit, int Result)> Edits);
|
||||
}
|
||||
@@ -0,0 +1,885 @@
|
||||
using System.Data.Common;
|
||||
using Khaemhat.Application.Audit;
|
||||
using Khaemhat.Application.Querying;
|
||||
using Khaemhat.Application.Security;
|
||||
using Khaemhat.Application.Tables;
|
||||
using Khaemhat.Core.Instance;
|
||||
using Khaemhat.Core.Items;
|
||||
using Khaemhat.Core.Parties;
|
||||
using Khaemhat.Core.Tables;
|
||||
using Khaemhat.Core.Validation;
|
||||
using Khaemhat.Data;
|
||||
using Khaemhat.Data.Querying;
|
||||
|
||||
namespace Khaemhat.Application.Items;
|
||||
|
||||
/// <summary>An item with all its details, as the record screen edits it (mockup 017).</summary>
|
||||
public sealed class ItemRecord
|
||||
{
|
||||
/// <summary>The item.</summary>
|
||||
public Item Item { get; set; } = new();
|
||||
|
||||
/// <summary>The alternative units.</summary>
|
||||
public List<ItemUnit> Units { get; set; } = [];
|
||||
|
||||
/// <summary>The alternative codes.</summary>
|
||||
public List<ItemBarcode> Barcodes { get; set; } = [];
|
||||
|
||||
/// <summary>The prices: of the price lists and net of the customers, each with its validity.</summary>
|
||||
public List<ItemPrice> Prices { get; set; } = [];
|
||||
|
||||
/// <summary>The suppliers.</summary>
|
||||
public List<ItemSupplier> Suppliers { get; set; } = [];
|
||||
|
||||
/// <summary>The substitutes.</summary>
|
||||
public List<ItemSubstitute> Substitutes { get; set; } = [];
|
||||
}
|
||||
|
||||
/// <summary>A row of the items radar.</summary>
|
||||
/// <param name="Id">The item.</param>
|
||||
/// <param name="Code">The code.</param>
|
||||
/// <param name="Description">The description.</param>
|
||||
/// <param name="Kind">What the item is.</param>
|
||||
/// <param name="CategoryId">The category.</param>
|
||||
/// <param name="UnitOfMeasureId">The base unit.</param>
|
||||
/// <param name="Barcode">The main bar code.</param>
|
||||
/// <param name="Brand">The brand.</param>
|
||||
/// <param name="Stocked">Kept in stock.</param>
|
||||
/// <param name="AverageCost">The average cost, only for who can see costs.</param>
|
||||
/// <param name="Disabled">Disabled.</param>
|
||||
public sealed record ItemRow(
|
||||
long Id, string Code, string Description, ItemKind Kind, long? CategoryId, long? UnitOfMeasureId, string? Barcode, string? Brand, bool Stocked,
|
||||
decimal? AverageCost, bool Disabled)
|
||||
{
|
||||
/// <summary>The price of the base list today.</summary>
|
||||
public decimal? BasePrice { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>What happened to an item asked to be deleted.</summary>
|
||||
public enum ItemDeleteOutcome
|
||||
{
|
||||
/// <summary>Deleted.</summary>
|
||||
Deleted = 0,
|
||||
|
||||
/// <summary>Used by other data: disabled instead.</summary>
|
||||
Disabled = 1,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Items (SPEC §11.2, mockup 017, ADR 0030): list, search by code, description, bar codes and codes of the parties,
|
||||
/// record with units, codes, prices, suppliers and substitutes, checks, automatic code per category, history.
|
||||
/// </summary>
|
||||
/// <remarks>Permissions <c>items.item.read</c>, <c>write</c>, <c>delete</c>; costs only with <c>items.cost.read</c>.</remarks>
|
||||
public sealed class ItemService
|
||||
{
|
||||
/// <summary>Permission to read items and price lists.</summary>
|
||||
public const string ReadPermission = "items.item.read";
|
||||
|
||||
/// <summary>Permission to write items and price lists.</summary>
|
||||
public const string WritePermission = "items.item.write";
|
||||
|
||||
/// <summary>Permission to delete items.</summary>
|
||||
public const string DeletePermission = "items.item.delete";
|
||||
|
||||
/// <summary>Permission to see costs and margins.</summary>
|
||||
public const string CostPermission = "items.cost.read";
|
||||
|
||||
/// <summary>The entity of the attachments of an item.</summary>
|
||||
public const string Entity = "items.item";
|
||||
|
||||
/// <summary>The code rule of the items (ADR 0027).</summary>
|
||||
public const string CodeRule = "items";
|
||||
|
||||
/// <summary>Error: no description.</summary>
|
||||
public const string DescriptionRequired = "items.description.required";
|
||||
|
||||
/// <summary>Error: the code is used by another item.</summary>
|
||||
public const string CodeDuplicate = "items.code.duplicate";
|
||||
|
||||
/// <summary>Error: the code mask needs the category.</summary>
|
||||
public const string CategoryRequired = "items.category.required";
|
||||
|
||||
/// <summary>Error: the bar code has a wrong check digit.</summary>
|
||||
public const string BarcodeInvalid = "items.barcode.invalid";
|
||||
|
||||
/// <summary>Error or warning (by preference): another item has the bar code.</summary>
|
||||
public const string BarcodeDuplicate = "items.barcode.duplicate";
|
||||
|
||||
/// <summary>Error: the NC8 code is not eight digits.</summary>
|
||||
public const string CustomsCodeInvalid = "items.customs-code.invalid";
|
||||
|
||||
/// <summary>Error: a negative quantity, weight, price or cost.</summary>
|
||||
public const string NotNegative = "items.value.negative";
|
||||
|
||||
/// <summary>Error: the factor of a unit is not above zero.</summary>
|
||||
public const string FactorInvalid = "items.factor.invalid";
|
||||
|
||||
/// <summary>Error: a unit is listed twice, or is the base unit.</summary>
|
||||
public const string UnitDuplicate = "items.unit.duplicate";
|
||||
|
||||
/// <summary>Error: a required detail field is empty.</summary>
|
||||
public const string DetailRequired = "items.detail.required";
|
||||
|
||||
/// <summary>Error: the party of a supplier row is not a supplier.</summary>
|
||||
public const string SupplierInvalid = "items.supplier.invalid";
|
||||
|
||||
/// <summary>Error: a supplier or a substitute is listed twice.</summary>
|
||||
public const string DetailDuplicate = "items.detail.duplicate";
|
||||
|
||||
/// <summary>Error: an item cannot be its own substitute.</summary>
|
||||
public const string SubstituteSelf = "items.substitute.self";
|
||||
|
||||
/// <summary>Error: a price is neither of a price list nor of a customer, or of both.</summary>
|
||||
public const string PriceTarget = "items.price.target";
|
||||
|
||||
/// <summary>Error: a net price is for a customer only.</summary>
|
||||
public const string PriceParty = "items.price.party";
|
||||
|
||||
/// <summary>Error: two prices of the same list or customer start on the same day.</summary>
|
||||
public const string PriceDuplicate = "items.price.duplicate";
|
||||
|
||||
/// <summary>Error: the code of a party is used for another item.</summary>
|
||||
public const string PartyCodeDuplicate = "items.party-code.duplicate";
|
||||
|
||||
/// <summary>Error: the item does not exist.</summary>
|
||||
public const string NotFound = "items.not-found";
|
||||
|
||||
private readonly IUnitOfWorkFactory _factory;
|
||||
private readonly PermissionService _permissions;
|
||||
private readonly AuditTrail _audit;
|
||||
private readonly CodeRuleService _codes;
|
||||
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="audit">The audit trail.</param>
|
||||
/// <param name="codes">The automatic codes.</param>
|
||||
/// <param name="clock">The clock.</param>
|
||||
public ItemService(IUnitOfWorkFactory factory, PermissionService permissions, AuditTrail audit, CodeRuleService codes, TimeProvider clock)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(factory);
|
||||
ArgumentNullException.ThrowIfNull(permissions);
|
||||
ArgumentNullException.ThrowIfNull(audit);
|
||||
ArgumentNullException.ThrowIfNull(codes);
|
||||
ArgumentNullException.ThrowIfNull(clock);
|
||||
_factory = factory;
|
||||
_permissions = permissions;
|
||||
_audit = audit;
|
||||
_codes = codes;
|
||||
_clock = clock;
|
||||
}
|
||||
|
||||
/// <summary>The fields of the items radar.</summary>
|
||||
public static ListFields<Item> Fields { get; } = new ListFields<Item>()
|
||||
.Add("code", i => i.Code, searchable: true)
|
||||
.Add("description", i => i.Description, searchable: true)
|
||||
.Add("barcode", i => i.Barcode, searchable: true)
|
||||
.Add("brand", i => i.Brand, searchable: true)
|
||||
.Add("manufacturer", i => i.Manufacturer, searchable: true)
|
||||
.Add("kind", i => i.Kind)
|
||||
.Add("category", i => i.CategoryId)
|
||||
.Add("unit", i => i.UnitOfMeasureId)
|
||||
.Add("stocked", i => i.Stocked)
|
||||
.Add("disabled", i => i.Disabled)
|
||||
.OrderByDefault(new ListSort("code"));
|
||||
|
||||
/// <summary>The items for the radar, with the price of the base list today.</summary>
|
||||
/// <param name="actor">Who reads.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="query">Search, filters, sort, page.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The page.</returns>
|
||||
public async Task<ListPage<ItemRow>> ListAsync(Actor actor, string companyCode, ListQuery query, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(query);
|
||||
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, ReadPermission, cancellationToken).ConfigureAwait(false);
|
||||
var costs = await CanSeeCostsAsync(actor, company, cancellationToken).ConfigureAwait(false);
|
||||
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
||||
var page = await uow.Repository<Item, long>().ListAsync(Fields.Apply(Query.For<Item>(), query), cancellationToken).ConfigureAwait(false);
|
||||
var book = await BookAsync(uow, [.. page.Items.Select(i => i.Id)], cancellationToken).ConfigureAwait(false);
|
||||
var today = Today();
|
||||
IReadOnlyList<ItemRow> rows =
|
||||
[
|
||||
.. page.Items.Select(i => RowOf(i, costs) with
|
||||
{
|
||||
BasePrice = book.Base is { } baseList ? book.ListPrice(i.Id, baseList.Id, today).Price : i.Price,
|
||||
}),
|
||||
];
|
||||
return new ListPage<ItemRow>(rows, page.TotalCount, new Dictionary<string, decimal>());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The active items matching a text, for the lookups: code, description, bar code and brand, or exactly an
|
||||
/// alternative code or the code a party uses for the item.
|
||||
/// </summary>
|
||||
/// <param name="actor">Who reads.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="text">The text.</param>
|
||||
/// <param name="partyId">The party of the document, whose codes count too.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>At most 20 items.</returns>
|
||||
public async Task<IReadOnlyList<ItemRow>> SearchAsync(Actor actor, string companyCode, string? text, long? partyId = null, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, ReadPermission, cancellationToken).ConfigureAwait(false);
|
||||
var costs = await CanSeeCostsAsync(actor, company, cancellationToken).ConfigureAwait(false);
|
||||
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
||||
var items = uow.Repository<Item, long>();
|
||||
var page = await items.ListAsync(
|
||||
Fields.Apply(Query.For<Item>(), new ListQuery { Search = text, Filters = [ListFilter.Of("disabled", ListFilterOperator.Equals, "false")], Limit = 20 }),
|
||||
cancellationToken).ConfigureAwait(false);
|
||||
var found = page.Items.ToList();
|
||||
var exact = text?.Trim();
|
||||
if (!string.IsNullOrEmpty(exact))
|
||||
{
|
||||
var ids = (await uow.Repository<ItemBarcode, long>().ListAsync(Query.For<ItemBarcode>().Where(b => b.Code == exact), cancellationToken).ConfigureAwait(false))
|
||||
.Items.Select(b => b.ItemId).ToList();
|
||||
if (partyId is { } party)
|
||||
{
|
||||
ids.AddRange((await uow.Repository<PartyItemCode, long>().ListAsync(
|
||||
Query.For<PartyItemCode>().Where(c => c.PartyId == party && c.Code == exact), cancellationToken).ConfigureAwait(false)).Items.Select(c => c.ItemId));
|
||||
}
|
||||
|
||||
foreach (var id in ids.Distinct().Where(id => found.All(i => i.Id != id)))
|
||||
{
|
||||
if (await items.GetAsync(id, cancellationToken).ConfigureAwait(false) is { Disabled: false } item)
|
||||
{
|
||||
found.Insert(0, item);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return [.. found.Take(20).Select(i => RowOf(i, costs))];
|
||||
}
|
||||
|
||||
/// <summary>An item with its details; costs hidden without <c>items.cost.read</c>.</summary>
|
||||
/// <param name="actor">Who reads.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="id">The item.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The record, or none.</returns>
|
||||
public async Task<ItemRecord?> GetAsync(Actor actor, string companyCode, long id, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, ReadPermission, cancellationToken).ConfigureAwait(false);
|
||||
var costs = await CanSeeCostsAsync(actor, company, cancellationToken).ConfigureAwait(false);
|
||||
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
||||
var record = await LoadAsync(uow, id, cancellationToken).ConfigureAwait(false);
|
||||
if (record is not null && !costs)
|
||||
{
|
||||
HideCosts(record);
|
||||
}
|
||||
|
||||
return record;
|
||||
}
|
||||
|
||||
/// <summary>A new item with the usual values: goods kept in stock, unit PZ, VAT 22, the default warehouse.</summary>
|
||||
/// <param name="actor">Who asks.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The record to fill.</returns>
|
||||
public async Task<ItemRecord> NewAsync(Actor actor, string companyCode, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, ReadPermission, cancellationToken).ConfigureAwait(false);
|
||||
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
||||
var unit = await uow.Repository<UnitOfMeasure, long>().FindAsync(Query.For<UnitOfMeasure>().Where(u => u.Code == "PZ" && !u.Disabled), cancellationToken).ConfigureAwait(false);
|
||||
var tax = await uow.Repository<TaxCode, long>().FindAsync(Query.For<TaxCode>().Where(t => t.Code == "22" && !t.Disabled), cancellationToken).ConfigureAwait(false);
|
||||
var warehouse = await uow.Repository<Warehouse, long>().FindAsync(Query.For<Warehouse>().Where(w => w.IsDefault && !w.Disabled), cancellationToken).ConfigureAwait(false);
|
||||
return new ItemRecord
|
||||
{
|
||||
Item = new Item
|
||||
{
|
||||
Kind = ItemKind.Goods, Stocked = true, UnitOfMeasureId = unit?.Id, SalesTaxCodeId = tax?.Id, PurchaseTaxCodeId = tax?.Id, WarehouseId = warehouse?.Id,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>Checks a record without saving it (also cleans it, as the save would).</summary>
|
||||
/// <param name="actor">Who asks.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="record">The record.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>Errors and warnings.</returns>
|
||||
public async Task<IReadOnlyList<TableProblem>> ValidateAsync(Actor actor, string companyCode, ItemRecord record, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(record);
|
||||
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, ReadPermission, cancellationToken).ConfigureAwait(false);
|
||||
var rule = await _codes.RuleAsync(company, CodeRule, cancellationToken).ConfigureAwait(false);
|
||||
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
||||
return await CheckAsync(uow, rule, record, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Saves an item and its details in one transaction; a new item gets its code from the rule of the items
|
||||
/// (<c>{categoria}</c> is the code of its category). Without <c>items.cost.read</c> the costs stay as they were.
|
||||
/// </summary>
|
||||
/// <param name="actor">Who saves.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="record">The record.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The record as saved.</returns>
|
||||
/// <exception cref="ValidationFailedException">With the errors (<c>field:code</c>).</exception>
|
||||
public async Task<ItemRecord> SaveAsync(Actor actor, string companyCode, ItemRecord record, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(record);
|
||||
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, WritePermission, cancellationToken).ConfigureAwait(false);
|
||||
var costs = await CanSeeCostsAsync(actor, company, cancellationToken).ConfigureAwait(false);
|
||||
var rule = await _codes.RuleAsync(company, CodeRule, cancellationToken).ConfigureAwait(false);
|
||||
var item = record.Item;
|
||||
long id;
|
||||
await using (var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
|
||||
var before = item.Id == 0 ? null : await LoadAsync(uow, item.Id, cancellationToken).ConfigureAwait(false) ?? throw new ValidationFailedException([":" + NotFound]);
|
||||
|
||||
// The last and average costs come from the receipts (M6); the standard cost only from who sees costs.
|
||||
item.LastCost = before?.Item.LastCost;
|
||||
item.AverageCost = before?.Item.AverageCost;
|
||||
if (!costs)
|
||||
{
|
||||
item.StandardCost = before?.Item.StandardCost;
|
||||
}
|
||||
|
||||
var problems = (await CheckAsync(uow, rule, record, cancellationToken).ConfigureAwait(false)).Where(p => !p.IsWarning).Select(p => p.Field + ":" + p.Code).ToList();
|
||||
if (problems.Count > 0)
|
||||
{
|
||||
throw new ValidationFailedException(problems);
|
||||
}
|
||||
|
||||
if (item.Code.Length == 0)
|
||||
{
|
||||
var category = item.CategoryId is { } categoryId ? (await uow.Repository<ItemCategory, long>().GetAsync(categoryId, cancellationToken).ConfigureAwait(false))?.Code : null;
|
||||
item.Code = await CodeRuleService.AssignAsync(uow, rule, Today(), category, (c, ct) => TakenAsync(uow, c, ct), cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
id = await WriteAsync(uow, record, before, actor.UserName, cancellationToken).ConfigureAwait(false);
|
||||
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
return await GetAsync(actor, company, id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(NotFound);
|
||||
}
|
||||
|
||||
/// <summary>Disables or enables items (radar selection).</summary>
|
||||
/// <param name="actor">Who does it.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="ids">The items.</param>
|
||||
/// <param name="disabled">Disable or enable.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>How many changed.</returns>
|
||||
public async Task<int> SetDisabledAsync(Actor actor, string companyCode, IEnumerable<long> ids, bool disabled, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(ids);
|
||||
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, WritePermission, 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<Item, long>();
|
||||
var changed = 0;
|
||||
foreach (var id in ids.Distinct())
|
||||
{
|
||||
if (await repository.GetAsync(id, cancellationToken).ConfigureAwait(false) is { } item && item.Disabled != disabled)
|
||||
{
|
||||
var before = Clone(item);
|
||||
item.Disabled = disabled;
|
||||
await repository.UpdateAsync(item, cancellationToken).ConfigureAwait(false);
|
||||
await _audit.RecordAsync(uow, AuditAction.Update, id, before, item, actor.UserName, cancellationToken).ConfigureAwait(false);
|
||||
changed++;
|
||||
}
|
||||
}
|
||||
|
||||
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
|
||||
return changed;
|
||||
}
|
||||
|
||||
/// <summary>Deletes an item; one used by other data (a substitute, documents from M5) is disabled instead.</summary>
|
||||
/// <param name="actor">Who deletes.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="id">The item.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>What happened.</returns>
|
||||
public async Task<ItemDeleteOutcome> DeleteAsync(Actor actor, string companyCode, long id, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, DeletePermission, cancellationToken).ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
||||
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
|
||||
var before = await uow.Repository<Item, long>().GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(NotFound);
|
||||
await uow.Repository<Item, long>().DeleteAsync(id, cancellationToken).ConfigureAwait(false);
|
||||
await _audit.RecordAsync(uow, AuditAction.Delete, id, before, null, actor.UserName, cancellationToken).ConfigureAwait(false);
|
||||
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
|
||||
return ItemDeleteOutcome.Deleted;
|
||||
}
|
||||
catch (DbException)
|
||||
{
|
||||
await SetDisabledAsync(actor, company, [id], true, cancellationToken).ConfigureAwait(false);
|
||||
return ItemDeleteOutcome.Disabled;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The history of an item and of its prices, newest first.</summary>
|
||||
/// <param name="actor">Who reads.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="id">The item.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The changes.</returns>
|
||||
public async Task<IReadOnlyList<AuditEntry>> HistoryAsync(Actor actor, string companyCode, long id, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, ReadPermission, cancellationToken).ConfigureAwait(false);
|
||||
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
||||
var key = id.ToString(System.Globalization.CultureInfo.InvariantCulture);
|
||||
var entries = new List<AuditEntry>();
|
||||
foreach (var entity in new[] { nameof(Item), nameof(ItemPrice) })
|
||||
{
|
||||
entries.AddRange(await AuditTrail.HistoryAsync(uow, entity, key, cancellationToken).ConfigureAwait(false));
|
||||
}
|
||||
|
||||
return [.. entries.OrderByDescending(e => e.At).ThenByDescending(e => e.Id)];
|
||||
}
|
||||
|
||||
/// <summary>The rows of some items, for the lookups that show them by id.</summary>
|
||||
/// <param name="actor">Who reads.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="ids">The items.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The rows found.</returns>
|
||||
public async Task<IReadOnlyList<ItemRow>> RowsAsync(Actor actor, string companyCode, IEnumerable<long> ids, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(ids);
|
||||
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, ReadPermission, cancellationToken).ConfigureAwait(false);
|
||||
var costs = await CanSeeCostsAsync(actor, company, cancellationToken).ConfigureAwait(false);
|
||||
long[] wanted = [.. ids.Distinct()];
|
||||
if (wanted.Length == 0)
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
||||
return [.. (await uow.Repository<Item, long>().ListAsync(Query.For<Item>().Where(i => wanted.Contains(i.Id)), cancellationToken).ConfigureAwait(false)).Items
|
||||
.Select(i => RowOf(i, costs))];
|
||||
}
|
||||
|
||||
/// <summary>Checks the codes of a party: code and item required, no code twice.</summary>
|
||||
/// <param name="codes">The codes.</param>
|
||||
/// <returns>The errors.</returns>
|
||||
public static IReadOnlyList<TableProblem> CheckPartyCodes(IReadOnlyList<PartyItemCode> codes)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(codes);
|
||||
var problems = new List<TableProblem>();
|
||||
var seen = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
|
||||
for (var i = 0; i < codes.Count; i++)
|
||||
{
|
||||
var code = codes[i];
|
||||
code.Code = code.Code.Trim();
|
||||
code.Description = Clean(code.Description);
|
||||
if (code.Code.Length == 0)
|
||||
{
|
||||
problems.Add(new($"ItemCodes.{i}.{nameof(PartyItemCode.Code)}", DetailRequired));
|
||||
}
|
||||
else if (!seen.Add(code.Code))
|
||||
{
|
||||
problems.Add(new($"ItemCodes.{i}.{nameof(PartyItemCode.Code)}", PartyCodeDuplicate));
|
||||
}
|
||||
|
||||
if (code.ItemId == 0)
|
||||
{
|
||||
problems.Add(new($"ItemCodes.{i}.{nameof(PartyItemCode.ItemId)}", DetailRequired));
|
||||
}
|
||||
}
|
||||
|
||||
return problems;
|
||||
}
|
||||
|
||||
/// <summary>Whether an actor sees costs and margins.</summary>
|
||||
/// <param name="actor">The actor.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>Whether costs are visible.</returns>
|
||||
public async Task<bool> CanSeeCostsAsync(Actor actor, string companyCode, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(actor);
|
||||
return (actor.IsInstanceAccount || string.Equals(actor.CompanyCode, CompanyCodes.Normalize(companyCode), StringComparison.Ordinal))
|
||||
&& (await _permissions.CheckAsync(actor, CostPermission, cancellationToken).ConfigureAwait(false)).Allowed;
|
||||
}
|
||||
|
||||
/// <summary>The prices of some items and all the price lists, in memory.</summary>
|
||||
/// <param name="uow">The unit of work of the company.</param>
|
||||
/// <param name="itemIds">The items.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The book.</returns>
|
||||
public static async Task<PriceBook> BookAsync(IUnitOfWork uow, IReadOnlyList<long> itemIds, CancellationToken cancellationToken)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(uow);
|
||||
ArgumentNullException.ThrowIfNull(itemIds);
|
||||
var lists = (await uow.Repository<PriceList, long>().ListAsync(Query.For<PriceList>(), cancellationToken).ConfigureAwait(false)).Items;
|
||||
var prices = new List<ItemPrice>();
|
||||
foreach (var chunk in itemIds.Distinct().Chunk(500))
|
||||
{
|
||||
long[] ids = [.. chunk];
|
||||
prices.AddRange((await uow.Repository<ItemPrice, long>().ListAsync(Query.For<ItemPrice>().Where(p => ids.Contains(p.ItemId)), cancellationToken).ConfigureAwait(false)).Items);
|
||||
}
|
||||
|
||||
return new PriceBook(lists, prices);
|
||||
}
|
||||
|
||||
private DateOnly Today() => DateOnly.FromDateTime(_clock.GetLocalNow().DateTime);
|
||||
|
||||
private static ItemRow RowOf(Item i, bool costs) =>
|
||||
new(i.Id, i.Code, i.Description, i.Kind, i.CategoryId, i.UnitOfMeasureId, i.Barcode, i.Brand, i.Stocked, costs ? i.AverageCost : null, i.Disabled);
|
||||
|
||||
private static void HideCosts(ItemRecord record)
|
||||
{
|
||||
record.Item.StandardCost = null;
|
||||
record.Item.LastCost = null;
|
||||
record.Item.AverageCost = null;
|
||||
}
|
||||
|
||||
private static async Task<bool> TakenAsync(IUnitOfWork uow, string code, CancellationToken cancellationToken) =>
|
||||
await uow.Repository<Item, long>().CountAsync(Query.For<Item>().Where(i => i.Code == code), cancellationToken).ConfigureAwait(false) > 0;
|
||||
|
||||
private static async Task<ItemRecord?> LoadAsync(IUnitOfWork uow, long id, CancellationToken cancellationToken)
|
||||
{
|
||||
if (await uow.Repository<Item, long>().GetAsync(id, cancellationToken).ConfigureAwait(false) is not { } item)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
return new ItemRecord
|
||||
{
|
||||
Item = item,
|
||||
Units = [.. (await uow.Repository<ItemUnit, long>().ListAsync(Query.For<ItemUnit>().Where(u => u.ItemId == id).OrderBy(u => u.Id), cancellationToken).ConfigureAwait(false)).Items],
|
||||
Barcodes = [.. (await uow.Repository<ItemBarcode, long>().ListAsync(Query.For<ItemBarcode>().Where(u => u.ItemId == id).OrderBy(u => u.Id), cancellationToken).ConfigureAwait(false)).Items],
|
||||
Prices = [.. (await uow.Repository<ItemPrice, long>().ListAsync(Query.For<ItemPrice>().Where(u => u.ItemId == id).OrderBy(u => u.Id), cancellationToken).ConfigureAwait(false)).Items],
|
||||
Suppliers = [.. (await uow.Repository<ItemSupplier, long>().ListAsync(Query.For<ItemSupplier>().Where(u => u.ItemId == id).OrderBy(u => u.Id), cancellationToken).ConfigureAwait(false)).Items],
|
||||
Substitutes = [.. (await uow.Repository<ItemSubstitute, long>().ListAsync(Query.For<ItemSubstitute>().Where(u => u.ItemId == id).OrderBy(u => u.Id), cancellationToken).ConfigureAwait(false)).Items],
|
||||
};
|
||||
}
|
||||
|
||||
private async Task<long> WriteAsync(IUnitOfWork uow, ItemRecord record, ItemRecord? before, string userName, CancellationToken cancellationToken)
|
||||
{
|
||||
var item = record.Item;
|
||||
var items = uow.Repository<Item, long>();
|
||||
if (before is null)
|
||||
{
|
||||
item.Id = await items.InsertAsync(item, cancellationToken).ConfigureAwait(false);
|
||||
await _audit.RecordAsync<Item>(uow, AuditAction.Insert, item.Id, null, item, userName, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
else
|
||||
{
|
||||
await items.UpdateAsync(item, cancellationToken).ConfigureAwait(false);
|
||||
await _audit.RecordAsync(uow, AuditAction.Update, item.Id, before.Item, item, userName, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
var id = item.Id;
|
||||
await ReplaceAsync(uow, record.Units, before?.Units ?? [], u => u.ItemId = id, cancellationToken).ConfigureAwait(false);
|
||||
await ReplaceAsync(uow, record.Barcodes, before?.Barcodes ?? [], u => u.ItemId = id, cancellationToken).ConfigureAwait(false);
|
||||
await ReplaceAsync(uow, record.Suppliers, before?.Suppliers ?? [], u => u.ItemId = id, cancellationToken).ConfigureAwait(false);
|
||||
await ReplaceAsync(uow, record.Substitutes, before?.Substitutes ?? [], u => u.ItemId = id, cancellationToken).ConfigureAwait(false);
|
||||
await ReplaceAsync(uow, record.Prices, before?.Prices ?? [], u => u.ItemId = id, cancellationToken, async (old, row, ct) =>
|
||||
await _audit.RecordAsync(uow, old is null ? AuditAction.Insert : row is null ? AuditAction.Delete : AuditAction.Update, id, old, row, userName, ct).ConfigureAwait(false))
|
||||
.ConfigureAwait(false);
|
||||
return id;
|
||||
}
|
||||
|
||||
// The lists: rows removed are deleted, rows kept are updated, new rows inserted; the prices are written in the history.
|
||||
private static async Task ReplaceAsync<T>(
|
||||
IUnitOfWork uow, List<T> rows, List<T> before, Action<T> link, CancellationToken cancellationToken, Func<T?, T?, CancellationToken, Task>? audit = null)
|
||||
where T : Core.Entities.Entity<long>, new()
|
||||
{
|
||||
var repository = uow.Repository<T, long>();
|
||||
var kept = rows.Where(r => r.Id != 0).Select(r => r.Id).ToHashSet();
|
||||
foreach (var old in before.Where(b => !kept.Contains(b.Id)))
|
||||
{
|
||||
await repository.DeleteAsync(old.Id, cancellationToken).ConfigureAwait(false);
|
||||
if (audit is not null)
|
||||
{
|
||||
await audit(old, null, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
var previous = before.ToDictionary(b => b.Id);
|
||||
foreach (var row in rows)
|
||||
{
|
||||
link(row);
|
||||
if (row.Id != 0 && previous.TryGetValue(row.Id, out var old))
|
||||
{
|
||||
row.RowVersion = old.RowVersion;
|
||||
await repository.UpdateAsync(row, cancellationToken).ConfigureAwait(false);
|
||||
if (audit is not null)
|
||||
{
|
||||
await audit(old, row, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
row.Id = await repository.InsertAsync(row, cancellationToken).ConfigureAwait(false);
|
||||
if (audit is not null)
|
||||
{
|
||||
await audit(null, row, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static async Task<IReadOnlyList<TableProblem>> CheckAsync(IUnitOfWork uow, CodeRule rule, ItemRecord record, CancellationToken cancellationToken)
|
||||
{
|
||||
var problems = new List<TableProblem>();
|
||||
var item = record.Item;
|
||||
Normalize(item);
|
||||
if (item.Description.Length == 0)
|
||||
{
|
||||
problems.Add(new(nameof(Item.Description), DescriptionRequired));
|
||||
}
|
||||
|
||||
var id = item.Id;
|
||||
if (item.Code.Length > 0)
|
||||
{
|
||||
var code = item.Code;
|
||||
if (await uow.Repository<Item, long>().CountAsync(Query.For<Item>().Where(i => i.Code == code && i.Id != id), cancellationToken).ConfigureAwait(false) > 0)
|
||||
{
|
||||
problems.Add(new(nameof(Item.Code), CodeDuplicate));
|
||||
}
|
||||
}
|
||||
else if (item.CategoryId is null && CodeMask.TryParse(rule.Mask, out var mask, out _) && mask!.UsesCategory)
|
||||
{
|
||||
problems.Add(new(nameof(Item.CategoryId), CategoryRequired));
|
||||
}
|
||||
|
||||
if (item.Barcode is { } barcode)
|
||||
{
|
||||
if (!EanValidator.IsValid(barcode))
|
||||
{
|
||||
problems.Add(new(nameof(Item.Barcode), BarcodeInvalid));
|
||||
}
|
||||
else if (await BarcodeUsedAsync(uow, barcode, id, cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
problems.Add(new(nameof(Item.Barcode), BarcodeDuplicate, IsWarning: !rule.UniqueBarcode));
|
||||
}
|
||||
}
|
||||
|
||||
if (item.CustomsCode is { } customs && (customs.Length != 8 || !customs.All(char.IsAsciiDigit)))
|
||||
{
|
||||
problems.Add(new(nameof(Item.CustomsCode), CustomsCodeInvalid));
|
||||
}
|
||||
|
||||
foreach (var (value, field) in new (decimal?, string)[]
|
||||
{
|
||||
(item.NetWeight, nameof(Item.NetWeight)), (item.GrossWeight, nameof(Item.GrossWeight)), (item.MinimumStock, nameof(Item.MinimumStock)),
|
||||
(item.ReorderPoint, nameof(Item.ReorderPoint)), (item.ReorderLot, nameof(Item.ReorderLot)), (item.Price, nameof(Item.Price)),
|
||||
(item.StandardCost, nameof(Item.StandardCost)),
|
||||
})
|
||||
{
|
||||
if (value < 0)
|
||||
{
|
||||
problems.Add(new(field, NotNegative));
|
||||
}
|
||||
}
|
||||
|
||||
CheckUnits(record, problems);
|
||||
CheckBarcodes(record, problems);
|
||||
await CheckPricesAsync(uow, record, problems, cancellationToken).ConfigureAwait(false);
|
||||
await CheckSuppliersAsync(uow, record, problems, cancellationToken).ConfigureAwait(false);
|
||||
CheckSubstitutes(record, problems);
|
||||
return problems;
|
||||
}
|
||||
|
||||
private static void Normalize(Item item)
|
||||
{
|
||||
item.Code = item.Code.Trim();
|
||||
item.Description = item.Description.Trim();
|
||||
item.ExtendedDescription = Clean(item.ExtendedDescription);
|
||||
item.Barcode = Clean(item.Barcode);
|
||||
item.CustomsCode = Clean(item.CustomsCode)?.Replace(" ", string.Empty, StringComparison.Ordinal).Replace(".", string.Empty, StringComparison.Ordinal);
|
||||
item.Manufacturer = Clean(item.Manufacturer);
|
||||
item.Brand = Clean(item.Brand);
|
||||
item.RevenueAccountCode = Clean(item.RevenueAccountCode);
|
||||
item.CostAccountCode = Clean(item.CostAccountCode);
|
||||
item.Notes = Clean(item.Notes);
|
||||
|
||||
// Only goods move in the warehouse.
|
||||
if (item.Kind != ItemKind.Goods)
|
||||
{
|
||||
item.Stocked = false;
|
||||
}
|
||||
}
|
||||
|
||||
private static async Task<bool> BarcodeUsedAsync(IUnitOfWork uow, string barcode, long id, CancellationToken cancellationToken) =>
|
||||
await uow.Repository<Item, long>().CountAsync(Query.For<Item>().Where(i => i.Barcode == barcode && i.Id != id), cancellationToken).ConfigureAwait(false) > 0
|
||||
|| await uow.Repository<ItemBarcode, long>().CountAsync(Query.For<ItemBarcode>().Where(b => b.Code == barcode && b.ItemId != id), cancellationToken).ConfigureAwait(false) > 0;
|
||||
|
||||
private static void CheckUnits(ItemRecord record, List<TableProblem> problems)
|
||||
{
|
||||
var seen = new HashSet<long>();
|
||||
if (record.Item.UnitOfMeasureId is { } baseUnit)
|
||||
{
|
||||
seen.Add(baseUnit);
|
||||
}
|
||||
|
||||
for (var i = 0; i < record.Units.Count; i++)
|
||||
{
|
||||
var unit = record.Units[i];
|
||||
unit.Barcode = Clean(unit.Barcode);
|
||||
if (unit.UnitOfMeasureId == 0)
|
||||
{
|
||||
problems.Add(new($"Units.{i}.{nameof(ItemUnit.UnitOfMeasureId)}", DetailRequired));
|
||||
}
|
||||
else if (!seen.Add(unit.UnitOfMeasureId))
|
||||
{
|
||||
problems.Add(new($"Units.{i}.{nameof(ItemUnit.UnitOfMeasureId)}", UnitDuplicate));
|
||||
}
|
||||
|
||||
if (unit.Factor <= 0)
|
||||
{
|
||||
problems.Add(new($"Units.{i}.{nameof(ItemUnit.Factor)}", FactorInvalid));
|
||||
}
|
||||
|
||||
if (unit.Barcode is { } barcode && !EanValidator.IsValid(barcode))
|
||||
{
|
||||
problems.Add(new($"Units.{i}.{nameof(ItemUnit.Barcode)}", BarcodeInvalid));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void CheckBarcodes(ItemRecord record, List<TableProblem> problems)
|
||||
{
|
||||
var seen = new HashSet<string>(StringComparer.Ordinal);
|
||||
if (record.Item.Barcode is { } main)
|
||||
{
|
||||
seen.Add(main);
|
||||
}
|
||||
|
||||
for (var i = 0; i < record.Barcodes.Count; i++)
|
||||
{
|
||||
var code = record.Barcodes[i];
|
||||
code.Code = code.Code.Trim();
|
||||
code.Description = Clean(code.Description);
|
||||
if (code.Code.Length == 0)
|
||||
{
|
||||
problems.Add(new($"Barcodes.{i}.{nameof(ItemBarcode.Code)}", DetailRequired));
|
||||
}
|
||||
else if (!seen.Add(code.Code))
|
||||
{
|
||||
problems.Add(new($"Barcodes.{i}.{nameof(ItemBarcode.Code)}", DetailDuplicate));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static async Task CheckPricesAsync(IUnitOfWork uow, ItemRecord record, List<TableProblem> problems, CancellationToken cancellationToken)
|
||||
{
|
||||
var seen = new HashSet<(long?, long?, DateOnly?)>();
|
||||
var parties = uow.Repository<Party, long>();
|
||||
for (var i = 0; i < record.Prices.Count; i++)
|
||||
{
|
||||
var price = record.Prices[i];
|
||||
var field = $"Prices.{i}.";
|
||||
if ((price.PriceListId is null) == (price.PartyId is null))
|
||||
{
|
||||
problems.Add(new(field + nameof(ItemPrice.PriceListId), PriceTarget));
|
||||
continue;
|
||||
}
|
||||
|
||||
// A row added on the screen and not filled has id 0.
|
||||
if (price.PriceListId is 0 || price.PartyId is 0)
|
||||
{
|
||||
problems.Add(new(field + (price.PartyId is null ? nameof(ItemPrice.PriceListId) : nameof(ItemPrice.PartyId)), DetailRequired));
|
||||
continue;
|
||||
}
|
||||
|
||||
if (price.PartyId is { } partyId && await parties.GetAsync(partyId, cancellationToken).ConfigureAwait(false) is not { IsCustomer: true })
|
||||
{
|
||||
problems.Add(new(field + nameof(ItemPrice.PartyId), PriceParty));
|
||||
}
|
||||
|
||||
if (price.Price < 0)
|
||||
{
|
||||
problems.Add(new(field + nameof(ItemPrice.Price), NotNegative));
|
||||
}
|
||||
|
||||
if (!seen.Add((price.PriceListId, price.PartyId, price.ValidFrom)))
|
||||
{
|
||||
problems.Add(new(field + nameof(ItemPrice.ValidFrom), PriceDuplicate));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static async Task CheckSuppliersAsync(IUnitOfWork uow, ItemRecord record, List<TableProblem> problems, CancellationToken cancellationToken)
|
||||
{
|
||||
var seen = new HashSet<long>();
|
||||
var parties = uow.Repository<Party, long>();
|
||||
for (var i = 0; i < record.Suppliers.Count; i++)
|
||||
{
|
||||
var supplier = record.Suppliers[i];
|
||||
var field = $"Suppliers.{i}.";
|
||||
supplier.SupplierCode = Clean(supplier.SupplierCode);
|
||||
if (supplier.PartyId == 0)
|
||||
{
|
||||
problems.Add(new(field + nameof(ItemSupplier.PartyId), DetailRequired));
|
||||
}
|
||||
else if (!seen.Add(supplier.PartyId))
|
||||
{
|
||||
problems.Add(new(field + nameof(ItemSupplier.PartyId), DetailDuplicate));
|
||||
}
|
||||
else if (await parties.GetAsync(supplier.PartyId, cancellationToken).ConfigureAwait(false) is not { IsSupplier: true })
|
||||
{
|
||||
problems.Add(new(field + nameof(ItemSupplier.PartyId), SupplierInvalid));
|
||||
}
|
||||
|
||||
if (supplier.Price < 0)
|
||||
{
|
||||
problems.Add(new(field + nameof(ItemSupplier.Price), NotNegative));
|
||||
}
|
||||
|
||||
if (supplier.MinimumQuantity < 0)
|
||||
{
|
||||
problems.Add(new(field + nameof(ItemSupplier.MinimumQuantity), NotNegative));
|
||||
}
|
||||
|
||||
if (supplier.LeadTimeDays < 0)
|
||||
{
|
||||
problems.Add(new(field + nameof(ItemSupplier.LeadTimeDays), NotNegative));
|
||||
}
|
||||
}
|
||||
|
||||
// One usual supplier: the first one marked.
|
||||
var found = false;
|
||||
foreach (var supplier in record.Suppliers.Where(s => s.IsDefault))
|
||||
{
|
||||
supplier.IsDefault = !found;
|
||||
found = true;
|
||||
}
|
||||
}
|
||||
|
||||
private static void CheckSubstitutes(ItemRecord record, List<TableProblem> problems)
|
||||
{
|
||||
var seen = new HashSet<long>();
|
||||
for (var i = 0; i < record.Substitutes.Count; i++)
|
||||
{
|
||||
var substitute = record.Substitutes[i];
|
||||
var field = $"Substitutes.{i}.{nameof(ItemSubstitute.SubstituteId)}";
|
||||
substitute.Notes = Clean(substitute.Notes);
|
||||
if (substitute.SubstituteId == 0)
|
||||
{
|
||||
problems.Add(new(field, DetailRequired));
|
||||
}
|
||||
else if (substitute.SubstituteId == record.Item.Id)
|
||||
{
|
||||
problems.Add(new(field, SubstituteSelf));
|
||||
}
|
||||
else if (!seen.Add(substitute.SubstituteId))
|
||||
{
|
||||
problems.Add(new(field, DetailDuplicate));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static string? Clean(string? value) => string.IsNullOrWhiteSpace(value) ? null : value.Trim();
|
||||
|
||||
private static Item Clone(Item item)
|
||||
{
|
||||
var copy = new Item();
|
||||
foreach (var property in typeof(Item).GetProperties().Where(p => p.CanRead && p.CanWrite))
|
||||
{
|
||||
property.SetValue(copy, property.GetValue(item));
|
||||
}
|
||||
|
||||
return copy;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,188 @@
|
||||
using Khaemhat.Application.Tables;
|
||||
using Khaemhat.Core.Items;
|
||||
using Khaemhat.Core.Parties;
|
||||
using Khaemhat.Core.Tables;
|
||||
|
||||
namespace Khaemhat.Application.Items;
|
||||
|
||||
/// <summary>The price proposed for an item and where it comes from (<c>price_source</c> of the document lines).</summary>
|
||||
/// <param name="Price">The price, or none.</param>
|
||||
/// <param name="Source">Where it comes from.</param>
|
||||
/// <param name="PriceListId">The price list it comes from.</param>
|
||||
/// <param name="VatIncluded">The price includes VAT (a price list with VAT included).</param>
|
||||
/// <param name="ValidFrom">The price is valid from this day.</param>
|
||||
public sealed record PriceQuote(decimal? Price, PriceSource Source, long? PriceListId, bool VatIncluded, DateOnly? ValidFrom)
|
||||
{
|
||||
/// <summary>No price.</summary>
|
||||
public static PriceQuote None { get; } = new(null, PriceSource.None, null, false, null);
|
||||
}
|
||||
|
||||
/// <summary>The discounts proposed on a line.</summary>
|
||||
/// <param name="Formula">The chain, such as <c>5+2</c>, or none.</param>
|
||||
/// <param name="Equivalent">The single discount equal to the chain, in percent.</param>
|
||||
public sealed record DiscountQuote(string? Formula, decimal Equivalent)
|
||||
{
|
||||
/// <summary>No discount.</summary>
|
||||
public static DiscountQuote None { get; } = new(null, 0m);
|
||||
}
|
||||
|
||||
/// <summary>A price of a price list for an item at a date.</summary>
|
||||
/// <param name="Price">The price, or none.</param>
|
||||
/// <param name="Derived">The price is computed from the base list of a derived list, not written.</param>
|
||||
/// <param name="ValidFrom">The price is valid from this day.</param>
|
||||
public sealed record PriceCell(decimal? Price, bool Derived, DateOnly? ValidFrom)
|
||||
{
|
||||
/// <summary>No price.</summary>
|
||||
public static PriceCell Empty { get; } = new(null, false, null);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The prices of some items in memory, and the search of SPEC §11.3 (ADR 0030): net price of the party for the item,
|
||||
/// then the price list of the party or of the document, then the base price list, then the price of the item. A
|
||||
/// derived list without its own price takes the price of its base list with the markup and the rounding of the list.
|
||||
/// </summary>
|
||||
public sealed class PriceBook
|
||||
{
|
||||
// A derived list of a derived list... is followed at most this deep (the table forbids only a list on itself).
|
||||
private const int MaxDepth = 5;
|
||||
|
||||
private readonly Dictionary<long, PriceList> _lists;
|
||||
private readonly ILookup<(long Item, long List), ItemPrice> _listPrices;
|
||||
private readonly ILookup<(long Item, long Party), ItemPrice> _netPrices;
|
||||
|
||||
/// <summary>Creates the book.</summary>
|
||||
/// <param name="lists">The price lists of the company.</param>
|
||||
/// <param name="prices">The prices of the items wanted (all their rows).</param>
|
||||
public PriceBook(IEnumerable<PriceList> lists, IEnumerable<ItemPrice> prices)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(lists);
|
||||
ArgumentNullException.ThrowIfNull(prices);
|
||||
_lists = lists.ToDictionary(l => l.Id);
|
||||
var all = prices.ToList();
|
||||
_listPrices = all.Where(p => p.PriceListId is not null).ToLookup(p => (p.ItemId, p.PriceListId!.Value));
|
||||
_netPrices = all.Where(p => p.PartyId is not null).ToLookup(p => (p.ItemId, p.PartyId!.Value));
|
||||
Base = BaseOf(_lists.Values);
|
||||
}
|
||||
|
||||
/// <summary>The base price list: the one marked, or the one with code <c>BASE</c>.</summary>
|
||||
public PriceList? Base { get; }
|
||||
|
||||
/// <summary>The price lists.</summary>
|
||||
public IReadOnlyCollection<PriceList> Lists => _lists.Values;
|
||||
|
||||
/// <summary>The base price list among some.</summary>
|
||||
/// <param name="lists">The price lists.</param>
|
||||
/// <returns>The base one, or none.</returns>
|
||||
public static PriceList? BaseOf(IEnumerable<PriceList> lists)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(lists);
|
||||
var active = lists.Where(l => !l.Disabled).OrderBy(l => l.Code, StringComparer.Ordinal).ToList();
|
||||
return active.FirstOrDefault(l => l.IsBase) ?? active.FirstOrDefault(l => l.Code == "BASE");
|
||||
}
|
||||
|
||||
/// <summary>The row in effect at a date: the latest start not after it (a row without start is always valid).</summary>
|
||||
/// <param name="rows">The rows of one item and one list or party.</param>
|
||||
/// <param name="date">The date.</param>
|
||||
/// <returns>The row, or none.</returns>
|
||||
public static ItemPrice? At(IEnumerable<ItemPrice> rows, DateOnly date)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(rows);
|
||||
return rows.Where(r => r.ValidFrom is null || r.ValidFrom <= date).OrderByDescending(r => r.ValidFrom ?? DateOnly.MinValue).FirstOrDefault();
|
||||
}
|
||||
|
||||
/// <summary>Whether a price list can be used at a date: active and within its validity.</summary>
|
||||
/// <param name="list">The list.</param>
|
||||
/// <param name="date">The date.</param>
|
||||
/// <returns>Whether it is valid.</returns>
|
||||
public static bool IsValid(PriceList list, DateOnly date)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(list);
|
||||
return !list.Disabled && (list.ValidFrom is null || list.ValidFrom <= date) && (list.ValidTo is null || list.ValidTo >= date);
|
||||
}
|
||||
|
||||
/// <summary>The price of an item in a list at a date, derived from the base list when the list has none.</summary>
|
||||
/// <param name="itemId">The item.</param>
|
||||
/// <param name="listId">The list.</param>
|
||||
/// <param name="date">The date.</param>
|
||||
/// <returns>The price.</returns>
|
||||
public PriceCell ListPrice(long itemId, long listId, DateOnly date) => ListPrice(itemId, listId, date, 0);
|
||||
|
||||
/// <summary>The price written in a list for an item at a date, without derivation.</summary>
|
||||
/// <param name="itemId">The item.</param>
|
||||
/// <param name="listId">The list.</param>
|
||||
/// <param name="date">The date.</param>
|
||||
/// <returns>The row, or none.</returns>
|
||||
public ItemPrice? OwnPrice(long itemId, long listId, DateOnly date) => At(_listPrices[(itemId, listId)], date);
|
||||
|
||||
/// <summary>The net price of a party for an item at a date.</summary>
|
||||
/// <param name="itemId">The item.</param>
|
||||
/// <param name="partyId">The party.</param>
|
||||
/// <param name="date">The date.</param>
|
||||
/// <returns>The row, or none.</returns>
|
||||
public ItemPrice? NetPrice(long itemId, long partyId, DateOnly date) => At(_netPrices[(itemId, partyId)], date);
|
||||
|
||||
/// <summary>The price proposed for an item (SPEC §11.3): net of the party, list, base list, item.</summary>
|
||||
/// <param name="item">The item.</param>
|
||||
/// <param name="partyId">The party of the document.</param>
|
||||
/// <param name="priceListId">The price list of the party or of the document.</param>
|
||||
/// <param name="date">The date of the document.</param>
|
||||
/// <returns>The price and its source.</returns>
|
||||
public PriceQuote Quote(Item item, long? partyId, long? priceListId, DateOnly date)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(item);
|
||||
if (partyId is { } party && NetPrice(item.Id, party, date) is { } net)
|
||||
{
|
||||
return new PriceQuote(net.Price, PriceSource.PartyNet, null, false, net.ValidFrom);
|
||||
}
|
||||
|
||||
if (priceListId is { } listId && _lists.TryGetValue(listId, out var list) && IsValid(list, date)
|
||||
&& ListPrice(item.Id, listId, date) is { Price: { } listPrice } cell)
|
||||
{
|
||||
return new PriceQuote(listPrice, PriceSource.PartyPriceList, listId, list.VatIncluded, cell.ValidFrom);
|
||||
}
|
||||
|
||||
if (Base is { } baseList && baseList.Id != priceListId && IsValid(baseList, date)
|
||||
&& ListPrice(item.Id, baseList.Id, date) is { Price: { } basePrice } baseCell)
|
||||
{
|
||||
return new PriceQuote(basePrice, PriceSource.BasePriceList, baseList.Id, baseList.VatIncluded, baseCell.ValidFrom);
|
||||
}
|
||||
|
||||
return item.Price is { } own ? new PriceQuote(own, PriceSource.Item, null, false, null) : PriceQuote.None;
|
||||
}
|
||||
|
||||
/// <summary>The discounts of the party on a price (SPEC §11.3): none on a net price, else the two of the sales terms.</summary>
|
||||
/// <param name="price">The price proposed.</param>
|
||||
/// <param name="terms">The sales terms of the party.</param>
|
||||
/// <returns>The discounts.</returns>
|
||||
public static DiscountQuote Discounts(PriceQuote price, PartySalesTerms? terms)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(price);
|
||||
if (price.Source == PriceSource.PartyNet || terms is null)
|
||||
{
|
||||
return DiscountQuote.None;
|
||||
}
|
||||
|
||||
decimal[] steps = [.. new[] { terms.Discount1, terms.Discount2 }.Where(d => d is > 0).Select(d => d!.Value)];
|
||||
return steps.Length == 0 ? DiscountQuote.None : new DiscountQuote(DiscountFormula.Format(steps), DiscountFormula.Equivalent(steps));
|
||||
}
|
||||
|
||||
private PriceCell ListPrice(long itemId, long listId, DateOnly date, int depth)
|
||||
{
|
||||
if (depth > MaxDepth || !_lists.TryGetValue(listId, out var list))
|
||||
{
|
||||
return PriceCell.Empty;
|
||||
}
|
||||
|
||||
if (OwnPrice(itemId, listId, date) is { } own)
|
||||
{
|
||||
return new PriceCell(own.Price, false, own.ValidFrom);
|
||||
}
|
||||
|
||||
if (list.BasePriceListId is { } parent && ListPrice(itemId, parent, date, depth + 1) is { Price: { } basePrice } from)
|
||||
{
|
||||
return new PriceCell(PriceRounding.Round(PriceRounding.Change(basePrice, list.MarkupPercent), list.RoundingStep), true, from.ValidFrom);
|
||||
}
|
||||
|
||||
return PriceCell.Empty;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,360 @@
|
||||
using Khaemhat.Application.Audit;
|
||||
using Khaemhat.Application.Querying;
|
||||
using Khaemhat.Application.Security;
|
||||
using Khaemhat.Application.Tables;
|
||||
using Khaemhat.Core.Items;
|
||||
using Khaemhat.Core.Parties;
|
||||
using Khaemhat.Core.Tables;
|
||||
using Khaemhat.Data;
|
||||
using Khaemhat.Data.Querying;
|
||||
|
||||
namespace Khaemhat.Application.Items;
|
||||
|
||||
/// <summary>A column of the price grid: a price list.</summary>
|
||||
/// <param name="Id">The list.</param>
|
||||
/// <param name="Code">Its code.</param>
|
||||
/// <param name="Description">Its description.</param>
|
||||
/// <param name="IsBase">The base list.</param>
|
||||
/// <param name="Derived">Derived from another list.</param>
|
||||
/// <param name="VatIncluded">Prices with VAT.</param>
|
||||
public sealed record PriceListColumn(long Id, string Code, string Description, bool IsBase, bool Derived, bool VatIncluded);
|
||||
|
||||
/// <summary>A row of the price grid: an item with its price in every list at the date.</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="AverageCost">Its average cost (standard when none), only for who sees costs.</param>
|
||||
/// <param name="Prices">The prices by list.</param>
|
||||
/// <param name="Net">The net price of the party chosen, if any.</param>
|
||||
public sealed record PriceGridRow(
|
||||
long ItemId, string Code, string Description, long? UnitOfMeasureId, decimal? AverageCost, IReadOnlyDictionary<long, PriceCell> Prices, PriceCell? Net);
|
||||
|
||||
/// <summary>The price grid (mockup 018).</summary>
|
||||
/// <param name="Lists">The columns.</param>
|
||||
/// <param name="Page">The rows.</param>
|
||||
public sealed record PriceGrid(IReadOnlyList<PriceListColumn> Lists, ListPage<PriceGridRow> Page);
|
||||
|
||||
/// <summary>A price to write: of a list or net of a customer, valid from a day; no price removes the row of that day.</summary>
|
||||
/// <param name="ItemId">The item.</param>
|
||||
/// <param name="PriceListId">The list.</param>
|
||||
/// <param name="PartyId">The customer.</param>
|
||||
/// <param name="Price">The price, or none to remove it.</param>
|
||||
/// <param name="ValidFrom">Valid from this day.</param>
|
||||
public sealed record PriceEdit(long ItemId, long? PriceListId, long? PartyId, decimal? Price, DateOnly? ValidFrom);
|
||||
|
||||
/// <summary>A mass update of a price list (mockup 018): from the list itself or another one, a percent and a rounding.</summary>
|
||||
public sealed record BulkUpdate
|
||||
{
|
||||
/// <summary>The list to update.</summary>
|
||||
public long PriceListId { get; init; }
|
||||
|
||||
/// <summary>The list the prices start from; none: the list itself.</summary>
|
||||
public long? SourcePriceListId { get; init; }
|
||||
|
||||
/// <summary>The change in percent, also negative.</summary>
|
||||
public decimal Percent { get; init; }
|
||||
|
||||
/// <summary>The rounding step, such as 0.10, 0.50 or 1.00; zero: cents.</summary>
|
||||
public decimal RoundingStep { get; init; }
|
||||
|
||||
/// <summary>Rounding up, down or to the nearest.</summary>
|
||||
public RoundingDirection Direction { get; init; }
|
||||
|
||||
/// <summary>The prices are read at this day and the new ones are valid from it.</summary>
|
||||
public DateOnly Date { get; init; }
|
||||
|
||||
/// <summary>Only the items of this category.</summary>
|
||||
public long? CategoryId { get; init; }
|
||||
|
||||
/// <summary>Only these items (the selection); none: all the active items with a price.</summary>
|
||||
public IReadOnlyList<long>? ItemIds { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Price lists (mockup 018, ADR 0030): the grid of items by lists at a date with the net prices of a customer, mass
|
||||
/// updates, the writing of prices with their validity, and the price and discounts proposed for a document line.
|
||||
/// </summary>
|
||||
/// <remarks>Permissions <c>items.item.read</c> and <c>write</c>; costs and margins with <c>items.cost.read</c>.</remarks>
|
||||
public sealed class PriceListService
|
||||
{
|
||||
/// <summary>Error: a price is negative.</summary>
|
||||
public const string NotNegative = ItemService.NotNegative;
|
||||
|
||||
/// <summary>Error: the list of a mass update does not exist.</summary>
|
||||
public const string ListUnknown = "items.price-list.unknown";
|
||||
|
||||
private readonly IUnitOfWorkFactory _factory;
|
||||
private readonly PermissionService _permissions;
|
||||
private readonly AuditTrail _audit;
|
||||
private readonly ItemService _items;
|
||||
|
||||
/// <summary>Creates the service.</summary>
|
||||
/// <param name="factory">The units of work.</param>
|
||||
/// <param name="permissions">The permissions.</param>
|
||||
/// <param name="audit">The audit trail.</param>
|
||||
/// <param name="items">The items (for the cost permission).</param>
|
||||
public PriceListService(IUnitOfWorkFactory factory, PermissionService permissions, AuditTrail audit, ItemService items)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(factory);
|
||||
ArgumentNullException.ThrowIfNull(permissions);
|
||||
ArgumentNullException.ThrowIfNull(audit);
|
||||
ArgumentNullException.ThrowIfNull(items);
|
||||
_factory = factory;
|
||||
_permissions = permissions;
|
||||
_audit = audit;
|
||||
_items = items;
|
||||
}
|
||||
|
||||
/// <summary>The active price lists: the base one first, then by code.</summary>
|
||||
/// <param name="actor">Who reads.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The lists.</returns>
|
||||
public async Task<IReadOnlyList<PriceListColumn>> ListsAsync(Actor actor, string companyCode, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, ItemService.ReadPermission, cancellationToken).ConfigureAwait(false);
|
||||
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
||||
return await ColumnsAsync(uow, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>The price grid: a page of items (no text items) with the price of every list at a date.</summary>
|
||||
/// <param name="actor">Who reads.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="query">Search, filters (those of the items radar), sort, page.</param>
|
||||
/// <param name="date">The day the prices are read at.</param>
|
||||
/// <param name="partyId">The customer whose net prices are shown.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The grid.</returns>
|
||||
public async Task<PriceGrid> GridAsync(Actor actor, string companyCode, ListQuery query, DateOnly date, long? partyId, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(query);
|
||||
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, ItemService.ReadPermission, cancellationToken).ConfigureAwait(false);
|
||||
var costs = await _items.CanSeeCostsAsync(actor, company, cancellationToken).ConfigureAwait(false);
|
||||
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
||||
var columns = await ColumnsAsync(uow, cancellationToken).ConfigureAwait(false);
|
||||
var page = await uow.Repository<Item, long>().ListAsync(
|
||||
ItemService.Fields.Apply(Query.For<Item>().Where(i => i.Kind != ItemKind.Text), query), cancellationToken).ConfigureAwait(false);
|
||||
var book = await ItemService.BookAsync(uow, [.. page.Items.Select(i => i.Id)], cancellationToken).ConfigureAwait(false);
|
||||
IReadOnlyList<PriceGridRow> rows =
|
||||
[
|
||||
.. page.Items.Select(i => new PriceGridRow(
|
||||
i.Id, i.Code, i.Description, i.UnitOfMeasureId, costs ? i.AverageCost ?? i.StandardCost : null,
|
||||
columns.ToDictionary(c => c.Id, c => book.ListPrice(i.Id, c.Id, date)),
|
||||
partyId is { } party ? book.NetPrice(i.Id, party, date) is { } net ? new PriceCell(net.Price, false, net.ValidFrom) : PriceCell.Empty : null)),
|
||||
];
|
||||
return new PriceGrid(columns, new ListPage<PriceGridRow>(rows, page.TotalCount, new Dictionary<string, decimal>()));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Computes a mass update without saving it: for every item with a price in the source list at the date, the new
|
||||
/// price of the list, changed by the percent and rounded. The screen shows them highlighted until saved.
|
||||
/// </summary>
|
||||
/// <param name="actor">Who asks.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="update">The update.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The prices to write; unchanged ones are left out.</returns>
|
||||
/// <exception cref="ValidationFailedException">When the lists are unknown or the step negative.</exception>
|
||||
public async Task<IReadOnlyList<PriceEdit>> PreviewAsync(Actor actor, string companyCode, BulkUpdate update, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(update);
|
||||
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, ItemService.WritePermission, cancellationToken).ConfigureAwait(false);
|
||||
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
||||
var lists = uow.Repository<PriceList, long>();
|
||||
var source = update.SourcePriceListId ?? update.PriceListId;
|
||||
if (await lists.GetAsync(update.PriceListId, cancellationToken).ConfigureAwait(false) is null || await lists.GetAsync(source, cancellationToken).ConfigureAwait(false) is null)
|
||||
{
|
||||
throw new ValidationFailedException([nameof(BulkUpdate.PriceListId) + ":" + ListUnknown]);
|
||||
}
|
||||
|
||||
if (update.RoundingStep < 0)
|
||||
{
|
||||
throw new ValidationFailedException([nameof(BulkUpdate.RoundingStep) + ":" + TableCatalog.NumberRange]);
|
||||
}
|
||||
|
||||
var select = Query.For<Item>().Where(i => !i.Disabled && i.Kind != ItemKind.Text);
|
||||
if (update.CategoryId is { } category)
|
||||
{
|
||||
select = select.Where(i => i.CategoryId == category);
|
||||
}
|
||||
|
||||
var items = (await uow.Repository<Item, long>().ListAsync(select, cancellationToken).ConfigureAwait(false)).Items;
|
||||
if (update.ItemIds is { } wanted)
|
||||
{
|
||||
var only = wanted.ToHashSet();
|
||||
items = [.. items.Where(i => only.Contains(i.Id))];
|
||||
}
|
||||
|
||||
var book = await ItemService.BookAsync(uow, [.. items.Select(i => i.Id)], cancellationToken).ConfigureAwait(false);
|
||||
var edits = new List<PriceEdit>();
|
||||
foreach (var item in items.OrderBy(i => i.Code, StringComparer.Ordinal))
|
||||
{
|
||||
if (book.ListPrice(item.Id, source, update.Date).Price is not { } from)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var price = PriceRounding.Round(PriceRounding.Change(from, update.Percent), update.RoundingStep, update.Direction);
|
||||
if (book.ListPrice(item.Id, update.PriceListId, update.Date).Price != price)
|
||||
{
|
||||
edits.Add(new PriceEdit(item.Id, update.PriceListId, null, price, update.Date));
|
||||
}
|
||||
}
|
||||
|
||||
return edits;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Writes prices: a row of the same list or customer and day is changed (or removed when the price is none), else a
|
||||
/// new row starts that day, so the prices before it stay for older documents. A price equal to the one in effect is
|
||||
/// not written again. Every change goes in the history of the item.
|
||||
/// </summary>
|
||||
/// <param name="actor">Who saves.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="edits">The prices.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>How many rows were written or removed.</returns>
|
||||
/// <exception cref="ValidationFailedException">With the errors (<c>index:code</c>).</exception>
|
||||
public async Task<int> SaveAsync(Actor actor, string companyCode, IReadOnlyList<PriceEdit> edits, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(edits);
|
||||
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, ItemService.WritePermission, cancellationToken).ConfigureAwait(false);
|
||||
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
||||
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
|
||||
var problems = new List<string>();
|
||||
var parties = uow.Repository<Party, long>();
|
||||
for (var i = 0; i < edits.Count; i++)
|
||||
{
|
||||
var edit = edits[i];
|
||||
if ((edit.PriceListId is null) == (edit.PartyId is null))
|
||||
{
|
||||
problems.Add(i + ":" + ItemService.PriceTarget);
|
||||
}
|
||||
else if (edit.PartyId is { } partyId && await parties.GetAsync(partyId, cancellationToken).ConfigureAwait(false) is not { IsCustomer: true })
|
||||
{
|
||||
problems.Add(i + ":" + ItemService.PriceParty);
|
||||
}
|
||||
|
||||
if (edit.Price < 0)
|
||||
{
|
||||
problems.Add(i + ":" + NotNegative);
|
||||
}
|
||||
}
|
||||
|
||||
if (problems.Count > 0)
|
||||
{
|
||||
throw new ValidationFailedException(problems);
|
||||
}
|
||||
|
||||
var prices = uow.Repository<ItemPrice, long>();
|
||||
var written = 0;
|
||||
foreach (var group in edits.GroupBy(e => e.ItemId))
|
||||
{
|
||||
var itemId = group.Key;
|
||||
var rows = (await prices.ListAsync(Query.For<ItemPrice>().Where(p => p.ItemId == itemId), cancellationToken).ConfigureAwait(false)).Items.ToList();
|
||||
foreach (var edit in group)
|
||||
{
|
||||
var same = rows.Where(r => r.PriceListId == edit.PriceListId && r.PartyId == edit.PartyId).ToList();
|
||||
var day = same.FirstOrDefault(r => r.ValidFrom == edit.ValidFrom);
|
||||
if (edit.Price is not { } price)
|
||||
{
|
||||
if (day is not null)
|
||||
{
|
||||
await prices.DeleteAsync(day.Id, cancellationToken).ConfigureAwait(false);
|
||||
await _audit.RecordAsync(uow, AuditAction.Delete, itemId, day, null, actor.UserName, cancellationToken).ConfigureAwait(false);
|
||||
rows.Remove(day);
|
||||
written++;
|
||||
}
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if (day is not null)
|
||||
{
|
||||
if (day.Price != price)
|
||||
{
|
||||
var before = Copy(day);
|
||||
day.Price = price;
|
||||
await prices.UpdateAsync(day, cancellationToken).ConfigureAwait(false);
|
||||
await _audit.RecordAsync(uow, AuditAction.Update, itemId, before, day, actor.UserName, cancellationToken).ConfigureAwait(false);
|
||||
written++;
|
||||
}
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if (edit.ValidFrom is { } from && PriceBook.At(same, from) is { } current && current.Price == price)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var row = new ItemPrice { ItemId = itemId, PriceListId = edit.PriceListId, PartyId = edit.PartyId, Price = price, ValidFrom = edit.ValidFrom };
|
||||
row.Id = await prices.InsertAsync(row, cancellationToken).ConfigureAwait(false);
|
||||
await _audit.RecordAsync<ItemPrice>(uow, AuditAction.Insert, itemId, null, row, actor.UserName, cancellationToken).ConfigureAwait(false);
|
||||
rows.Add(row);
|
||||
written++;
|
||||
}
|
||||
}
|
||||
|
||||
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
|
||||
return written;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The price and the discounts proposed for an item on a document (SPEC §11.3): net price of the party, then the
|
||||
/// list given or the one of the party, then the base list, then the item; the discounts of the party unless net.
|
||||
/// </summary>
|
||||
/// <param name="actor">Who asks.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="itemId">The item.</param>
|
||||
/// <param name="partyId">The party of the document.</param>
|
||||
/// <param name="priceListId">The list of the document; none: the one of the party.</param>
|
||||
/// <param name="date">The date of the document.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The price and the discounts.</returns>
|
||||
public async Task<(PriceQuote Price, DiscountQuote Discounts)> QuoteAsync(
|
||||
Actor actor, string companyCode, long itemId, long? partyId, long? priceListId, DateOnly date, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, ItemService.ReadPermission, cancellationToken).ConfigureAwait(false);
|
||||
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
||||
return await QuoteAsync(uow, itemId, partyId, priceListId, date, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>The price and the discounts of a line, inside the unit of work of a document.</summary>
|
||||
/// <param name="uow">The unit of work of the company.</param>
|
||||
/// <param name="itemId">The item.</param>
|
||||
/// <param name="partyId">The party of the document.</param>
|
||||
/// <param name="priceListId">The list of the document; none: the one of the party.</param>
|
||||
/// <param name="date">The date of the document.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The price and the discounts.</returns>
|
||||
public static async Task<(PriceQuote Price, DiscountQuote Discounts)> QuoteAsync(
|
||||
IUnitOfWork uow, long itemId, long? partyId, long? priceListId, DateOnly date, CancellationToken cancellationToken)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(uow);
|
||||
var item = await uow.Repository<Item, long>().GetAsync(itemId, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(ItemService.NotFound);
|
||||
var terms = partyId is { } party
|
||||
? await uow.Repository<PartySalesTerms, long>().FindAsync(Query.For<PartySalesTerms>().Where(t => t.PartyId == party), cancellationToken).ConfigureAwait(false)
|
||||
: null;
|
||||
var book = await ItemService.BookAsync(uow, [itemId], cancellationToken).ConfigureAwait(false);
|
||||
var price = book.Quote(item, partyId, priceListId ?? terms?.PriceListId, date);
|
||||
return (price, PriceBook.Discounts(price, terms));
|
||||
}
|
||||
|
||||
private static async Task<IReadOnlyList<PriceListColumn>> ColumnsAsync(IUnitOfWork uow, CancellationToken cancellationToken)
|
||||
{
|
||||
var lists = (await uow.Repository<PriceList, long>().ListAsync(Query.For<PriceList>().Where(l => !l.Disabled), cancellationToken).ConfigureAwait(false)).Items;
|
||||
var baseList = PriceBook.BaseOf(lists);
|
||||
return
|
||||
[
|
||||
.. lists.OrderBy(l => l.Id == baseList?.Id ? 0 : 1).ThenBy(l => l.Code, StringComparer.Ordinal)
|
||||
.Select(l => new PriceListColumn(l.Id, l.Code, l.Description, l.Id == baseList?.Id, l.BasePriceListId is not null, l.VatIncluded)),
|
||||
];
|
||||
}
|
||||
|
||||
private static ItemPrice Copy(ItemPrice price) => new()
|
||||
{
|
||||
Id = price.Id, ItemId = price.ItemId, PriceListId = price.PriceListId, PartyId = price.PartyId, Price = price.Price, ValidFrom = price.ValidFrom,
|
||||
};
|
||||
}
|
||||
@@ -39,7 +39,8 @@ public interface IScheduledJob
|
||||
/// <param name="JobType">The job type.</param>
|
||||
/// <param name="Cron">When it runs.</param>
|
||||
/// <param name="TimeoutSeconds">Its timeout.</param>
|
||||
public sealed record SystemTaskDefinition(string Code, string Name, string JobType, string Cron, int TimeoutSeconds = 600);
|
||||
/// <param name="UsesNetwork">Whether it calls services outside the instance (the tests run it with a stub).</param>
|
||||
public sealed record SystemTaskDefinition(string Code, string Name, string JobType, string Cron, int TimeoutSeconds = 600, bool UsesNetwork = false);
|
||||
|
||||
/// <summary>
|
||||
/// The scheduler (SPEC §9.4; mockup 083): reads <c>sys_scheduled_tasks</c>, runs the due ones with a lock in
|
||||
@@ -49,13 +50,14 @@ public sealed record SystemTaskDefinition(string Code, string Name, string JobTy
|
||||
/// </summary>
|
||||
public sealed class JobScheduler
|
||||
{
|
||||
/// <summary>The system tasks (M2, attachments trash from M3).</summary>
|
||||
/// <summary>The system tasks (M2, attachments trash from M3, ECB rates from M4).</summary>
|
||||
public static readonly IReadOnlyList<SystemTaskDefinition> SystemTasks =
|
||||
[
|
||||
new("system.sessions-cleanup", "Pulizia sessioni scadute", SessionCleanupJob.JobType, "15 * * * *", 300),
|
||||
new("system.license-check", "Verifica licenza", LicenseCheckJob.JobType, "0 * * * *", 120),
|
||||
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),
|
||||
];
|
||||
|
||||
private readonly IUnitOfWorkFactory _factory;
|
||||
|
||||
@@ -9,6 +9,11 @@
|
||||
<FrameworkReference Include="Microsoft.AspNetCore.App" />
|
||||
</ItemGroup>
|
||||
|
||||
<!-- Base data shipped with the code (SPEC §14). -->
|
||||
<ItemGroup>
|
||||
<EmbeddedResource Include="Seeding/Data/*.csv" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="../Khaemhat.Core/Khaemhat.Core.csproj" />
|
||||
<ProjectReference Include="../Khaemhat.Data/Khaemhat.Data.csproj" />
|
||||
|
||||
@@ -0,0 +1,265 @@
|
||||
using Khaemhat.Application.Modules;
|
||||
using Khaemhat.Application.Tables;
|
||||
using Khaemhat.Core.Tables;
|
||||
using Khaemhat.Data.Querying;
|
||||
using Khaemhat.Fiscal.Abstractions;
|
||||
using Khaemhat.Infrastructure.Files;
|
||||
|
||||
namespace Khaemhat.Application.Seeding;
|
||||
|
||||
/// <summary>
|
||||
/// The base tables of SPEC §14 available from M4: countries, currencies, units, VAT codes (from the fiscal pack),
|
||||
/// payment methods and terms and document types (from the pack's <see cref="IBaseTablesTemplate"/>), transport tables,
|
||||
/// warehouse reasons, the main warehouse, categories, the base price list, the numerators and the fiscal year of the
|
||||
/// current year, and the provinces and municipalities of the pack's <see cref="IPlaceDirectory"/> (ADR 0028). Banks
|
||||
/// come from a dataset loaded separately (ADR 0026).
|
||||
/// </summary>
|
||||
/// <param name="years">Creates the current fiscal year.</param>
|
||||
public sealed class BaseTablesSeeder(FiscalYearService years) : ISeeder
|
||||
{
|
||||
/// <summary>The currencies of the ECB reference rates, plus the euro: code, name, symbol, decimals.</summary>
|
||||
public static readonly IReadOnlyList<(string Code, string Name, string Symbol, int Decimals)> Currencies =
|
||||
[
|
||||
("EUR", "Euro", "€", 2), ("USD", "Dollaro statunitense", "$", 2), ("GBP", "Sterlina britannica", "£", 2), ("CHF", "Franco svizzero", "CHF", 2),
|
||||
("JPY", "Yen giapponese", "¥", 0), ("CZK", "Corona ceca", "Kč", 2), ("DKK", "Corona danese", "kr", 2), ("HUF", "Fiorino ungherese", "Ft", 2),
|
||||
("PLN", "Zloty polacco", "zł", 2), ("RON", "Leu rumeno", "lei", 2), ("SEK", "Corona svedese", "kr", 2), ("ISK", "Corona islandese", "kr", 0),
|
||||
("NOK", "Corona norvegese", "kr", 2), ("TRY", "Lira turca", "₺", 2), ("AUD", "Dollaro australiano", "A$", 2), ("BRL", "Real brasiliano", "R$", 2),
|
||||
("CAD", "Dollaro canadese", "C$", 2), ("CNY", "Renminbi cinese", "¥", 2), ("HKD", "Dollaro di Hong Kong", "HK$", 2), ("IDR", "Rupia indonesiana", "Rp", 2),
|
||||
("ILS", "Nuovo siclo israeliano", "₪", 2), ("INR", "Rupia indiana", "₹", 2), ("KRW", "Won sudcoreano", "₩", 0), ("MXN", "Peso messicano", "Mex$", 2),
|
||||
("MYR", "Ringgit malese", "RM", 2), ("NZD", "Dollaro neozelandese", "NZ$", 2), ("PHP", "Peso filippino", "₱", 2), ("SGD", "Dollaro di Singapore", "S$", 2),
|
||||
("THB", "Baht thailandese", "฿", 2), ("ZAR", "Rand sudafricano", "R", 2),
|
||||
];
|
||||
|
||||
/// <summary>The numerators of the base data: code, description, family, section, format, gaps allowed.</summary>
|
||||
public static readonly IReadOnlyList<(string Code, string Description, NumeratorKind Kind, string? Section, string Format, bool Gaps)> Numerators =
|
||||
[
|
||||
("PRE", "Preventivi", NumeratorKind.Quotation, null, "PRE-{year}-{number:D4}", true),
|
||||
("ORD", "Ordini clienti", NumeratorKind.SalesOrder, null, "OC-{year}-{number:D4}", true),
|
||||
("DDT", "Documenti di trasporto", NumeratorKind.DeliveryNote, null, "{number}/{year}", true),
|
||||
("FAT", "Fatture e note di credito", NumeratorKind.SalesInvoice, null, "{number}/{year}", false),
|
||||
("AUT", "Autofatture e integrazioni", NumeratorKind.SalesInvoice, "AF", "{number}/AF/{year}", false),
|
||||
("PRF", "Pro forma", NumeratorKind.Other, null, "PF-{year}-{number:D4}", true),
|
||||
("ORF", "Ordini fornitori", NumeratorKind.PurchaseOrder, null, "OF-{year}-{number:D4}", true),
|
||||
("PRA", "Protocollo acquisti", NumeratorKind.PurchaseInvoice, null, "{number}", false),
|
||||
("MAG", "Movimenti di magazzino", NumeratorKind.Inventory, null, "MM-{year}-{number:D5}", true),
|
||||
("PN", "Registrazioni contabili", NumeratorKind.Journal, null, "{number}", false),
|
||||
];
|
||||
|
||||
/// <inheritdoc />
|
||||
public string ModuleCode => ModuleCodes.Core;
|
||||
|
||||
/// <inheritdoc />
|
||||
public SeedKind Kind => SeedKind.Base;
|
||||
|
||||
/// <inheritdoc />
|
||||
public int Order => 0;
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task RunAsync(SeedContext context, CancellationToken cancellationToken)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(context);
|
||||
await context.EnsureAsync("countries", ReadCountries(), cancellationToken).ConfigureAwait(false);
|
||||
if (context.Pack.GetFeature<IPlaceDirectory>() is { } places)
|
||||
{
|
||||
await context.EnsureAsync("provinces", places.Provinces.Select(p => new Province { Code = p.Code, Description = p.Name, Region = p.Region }), cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
await context.EnsureAsync(
|
||||
"municipalities",
|
||||
places.Municipalities.Select(m => new Municipality
|
||||
{
|
||||
Code = m.Code,
|
||||
Description = m.Name,
|
||||
ProvinceCode = m.ProvinceCode,
|
||||
Region = m.Region,
|
||||
IstatCode = m.StatisticalCode,
|
||||
PostalCodes = m.PostalCodes,
|
||||
}),
|
||||
cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
await context.EnsureAsync("currencies", Currencies.Select(c => new Currency { Code = c.Code, Description = c.Name, Symbol = c.Symbol, Decimals = c.Decimals }), cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
await context.EnsureAsync("units_of_measure", Units(), cancellationToken).ConfigureAwait(false);
|
||||
await context.EnsureAsync("tax_codes", TaxCodes(context.Pack), cancellationToken).ConfigureAwait(false);
|
||||
|
||||
var reasons = await context.EnsureAsync("inventory_reasons", InventoryReasons(), cancellationToken).ConfigureAwait(false);
|
||||
await context.EnsureAsync("warehouses", [new Warehouse { Code = "SEDE", Description = "Magazzino sede", IsDefault = true }], cancellationToken).ConfigureAwait(false);
|
||||
await context.EnsureAsync("shipping_terms", Coded<ShippingTerm>(("FRANCO", "Porto franco"), ("ASSEGNATO", "Porto assegnato"), ("ADDEBITO", "Franco con addebito in fattura")), cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
await context.EnsureAsync("transport_means", Coded<TransportMean>(("MITT", "Mittente"), ("DEST", "Destinatario"), ("VETT", "Vettore")), cancellationToken).ConfigureAwait(false);
|
||||
await context.EnsureAsync(
|
||||
"goods_appearances",
|
||||
Coded<GoodsAppearance>(("CARTONI", "Cartoni"), ("SCATOLE", "Scatole"), ("BANCALI", "Bancali"), ("COLLI", "Colli"), ("BUSTE", "Buste"), ("SFUSO", "Sfuso"), ("VISTA", "A vista")),
|
||||
cancellationToken).ConfigureAwait(false);
|
||||
await context.EnsureAsync("delivery_terms", Incoterms(), cancellationToken).ConfigureAwait(false);
|
||||
await context.EnsureAsync(
|
||||
"transport_reasons",
|
||||
Coded<TransportReason>(
|
||||
("VEN", "Vendita"), ("CV", "Conto visione"), ("CD", "Conto deposito"), ("CL", "Conto lavorazione"), ("RES", "Reso"), ("RIP", "Riparazione"),
|
||||
("OMA", "Omaggio"), ("TRA", "Trasferimento tra depositi")),
|
||||
cancellationToken).ConfigureAwait(false);
|
||||
await context.EnsureAsync("item_categories", [new ItemCategory { Code = "GEN", Description = "Generica" }], cancellationToken).ConfigureAwait(false);
|
||||
await context.EnsureAsync("party_categories", Coded<PartyCategory>(("GEN", "Generica")), cancellationToken).ConfigureAwait(false);
|
||||
await context.EnsureAsync("price_lists", [new PriceList { Code = "BASE", Description = "Listino base", IsBase = true }], cancellationToken).ConfigureAwait(false);
|
||||
|
||||
var year = context.Today.Year;
|
||||
var numerators = new Dictionary<string, DocumentNumerator>(StringComparer.Ordinal);
|
||||
foreach (var n in Numerators)
|
||||
{
|
||||
numerators[n.Code] = await context.EnsureOneAsync(
|
||||
"document_numerators",
|
||||
x => x.Code == n.Code && x.Year == year,
|
||||
new DocumentNumerator { Code = n.Code, Description = n.Description, Kind = n.Kind, Section = n.Section, Year = year, Format = n.Format, GapsAllowed = n.Gaps },
|
||||
cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
if (context.Pack.GetFeature<IBaseTablesTemplate>() is { } template)
|
||||
{
|
||||
await SeedPaymentsAsync(context, template, cancellationToken).ConfigureAwait(false);
|
||||
await context.EnsureAsync(
|
||||
"document_types",
|
||||
template.DocumentTypes.Select(d => new DocumentType
|
||||
{
|
||||
Code = d.Code,
|
||||
Description = d.Description,
|
||||
Kind = d.Kind,
|
||||
NumeratorId = d.NumeratorCode is { } n && numerators.TryGetValue(n, out var numerator) ? numerator.Id : null,
|
||||
InventoryReasonId = d.InventoryReasonCode is { } r && reasons.TryGetValue(r, out var reason) ? reason.Id : null,
|
||||
EInvoiceType = d.EInvoiceType,
|
||||
}),
|
||||
cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
var calendar = await context.UnitOfWork.Repository<FiscalYear, long>()
|
||||
.CountAsync(Query.For<FiscalYear>().Where(y => y.StartDate <= context.Today && y.EndDate >= context.Today), cancellationToken).ConfigureAwait(false);
|
||||
if (calendar == 0 && await context.UnitOfWork.Repository<FiscalYear, long>().CountAsync(Query.For<FiscalYear>(), cancellationToken).ConfigureAwait(false) == 0)
|
||||
{
|
||||
await years.CreateAsync(context.UnitOfWork, context.Today, "system", cancellationToken).ConfigureAwait(false);
|
||||
context.Count("fiscal_years");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The countries of the embedded list (ISO 3166-1, Italian names, EU members, currency).</summary>
|
||||
/// <returns>The rows.</returns>
|
||||
public static IReadOnlyList<Country> ReadCountries()
|
||||
{
|
||||
using var stream = typeof(BaseTablesSeeder).Assembly.GetManifestResourceStream("Khaemhat.Application.Seeding.Data.countries.csv")
|
||||
?? throw new InvalidOperationException("The country list is missing from the assembly.");
|
||||
using var reader = new StreamReader(stream);
|
||||
var lines = CsvReader.Parse(reader.ReadToEnd(), ';');
|
||||
return
|
||||
[
|
||||
.. lines.Skip(1).Select(l => new Country
|
||||
{
|
||||
Code = l[0],
|
||||
Iso3 = l[1].Length == 0 ? null : l[1],
|
||||
Description = l[2],
|
||||
EuMember = l[3] == "1",
|
||||
CurrencyCode = l[4].Length == 0 ? null : l[4],
|
||||
|
||||
// Greece uses EL in VAT numbers and VIES.
|
||||
VatPrefix = l[0] == "GR" ? "EL" : null,
|
||||
}),
|
||||
];
|
||||
}
|
||||
|
||||
private static async Task SeedPaymentsAsync(SeedContext context, IBaseTablesTemplate template, CancellationToken cancellationToken)
|
||||
{
|
||||
var methods = await context.EnsureAsync(
|
||||
"payment_methods",
|
||||
template.PaymentMethods.Select(m => new PaymentMethod { Code = m.Code, Description = m.Description, EInvoiceCode = m.EInvoiceCode, NeedsBank = m.NeedsBank }),
|
||||
cancellationToken).ConfigureAwait(false);
|
||||
var existing = (await context.UnitOfWork.Repository<PaymentTerm, long>().ListAsync(Query.For<PaymentTerm>(), cancellationToken).ConfigureAwait(false)).Items
|
||||
.Select(t => t.Code)
|
||||
.ToHashSet(StringComparer.OrdinalIgnoreCase);
|
||||
var lines = context.UnitOfWork.Repository<PaymentTermLine, long>();
|
||||
foreach (var t in template.PaymentTerms.Where(t => !existing.Contains(t.Code)))
|
||||
{
|
||||
var terms = await context.EnsureOneAsync(
|
||||
"payment_terms",
|
||||
x => x.Code == t.Code,
|
||||
new PaymentTerm
|
||||
{
|
||||
Code = t.Code,
|
||||
Description = t.Description,
|
||||
Condition = t.Condition,
|
||||
PaymentMethodId = methods.TryGetValue(t.PaymentMethodCode, out var method) ? method.Id : null,
|
||||
},
|
||||
cancellationToken).ConfigureAwait(false);
|
||||
var number = 1;
|
||||
foreach (var i in t.Installments)
|
||||
{
|
||||
await lines.InsertAsync(new PaymentTermLine { PaymentTermId = terms.Id, Number = number++, Days = i.Days, EndOfMonth = i.EndOfMonth, Percent = i.Percent }, cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static IEnumerable<TaxCode> TaxCodes(IFiscalPack pack) =>
|
||||
pack.TaxCodes.BaseCodes.Select(c => new TaxCode
|
||||
{
|
||||
Code = c.Code,
|
||||
Description = c.Description,
|
||||
Rate = c.Rate,
|
||||
Nature = c.Nature,
|
||||
Exigibility = c.Exigibility,
|
||||
NonDeductiblePercent = c.NonDeductiblePercent,
|
||||
LegalReference = c.LegalReference,
|
||||
Kind = pack.TaxCodes.KindOf(c.Rate, c.Nature),
|
||||
});
|
||||
|
||||
private static IEnumerable<UnitOfMeasure> Units() =>
|
||||
[
|
||||
new() { Code = "NR", Description = "Numero", Decimals = 0 },
|
||||
new() { Code = "PZ", Description = "Pezzi", Decimals = 0 },
|
||||
new() { Code = "CF", Description = "Confezioni", Decimals = 0 },
|
||||
new() { Code = "CT", Description = "Cartoni", Decimals = 0 },
|
||||
new() { Code = "PAL", Description = "Pallet", Decimals = 0 },
|
||||
new() { Code = "KG", Description = "Chilogrammi", Decimals = 3 },
|
||||
new() { Code = "G", Description = "Grammi", Decimals = 0 },
|
||||
new() { Code = "T", Description = "Tonnellate", Decimals = 3 },
|
||||
new() { Code = "L", Description = "Litri", Decimals = 3 },
|
||||
new() { Code = "M", Description = "Metri", Decimals = 3 },
|
||||
new() { Code = "M2", Description = "Metri quadrati", Decimals = 3 },
|
||||
new() { Code = "M3", Description = "Metri cubi", Decimals = 3 },
|
||||
new() { Code = "KM", Description = "Chilometri", Decimals = 2 },
|
||||
new() { Code = "KWH", Description = "Kilowattora", Decimals = 3 },
|
||||
new() { Code = "ORE", Description = "Ore", Decimals = 2 },
|
||||
new() { Code = "GG", Description = "Giorni", Decimals = 2 },
|
||||
new() { Code = "MESI", Description = "Mesi", Decimals = 0 },
|
||||
new() { Code = "SERV", Description = "Servizio", Decimals = 0 },
|
||||
];
|
||||
|
||||
private static IEnumerable<InventoryReason> InventoryReasons() =>
|
||||
[
|
||||
new() { Code = "CAR", Description = "Carico da acquisto", Effect = StockEffect.Load },
|
||||
new() { Code = "SCA", Description = "Scarico per vendita", Effect = StockEffect.Unload },
|
||||
new() { Code = "RESC", Description = "Reso da cliente", Effect = StockEffect.Load },
|
||||
new() { Code = "RESF", Description = "Reso a fornitore", Effect = StockEffect.Unload },
|
||||
new() { Code = "TRA", Description = "Trasferimento tra depositi", Effect = StockEffect.None, AffectsValue = false, IsTransfer = true },
|
||||
new() { Code = "INVP", Description = "Rettifica inventariale in aumento", Effect = StockEffect.Load },
|
||||
new() { Code = "INVN", Description = "Rettifica inventariale in diminuzione", Effect = StockEffect.Unload },
|
||||
new() { Code = "CVU", Description = "Uscita in conto visione", Effect = StockEffect.Unload, AffectsValue = false },
|
||||
new() { Code = "CVR", Description = "Rientro da conto visione", Effect = StockEffect.Load, AffectsValue = false },
|
||||
new() { Code = "OMA", Description = "Omaggio", Effect = StockEffect.Unload },
|
||||
new() { Code = "AUTO", Description = "Autoconsumo", Effect = StockEffect.Unload },
|
||||
new() { Code = "APE", Description = "Esistenza iniziale", Effect = StockEffect.Load },
|
||||
];
|
||||
|
||||
private static IEnumerable<DeliveryTerm> Incoterms() => Coded<DeliveryTerm>(
|
||||
("EXW", "Franco fabbrica (Ex Works)"),
|
||||
("FCA", "Franco vettore (Free Carrier)"),
|
||||
("CPT", "Trasporto pagato fino a (Carriage Paid To)"),
|
||||
("CIP", "Trasporto e assicurazione pagati fino a (Carriage and Insurance Paid To)"),
|
||||
("DAP", "Reso al luogo di destinazione (Delivered at Place)"),
|
||||
("DPU", "Reso al luogo di destinazione scaricato (Delivered at Place Unloaded)"),
|
||||
("DDP", "Reso sdoganato (Delivered Duty Paid)"),
|
||||
("FAS", "Franco lungo bordo (Free Alongside Ship)"),
|
||||
("FOB", "Franco a bordo (Free On Board)"),
|
||||
("CFR", "Costo e nolo (Cost and Freight)"),
|
||||
("CIF", "Costo, assicurazione e nolo (Cost, Insurance and Freight)"));
|
||||
|
||||
private static IEnumerable<T> Coded<T>(params (string Code, string Description)[] rows)
|
||||
where T : CodedEntity, new() =>
|
||||
rows.Select(r => new T { Code = r.Code, Description = r.Description });
|
||||
}
|
||||
@@ -0,0 +1,252 @@
|
||||
code;iso3;name;eu;currency
|
||||
AD;AND;Andorra;0;EUR
|
||||
AE;ARE;Emirati Arabi Uniti;0;AED
|
||||
AF;AFG;Afghanistan;0;AFN
|
||||
AG;ATG;Antigua e Barbuda;0;XCD
|
||||
AI;AIA;Anguilla;0;XCD
|
||||
AL;ALB;Albania;0;ALL
|
||||
AM;ARM;Armenia;0;AMD
|
||||
AO;AGO;Angola;0;AOA
|
||||
AQ;ATA;Antartide;0;
|
||||
AR;ARG;Argentina;0;ARS
|
||||
AS;ASM;Samoa americane;0;USD
|
||||
AT;AUT;Austria;1;EUR
|
||||
AU;AUS;Australia;0;AUD
|
||||
AW;ABW;Aruba;0;AWG
|
||||
AX;ALA;Isole Åland;0;EUR
|
||||
AZ;AZE;Azerbaigian;0;AZN
|
||||
BA;BIH;Bosnia ed Erzegovina;0;BAM
|
||||
BB;BRB;Barbados;0;BBD
|
||||
BD;BGD;Bangladesh;0;BDT
|
||||
BE;BEL;Belgio;1;EUR
|
||||
BF;BFA;Burkina Faso;0;XOF
|
||||
BG;BGR;Bulgaria;1;EUR
|
||||
BH;BHR;Bahrein;0;BHD
|
||||
BI;BDI;Burundi;0;BIF
|
||||
BJ;BEN;Benin;0;XOF
|
||||
BL;BLM;Saint-Barthélemy;0;EUR
|
||||
BM;BMU;Bermuda;0;BMD
|
||||
BN;BRN;Brunei;0;BND
|
||||
BO;BOL;Bolivia;0;BOB
|
||||
BQ;BES;Caraibi olandesi;0;USD
|
||||
BR;BRA;Brasile;0;BRL
|
||||
BS;BHS;Bahamas;0;BSD
|
||||
BT;BTN;Bhutan;0;BTN
|
||||
BV;BVT;Isola Bouvet;0;NOK
|
||||
BW;BWA;Botswana;0;BWP
|
||||
BY;BLR;Bielorussia;0;BYN
|
||||
BZ;BLZ;Belize;0;BZD
|
||||
CA;CAN;Canada;0;CAD
|
||||
CC;CCK;Isole Cocos (Keeling);0;AUD
|
||||
CD;COD;Repubblica Democratica del Congo;0;CDF
|
||||
CF;CAF;Repubblica Centrafricana;0;XAF
|
||||
CG;COG;Repubblica del Congo;0;XAF
|
||||
CH;CHE;Svizzera;0;CHF
|
||||
CI;CIV;Costa d'Avorio;0;XOF
|
||||
CK;COK;Isole Cook;0;NZD
|
||||
CL;CHL;Cile;0;CLP
|
||||
CM;CMR;Camerun;0;XAF
|
||||
CN;CHN;Cina;0;CNY
|
||||
CO;COL;Colombia;0;COP
|
||||
CR;CRI;Costa Rica;0;CRC
|
||||
CU;CUB;Cuba;0;CUP
|
||||
CV;CPV;Capo Verde;0;CVE
|
||||
CW;CUW;Curaçao;0;XCG
|
||||
CX;CXR;Isola di Natale;0;AUD
|
||||
CY;CYP;Cipro;1;EUR
|
||||
CZ;CZE;Cechia;1;CZK
|
||||
DE;DEU;Germania;1;EUR
|
||||
DJ;DJI;Gibuti;0;DJF
|
||||
DK;DNK;Danimarca;1;DKK
|
||||
DM;DMA;Dominica;0;XCD
|
||||
DO;DOM;Repubblica Dominicana;0;DOP
|
||||
DZ;DZA;Algeria;0;DZD
|
||||
EC;ECU;Ecuador;0;USD
|
||||
EE;EST;Estonia;1;EUR
|
||||
EG;EGY;Egitto;0;EGP
|
||||
EH;ESH;Sahara Occidentale;0;MAD
|
||||
ER;ERI;Eritrea;0;ERN
|
||||
ES;ESP;Spagna;1;EUR
|
||||
ET;ETH;Etiopia;0;ETB
|
||||
FI;FIN;Finlandia;1;EUR
|
||||
FJ;FJI;Figi;0;FJD
|
||||
FK;FLK;Isole Falkland;0;FKP
|
||||
FM;FSM;Micronesia;0;USD
|
||||
FO;FRO;Isole Fær Øer;0;DKK
|
||||
FR;FRA;Francia;1;EUR
|
||||
GA;GAB;Gabon;0;XAF
|
||||
GB;GBR;Regno Unito;0;GBP
|
||||
GD;GRD;Grenada;0;XCD
|
||||
GE;GEO;Georgia;0;GEL
|
||||
GF;GUF;Guyana francese;0;EUR
|
||||
GG;GGY;Guernsey;0;GBP
|
||||
GH;GHA;Ghana;0;GHS
|
||||
GI;GIB;Gibilterra;0;GIP
|
||||
GL;GRL;Groenlandia;0;DKK
|
||||
GM;GMB;Gambia;0;GMD
|
||||
GN;GIN;Guinea;0;GNF
|
||||
GP;GLP;Guadalupa;0;EUR
|
||||
GQ;GNQ;Guinea Equatoriale;0;XAF
|
||||
GR;GRC;Grecia;1;EUR
|
||||
GS;SGS;Georgia del Sud e isole Sandwich australi;0;GBP
|
||||
GT;GTM;Guatemala;0;GTQ
|
||||
GU;GUM;Guam;0;USD
|
||||
GW;GNB;Guinea-Bissau;0;XOF
|
||||
GY;GUY;Guyana;0;GYD
|
||||
HK;HKG;Hong Kong;0;HKD
|
||||
HM;HMD;Isole Heard e McDonald;0;AUD
|
||||
HN;HND;Honduras;0;HNL
|
||||
HR;HRV;Croazia;1;EUR
|
||||
HT;HTI;Haiti;0;HTG
|
||||
HU;HUN;Ungheria;1;HUF
|
||||
ID;IDN;Indonesia;0;IDR
|
||||
IE;IRL;Irlanda;1;EUR
|
||||
IL;ISR;Israele;0;ILS
|
||||
IM;IMN;Isola di Man;0;GBP
|
||||
IN;IND;India;0;INR
|
||||
IO;IOT;Territorio britannico dell'Oceano Indiano;0;USD
|
||||
IQ;IRQ;Iraq;0;IQD
|
||||
IR;IRN;Iran;0;IRR
|
||||
IS;ISL;Islanda;0;ISK
|
||||
IT;ITA;Italia;1;EUR
|
||||
JE;JEY;Jersey;0;GBP
|
||||
JM;JAM;Giamaica;0;JMD
|
||||
JO;JOR;Giordania;0;JOD
|
||||
JP;JPN;Giappone;0;JPY
|
||||
KE;KEN;Kenya;0;KES
|
||||
KG;KGZ;Kirghizistan;0;KGS
|
||||
KH;KHM;Cambogia;0;KHR
|
||||
KI;KIR;Kiribati;0;AUD
|
||||
KM;COM;Comore;0;KMF
|
||||
KN;KNA;Saint Kitts e Nevis;0;XCD
|
||||
KP;PRK;Corea del Nord;0;KPW
|
||||
KR;KOR;Corea del Sud;0;KRW
|
||||
KW;KWT;Kuwait;0;KWD
|
||||
KY;CYM;Isole Cayman;0;KYD
|
||||
KZ;KAZ;Kazakistan;0;KZT
|
||||
LA;LAO;Laos;0;LAK
|
||||
LB;LBN;Libano;0;LBP
|
||||
LC;LCA;Santa Lucia;0;XCD
|
||||
LI;LIE;Liechtenstein;0;CHF
|
||||
LK;LKA;Sri Lanka;0;LKR
|
||||
LR;LBR;Liberia;0;LRD
|
||||
LS;LSO;Lesotho;0;LSL
|
||||
LT;LTU;Lituania;1;EUR
|
||||
LU;LUX;Lussemburgo;1;EUR
|
||||
LV;LVA;Lettonia;1;EUR
|
||||
LY;LBY;Libia;0;LYD
|
||||
MA;MAR;Marocco;0;MAD
|
||||
MC;MCO;Monaco;0;EUR
|
||||
MD;MDA;Moldavia;0;MDL
|
||||
ME;MNE;Montenegro;0;EUR
|
||||
MF;MAF;Saint-Martin;0;EUR
|
||||
MG;MDG;Madagascar;0;MGA
|
||||
MH;MHL;Isole Marshall;0;USD
|
||||
MK;MKD;Macedonia del Nord;0;MKD
|
||||
ML;MLI;Mali;0;XOF
|
||||
MM;MMR;Myanmar;0;MMK
|
||||
MN;MNG;Mongolia;0;MNT
|
||||
MO;MAC;Macao;0;MOP
|
||||
MP;MNP;Isole Marianne Settentrionali;0;USD
|
||||
MQ;MTQ;Martinica;0;EUR
|
||||
MR;MRT;Mauritania;0;MRU
|
||||
MS;MSR;Montserrat;0;XCD
|
||||
MT;MLT;Malta;1;EUR
|
||||
MU;MUS;Mauritius;0;MUR
|
||||
MV;MDV;Maldive;0;MVR
|
||||
MW;MWI;Malawi;0;MWK
|
||||
MX;MEX;Messico;0;MXN
|
||||
MY;MYS;Malaysia;0;MYR
|
||||
MZ;MOZ;Mozambico;0;MZN
|
||||
NA;NAM;Namibia;0;NAD
|
||||
NC;NCL;Nuova Caledonia;0;XPF
|
||||
NE;NER;Niger;0;XOF
|
||||
NF;NFK;Isola Norfolk;0;AUD
|
||||
NG;NGA;Nigeria;0;NGN
|
||||
NI;NIC;Nicaragua;0;NIO
|
||||
NL;NLD;Paesi Bassi;1;EUR
|
||||
NO;NOR;Norvegia;0;NOK
|
||||
NP;NPL;Nepal;0;NPR
|
||||
NR;NRU;Nauru;0;AUD
|
||||
NU;NIU;Niue;0;NZD
|
||||
NZ;NZL;Nuova Zelanda;0;NZD
|
||||
OM;OMN;Oman;0;OMR
|
||||
PA;PAN;Panama;0;PAB
|
||||
PE;PER;Perù;0;PEN
|
||||
PF;PYF;Polinesia francese;0;XPF
|
||||
PG;PNG;Papua Nuova Guinea;0;PGK
|
||||
PH;PHL;Filippine;0;PHP
|
||||
PK;PAK;Pakistan;0;PKR
|
||||
PL;POL;Polonia;1;PLN
|
||||
PM;SPM;Saint-Pierre e Miquelon;0;EUR
|
||||
PN;PCN;Isole Pitcairn;0;NZD
|
||||
PR;PRI;Porto Rico;0;USD
|
||||
PS;PSE;Palestina;0;ILS
|
||||
PT;PRT;Portogallo;1;EUR
|
||||
PW;PLW;Palau;0;USD
|
||||
PY;PRY;Paraguay;0;PYG
|
||||
QA;QAT;Qatar;0;QAR
|
||||
RE;REU;Riunione;0;EUR
|
||||
RO;ROU;Romania;1;RON
|
||||
RS;SRB;Serbia;0;RSD
|
||||
RU;RUS;Russia;0;RUB
|
||||
RW;RWA;Ruanda;0;RWF
|
||||
SA;SAU;Arabia Saudita;0;SAR
|
||||
SB;SLB;Isole Salomone;0;SBD
|
||||
SC;SYC;Seychelles;0;SCR
|
||||
SD;SDN;Sudan;0;SDG
|
||||
SE;SWE;Svezia;1;SEK
|
||||
SG;SGP;Singapore;0;SGD
|
||||
SH;SHN;Sant'Elena, Ascensione e Tristan da Cunha;0;SHP
|
||||
SI;SVN;Slovenia;1;EUR
|
||||
SJ;SJM;Svalbard e Jan Mayen;0;NOK
|
||||
SK;SVK;Slovacchia;1;EUR
|
||||
SL;SLE;Sierra Leone;0;SLE
|
||||
SM;SMR;San Marino;0;EUR
|
||||
SN;SEN;Senegal;0;XOF
|
||||
SO;SOM;Somalia;0;SOS
|
||||
SR;SUR;Suriname;0;SRD
|
||||
SS;SSD;Sudan del Sud;0;SSP
|
||||
ST;STP;São Tomé e Príncipe;0;STN
|
||||
SV;SLV;El Salvador;0;USD
|
||||
SX;SXM;Sint Maarten;0;XCG
|
||||
SY;SYR;Siria;0;SYP
|
||||
SZ;SWZ;Eswatini;0;SZL
|
||||
TC;TCA;Isole Turks e Caicos;0;USD
|
||||
TD;TCD;Ciad;0;XAF
|
||||
TF;ATF;Terre australi e antartiche francesi;0;EUR
|
||||
TG;TGO;Togo;0;XOF
|
||||
TH;THA;Thailandia;0;THB
|
||||
TJ;TJK;Tagikistan;0;TJS
|
||||
TK;TKL;Tokelau;0;NZD
|
||||
TL;TLS;Timor Est;0;USD
|
||||
TM;TKM;Turkmenistan;0;TMT
|
||||
TN;TUN;Tunisia;0;TND
|
||||
TO;TON;Tonga;0;TOP
|
||||
TR;TUR;Turchia;0;TRY
|
||||
TT;TTO;Trinidad e Tobago;0;TTD
|
||||
TV;TUV;Tuvalu;0;AUD
|
||||
TW;TWN;Taiwan;0;TWD
|
||||
TZ;TZA;Tanzania;0;TZS
|
||||
UA;UKR;Ucraina;0;UAH
|
||||
UG;UGA;Uganda;0;UGX
|
||||
UM;UMI;Isole minori esterne degli Stati Uniti;0;USD
|
||||
US;USA;Stati Uniti;0;USD
|
||||
UY;URY;Uruguay;0;UYU
|
||||
UZ;UZB;Uzbekistan;0;UZS
|
||||
VA;VAT;Città del Vaticano;0;EUR
|
||||
VC;VCT;Saint Vincent e Grenadine;0;XCD
|
||||
VE;VEN;Venezuela;0;VES
|
||||
VG;VGB;Isole Vergini britanniche;0;USD
|
||||
VI;VIR;Isole Vergini americane;0;USD
|
||||
VN;VNM;Vietnam;0;VND
|
||||
VU;VUT;Vanuatu;0;VUV
|
||||
WF;WLF;Wallis e Futuna;0;XPF
|
||||
WS;WSM;Samoa;0;WST
|
||||
XI;;Irlanda del Nord (IVA);1;GBP
|
||||
XK;XKX;Kosovo;0;EUR
|
||||
YE;YEM;Yemen;0;YER
|
||||
YT;MYT;Mayotte;0;EUR
|
||||
ZA;ZAF;Sudafrica;0;ZAR
|
||||
ZM;ZMB;Zambia;0;ZMW
|
||||
ZW;ZWE;Zimbabwe;0;ZWG
|
||||
|
@@ -0,0 +1,382 @@
|
||||
using System.Globalization;
|
||||
using Khaemhat.Application.Items;
|
||||
using Khaemhat.Application.Modules;
|
||||
using Khaemhat.Application.Tables;
|
||||
using Khaemhat.Core.Items;
|
||||
using Khaemhat.Core.Parties;
|
||||
using Khaemhat.Core.Tables;
|
||||
using Khaemhat.Core.Validation;
|
||||
using Khaemhat.Data;
|
||||
using Khaemhat.Data.Querying;
|
||||
|
||||
namespace Khaemhat.Application.Seeding;
|
||||
|
||||
/// <summary>
|
||||
/// The items of the demo company (SPEC §14, issue #42): 120 items of a plumbing and heating wholesaler in ten categories
|
||||
/// (goods, services, expenses and description lines), two price lists derived from the base one (public with markup and
|
||||
/// rounding, resellers with a discount), prices with an older row for the history, the net prices and the item codes of
|
||||
/// a customer, usual suppliers, alternative units and codes, substitutes, demo costs. Names and brands are fictitious;
|
||||
/// the bar codes use the prefix 200-299, reserved for internal use, with a valid check digit. Runs only on a company
|
||||
/// without items; <c>seed --demo --scale N</c> repeats the catalogue N times. The rows are marked as demo.
|
||||
/// </summary>
|
||||
/// <param name="codes">The automatic code rules.</param>
|
||||
public sealed class DemoItemsSeeder(CodeRuleService codes) : ISeeder
|
||||
{
|
||||
/// <summary>The items of one scale.</summary>
|
||||
public const int ItemsPerScale = 120;
|
||||
|
||||
private static readonly string[] Sizes = ["1/2\"", "3/4\"", "1\"", "1 1/4\"", "1 1/2\"", "2\""];
|
||||
|
||||
/// <inheritdoc />
|
||||
public string ModuleCode => ModuleCodes.Core;
|
||||
|
||||
/// <inheritdoc />
|
||||
public SeedKind Kind => SeedKind.Demo;
|
||||
|
||||
/// <inheritdoc />
|
||||
public int Order => 20;
|
||||
|
||||
/// <summary>The catalogue of one scale, in order.</summary>
|
||||
/// <returns>The items to create.</returns>
|
||||
public static IReadOnlyList<DemoItem> Catalogue()
|
||||
{
|
||||
var items = new List<DemoItem>();
|
||||
|
||||
// Valves: ball valves with lever and butterfly handle, check valves, gate valves.
|
||||
for (var i = 0; i < Sizes.Length; i++)
|
||||
{
|
||||
items.Add(Goods("VALV", "Valvola a sfera " + Sizes[i] + " ottone cromato leva", "PZ", 12.80m + (i * 9.6m), "Idrodemo", "84818081", 0.25m + (i * 0.2m)));
|
||||
items.Add(Goods("VALV", "Valvola a sfera " + Sizes[i] + " ottone cromato farfalla", "PZ", 11.90m + (i * 9.1m), "Idrodemo", "84818081", 0.24m + (i * 0.2m)));
|
||||
items.Add(Goods("VALV", "Valvola di ritegno " + Sizes[i] + " a molla", "PZ", 9.40m + (i * 6.2m), "Idrodemo", "84813091", 0.2m + (i * 0.15m)));
|
||||
}
|
||||
|
||||
for (var i = 0; i < 4; i++)
|
||||
{
|
||||
items.Add(Goods("VALV", "Saracinesca " + Sizes[i] + " ottone", "PZ", 14.50m + (i * 8.3m), "Idrodemo", "84818081", 0.4m + (i * 0.25m)));
|
||||
}
|
||||
|
||||
items.Add(Goods("VALV", "Valvola miscelatrice termostatica 3/4\"", "PZ", 54m, "Idrodemo", "84818019", 0.7m));
|
||||
items.Add(Goods("VALV", "Riduttore di pressione 1/2\" con manometro", "PZ", 39.50m, "Idrodemo", "84811019", 0.6m));
|
||||
items.Add(Goods("VALV", "Filtro autopulente 3/4\"", "PZ", 68m, "Idrodemo", "84212100", 0.9m));
|
||||
|
||||
// Fittings: five shapes in four sizes.
|
||||
foreach (var shape in new[] { "Manicotto", "Gomito 90 gradi", "Raccordo a T", "Nipplo", "Riduzione" })
|
||||
{
|
||||
for (var i = 0; i < 4; i++)
|
||||
{
|
||||
items.Add(Goods("RACC", shape + " " + Sizes[i] + " ottone M/F", "PZ", 1.60m + (i * 1.35m) + (shape.Length / 10m), "Raccordemo", "74122000", 0.05m + (i * 0.04m)));
|
||||
}
|
||||
}
|
||||
|
||||
// Pipes: copper bars, multilayer and polyethylene rolls.
|
||||
foreach (var (diameter, price) in new[] { (12, 2.10m), (14, 2.45m), (15, 2.78m), (16, 3.05m), (18, 3.60m), (22, 4.85m) })
|
||||
{
|
||||
items.Add(Goods("TUBI", "Tubo rame " + diameter.ToString(CultureInfo.InvariantCulture) + "x1 barra 5 m", "M", price, "Ramedemo", "74111010", 0.4m));
|
||||
}
|
||||
|
||||
foreach (var (diameter, price) in new[] { (16, 1.15m), (20, 1.65m), (26, 2.70m) })
|
||||
{
|
||||
items.Add(Goods("TUBI", "Tubo multistrato " + diameter.ToString(CultureInfo.InvariantCulture) + "x2 rotolo 100 m", "M", price, "Plastidemo", "39172110", 0.15m));
|
||||
items.Add(Goods("TUBI", "Tubo polietilene PE100 " + (diameter + 9).ToString(CultureInfo.InvariantCulture) + " mm rotolo 50 m", "M", price * 0.8m, "Plastidemo", "39172110", 0.2m));
|
||||
}
|
||||
|
||||
// Heating: boilers, radiators, thermostats, manifolds, expansion vessels.
|
||||
foreach (var (kw, price) in new[] { (24, 1180m), (28, 1290m), (35, 1520m) })
|
||||
{
|
||||
items.Add(Goods("CALD", "Caldaia a condensazione " + kw.ToString(CultureInfo.InvariantCulture) + " kW", "PZ", price, "Termodemo", "84031090", 32m + kw));
|
||||
}
|
||||
|
||||
foreach (var (height, price) in new[] { (500, 9.20m), (600, 10.40m), (700, 11.60m), (800, 12.90m) })
|
||||
{
|
||||
items.Add(Goods("CALD", "Elemento radiatore alluminio interasse " + height.ToString(CultureInfo.InvariantCulture), "PZ", price, "Termodemo", "76169990", 1.2m));
|
||||
}
|
||||
|
||||
items.Add(Goods("CALD", "Termostato ambiente digitale", "PZ", 48m, "Termodemo", "90321020", 0.3m));
|
||||
items.Add(Goods("CALD", "Cronotermostato settimanale wifi", "PZ", 129m, "Termodemo", "90321020", 0.35m));
|
||||
for (var ways = 2; ways <= 5; ways++)
|
||||
{
|
||||
items.Add(Goods("CALD", "Collettore " + ways.ToString(CultureInfo.InvariantCulture) + " vie con valvole", "PZ", 58m + (ways * 23m), "Idrodemo", "84818081", 0.6m * ways));
|
||||
}
|
||||
|
||||
foreach (var (liters, price) in new[] { (8, 32m), (18, 46m), (24, 58m) })
|
||||
{
|
||||
items.Add(Goods("CALD", "Vaso di espansione " + liters.ToString(CultureInfo.InvariantCulture) + " l", "PZ", price, "Termodemo", "73110099", liters / 4m));
|
||||
}
|
||||
|
||||
// Taps and sanitary.
|
||||
foreach (var (name, price) in new[] { ("Miscelatore lavabo monocomando", 64m), ("Miscelatore bidet monocomando", 61m), ("Miscelatore doccia esterno", 72m), ("Miscelatore cucina canna alta", 89m), ("Sifone lavabo 1 1/4\"", 7.80m), ("Sifone lavello doppio", 14.50m) })
|
||||
{
|
||||
items.Add(Goods("SAN", name, "PZ", price, "Rubidemo", "84818011", 0.9m));
|
||||
}
|
||||
|
||||
foreach (var length in new[] { 30, 40, 50 })
|
||||
{
|
||||
items.Add(Goods("SAN", "Flessibile inox 1/2\" F/F " + length.ToString(CultureInfo.InvariantCulture) + " cm", "PZ", 3.10m + (length / 20m), "Rubidemo", "83071000", 0.12m));
|
||||
}
|
||||
|
||||
// Consumables.
|
||||
foreach (var (name, unit, price) in new[]
|
||||
{
|
||||
("Nastro PTFE 12 mm x 12 m", "PZ", 0.95m), ("Canapa pettinata 100 g", "PZ", 2.40m), ("Pasta sigillante 500 g", "PZ", 6.90m),
|
||||
("Silicone sanitario trasparente 280 ml", "PZ", 5.20m), ("Kit guarnizioni assortite", "CF", 9.80m), ("Collare fissatubo 1/2\" con tassello", "CF", 12.40m),
|
||||
("Tassello nylon 8 mm", "CF", 4.60m), ("Fascetta stringitubo 20-32", "CF", 7.30m), ("Saldatura stagno-rame 250 g", "PZ", 18.50m), ("Disossidante 125 ml", "PZ", 4.10m),
|
||||
})
|
||||
{
|
||||
items.Add(Goods("CONS", name, unit, price, null, null, 0.2m));
|
||||
}
|
||||
|
||||
// Pumps.
|
||||
foreach (var (name, price) in new[] { ("Circolatore elettronico 25-40", 168m), ("Circolatore elettronico 25-60", 196m), ("Circolatore elettronico 25-80", 254m), ("Pompa sommersa 0,75 kW", 312m), ("Pompa sommersa 1,1 kW", 389m), ("Pompa sommersa 1,5 kW", 465m), ("Autoclave 24 l 0,8 kW", 278m), ("Autoclave 60 l 1,1 kW", 412m) })
|
||||
{
|
||||
items.Add(Goods("POMP", name, "PZ", price, "Pompdemo", "84137035", 4.5m));
|
||||
}
|
||||
|
||||
// Tools.
|
||||
foreach (var (name, price) in new[] { ("Chiave stringitubi 14\"", 24.50m), ("Tagliatubi rame 3-35 mm", 19.80m), ("Piegatubi a molla set", 15.40m), ("Svasatubi", 28.90m), ("Cannello a gas", 32m), ("Pinza regolabile 250 mm", 16.70m), ("Seghetto per metalli", 12.30m), ("Livella 60 cm", 14.90m) })
|
||||
{
|
||||
items.Add(Goods("UTEN", name, "PZ", price, "Utendemo", "82055980", 0.6m));
|
||||
}
|
||||
|
||||
// Services, expenses and description lines: never in stock.
|
||||
items.Add(Other(ItemKind.Service, "SERV", "Manodopera idraulico", "ORE", 38m));
|
||||
items.Add(Other(ItemKind.Service, "SERV", "Manodopera apprendista", "ORE", 26m));
|
||||
items.Add(Other(ItemKind.Service, "SERV", "Uscita e diritto di chiamata", "SERV", 35m));
|
||||
items.Add(Other(ItemKind.Service, "SERV", "Sopralluogo tecnico", "SERV", 60m));
|
||||
items.Add(Other(ItemKind.Service, "SERV", "Manutenzione annuale caldaia", "SERV", 95m));
|
||||
items.Add(Other(ItemKind.Service, "SERV", "Analisi fumi e libretto impianto", "SERV", 45m));
|
||||
items.Add(Other(ItemKind.Service, "SERV", "Dichiarazione di conformità impianto", "SERV", 120m));
|
||||
items.Add(Other(ItemKind.Expense, "SPESE", "Spese di trasporto", "SERV", 15m));
|
||||
items.Add(Other(ItemKind.Expense, "SPESE", "Spese di imballo", "SERV", 5m));
|
||||
items.Add(Other(ItemKind.Expense, "SPESE", "Smaltimento materiale rimosso", "SERV", 25m));
|
||||
items.Add(Other(ItemKind.Text, "SERV", "Riga descrittiva", "NR", null));
|
||||
items.Add(Other(ItemKind.Text, "SERV", "Materiale fornito dal cliente", "NR", null));
|
||||
|
||||
return items;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task RunAsync(SeedContext context, CancellationToken cancellationToken)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(context);
|
||||
var uow = context.UnitOfWork;
|
||||
if (await uow.Repository<Item, long>().CountAsync(Query.For<Item>(), cancellationToken).ConfigureAwait(false) > 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var categories = await context.EnsureAsync(
|
||||
"item_categories",
|
||||
[
|
||||
new ItemCategory { Code = "VALV", Description = "Valvolame", IsDemo = true },
|
||||
new ItemCategory { Code = "RACC", Description = "Raccorderia", IsDemo = true },
|
||||
new ItemCategory { Code = "TUBI", Description = "Tubi", IsDemo = true },
|
||||
new ItemCategory { Code = "CALD", Description = "Caldaie e riscaldamento", IsDemo = true },
|
||||
new ItemCategory { Code = "SAN", Description = "Rubinetteria e sanitari", IsDemo = true },
|
||||
new ItemCategory { Code = "CONS", Description = "Materiale di consumo", IsDemo = true },
|
||||
new ItemCategory { Code = "POMP", Description = "Pompe e circolatori", IsDemo = true },
|
||||
new ItemCategory { Code = "UTEN", Description = "Utensili", IsDemo = true },
|
||||
new ItemCategory { Code = "SERV", Description = "Servizi e manodopera", IsDemo = true },
|
||||
new ItemCategory { Code = "SPESE", Description = "Spese accessorie", IsDemo = true },
|
||||
],
|
||||
cancellationToken).ConfigureAwait(false);
|
||||
var lists = uow.Repository<PriceList, long>();
|
||||
var allLists = (await lists.ListAsync(Query.For<PriceList>(), cancellationToken).ConfigureAwait(false)).Items;
|
||||
var baseList = PriceBook.BaseOf(allLists);
|
||||
if (baseList is null)
|
||||
{
|
||||
baseList = new PriceList { Code = "BASE", Description = "Listino base", IsBase = true, IsDemo = true };
|
||||
baseList.Id = await lists.InsertAsync(baseList, cancellationToken).ConfigureAwait(false);
|
||||
context.Count("price_lists");
|
||||
}
|
||||
|
||||
await context.EnsureAsync(
|
||||
"price_lists",
|
||||
[
|
||||
new PriceList { Code = "PUBB", Description = "Pubblico", BasePriceListId = baseList.Id, MarkupPercent = 45m, RoundingStep = 0.10m, IsDemo = true },
|
||||
new PriceList { Code = "RIV", Description = "Rivenditori", BasePriceListId = baseList.Id, MarkupPercent = -10m, RoundingStep = 0.01m, IsDemo = true },
|
||||
],
|
||||
cancellationToken).ConfigureAwait(false);
|
||||
|
||||
var units = (await uow.Repository<UnitOfMeasure, long>().ListAsync(Query.For<UnitOfMeasure>(), cancellationToken).ConfigureAwait(false)).Items
|
||||
.ToDictionary(u => u.Code, u => u.Id, StringComparer.OrdinalIgnoreCase);
|
||||
var tax = (await uow.Repository<TaxCode, long>().FindAsync(Query.For<TaxCode>().Where(t => t.Code == "22"), cancellationToken).ConfigureAwait(false))?.Id;
|
||||
var warehouse = (await uow.Repository<Warehouse, long>().FindAsync(Query.For<Warehouse>().Where(w => w.IsDefault), cancellationToken).ConfigureAwait(false))?.Id;
|
||||
var parties = (await uow.Repository<Party, long>().ListAsync(Query.For<Party>(), cancellationToken).ConfigureAwait(false)).Items
|
||||
.GroupBy(p => p.Name, StringComparer.Ordinal).ToDictionary(g => g.Key, g => g.First().Id, StringComparer.Ordinal);
|
||||
long? PartyOf(string name) => parties.TryGetValue(name, out var id) ? id : null;
|
||||
var suppliers = new Dictionary<string, long?>(StringComparer.Ordinal)
|
||||
{
|
||||
["VALV"] = PartyOf("Metalli Nord S.p.A."), ["RACC"] = PartyOf("Metalli Nord S.p.A."), ["TUBI"] = PartyOf("Metalli Nord S.p.A."),
|
||||
["SAN"] = PartyOf("Metalli Nord S.p.A."), ["CONS"] = PartyOf("Plastica Sud S.r.l."), ["CALD"] = PartyOf("Elektro Werke Süd GmbH"),
|
||||
["POMP"] = PartyOf("Elektro Werke Süd GmbH"), ["UTEN"] = PartyOf("Plastica Sud S.r.l."),
|
||||
};
|
||||
var customer = PartyOf("Rossi Impianti S.r.l.");
|
||||
|
||||
var rule = await codes.RuleAsync(context.CompanyCode, ItemService.CodeRule, cancellationToken).ConfigureAwait(false);
|
||||
var items = uow.Repository<Item, long>();
|
||||
var thisYear = new DateOnly(context.Today.Year, 1, 1);
|
||||
var lastYear = thisYear.AddYears(-1);
|
||||
var catalogue = Catalogue();
|
||||
var created = new List<(DemoItem Seed, Item Item)>();
|
||||
var ean = 0;
|
||||
for (var round = 1; round <= Math.Max(1, context.Scale); round++)
|
||||
{
|
||||
foreach (var seed in catalogue)
|
||||
{
|
||||
var category = categories[seed.Category];
|
||||
var cost = seed.Price is { } p && seed.Kind == ItemKind.Goods ? Math.Round(p * 0.58m, 2) : (decimal?)null;
|
||||
var item = new Item
|
||||
{
|
||||
Kind = seed.Kind,
|
||||
Description = round == 1 ? seed.Description : seed.Description + " (serie " + round.ToString(CultureInfo.InvariantCulture) + ")",
|
||||
CategoryId = category.Id,
|
||||
UnitOfMeasureId = units.TryGetValue(seed.Unit, out var unit) ? unit : null,
|
||||
SalesTaxCodeId = tax,
|
||||
PurchaseTaxCodeId = tax,
|
||||
Barcode = seed.Kind == ItemKind.Goods ? Ean(++ean) : null,
|
||||
CustomsCode = seed.CustomsCode,
|
||||
Brand = seed.Brand,
|
||||
Manufacturer = seed.Brand is null ? null : seed.Brand + " Industrie",
|
||||
NetWeight = seed.Weight,
|
||||
GrossWeight = seed.Weight is { } w ? Math.Round(w * 1.08m, 3) : null,
|
||||
Stocked = seed.Kind == ItemKind.Goods,
|
||||
WarehouseId = seed.Kind == ItemKind.Goods ? warehouse : null,
|
||||
MinimumStock = seed.Kind == ItemKind.Goods && seed.Unit == "PZ" ? 5m : null,
|
||||
ReorderPoint = seed.Kind == ItemKind.Goods && seed.Unit == "PZ" ? 10m : null,
|
||||
ReorderLot = seed.Kind == ItemKind.Goods && seed.Unit == "PZ" ? 20m : null,
|
||||
Price = seed.Kind is ItemKind.Service or ItemKind.Expense ? seed.Price : null,
|
||||
StandardCost = cost,
|
||||
AverageCost = cost,
|
||||
LastCost = cost is { } c ? Math.Round(c * 1.02m, 2) : null,
|
||||
IsDemo = true,
|
||||
};
|
||||
item.Code = await CodeRuleService.AssignAsync(
|
||||
uow, rule, context.Today, category.Code,
|
||||
async (code, ct) => await items.CountAsync(Query.For<Item>().Where(i => i.Code == code), ct).ConfigureAwait(false) > 0,
|
||||
cancellationToken).ConfigureAwait(false);
|
||||
item.Id = await items.InsertAsync(item, cancellationToken).ConfigureAwait(false);
|
||||
context.Count("items");
|
||||
created.Add((seed, item));
|
||||
|
||||
if (seed.Kind == ItemKind.Goods && seed.Price is { } price)
|
||||
{
|
||||
// The price of this year, and the one of last year for the history.
|
||||
await AddAsync(uow, context, "item_prices", new ItemPrice { ItemId = item.Id, PriceListId = baseList.Id, Price = price, ValidFrom = thisYear }, cancellationToken).ConfigureAwait(false);
|
||||
await AddAsync(uow, context, "item_prices",
|
||||
new ItemPrice { ItemId = item.Id, PriceListId = baseList.Id, Price = PriceRounding.Round(price * 0.96m, 0.10m), ValidFrom = lastYear }, cancellationToken).ConfigureAwait(false);
|
||||
if (suppliers.GetValueOrDefault(seed.Category) is { } supplier)
|
||||
{
|
||||
await AddAsync(uow, context, "item_suppliers", new ItemSupplier
|
||||
{
|
||||
ItemId = item.Id, PartyId = supplier, SupplierCode = "F-" + item.Code, Price = cost, LeadTimeDays = 7, MinimumQuantity = seed.Unit == "M" ? 50m : 1m, IsDefault = true,
|
||||
}, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
await DetailsAsync(uow, context, created, units, customer, baseList, thisYear, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private static async Task DetailsAsync(IUnitOfWork uow, SeedContext context, List<(DemoItem Seed, Item Item)> created, Dictionary<string, long> units,
|
||||
long? customer, PriceList baseList, DateOnly thisYear, CancellationToken cancellationToken)
|
||||
{
|
||||
Item? Find(string description) => created.FirstOrDefault(c => c.Item.Description == description).Item;
|
||||
|
||||
// Copper bars are sold also by the bar of 5 m; small valves and fittings by the box of 10.
|
||||
foreach (var (seed, item) in created.Where(c => c.Item.Description.StartsWith("Tubo rame", StringComparison.Ordinal)))
|
||||
{
|
||||
if (units.TryGetValue("PZ", out var bar))
|
||||
{
|
||||
await AddAsync(uow, context, "item_uoms", new ItemUnit { ItemId = item.Id, UnitOfMeasureId = bar, Factor = 5m }, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
foreach (var (seed, item) in created.Where(c => c.Seed.Category is "VALV" or "RACC" && c.Seed.Unit == "PZ").Take(30))
|
||||
{
|
||||
if (units.TryGetValue("CT", out var box))
|
||||
{
|
||||
await AddAsync(uow, context, "item_uoms", new ItemUnit { ItemId = item.Id, UnitOfMeasureId = box, Factor = 10m, Barcode = Ean(500_000 + (int)item.Id) }, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
// The codes of the old system, found by the search.
|
||||
foreach (var (seed, item) in created.Where(c => c.Seed.Category == "VALV").Take(6))
|
||||
{
|
||||
await AddAsync(uow, context, "item_barcodes", new ItemBarcode { ItemId = item.Id, Code = "OLD-" + item.Id.ToString("00000", CultureInfo.InvariantCulture), Description = "Codice del gestionale precedente" }, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
// Substitutes: the butterfly valve for the lever one of the same size, the bigger boiler for the smaller one.
|
||||
foreach (var size in Sizes)
|
||||
{
|
||||
if (Find("Valvola a sfera " + size + " ottone cromato leva") is { } lever && Find("Valvola a sfera " + size + " ottone cromato farfalla") is { } butterfly)
|
||||
{
|
||||
await AddAsync(uow, context, "item_substitutes", new ItemSubstitute { ItemId = lever.Id, SubstituteId = butterfly.Id, Notes = "Stessa misura, maniglia a farfalla" }, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
if (Find("Caldaia a condensazione 24 kW") is { } small && Find("Caldaia a condensazione 28 kW") is { } big)
|
||||
{
|
||||
await AddAsync(uow, context, "item_substitutes", new ItemSubstitute { ItemId = small.Id, SubstituteId = big.Id, Notes = "Potenza superiore, stessi attacchi" }, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
if (customer is not { } rossi)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// The usual customer has net prices on the valves and calls some items with its own codes.
|
||||
var valves = created.Where(c => c.Seed.Category == "VALV" && c.Seed.Price is not null).Take(8).ToList();
|
||||
for (var i = 0; i < valves.Count; i++)
|
||||
{
|
||||
var (seed, item) = valves[i];
|
||||
await AddAsync(uow, context, "item_prices", new ItemPrice { ItemId = item.Id, PartyId = rossi, Price = PriceRounding.Round(seed.Price!.Value * 0.95m, 0.05m), ValidFrom = thisYear }, cancellationToken).ConfigureAwait(false);
|
||||
if (i < 5)
|
||||
{
|
||||
await AddAsync(uow, context, "party_item_codes",
|
||||
new PartyItemCode { PartyId = rossi, ItemId = item.Id, Code = "RI-" + (100 + i).ToString(CultureInfo.InvariantCulture), Description = "Valvola " + (i + 1).ToString(CultureInfo.InvariantCulture) }, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
// A price of the public list written by hand, over the derived one.
|
||||
if (Find("Caldaia a condensazione 24 kW") is { } boiler
|
||||
&& await uow.Repository<PriceList, long>().FindAsync(Query.For<PriceList>().Where(l => l.Code == "PUBB"), cancellationToken).ConfigureAwait(false) is { } publicList
|
||||
&& publicList.BasePriceListId == baseList.Id)
|
||||
{
|
||||
await AddAsync(uow, context, "item_prices", new ItemPrice { ItemId = boiler.Id, PriceListId = publicList.Id, Price = 1690m, ValidFrom = thisYear }, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
private static async Task AddAsync<T>(IUnitOfWork uow, SeedContext context, string table, T row, CancellationToken cancellationToken)
|
||||
where T : class, Khaemhat.Core.Entities.IEntity<long>, new()
|
||||
{
|
||||
await uow.Repository<T, long>().InsertAsync(row, cancellationToken).ConfigureAwait(false);
|
||||
context.Count(table);
|
||||
}
|
||||
|
||||
/// <summary>A fictitious EAN-13 with the prefix 200, for internal use, and a valid check digit.</summary>
|
||||
/// <param name="number">The progressive number.</param>
|
||||
/// <returns>The code.</returns>
|
||||
public static string Ean(int number)
|
||||
{
|
||||
var digits = "200" + number.ToString("000000000", CultureInfo.InvariantCulture);
|
||||
return digits + EanValidator.CheckDigit(digits).ToString(CultureInfo.InvariantCulture);
|
||||
}
|
||||
|
||||
private static DemoItem Goods(string category, string description, string unit, decimal price, string? brand, string? customs, decimal? weight) =>
|
||||
new(category, ItemKind.Goods, description, unit, Math.Round(price, 2), brand, customs, weight);
|
||||
|
||||
private static DemoItem Other(ItemKind kind, string category, string description, string unit, decimal? price) =>
|
||||
new(category, kind, description, unit, price, null, null, null);
|
||||
}
|
||||
|
||||
/// <summary>An item of the demo catalogue.</summary>
|
||||
/// <param name="Category">The category code.</param>
|
||||
/// <param name="Kind">What it is.</param>
|
||||
/// <param name="Description">The description.</param>
|
||||
/// <param name="Unit">The unit code.</param>
|
||||
/// <param name="Price">The price of the base list (goods) or of the item (services and expenses).</param>
|
||||
/// <param name="Brand">The fictitious brand.</param>
|
||||
/// <param name="CustomsCode">The combined nomenclature.</param>
|
||||
/// <param name="Weight">The net weight in kg.</param>
|
||||
public sealed record DemoItem(string Category, ItemKind Kind, string Description, string Unit, decimal? Price, string? Brand, string? CustomsCode, decimal? Weight);
|
||||
@@ -0,0 +1,293 @@
|
||||
using Khaemhat.Application.Modules;
|
||||
using Khaemhat.Application.Parties;
|
||||
using Khaemhat.Application.Tables;
|
||||
using Khaemhat.Core.Parties;
|
||||
using Khaemhat.Core.Tables;
|
||||
using Khaemhat.Data;
|
||||
using Khaemhat.Data.Querying;
|
||||
using Khaemhat.Fiscal.Abstractions;
|
||||
|
||||
namespace Khaemhat.Application.Seeding;
|
||||
|
||||
/// <summary>
|
||||
/// The parties of the demo company (SPEC §14, issue #41): customers of every kind of subject (companies, public
|
||||
/// administration with split payment, private persons, EU and non-EU companies, flat rate, a declaration of intent, a
|
||||
/// customer blocked over its credit, one that is also a supplier, one disabled), suppliers (a professional with
|
||||
/// withholding, an ENASARCO agent, an EU supplier), prospects and leads, and three salespeople. Every name, number and
|
||||
/// bank account is fictitious: the VAT numbers have a valid check digit, the IBANs a valid check, the ABI codes belong
|
||||
/// to no bank. Runs only on a company without parties; the rows are marked as demo.
|
||||
/// </summary>
|
||||
/// <param name="codes">The automatic code rules.</param>
|
||||
public sealed class DemoPartiesSeeder(CodeRuleService codes) : ISeeder
|
||||
{
|
||||
/// <summary>The fictitious VAT numbers, valid for the Italian check digit (tests check them with the pack).</summary>
|
||||
public static readonly IReadOnlyList<string> VatNumbers =
|
||||
[
|
||||
"04123456784", "05234567898", "06345678905", "07456789010", "08567890127", "09678901233", "10789012340", "11890123455",
|
||||
"12901234562", "13012345677", "14123456700", "15234567814", "16345678920", "17456789035",
|
||||
];
|
||||
|
||||
/// <summary>The fictitious tax code of the public administration (numeric, valid check digit).</summary>
|
||||
public const string AdministrationTaxCode = "80012345676";
|
||||
|
||||
/// <summary>The fictitious IBANs, with a valid check and ABI codes of no bank.</summary>
|
||||
public static readonly IReadOnlyList<string> Ibans = ["IT53X0123410100000012345678", "IT21X0567822000000000987654", "IT11X0987645600000101234567"];
|
||||
|
||||
/// <inheritdoc />
|
||||
public string ModuleCode => ModuleCodes.Core;
|
||||
|
||||
/// <inheritdoc />
|
||||
public SeedKind Kind => SeedKind.Demo;
|
||||
|
||||
/// <inheritdoc />
|
||||
public int Order => 10;
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task RunAsync(SeedContext context, CancellationToken cancellationToken)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(context);
|
||||
var uow = context.UnitOfWork;
|
||||
if (await uow.Repository<Party, long>().CountAsync(Query.For<Party>(), cancellationToken).ConfigureAwait(false) > 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var rules = new Dictionary<PartyKind, CodeRule>();
|
||||
foreach (var kind in Enum.GetValues<PartyKind>())
|
||||
{
|
||||
rules[kind] = await codes.RuleAsync(context.CompanyCode, PartyService.CodeRuleOf(kind), cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
var salespeople = await context.EnsureAsync(
|
||||
"salespeople",
|
||||
[
|
||||
new Salesperson { Code = "VERDI", Description = "Marco Verdi", Email = "m.verdi@demo.example", CommissionPercent = 5m, Enasarco = true },
|
||||
new Salesperson { Code = "NERI", Description = "Laura Neri", Email = "l.neri@demo.example", CommissionPercent = 4m, Enasarco = true },
|
||||
new Salesperson { Code = "BIANCO", Description = "Paolo Bianco", Email = "p.bianco@demo.example", CommissionPercent = 3m },
|
||||
],
|
||||
cancellationToken).ConfigureAwait(false);
|
||||
var terms = (await uow.Repository<PaymentTerm, long>().ListAsync(Query.For<PaymentTerm>(), cancellationToken).ConfigureAwait(false)).Items
|
||||
.ToDictionary(t => t.Code, t => t.Id, StringComparer.OrdinalIgnoreCase);
|
||||
var priceList = (await uow.Repository<PriceList, long>().FindAsync(Query.For<PriceList>().Where(p => p.Code == "BASE"), cancellationToken).ConfigureAwait(false))?.Id;
|
||||
long? Term(string code) => terms.TryGetValue(code, out var id) ? id : null;
|
||||
long? Agent(string code) => salespeople.TryGetValue(code, out var s) ? s.Id : null;
|
||||
var identifiers = context.Pack.GetFeature<ITaxIdentifierRules>();
|
||||
var year = context.Today.Year;
|
||||
|
||||
var seeds = new List<PartyRecord>
|
||||
{
|
||||
Customer("Rossi Impianti S.r.l.", SubjectType.Company, VatNumbers[0], "Via Nizza", "120", "10126", "Torino", "TO", Term("RB60FM"), Agent("VERDI"), r =>
|
||||
{
|
||||
r.Fiscal.RecipientCode = "M5UXCR1";
|
||||
r.Party.Phone = "011 5550101";
|
||||
r.Party.Email = "amministrazione@rossi-impianti.example";
|
||||
r.Contacts.Add(new PartyContact { Name = "Mario Rossi", Role = "Titolare", Mobile = "333 5550101", Email = "mario@rossi-impianti.example", IsDefault = true });
|
||||
r.Contacts.Add(new PartyContact { Name = "Anna Ferri", Role = "Amministrazione", Phone = "011 5550102", Email = "amministrazione@rossi-impianti.example" });
|
||||
r.Addresses.Add(new PartyAddress { Kind = PartyAddressKind.Site, Name = "Cantiere Lingotto", Address = "Via Ventimiglia", StreetNumber = "88", PostalCode = "10126", City = "Torino", Province = "TO", IsDefault = true });
|
||||
r.BankAccounts.Add(new PartyBankAccount { Iban = Ibans[0], BankCode = "01234", BranchCode = "10100", IsDefault = true });
|
||||
r.Sales.Discount1 = 5m;
|
||||
r.Sales.CreditLimit = 30000m;
|
||||
r.Sales.SendDocuments = DocumentDelivery.Email;
|
||||
r.Sales.DocumentsEmail = "amministrazione@rossi-impianti.example";
|
||||
}),
|
||||
Customer("Bianchi & Figli S.n.c.", SubjectType.Company, VatNumbers[1], "Corso Langhe", "5", "12051", "Alba", "CN", Term("RB3060FM"), Agent("VERDI"), r =>
|
||||
{
|
||||
r.Fiscal.RecipientCode = "0000000";
|
||||
r.Fiscal.RecipientPec = "bianchiefigli@pec.demo.example";
|
||||
r.Party.Pec = "bianchiefigli@pec.demo.example";
|
||||
}),
|
||||
Customer("Comune di Valdora", SubjectType.PublicAdministration, null, "Piazza del Municipio", "1", "12060", "Valdora", "CN", Term("BB30"), null, r =>
|
||||
{
|
||||
r.Party.TaxCode = AdministrationTaxCode;
|
||||
r.Fiscal.RecipientCode = "UFX9K2";
|
||||
r.Fiscal.SplitPayment = true;
|
||||
r.Fiscal.Exigibility = "S";
|
||||
r.Fiscal.AdministrationReference = "SETT-TECNICO";
|
||||
}),
|
||||
Customer("Ferramenta Gallo", SubjectType.Company, VatNumbers[2], "Corso Alfieri", "210", "14100", "Asti", "AT", Term("RD"), Agent("NERI"), r =>
|
||||
{
|
||||
r.Fiscal.RecipientCode = "KRRH6B9";
|
||||
r.Sales.CreditLimit = 5000m;
|
||||
r.Sales.Blocked = true;
|
||||
r.Party.Notes = "Ordini bloccati: fido superato, rientro concordato entro fine mese.";
|
||||
}),
|
||||
Customer("Bergwerk Bau GmbH", SubjectType.EuCompany, "U12345678", "Museumstrasse", "12", "6020", "Innsbruck", null, Term("BB30"), Agent("NERI"), r =>
|
||||
{
|
||||
r.Party.CountryCode = "AT";
|
||||
r.Party.Language = "de";
|
||||
r.Fiscal.RecipientCode = "XXXXXXX";
|
||||
}),
|
||||
Customer("Esposito Mario", SubjectType.Person, null, "Via Po", "18", "10124", "Torino", "TO", Term("RD"), null, r =>
|
||||
{
|
||||
r.Party.LastName = "Esposito";
|
||||
r.Party.FirstName = "Mario";
|
||||
r.Party.TaxCode = Personal(identifiers, "Esposito", "Mario", new DateOnly(1980, 1, 1), PersonSex.Male, "L219");
|
||||
r.Party.Email = "mario.esposito@posta.example";
|
||||
r.Fiscal.RecipientCode = "0000000";
|
||||
r.Party.PrivacyAccepted = true;
|
||||
}),
|
||||
Customer("Idrotermica Piemonte S.r.l.", SubjectType.Company, VatNumbers[3], "Via Roma", "44", "12100", "Cuneo", "CN", Term("RB3060FM"), Agent("VERDI"), r =>
|
||||
{
|
||||
r.Fiscal.RecipientCode = "T04ZHR3";
|
||||
r.Fiscal.IntentActive = true;
|
||||
r.Fiscal.IntentNumber = "14/" + year;
|
||||
r.Fiscal.IntentDate = new DateOnly(year, 1, 15);
|
||||
r.Fiscal.IntentProtocol = "26011512345678901-000001";
|
||||
r.Fiscal.IntentCeiling = 150000m;
|
||||
r.Fiscal.IntentFrom = new DateOnly(year, 1, 1);
|
||||
r.Fiscal.IntentTo = new DateOnly(year, 12, 31);
|
||||
}),
|
||||
Customer("Nordic Pipes AS", SubjectType.NonEuCompany, "987654321", "Storgata", "7", "0155", "Oslo", null, Term("RD"), Agent("NERI"), r =>
|
||||
{
|
||||
r.Party.CountryCode = "NO";
|
||||
r.Party.Language = "en";
|
||||
r.Fiscal.RecipientCode = "XXXXXXX";
|
||||
}),
|
||||
Customer("Studio Tecnico Ing. Ferrero", SubjectType.FlatRate, VatNumbers[4], "Via Vittorio Emanuele", "3", "12051", "Alba", "CN", Term("BB30"), null, r =>
|
||||
{
|
||||
r.Fiscal.RecipientCode = "USAL8PV";
|
||||
r.Fiscal.StampDutyCharged = true;
|
||||
}),
|
||||
Customer("Edilizia Moderna S.p.A.", SubjectType.Company, VatNumbers[5], "Viale Monza", "250", "20126", "Milano", "MI", Term("RB3060FM"), Agent("BIANCO"), r =>
|
||||
{
|
||||
r.Party.IsAlsoSupplier = true;
|
||||
r.Fiscal.RecipientCode = "W7YVJK9";
|
||||
r.Purchase.PaymentTermId = Term("BB30FM");
|
||||
r.Sales.Discount1 = 10m;
|
||||
r.Sales.Discount2 = 3m;
|
||||
}),
|
||||
Customer("Termoidraulica Sacco", SubjectType.Company, VatNumbers[6], "Via Cavour", "9", "12042", "Bra", "CN", Term("RD"), Agent("NERI"), r =>
|
||||
{
|
||||
r.Fiscal.RecipientCode = "SUBM70N";
|
||||
r.Party.Disabled = true;
|
||||
r.Party.Notes = "Attività cessata.";
|
||||
}),
|
||||
Customer("Hotel Belvedere S.r.l.", SubjectType.Company, VatNumbers[7], "Passeggiata Cadorna", "15", "17021", "Alassio", "SV", Term("BB30FM"), Agent("BIANCO"), r =>
|
||||
{
|
||||
r.Fiscal.RecipientCode = "5RUO82D";
|
||||
r.Contacts.Add(new PartyContact { Name = "Giulia Marino", Role = "Direzione", Phone = "0182 555010", IsDefault = true });
|
||||
}),
|
||||
Supplier("Metalli Nord S.p.A.", VatNumbers[8], "Via Industriale", "40", "25125", "Brescia", "BS", Term("RB60FM"), r =>
|
||||
{
|
||||
r.Purchase.LeadTimeDays = 10;
|
||||
r.Purchase.MinimumOrder = 500m;
|
||||
r.Purchase.OrdersEmail = "ordini@metalli-nord.example";
|
||||
r.BankAccounts.Add(new PartyBankAccount { Iban = Ibans[1], BankCode = "05678", BranchCode = "22000", IsDefault = true });
|
||||
}),
|
||||
Supplier("Plastica Sud S.r.l.", VatNumbers[9], "Via Appia", "301", "81100", "Caserta", "CE", Term("BB30FM"), r => r.Purchase.LeadTimeDays = 15),
|
||||
Supplier("Studio Rag. Neri Paola", VatNumbers[10], "Via Vittorio Veneto", "21", "12100", "Cuneo", "CN", Term("RD"), r =>
|
||||
{
|
||||
r.Fiscal.Withholding = true;
|
||||
r.Fiscal.WithholdingRate = 20m;
|
||||
r.Fiscal.WithholdingReason = "A";
|
||||
r.Fiscal.PensionFund = "TC04";
|
||||
r.Fiscal.PensionFundRate = 4m;
|
||||
r.BankAccounts.Add(new PartyBankAccount { Iban = Ibans[2], BankCode = "09876", BranchCode = "45600", IsDefault = true });
|
||||
}),
|
||||
Supplier("Agenzia Commerciale Bruno", VatNumbers[11], "Corso Francia", "77", "10138", "Torino", "TO", Term("BB30FM"), r =>
|
||||
{
|
||||
r.Fiscal.Withholding = true;
|
||||
r.Fiscal.WithholdingRate = 23m;
|
||||
r.Fiscal.WithholdingReason = "R";
|
||||
r.Fiscal.Enasarco = true;
|
||||
}),
|
||||
Supplier("Elektro Werke Süd GmbH", "123456789", "Industriestrasse", "5", "80331", "München", null, Term("BB30"), r =>
|
||||
{
|
||||
r.Party.SubjectType = SubjectType.EuCompany;
|
||||
r.Party.CountryCode = "DE";
|
||||
r.Party.Language = "de";
|
||||
}),
|
||||
Contact(PartyKind.Prospect, "Caseificio Valle Stura S.r.l.", VatNumbers[12], "12014", "Demonte", "CN", Agent("VERDI")),
|
||||
Contact(PartyKind.Prospect, "Agriturismo Le Vigne", VatNumbers[13], "12060", "Barolo", "CN", Agent("BIANCO")),
|
||||
Contact(PartyKind.Lead, "Fontana Marco (fiera di Bologna)", null, null, null, null, Agent("NERI")),
|
||||
Contact(PartyKind.Lead, "Cantina Sociale del Roero", null, "12043", "Canale", "CN", null),
|
||||
};
|
||||
|
||||
foreach (var record in seeds)
|
||||
{
|
||||
record.Sales.PriceListId ??= record.Party.IsCustomer ? priceList : null;
|
||||
await InsertAsync(uow, record, rules[record.Party.Kind], context.Today, cancellationToken).ConfigureAwait(false);
|
||||
context.Count("parties");
|
||||
}
|
||||
}
|
||||
|
||||
private static PartyRecord Customer(string name, SubjectType subject, string? vat, string address, string number, string postalCode, string city, string? province,
|
||||
long? paymentTermId, long? salespersonId, Action<PartyRecord> more)
|
||||
{
|
||||
var record = New(PartyKind.Customer, name, subject, vat, postalCode, city, province, salespersonId);
|
||||
record.Party.Address = address;
|
||||
record.Party.StreetNumber = number;
|
||||
record.Sales.PaymentTermId = paymentTermId;
|
||||
more(record);
|
||||
return record;
|
||||
}
|
||||
|
||||
private static PartyRecord Supplier(string name, string vat, string address, string number, string postalCode, string city, string? province, long? paymentTermId,
|
||||
Action<PartyRecord> more)
|
||||
{
|
||||
var record = New(PartyKind.Supplier, name, SubjectType.Company, vat, postalCode, city, province, null);
|
||||
record.Party.Address = address;
|
||||
record.Party.StreetNumber = number;
|
||||
record.Purchase.PaymentTermId = paymentTermId;
|
||||
more(record);
|
||||
return record;
|
||||
}
|
||||
|
||||
private static PartyRecord Contact(PartyKind kind, string name, string? vat, string? postalCode, string? city, string? province, long? salespersonId) =>
|
||||
New(kind, name, SubjectType.Company, vat, postalCode, city, province, salespersonId);
|
||||
|
||||
private static PartyRecord New(PartyKind kind, string name, SubjectType subject, string? vat, string? postalCode, string? city, string? province, long? salespersonId) => new()
|
||||
{
|
||||
Party = new Party
|
||||
{
|
||||
Kind = kind, Name = name, SubjectType = subject, VatNumber = vat, PostalCode = postalCode, City = city, Province = province, SalespersonId = salespersonId,
|
||||
CategoryId = null, PrivacyAccepted = kind is PartyKind.Customer or PartyKind.Supplier, IsDemo = true,
|
||||
},
|
||||
};
|
||||
|
||||
private static string? Personal(ITaxIdentifierRules? rules, string surname, string name, DateOnly birth, PersonSex sex, string place) =>
|
||||
rules?.ComputePersonalTaxCode(new PersonalTaxCodeData(surname, name, birth, sex, place));
|
||||
|
||||
private static async Task InsertAsync(IUnitOfWork uow, PartyRecord record, CodeRule rule, DateOnly today, CancellationToken cancellationToken)
|
||||
{
|
||||
var parties = uow.Repository<Party, long>();
|
||||
var party = record.Party;
|
||||
party.Code = await CodeRuleService.AssignAsync(
|
||||
uow, rule, today, null,
|
||||
async (code, ct) => await parties.CountAsync(Query.For<Party>().Where(p => p.Code == code), ct).ConfigureAwait(false) > 0,
|
||||
cancellationToken).ConfigureAwait(false);
|
||||
party.Id = await parties.InsertAsync(party, cancellationToken).ConfigureAwait(false);
|
||||
if (party.IsCustomer)
|
||||
{
|
||||
record.Sales.PartyId = party.Id;
|
||||
await uow.Repository<PartySalesTerms, long>().InsertAsync(record.Sales, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
if (party.IsSupplier)
|
||||
{
|
||||
record.Purchase.PartyId = party.Id;
|
||||
await uow.Repository<PartyPurchaseTerms, long>().InsertAsync(record.Purchase, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
record.Fiscal.PartyId = party.Id;
|
||||
await uow.Repository<PartyFiscal, long>().InsertAsync(record.Fiscal, cancellationToken).ConfigureAwait(false);
|
||||
foreach (var address in record.Addresses)
|
||||
{
|
||||
address.PartyId = party.Id;
|
||||
address.CountryCode = address.CountryCode.Length == 0 ? party.CountryCode : address.CountryCode;
|
||||
await uow.Repository<PartyAddress, long>().InsertAsync(address, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
foreach (var contact in record.Contacts)
|
||||
{
|
||||
contact.PartyId = party.Id;
|
||||
await uow.Repository<PartyContact, long>().InsertAsync(contact, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
foreach (var account in record.BankAccounts)
|
||||
{
|
||||
account.PartyId = party.Id;
|
||||
await uow.Repository<PartyBankAccount, long>().InsertAsync(account, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,305 @@
|
||||
using Khaemhat.Application.Instance;
|
||||
using Khaemhat.Application.Security;
|
||||
using Khaemhat.Application.Tables;
|
||||
using Khaemhat.Core.Entities;
|
||||
using Khaemhat.Core.Instance;
|
||||
using Khaemhat.Core.Tables;
|
||||
using Khaemhat.Data;
|
||||
using Khaemhat.Data.Querying;
|
||||
using Khaemhat.Fiscal.Abstractions;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace Khaemhat.Application.Seeding;
|
||||
|
||||
/// <summary>The kind of data a seeder loads (SPEC §14).</summary>
|
||||
public enum SeedKind
|
||||
{
|
||||
/// <summary>The base tables every company needs.</summary>
|
||||
Base = 0,
|
||||
|
||||
/// <summary>The fictitious demo company.</summary>
|
||||
Demo = 1,
|
||||
}
|
||||
|
||||
/// <summary>A source of base or demo data (SPEC §14). Seeders are idempotent: they add what is missing and change nothing else.</summary>
|
||||
public interface ISeeder
|
||||
{
|
||||
/// <summary>The licence module whose tables it fills (<c>CORE</c>, <c>ACCT</c>...).</summary>
|
||||
string ModuleCode { get; }
|
||||
|
||||
/// <summary>Base or demo.</summary>
|
||||
SeedKind Kind { get; }
|
||||
|
||||
/// <summary>The order among seeders of the same kind (lower first).</summary>
|
||||
int Order { get; }
|
||||
|
||||
/// <summary>Loads the data.</summary>
|
||||
/// <param name="context">The company, its unit of work and fiscal pack.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>A task.</returns>
|
||||
Task RunAsync(SeedContext context, CancellationToken cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>What a seeder works with, and the counts of what it added.</summary>
|
||||
public sealed class SeedContext
|
||||
{
|
||||
private readonly Dictionary<string, int> _added = new(StringComparer.Ordinal);
|
||||
|
||||
/// <summary>Creates the context.</summary>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="unitOfWork">The company unit of work, committed by the runner.</param>
|
||||
/// <param name="pack">The fiscal pack of the company.</param>
|
||||
/// <param name="today">Today, for the current year.</param>
|
||||
public SeedContext(string companyCode, IUnitOfWork unitOfWork, IFiscalPack pack, DateOnly today)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(companyCode);
|
||||
ArgumentNullException.ThrowIfNull(unitOfWork);
|
||||
ArgumentNullException.ThrowIfNull(pack);
|
||||
CompanyCode = companyCode;
|
||||
UnitOfWork = unitOfWork;
|
||||
Pack = pack;
|
||||
Today = today;
|
||||
}
|
||||
|
||||
/// <summary>The company.</summary>
|
||||
public string CompanyCode { get; }
|
||||
|
||||
/// <summary>The company unit of work.</summary>
|
||||
public IUnitOfWork UnitOfWork { get; }
|
||||
|
||||
/// <summary>The fiscal pack.</summary>
|
||||
public IFiscalPack Pack { get; }
|
||||
|
||||
/// <summary>Today.</summary>
|
||||
public DateOnly Today { get; }
|
||||
|
||||
/// <summary>How many times the demo seeders repeat their catalogues (<c>seed --demo --scale N</c>), at least 1.</summary>
|
||||
public int Scale { get; init; } = 1;
|
||||
|
||||
/// <summary>Rows added, by table.</summary>
|
||||
public IReadOnlyDictionary<string, int> Added => _added;
|
||||
|
||||
/// <summary>Adds the rows whose code is missing; existing rows are left as the users made them.</summary>
|
||||
/// <typeparam name="T">The entity.</typeparam>
|
||||
/// <param name="table">The table, for the counts.</param>
|
||||
/// <param name="rows">The rows.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>Every row of the seed as stored (the existing one when the code was there).</returns>
|
||||
public async Task<IReadOnlyDictionary<string, T>> EnsureAsync<T>(string table, IEnumerable<T> rows, CancellationToken cancellationToken)
|
||||
where T : CodedEntity, new()
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(rows);
|
||||
var repository = UnitOfWork.Repository<T, long>();
|
||||
var existing = (await repository.ListAsync(Query.For<T>(), cancellationToken).ConfigureAwait(false)).Items
|
||||
.GroupBy(r => r.Code, StringComparer.OrdinalIgnoreCase)
|
||||
.ToDictionary(g => g.Key, g => g.First(), StringComparer.OrdinalIgnoreCase);
|
||||
var result = new Dictionary<string, T>(StringComparer.OrdinalIgnoreCase);
|
||||
foreach (var row in rows)
|
||||
{
|
||||
if (existing.TryGetValue(row.Code, out var found))
|
||||
{
|
||||
result[row.Code] = found;
|
||||
continue;
|
||||
}
|
||||
|
||||
row.Id = await repository.InsertAsync(row, cancellationToken).ConfigureAwait(false);
|
||||
existing[row.Code] = row;
|
||||
result[row.Code] = row;
|
||||
Count(table);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>Adds one row when nothing matches a condition.</summary>
|
||||
/// <typeparam name="T">The entity.</typeparam>
|
||||
/// <param name="table">The table, for the counts.</param>
|
||||
/// <param name="match">Finds the row.</param>
|
||||
/// <param name="row">The row to add.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The stored row.</returns>
|
||||
public async Task<T> EnsureOneAsync<T>(string table, System.Linq.Expressions.Expression<Func<T, bool>> match, T row, CancellationToken cancellationToken)
|
||||
where T : class, IEntity<long>, new()
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(row);
|
||||
var repository = UnitOfWork.Repository<T, long>();
|
||||
var found = await repository.FindAsync(Query.For<T>().Where(match), cancellationToken).ConfigureAwait(false);
|
||||
if (found is not null)
|
||||
{
|
||||
return found;
|
||||
}
|
||||
|
||||
row.Id = await repository.InsertAsync(row, cancellationToken).ConfigureAwait(false);
|
||||
Count(table);
|
||||
return row;
|
||||
}
|
||||
|
||||
/// <summary>Counts a row added by hand.</summary>
|
||||
/// <param name="table">The table.</param>
|
||||
public void Count(string table) => _added[table] = _added.GetValueOrDefault(table) + 1;
|
||||
}
|
||||
|
||||
/// <summary>The outcome of a seed run.</summary>
|
||||
/// <param name="DataVersion">The data version now recorded, such as <c>IT 2026.2</c>.</param>
|
||||
/// <param name="Added">Rows added, by table.</param>
|
||||
public sealed record SeedReport(string DataVersion, IReadOnlyDictionary<string, int> Added)
|
||||
{
|
||||
/// <summary>Total rows added.</summary>
|
||||
public int Total => Added.Values.Sum();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Runs the seeders of a kind on a company in one unit of work and records the data version in the company setting
|
||||
/// <see cref="VersionSetting"/> (SPEC §14). At company creation and at every start it runs the base seeders when
|
||||
/// <c>KHAEMHAT_SEED_BASE</c> is on; the button <i>Aggiorna tabelle di base</i> and <c>scripts/seed.sh --base</c> run
|
||||
/// them on demand. Being idempotent, running again only adds what a newer data version brings.
|
||||
/// </summary>
|
||||
public sealed partial class SeedRunner : ICompanySeeder
|
||||
{
|
||||
/// <summary>The company setting with the version of the base data.</summary>
|
||||
public const string VersionSetting = "seed.base.version";
|
||||
|
||||
private readonly IReadOnlyList<ISeeder> _seeders;
|
||||
private readonly IUnitOfWorkFactory _factory;
|
||||
private readonly CompanyFiscalContext _fiscal;
|
||||
private readonly PermissionService _permissions;
|
||||
private readonly TableService _tables;
|
||||
private readonly FiscalYearService _years;
|
||||
private readonly TimeProvider _clock;
|
||||
private readonly ILogger<SeedRunner> _logger;
|
||||
|
||||
/// <summary>Creates the runner.</summary>
|
||||
/// <param name="seeders">The seeders.</param>
|
||||
/// <param name="factory">Opens the company databases.</param>
|
||||
/// <param name="fiscal">The fiscal pack of each company.</param>
|
||||
/// <param name="permissions">Checks permissions (the button).</param>
|
||||
/// <param name="tables">The tables (cache invalidation).</param>
|
||||
/// <param name="years">The fiscal years (cache invalidation).</param>
|
||||
/// <param name="clock">The clock.</param>
|
||||
/// <param name="logger">The log.</param>
|
||||
public SeedRunner(
|
||||
IEnumerable<ISeeder> seeders, IUnitOfWorkFactory factory, CompanyFiscalContext fiscal, PermissionService permissions, TableService tables,
|
||||
FiscalYearService years, TimeProvider clock, ILogger<SeedRunner> logger)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(seeders);
|
||||
ArgumentNullException.ThrowIfNull(factory);
|
||||
ArgumentNullException.ThrowIfNull(fiscal);
|
||||
ArgumentNullException.ThrowIfNull(permissions);
|
||||
ArgumentNullException.ThrowIfNull(tables);
|
||||
ArgumentNullException.ThrowIfNull(years);
|
||||
ArgumentNullException.ThrowIfNull(clock);
|
||||
ArgumentNullException.ThrowIfNull(logger);
|
||||
_seeders = [.. seeders.OrderBy(s => s.Kind).ThenBy(s => s.Order)];
|
||||
_factory = factory;
|
||||
_fiscal = fiscal;
|
||||
_permissions = permissions;
|
||||
_tables = tables;
|
||||
_years = years;
|
||||
_clock = clock;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public int Order => 10;
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task SeedAsync(string companyCode, CompanySeedContext context, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(context);
|
||||
if (context.Base)
|
||||
{
|
||||
await RunAsync(companyCode, SeedKind.Base, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
// The demo seeders fill only a company without data of their own (each checks its tables).
|
||||
if (context.Demo)
|
||||
{
|
||||
await RunAsync(companyCode, SeedKind.Demo, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The button <i>Aggiorna tabelle di base</i>: runs the base seeders for a company.</summary>
|
||||
/// <param name="actor">Who asks: needs <c>company.settings.write</c>.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>What was added.</returns>
|
||||
public async Task<SeedReport> UpdateBaseAsync(Actor actor, string companyCode, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, TableService.WritePermission, cancellationToken).ConfigureAwait(false);
|
||||
return await RunAsync(company, SeedKind.Base, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>The data version recorded in a company, or <see langword="null"/> before the first run.</summary>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The version.</returns>
|
||||
public async Task<string?> VersionAsync(string companyCode, CancellationToken cancellationToken = default)
|
||||
{
|
||||
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(CompanyCodes.Normalize(companyCode)), cancellationToken).ConfigureAwait(false);
|
||||
var setting = await uow.Repository<CompanySetting, long>().FindAsync(Query.For<CompanySetting>().Where(s => s.Key == VersionSetting), cancellationToken).ConfigureAwait(false);
|
||||
return setting?.Value;
|
||||
}
|
||||
|
||||
/// <summary>Runs every seeder of a kind on a company.</summary>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="kind">Base or demo.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>What was added.</returns>
|
||||
public Task<SeedReport> RunAsync(string companyCode, SeedKind kind, CancellationToken cancellationToken = default) =>
|
||||
RunAsync(companyCode, kind, 1, cancellationToken);
|
||||
|
||||
/// <summary>Runs every seeder of a kind on a company, the demo ones repeating their catalogues.</summary>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="kind">Base or demo.</param>
|
||||
/// <param name="scale">How many times the demo catalogues are repeated (<c>--scale</c>), at least 1.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>What was added.</returns>
|
||||
public async Task<SeedReport> RunAsync(string companyCode, SeedKind kind, int scale, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var company = CompanyCodes.Normalize(companyCode);
|
||||
var pack = await _fiscal.PackOfAsync(company, cancellationToken).ConfigureAwait(false);
|
||||
var today = DateOnly.FromDateTime(_clock.GetLocalNow().DateTime);
|
||||
SeedContext context;
|
||||
await using (var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
|
||||
context = new SeedContext(company, uow, pack, today) { Scale = Math.Max(1, scale) };
|
||||
foreach (var seeder in _seeders.Where(s => s.Kind == kind))
|
||||
{
|
||||
await seeder.RunAsync(context, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
if (kind == SeedKind.Base)
|
||||
{
|
||||
await WriteVersionAsync(uow, pack.DataVersion, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
await _tables.InvalidateAllAsync(company, cancellationToken).ConfigureAwait(false);
|
||||
await _years.InvalidateAsync(company, cancellationToken).ConfigureAwait(false);
|
||||
await _fiscal.InvalidateAsync(company, cancellationToken).ConfigureAwait(false);
|
||||
var report = new SeedReport(pack.DataVersion, context.Added);
|
||||
LogSeeded(_logger, kind, company, pack.DataVersion, report.Total);
|
||||
return report;
|
||||
}
|
||||
|
||||
private static async Task WriteVersionAsync(IUnitOfWork uow, string version, CancellationToken cancellationToken)
|
||||
{
|
||||
var settings = uow.Repository<CompanySetting, long>();
|
||||
var setting = await settings.FindAsync(Query.For<CompanySetting>().Where(s => s.Key == VersionSetting), cancellationToken).ConfigureAwait(false);
|
||||
if (setting is null)
|
||||
{
|
||||
await settings.InsertAsync(new CompanySetting { Key = VersionSetting, Value = version }, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
else if (setting.Value != version)
|
||||
{
|
||||
setting.Value = version;
|
||||
await settings.UpdateAsync(setting, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
[LoggerMessage(Level = LogLevel.Information, Message = "Dati {Kind} dell'azienda {Company} (versione {Version}): {Added} righe aggiunte.")]
|
||||
private static partial void LogSeeded(ILogger logger, SeedKind kind, string company, string version, int added);
|
||||
}
|
||||
@@ -0,0 +1,289 @@
|
||||
using Khaemhat.Application.Instance;
|
||||
using Khaemhat.Application.Security;
|
||||
using Khaemhat.Core.Tables;
|
||||
using Khaemhat.Fiscal.Abstractions;
|
||||
using Khaemhat.Infrastructure.Http;
|
||||
|
||||
namespace Khaemhat.Application.Tables;
|
||||
|
||||
/// <summary>A municipality proposed for an address.</summary>
|
||||
/// <param name="MunicipalityCode">The code of the municipality (Italy: cadastral code).</param>
|
||||
/// <param name="Name">The name.</param>
|
||||
/// <param name="ProvinceCode">The province.</param>
|
||||
/// <param name="Region">The region.</param>
|
||||
/// <param name="PostalCode">The postal code: the one typed, or the only one of the municipality.</param>
|
||||
public sealed record PlaceSuggestion(string MunicipalityCode, string Name, string ProvinceCode, string? Region, string? PostalCode);
|
||||
|
||||
/// <summary>An option of the automatic filling (mockup 074).</summary>
|
||||
/// <param name="Key">The key, also the setting <c>autofill.<key></c>.</param>
|
||||
/// <param name="Default">Whether it is on in a new company.</param>
|
||||
public sealed record AutoFillOption(string Key, bool Default = true);
|
||||
|
||||
/// <summary>
|
||||
/// The automatic filling of SPEC §11.12: municipality, province and region from the postal code, the personal tax code
|
||||
/// from the personal data, the VIES check of EU VAT numbers, bank and BIC from the IBAN, delivery dates from the lead
|
||||
/// time. Each option can be switched off in the company preferences; the forms ask <see cref="IsOnAsync"/> before
|
||||
/// filling. The defaults that documents take from the customer and the document type come with the documents (M5).
|
||||
/// </summary>
|
||||
/// <param name="tables">The company tables.</param>
|
||||
/// <param name="fiscal">The fiscal pack of the company.</param>
|
||||
/// <param name="settings">The company settings.</param>
|
||||
/// <param name="permissions">The permissions.</param>
|
||||
/// <param name="vies">The VIES client.</param>
|
||||
public sealed class AutoFillService(TableService tables, CompanyFiscalContext fiscal, CompanySettingsService settings, PermissionService permissions, ViesClient vies)
|
||||
{
|
||||
/// <summary>The start of the setting keys.</summary>
|
||||
public const string SettingPrefix = "autofill.";
|
||||
|
||||
/// <summary>Municipality, province and region from the postal code.</summary>
|
||||
public const string PostalCode = "postal-code";
|
||||
|
||||
/// <summary>Personal tax code from the personal data.</summary>
|
||||
public const string TaxCode = "tax-code";
|
||||
|
||||
/// <summary>VIES check of EU VAT numbers when saving.</summary>
|
||||
public const string Vies = "vies";
|
||||
|
||||
/// <summary>Bank and BIC from the IBAN.</summary>
|
||||
public const string BankFromIban = "bank-from-iban";
|
||||
|
||||
/// <summary>Daily ECB exchange rates.</summary>
|
||||
public const string EcbRates = "ecb-rates";
|
||||
|
||||
/// <summary>Item description copied into document lines.</summary>
|
||||
public const string ItemDescription = "item-description";
|
||||
|
||||
/// <summary>Last price charged to the customer shown as reference.</summary>
|
||||
public const string LastPrice = "last-price";
|
||||
|
||||
/// <summary>Start from the last similar document of the customer.</summary>
|
||||
public const string LastDocument = "last-document";
|
||||
|
||||
/// <summary>Delivery date = document date + lead time.</summary>
|
||||
public const string DeliveryDate = "delivery-date";
|
||||
|
||||
/// <summary>Revenue and cost accounts from item, category and reason.</summary>
|
||||
public const string Accounts = "accounts";
|
||||
|
||||
private const int MaxSuggestions = 20;
|
||||
|
||||
/// <summary>The options, in the order of the preferences page.</summary>
|
||||
public static readonly IReadOnlyList<AutoFillOption> Options =
|
||||
[
|
||||
new(PostalCode), new(TaxCode), new(Vies), new(BankFromIban), new(EcbRates),
|
||||
new(ItemDescription), new(LastPrice), new(LastDocument, Default: false), new(DeliveryDate), new(Accounts),
|
||||
];
|
||||
|
||||
/// <summary>The options of a company.</summary>
|
||||
/// <param name="actor">Who reads.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>Whether each option is on, by key.</returns>
|
||||
public async Task<IReadOnlyDictionary<string, bool>> OptionsAsync(Actor actor, string companyCode, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var company = await CompanyGuard.DemandAsync(permissions, actor, companyCode, TableService.ReadPermission, cancellationToken).ConfigureAwait(false);
|
||||
return await ReadAsync(company, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>Whether an option is on, for the forms and services that fill fields (no permission check).</summary>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="key">The option.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns><see langword="true"/> when on.</returns>
|
||||
public async Task<bool> IsOnAsync(string companyCode, string key, CancellationToken cancellationToken = default) =>
|
||||
(await ReadAsync(companyCode, cancellationToken).ConfigureAwait(false)).GetValueOrDefault(key);
|
||||
|
||||
/// <summary>Saves the options of a company.</summary>
|
||||
/// <param name="actor">Who saves.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="values">The options to change, by key.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The options now in force.</returns>
|
||||
public async Task<IReadOnlyDictionary<string, bool>> SaveOptionsAsync(Actor actor, string companyCode, IReadOnlyDictionary<string, bool> values,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(values);
|
||||
var company = await CompanyGuard.DemandAsync(permissions, actor, companyCode, TableService.WritePermission, cancellationToken).ConfigureAwait(false);
|
||||
var known = Options.Select(o => o.Key).ToHashSet(StringComparer.Ordinal);
|
||||
await settings.SetManyAsync(
|
||||
actor,
|
||||
company,
|
||||
values.Where(v => known.Contains(v.Key)).ToDictionary(v => SettingPrefix + v.Key, v => (string?)(v.Value ? "true" : "false"), StringComparer.Ordinal),
|
||||
cancellationToken).ConfigureAwait(false);
|
||||
return await ReadAsync(company, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>The municipalities with a postal code.</summary>
|
||||
/// <param name="actor">Who asks.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="postalCode">The postal code.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The municipalities, by name; empty when none or when the code is not complete.</returns>
|
||||
public async Task<IReadOnlyList<PlaceSuggestion>> PlacesByPostalCodeAsync(Actor actor, string companyCode, string? postalCode, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var code = postalCode?.Trim() ?? string.Empty;
|
||||
if (code.Length < 4 || !code.All(char.IsAsciiDigit))
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
return
|
||||
[
|
||||
.. (await MunicipalitiesAsync(actor, companyCode, cancellationToken).ConfigureAwait(false))
|
||||
.Where(m => PostalCodeMatches(m.PostalCodes, code))
|
||||
.OrderBy(m => m.Description, StringComparer.CurrentCulture)
|
||||
.Take(MaxSuggestions)
|
||||
.Select(m => Suggest(m, code)),
|
||||
];
|
||||
}
|
||||
|
||||
/// <summary>The municipalities whose name starts with some text.</summary>
|
||||
/// <param name="actor">Who asks.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="name">The start of the name.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The municipalities, exact name first.</returns>
|
||||
public async Task<IReadOnlyList<PlaceSuggestion>> PlacesByNameAsync(Actor actor, string companyCode, string? name, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var text = name?.Trim() ?? string.Empty;
|
||||
if (text.Length < 2)
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
return
|
||||
[
|
||||
.. (await MunicipalitiesAsync(actor, companyCode, cancellationToken).ConfigureAwait(false))
|
||||
.Where(m => m.Description.StartsWith(text, StringComparison.CurrentCultureIgnoreCase))
|
||||
.OrderBy(m => m.Description.Length == text.Length ? 0 : 1)
|
||||
.ThenBy(m => m.Description, StringComparer.CurrentCulture)
|
||||
.Take(MaxSuggestions)
|
||||
.Select(m => Suggest(m, null)),
|
||||
];
|
||||
}
|
||||
|
||||
/// <summary>Whether a postal code is in a list such as <c>10121,10122</c> or <c>00118-00199</c>.</summary>
|
||||
/// <param name="list">The postal codes of a municipality.</param>
|
||||
/// <param name="code">The postal code.</param>
|
||||
/// <returns><see langword="true"/> when it is one of them.</returns>
|
||||
public static bool PostalCodeMatches(string? list, string code)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(code);
|
||||
foreach (var item in (list ?? string.Empty).Split([',', ';', ' '], StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries))
|
||||
{
|
||||
var dash = item.IndexOf('-', StringComparison.Ordinal);
|
||||
if (dash < 0)
|
||||
{
|
||||
if (string.Equals(item, code, StringComparison.Ordinal))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
var from = item[..dash].Trim();
|
||||
var to = item[(dash + 1)..].Trim();
|
||||
if (from.Length == code.Length && to.Length == code.Length
|
||||
&& string.CompareOrdinal(code, from) >= 0 && string.CompareOrdinal(code, to) <= 0)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>The personal tax code of a person, computed by the fiscal pack of the company.</summary>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="data">The personal data.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The code, or <see langword="null"/> when the country has no such code or the data are incomplete.</returns>
|
||||
public async Task<string?> PersonalTaxCodeAsync(string companyCode, PersonalTaxCodeData data, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(data);
|
||||
var pack = await fiscal.PackOfAsync(companyCode, cancellationToken).ConfigureAwait(false);
|
||||
if (pack.GetFeature<ITaxIdentifierRules>() is not { } rules
|
||||
|| string.IsNullOrWhiteSpace(data.Surname) || string.IsNullOrWhiteSpace(data.GivenName) || string.IsNullOrWhiteSpace(data.BirthPlaceCode))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
return rules.ComputePersonalTaxCode(data);
|
||||
}
|
||||
catch (ArgumentException)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Checks an EU VAT number with VIES.</summary>
|
||||
/// <param name="countryCode">The ISO country code.</param>
|
||||
/// <param name="vatNumber">The number.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The outcome; a service that does not answer gives <see cref="ViesStatus.Unavailable"/>.</returns>
|
||||
public Task<ViesResult> CheckVatAsync(string countryCode, string vatNumber, CancellationToken cancellationToken = default) =>
|
||||
vies.CheckAsync(countryCode, vatNumber, cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// The bank of an IBAN: name and BIC from the directory of the fiscal pack or, when the directory does not know the
|
||||
/// bank, from an account of the company at the same bank.
|
||||
/// </summary>
|
||||
/// <param name="actor">Who asks.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="iban">The IBAN.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The bank, or <see langword="null"/> when the IBAN is not a domestic one.</returns>
|
||||
public async Task<BankInfo?> BankFromIbanAsync(Actor actor, string companyCode, string? iban, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var pack = await fiscal.PackOfAsync(companyCode, cancellationToken).ConfigureAwait(false);
|
||||
if (pack.GetFeature<IBankDirectory>() is not { } directory || directory.ReadIban(iban) is not { } bank)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
if (bank.Name is not null)
|
||||
{
|
||||
return bank;
|
||||
}
|
||||
|
||||
var known = (await tables.ActiveAsync<BankAccount>(actor, companyCode, cancellationToken).ConfigureAwait(false))
|
||||
.Select(a => (Account: a, Bank: directory.ReadIban(a.Iban)))
|
||||
.FirstOrDefault(a => a.Bank?.BankCode == bank.BankCode && !string.IsNullOrWhiteSpace(a.Account.BankName));
|
||||
return known.Account is { } account ? bank with { Name = account.BankName, Bic = account.Bic } : bank;
|
||||
}
|
||||
|
||||
/// <summary>The delivery date of a record: its date plus the lead time, moved to the next working day.</summary>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="date">The date of the document.</param>
|
||||
/// <param name="leadTimeDays">The lead time in calendar days.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The date.</returns>
|
||||
public async Task<DateOnly> DeliveryDateAsync(string companyCode, DateOnly date, int leadTimeDays, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var pack = await fiscal.PackOfAsync(companyCode, cancellationToken).ConfigureAwait(false);
|
||||
return pack.Calendar.NextWorkingDay(date.AddDays(Math.Max(0, leadTimeDays)));
|
||||
}
|
||||
|
||||
private async Task<IReadOnlyList<Municipality>> MunicipalitiesAsync(Actor actor, string companyCode, CancellationToken cancellationToken) =>
|
||||
await tables.ActiveAsync<Municipality>(actor, companyCode, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
private static PlaceSuggestion Suggest(Municipality municipality, string? postalCode)
|
||||
{
|
||||
var single = municipality.PostalCodes is { } codes && !codes.Contains(',', StringComparison.Ordinal) && !codes.Contains('-', StringComparison.Ordinal)
|
||||
? codes.Trim()
|
||||
: null;
|
||||
return new PlaceSuggestion(municipality.Code, municipality.Description, municipality.ProvinceCode, municipality.Region, postalCode ?? single);
|
||||
}
|
||||
|
||||
private async Task<IReadOnlyDictionary<string, bool>> ReadAsync(string company, CancellationToken cancellationToken)
|
||||
{
|
||||
var values = await settings.GetAllAsync(company, SettingPrefix, cancellationToken).ConfigureAwait(false);
|
||||
return Options.ToDictionary(
|
||||
o => o.Key,
|
||||
o => values.TryGetValue(SettingPrefix + o.Key, out var value) && bool.TryParse(value, out var on) ? on : o.Default,
|
||||
StringComparer.Ordinal);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,286 @@
|
||||
using Khaemhat.Application.Instance;
|
||||
using Khaemhat.Application.Modules;
|
||||
using Khaemhat.Application.Security;
|
||||
using Khaemhat.Core.Tables;
|
||||
using Khaemhat.Data;
|
||||
using Khaemhat.Data.Querying;
|
||||
|
||||
namespace Khaemhat.Application.Tables;
|
||||
|
||||
/// <summary>A table whose codes can be given automatically (SPEC §11.12, mockup 074).</summary>
|
||||
/// <param name="Key">The rule key, also the start of the sequence keys, such as <c>customers</c>.</param>
|
||||
/// <param name="Group">The box of the preferences page: <c>parties</c>, <c>items</c> or <c>crm</c>.</param>
|
||||
/// <param name="DefaultMask">The mask of a new company.</param>
|
||||
/// <param name="Module">The licence module the table belongs to.</param>
|
||||
/// <param name="CategoriesAllowed">Whether the mask may use the category.</param>
|
||||
/// <param name="MaxLength">The longest code the table accepts.</param>
|
||||
public sealed record CodeRuleDefinition(string Key, string Group, string DefaultMask, string Module, bool CategoriesAllowed = false, int MaxLength = 20);
|
||||
|
||||
/// <summary>The automatic code of a table as the company set it.</summary>
|
||||
/// <param name="Key">The rule key.</param>
|
||||
/// <param name="Mask">The mask.</param>
|
||||
/// <param name="AllowManual">Whether a user may write a code instead of the automatic one.</param>
|
||||
/// <param name="UniqueBarcode">Items only: refuse two items with the same EAN.</param>
|
||||
public sealed record CodeRule(string Key, string Mask, bool AllowManual, bool UniqueBarcode = false);
|
||||
|
||||
/// <summary>
|
||||
/// The automatic codes of a company (SPEC §11.12): the mask of each table in the company settings
|
||||
/// (<c>codes.<table>.mask</c>, <c>codes.<table>.manual</c>) and the numbers in <c>code_sequences</c>, given
|
||||
/// under a lock inside the transaction that saves the record, so two saves at the same time never get the same code. A
|
||||
/// number whose code is already taken (a code written by hand) is skipped.
|
||||
/// </summary>
|
||||
/// <param name="factory">The units of work.</param>
|
||||
/// <param name="permissions">The permissions.</param>
|
||||
/// <param name="settings">The company settings.</param>
|
||||
public sealed class CodeRuleService(IUnitOfWorkFactory factory, PermissionService permissions, CompanySettingsService settings)
|
||||
{
|
||||
/// <summary>The start of the setting keys.</summary>
|
||||
public const string SettingPrefix = "codes.";
|
||||
|
||||
/// <summary>Error: the code was written by hand where only automatic codes are allowed.</summary>
|
||||
public const string ManualNotAllowed = "codes.manual";
|
||||
|
||||
/// <summary>Error: the mask uses the category and the record has none.</summary>
|
||||
public const string CategoryRequired = "codes.category-required";
|
||||
|
||||
/// <summary>Error: the code is longer than the table accepts.</summary>
|
||||
public const string CodeTooLong = "codes.too-long";
|
||||
|
||||
/// <summary>Error: no free code was found (too many codes taken by hand).</summary>
|
||||
public const string Exhausted = "codes.exhausted";
|
||||
|
||||
/// <summary>The field the errors of a record's code are reported on.</summary>
|
||||
public const string CodeField = "Code";
|
||||
|
||||
/// <summary>The field the errors of a mask are reported on.</summary>
|
||||
public const string MaskField = "Mask";
|
||||
|
||||
private const int MaxSkips = 1000;
|
||||
|
||||
/// <summary>The tables with automatic codes and their masks of SPEC §11.12.</summary>
|
||||
public static readonly IReadOnlyList<CodeRuleDefinition> Definitions =
|
||||
[
|
||||
new("customers", "parties", "C{seq:000000}", ModuleCodes.Core),
|
||||
new("suppliers", "parties", "F{seq:000000}", ModuleCodes.Core),
|
||||
new("leads", "parties", "L{anno}-{seq:0000}", ModuleCodes.Crm),
|
||||
new("items", "items", "{categoria}-{seq:0000}", ModuleCodes.Core, CategoriesAllowed: true, MaxLength: 30),
|
||||
new("assets", "items", "CESP-{seq:0000}", ModuleCodes.Assets),
|
||||
new("opportunities", "crm", "OPP-{anno}-{seq:0000}", ModuleCodes.Crm),
|
||||
new("tickets", "crm", "TK-{anno}-{seq:0000}", ModuleCodes.Services),
|
||||
new("service-contracts", "crm", "SVC-{seq:0000}", ModuleCodes.Services),
|
||||
new("interventions", "crm", "MAN-{anno}-{seq:0000}", ModuleCodes.Services),
|
||||
];
|
||||
|
||||
/// <summary>The definition of a rule.</summary>
|
||||
/// <param name="key">The rule key.</param>
|
||||
/// <returns>The definition.</returns>
|
||||
/// <exception cref="KeyNotFoundException">The key is not a rule.</exception>
|
||||
public static CodeRuleDefinition Definition(string key) =>
|
||||
Definitions.FirstOrDefault(d => d.Key == key) ?? throw new KeyNotFoundException("Unknown code rule " + key + ".");
|
||||
|
||||
/// <summary>The rule of a new company.</summary>
|
||||
/// <param name="definition">The table.</param>
|
||||
/// <returns>The rule.</returns>
|
||||
public static CodeRule DefaultRule(CodeRuleDefinition definition)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(definition);
|
||||
return new CodeRule(definition.Key, definition.DefaultMask, AllowManual: true, UniqueBarcode: definition.Key == "items");
|
||||
}
|
||||
|
||||
/// <summary>Checks a set of rules.</summary>
|
||||
/// <param name="rules">The rules.</param>
|
||||
/// <returns>The errors, on <c><key>.Mask</c>.</returns>
|
||||
public static IReadOnlyList<TableProblem> Validate(IEnumerable<CodeRule> rules)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(rules);
|
||||
var problems = new List<TableProblem>();
|
||||
foreach (var rule in rules)
|
||||
{
|
||||
var definition = Definition(rule.Key);
|
||||
if (CodeMask.Check(rule.Mask, definition.MaxLength, definition.CategoriesAllowed) is { } error)
|
||||
{
|
||||
problems.Add(new(rule.Key + "." + MaskField, error));
|
||||
}
|
||||
}
|
||||
|
||||
return problems;
|
||||
}
|
||||
|
||||
/// <summary>The rules of a company, every table included (the default where the company set nothing).</summary>
|
||||
/// <param name="actor">Who reads.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The rules, in the order of <see cref="Definitions"/>.</returns>
|
||||
public async Task<IReadOnlyList<CodeRule>> RulesAsync(Actor actor, string companyCode, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var company = await CompanyGuard.DemandAsync(permissions, actor, companyCode, TableService.ReadPermission, cancellationToken).ConfigureAwait(false);
|
||||
return await ReadRulesAsync(company, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>The rule of one table, for the services that save its records (no permission check).</summary>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="key">The rule key.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The rule.</returns>
|
||||
public async Task<CodeRule> RuleAsync(string companyCode, string key, CancellationToken cancellationToken = default)
|
||||
{
|
||||
_ = Definition(key);
|
||||
return (await ReadRulesAsync(CompanyCodes.Normalize(companyCode), cancellationToken).ConfigureAwait(false)).First(r => r.Key == key);
|
||||
}
|
||||
|
||||
/// <summary>Saves the rules of a company.</summary>
|
||||
/// <param name="actor">Who saves.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="rules">The rules (tables left out keep their rule).</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The rules now in force.</returns>
|
||||
/// <exception cref="ValidationFailedException">A mask is not valid (<c><key>.Mask:code</c>).</exception>
|
||||
public async Task<IReadOnlyList<CodeRule>> SaveAsync(Actor actor, string companyCode, IReadOnlyList<CodeRule> rules, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(rules);
|
||||
var company = await CompanyGuard.DemandAsync(permissions, actor, companyCode, TableService.WritePermission, cancellationToken).ConfigureAwait(false);
|
||||
var problems = Validate(rules);
|
||||
if (problems.Count > 0)
|
||||
{
|
||||
throw new ValidationFailedException([.. problems.Select(p => p.Field + ":" + p.Code)]);
|
||||
}
|
||||
|
||||
var values = new Dictionary<string, string?>(StringComparer.Ordinal);
|
||||
foreach (var rule in rules)
|
||||
{
|
||||
values[SettingPrefix + rule.Key + ".mask"] = CodeMask.Parse(rule.Mask).Text;
|
||||
values[SettingPrefix + rule.Key + ".manual"] = rule.AllowManual ? "true" : "false";
|
||||
if (rule.Key == "items")
|
||||
{
|
||||
values[SettingPrefix + "items.unique-barcode"] = rule.UniqueBarcode ? "true" : "false";
|
||||
}
|
||||
}
|
||||
|
||||
await settings.SetManyAsync(actor, company, values, cancellationToken).ConfigureAwait(false);
|
||||
return await ReadRulesAsync(company, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>The code the next record would get, without taking it.</summary>
|
||||
/// <param name="actor">Who asks.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="rule">The rule, possibly not saved yet.</param>
|
||||
/// <param name="date">The date of the record (for masks with the year).</param>
|
||||
/// <param name="category">The category (for masks with the category).</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The code, or <see langword="null"/> when the mask is not valid.</returns>
|
||||
public async Task<string?> PreviewAsync(Actor actor, string companyCode, CodeRule rule, DateOnly date, string? category, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(rule);
|
||||
var company = await CompanyGuard.DemandAsync(permissions, actor, companyCode, TableService.ReadPermission, cancellationToken).ConfigureAwait(false);
|
||||
if (!CodeMask.TryParse(rule.Mask, out var mask, out _) || (mask!.UsesCategory && string.IsNullOrWhiteSpace(category)))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
await using var uow = await factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
||||
var key = mask.SequenceKey(rule.Key, date.Year, category);
|
||||
var last = await uow.Repository<CodeSequence, long>().FindAsync(Query.For<CodeSequence>().Where(s => s.Key == key), cancellationToken).ConfigureAwait(false);
|
||||
return mask.Format((last?.LastValue ?? 0) + 1, date.Year, category);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Takes the next free code inside the caller's transaction; the number is used up only if the transaction commits.
|
||||
/// </summary>
|
||||
/// <param name="unitOfWork">The unit of work of the save, with a transaction open.</param>
|
||||
/// <param name="rule">The rule.</param>
|
||||
/// <param name="date">The date of the record.</param>
|
||||
/// <param name="category">The category, for masks with the category.</param>
|
||||
/// <param name="taken">Whether a code is already used in the table.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The code.</returns>
|
||||
/// <exception cref="ValidationFailedException">No category, code too long, or no free code (<c>Code:code</c>).</exception>
|
||||
public static async Task<string> AssignAsync(IUnitOfWork unitOfWork, CodeRule rule, DateOnly date, string? category,
|
||||
Func<string, CancellationToken, Task<bool>> taken, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(unitOfWork);
|
||||
ArgumentNullException.ThrowIfNull(rule);
|
||||
ArgumentNullException.ThrowIfNull(taken);
|
||||
var definition = Definition(rule.Key);
|
||||
var mask = CodeMask.Parse(rule.Mask);
|
||||
if (mask.UsesCategory && string.IsNullOrWhiteSpace(category))
|
||||
{
|
||||
throw new ValidationFailedException([CodeField + ":" + CategoryRequired]);
|
||||
}
|
||||
|
||||
var key = mask.SequenceKey(rule.Key, date.Year, category);
|
||||
await unitOfWork.AcquireLockAsync("code:" + key, cancellationToken).ConfigureAwait(false);
|
||||
var repository = unitOfWork.Repository<CodeSequence, long>();
|
||||
var sequence = await repository.FindAsync(Query.For<CodeSequence>().Where(s => s.Key == key), cancellationToken).ConfigureAwait(false)
|
||||
?? new CodeSequence { Key = key };
|
||||
for (var skip = 0; skip < MaxSkips; skip++)
|
||||
{
|
||||
sequence.LastValue++;
|
||||
var code = mask.Format(sequence.LastValue, date.Year, category);
|
||||
if (code.Length > definition.MaxLength)
|
||||
{
|
||||
throw new ValidationFailedException([CodeField + ":" + CodeTooLong]);
|
||||
}
|
||||
|
||||
if (await taken(code, cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
if (sequence.Id == 0)
|
||||
{
|
||||
await repository.InsertAsync(sequence, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
else
|
||||
{
|
||||
await repository.UpdateAsync(sequence, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
return code;
|
||||
}
|
||||
|
||||
throw new ValidationFailedException([CodeField + ":" + Exhausted]);
|
||||
}
|
||||
|
||||
/// <summary>Checks a code written by hand against the rule.</summary>
|
||||
/// <param name="rule">The rule.</param>
|
||||
/// <param name="code">The code, empty to get the automatic one.</param>
|
||||
/// <returns>The error code, or <see langword="null"/>.</returns>
|
||||
public static string? CheckManual(CodeRule rule, string? code)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(rule);
|
||||
if (string.IsNullOrWhiteSpace(code))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
if (!rule.AllowManual)
|
||||
{
|
||||
return ManualNotAllowed;
|
||||
}
|
||||
|
||||
return code.Trim().Length > Definition(rule.Key).MaxLength ? CodeTooLong : null;
|
||||
}
|
||||
|
||||
private async Task<IReadOnlyList<CodeRule>> ReadRulesAsync(string company, CancellationToken cancellationToken)
|
||||
{
|
||||
var values = await settings.GetAllAsync(company, SettingPrefix, cancellationToken).ConfigureAwait(false);
|
||||
return
|
||||
[
|
||||
.. Definitions.Select(d =>
|
||||
{
|
||||
var rule = DefaultRule(d);
|
||||
var mask = values.GetValueOrDefault(SettingPrefix + d.Key + ".mask");
|
||||
return rule with
|
||||
{
|
||||
Mask = mask is { Length: > 0 } && CodeMask.Check(mask, d.MaxLength, d.CategoriesAllowed) is null ? mask : rule.Mask,
|
||||
AllowManual = ReadFlag(values, SettingPrefix + d.Key + ".manual", rule.AllowManual),
|
||||
UniqueBarcode = d.Key == "items" && ReadFlag(values, SettingPrefix + "items.unique-barcode", rule.UniqueBarcode),
|
||||
};
|
||||
}),
|
||||
];
|
||||
}
|
||||
|
||||
private static bool ReadFlag(IReadOnlyDictionary<string, string?> values, string key, bool fallback) =>
|
||||
values.TryGetValue(key, out var value) && bool.TryParse(value, out var flag) ? flag : fallback;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
using Khaemhat.Application.Configuration;
|
||||
using Khaemhat.Core.Caching;
|
||||
using Khaemhat.Core.Tables;
|
||||
using Khaemhat.Data;
|
||||
using Khaemhat.Data.Querying;
|
||||
using Khaemhat.Fiscal.Abstractions;
|
||||
|
||||
namespace Khaemhat.Application.Tables;
|
||||
|
||||
/// <summary>
|
||||
/// The fiscal pack of each company: the one of <c>company_profile.country</c>, or of <c>KHAEMHAT_COUNTRY</c> while the
|
||||
/// profile is missing (ADR 0025). The country is cached per company.
|
||||
/// </summary>
|
||||
public sealed class CompanyFiscalContext
|
||||
{
|
||||
private static readonly TimeSpan CacheTime = TimeSpan.FromHours(1);
|
||||
|
||||
private readonly IUnitOfWorkFactory _factory;
|
||||
private readonly FiscalPackCatalog _packs;
|
||||
private readonly ICacheProvider _cache;
|
||||
private readonly string _defaultCountry;
|
||||
|
||||
/// <summary>Creates the context.</summary>
|
||||
/// <param name="factory">Opens the company databases.</param>
|
||||
/// <param name="packs">The fiscal packs.</param>
|
||||
/// <param name="cache">The cache.</param>
|
||||
/// <param name="options">The instance options (<c>KHAEMHAT_COUNTRY</c>).</param>
|
||||
public CompanyFiscalContext(IUnitOfWorkFactory factory, FiscalPackCatalog packs, ICacheProvider cache, KhaemhatOptions options)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(factory);
|
||||
ArgumentNullException.ThrowIfNull(packs);
|
||||
ArgumentNullException.ThrowIfNull(cache);
|
||||
ArgumentNullException.ThrowIfNull(options);
|
||||
_factory = factory;
|
||||
_packs = packs;
|
||||
_cache = cache;
|
||||
_defaultCountry = options.Country;
|
||||
}
|
||||
|
||||
/// <summary>The country given to new companies.</summary>
|
||||
public string DefaultCountry => _defaultCountry;
|
||||
|
||||
/// <summary>The pack of the instance's default country.</summary>
|
||||
public IFiscalPack DefaultPack => _packs.ForCountry(_defaultCountry);
|
||||
|
||||
/// <summary>The fiscal pack of a company.</summary>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The pack.</returns>
|
||||
public async Task<IFiscalPack> PackOfAsync(string companyCode, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var company = CompanyCodes.Normalize(companyCode);
|
||||
var country = await _cache.GetOrCreateAsync(
|
||||
CacheKeys.For(company, "fiscal", "country"),
|
||||
async ct =>
|
||||
{
|
||||
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), ct).ConfigureAwait(false);
|
||||
var profile = await uow.Repository<CompanyProfile, long>().FindAsync(Query.For<CompanyProfile>(), ct).ConfigureAwait(false);
|
||||
return profile?.Country ?? _defaultCountry;
|
||||
},
|
||||
CacheTime,
|
||||
cancellationToken).ConfigureAwait(false);
|
||||
return _packs.TryForCountry(country, out var pack) ? pack : DefaultPack;
|
||||
}
|
||||
|
||||
/// <summary>Forgets the cached country of a company (after the profile changes).</summary>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>A task.</returns>
|
||||
public ValueTask InvalidateAsync(string companyCode, CancellationToken cancellationToken = default) =>
|
||||
_cache.PublishInvalidationAsync(CacheKeys.Prefix(CompanyCodes.Normalize(companyCode), "fiscal"), cancellationToken);
|
||||
}
|
||||
@@ -0,0 +1,287 @@
|
||||
using System.Text.RegularExpressions;
|
||||
using Khaemhat.Application.Audit;
|
||||
using Khaemhat.Application.Security;
|
||||
using Khaemhat.Core.Tables;
|
||||
using Khaemhat.Core.Tax;
|
||||
using Khaemhat.Core.Validation;
|
||||
using Khaemhat.Data;
|
||||
using Khaemhat.Data.Companies;
|
||||
using Khaemhat.Data.Querying;
|
||||
using Khaemhat.Fiscal.Abstractions;
|
||||
|
||||
namespace Khaemhat.Application.Tables;
|
||||
|
||||
/// <summary>
|
||||
/// The company profile (SPEC §11.1, mockup 075): one row per company, created on the first save. The country chooses
|
||||
/// the fiscal pack; changing it is refused once documents exist (from M5).
|
||||
/// </summary>
|
||||
public sealed partial class CompanyProfileService
|
||||
{
|
||||
/// <summary>Error: the name is missing.</summary>
|
||||
public const string NameRequired = "profile.name.required";
|
||||
|
||||
/// <summary>Error: no fiscal pack for the country.</summary>
|
||||
public const string CountryUnknown = "profile.country.unknown";
|
||||
|
||||
/// <summary>Error: the month is outside 1-12.</summary>
|
||||
public const string MonthRange = "profile.month.range";
|
||||
|
||||
/// <summary>Error: a code that must be two letters.</summary>
|
||||
public const string TwoLettersRequired = "profile.two-letters";
|
||||
|
||||
/// <summary>Error: the tax code is not valid.</summary>
|
||||
public const string TaxCodeInvalid = "profile.tax-code.invalid";
|
||||
|
||||
/// <summary>Error: the recipient code is not seven characters.</summary>
|
||||
public const string RecipientCodeInvalid = "profile.recipient-code.invalid";
|
||||
|
||||
/// <summary>Error: a value outside the list (<c>SU/SM</c>, <c>LS/LN</c>).</summary>
|
||||
public const string ValueInvalid = "profile.value.invalid";
|
||||
|
||||
private readonly IUnitOfWorkFactory _factory;
|
||||
private readonly PermissionService _permissions;
|
||||
private readonly AuditTrail _audit;
|
||||
private readonly CompanyFiscalContext _fiscal;
|
||||
private readonly FiscalPackCatalog _packs;
|
||||
private readonly ICompanyRegistry _companies;
|
||||
|
||||
/// <summary>Creates the service.</summary>
|
||||
/// <param name="factory">Opens the company databases.</param>
|
||||
/// <param name="permissions">Checks permissions.</param>
|
||||
/// <param name="audit">Writes the history.</param>
|
||||
/// <param name="fiscal">The fiscal pack of each company.</param>
|
||||
/// <param name="packs">The installed fiscal packs.</param>
|
||||
/// <param name="companies">The registry, for the name of a company without a profile yet.</param>
|
||||
public CompanyProfileService(IUnitOfWorkFactory factory, PermissionService permissions, AuditTrail audit, CompanyFiscalContext fiscal, FiscalPackCatalog packs, ICompanyRegistry companies)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(factory);
|
||||
ArgumentNullException.ThrowIfNull(permissions);
|
||||
ArgumentNullException.ThrowIfNull(audit);
|
||||
ArgumentNullException.ThrowIfNull(fiscal);
|
||||
ArgumentNullException.ThrowIfNull(packs);
|
||||
ArgumentNullException.ThrowIfNull(companies);
|
||||
_companies = companies;
|
||||
_factory = factory;
|
||||
_permissions = permissions;
|
||||
_audit = audit;
|
||||
_fiscal = fiscal;
|
||||
_packs = packs;
|
||||
}
|
||||
|
||||
/// <summary>The profile, or a new one with the defaults of the instance when the company has none yet.</summary>
|
||||
/// <param name="actor">Who reads.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The profile (<see cref="Core.Entities.Entity{TKey}.Id"/> 0 when new).</returns>
|
||||
public async Task<CompanyProfile> GetAsync(Actor actor, string companyCode, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, TableService.ReadPermission, cancellationToken).ConfigureAwait(false);
|
||||
await using (var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
if (await LoadAsync(uow, cancellationToken).ConfigureAwait(false) is { } profile)
|
||||
{
|
||||
return profile;
|
||||
}
|
||||
}
|
||||
|
||||
// A new profile starts from the name the company was registered with.
|
||||
var registered = await _companies.FindAsync(company, cancellationToken).ConfigureAwait(false);
|
||||
return NewProfile(registered?.Name is { Length: > 0 } name ? name : company);
|
||||
}
|
||||
|
||||
/// <summary>Checks a profile without saving it.</summary>
|
||||
/// <param name="profile">The profile (normalized in place).</param>
|
||||
/// <returns>Errors and warnings by field.</returns>
|
||||
public IReadOnlyList<TableProblem> Validate(CompanyProfile profile)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(profile);
|
||||
var problems = new List<TableProblem>();
|
||||
profile.LegalName = profile.LegalName.Trim();
|
||||
profile.Country = profile.Country.Trim().ToUpperInvariant();
|
||||
if (profile.LegalName.Length == 0)
|
||||
{
|
||||
problems.Add(new(nameof(CompanyProfile.LegalName), NameRequired));
|
||||
}
|
||||
|
||||
if (!_packs.TryForCountry(profile.Country, out var pack))
|
||||
{
|
||||
problems.Add(new(nameof(CompanyProfile.Country), CountryUnknown));
|
||||
pack = _fiscal.DefaultPack;
|
||||
}
|
||||
|
||||
if (pack.GetFeature<ITaxIdentifierRules>() is { } rules)
|
||||
{
|
||||
if (!string.IsNullOrWhiteSpace(profile.VatNumber))
|
||||
{
|
||||
profile.VatNumber = rules.NormalizeVatNumber(profile.VatNumber);
|
||||
if (!rules.IsValidVatNumber(profile.VatNumber))
|
||||
{
|
||||
problems.Add(new(nameof(CompanyProfile.VatNumber), TableCatalog.VatNumberInvalid));
|
||||
}
|
||||
}
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(profile.TaxCode))
|
||||
{
|
||||
profile.TaxCode = profile.TaxCode.Trim().ToUpperInvariant();
|
||||
if (!rules.IsValidTaxCode(profile.TaxCode))
|
||||
{
|
||||
problems.Add(new(nameof(CompanyProfile.TaxCode), TaxCodeInvalid));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (pack.GetFeature<IEInvoiceFormat>() is { } format && format.TaxRegimes.Find(profile.TaxRegime) is not { Obsolete: false })
|
||||
{
|
||||
problems.Add(new(nameof(CompanyProfile.TaxRegime), TableCatalog.NotInCodeList));
|
||||
}
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(profile.RecipientCode))
|
||||
{
|
||||
profile.RecipientCode = profile.RecipientCode.Trim().ToUpperInvariant();
|
||||
if (!RecipientCode().IsMatch(profile.RecipientCode))
|
||||
{
|
||||
problems.Add(new(nameof(CompanyProfile.RecipientCode), RecipientCodeInvalid));
|
||||
}
|
||||
}
|
||||
|
||||
CheckTwoLetters(profile.ProvinceCode, nameof(CompanyProfile.ProvinceCode), problems, v => profile.ProvinceCode = v);
|
||||
CheckTwoLetters(profile.ReaOffice, nameof(CompanyProfile.ReaOffice), problems, v => profile.ReaOffice = v);
|
||||
CheckTwoLetters(profile.AddressCountry, nameof(CompanyProfile.AddressCountry), problems, v => profile.AddressCountry = v);
|
||||
CheckTwoLetters(profile.TransmitterCountry, nameof(CompanyProfile.TransmitterCountry), problems, v => profile.TransmitterCountry = v);
|
||||
if (profile.Shareholders is { Length: > 0 } shareholders && shareholders is not ("SU" or "SM"))
|
||||
{
|
||||
problems.Add(new(nameof(CompanyProfile.Shareholders), ValueInvalid));
|
||||
}
|
||||
|
||||
if (profile.LiquidationStatus is { Length: > 0 } liquidation && liquidation is not ("LS" or "LN"))
|
||||
{
|
||||
problems.Add(new(nameof(CompanyProfile.LiquidationStatus), ValueInvalid));
|
||||
}
|
||||
|
||||
foreach (var (value, field) in new[] { (profile.Email, nameof(CompanyProfile.Email)), (profile.Pec, nameof(CompanyProfile.Pec)) })
|
||||
{
|
||||
if (!string.IsNullOrWhiteSpace(value) && !EmailValidator.IsValid(value))
|
||||
{
|
||||
problems.Add(new(field, TableCatalog.EmailInvalid));
|
||||
}
|
||||
}
|
||||
|
||||
if (profile.ProRataPercent is < 0 or > 100)
|
||||
{
|
||||
problems.Add(new(nameof(CompanyProfile.ProRataPercent), TableCatalog.PercentRange));
|
||||
}
|
||||
|
||||
if (profile.FiscalYearStartMonth is < 1 or > 12)
|
||||
{
|
||||
problems.Add(new(nameof(CompanyProfile.FiscalYearStartMonth), MonthRange));
|
||||
}
|
||||
|
||||
profile.CurrencyCode = profile.CurrencyCode.Trim().ToUpperInvariant();
|
||||
if (profile.CurrencyCode.Length != 3)
|
||||
{
|
||||
problems.Add(new(nameof(CompanyProfile.CurrencyCode), TableCatalog.CodePattern));
|
||||
}
|
||||
|
||||
return problems;
|
||||
}
|
||||
|
||||
/// <summary>Saves the profile (inserted the first time).</summary>
|
||||
/// <param name="actor">Who saves.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="profile">The profile.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The saved profile.</returns>
|
||||
/// <exception cref="ValidationFailedException">A rule failed (<c>Field:code</c>).</exception>
|
||||
public async Task<CompanyProfile> SaveAsync(Actor actor, string companyCode, CompanyProfile profile, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(profile);
|
||||
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, TableService.WritePermission, cancellationToken).ConfigureAwait(false);
|
||||
var errors = Validate(profile).Where(p => !p.IsWarning).Select(p => p.Field + ":" + p.Code).ToList();
|
||||
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<CompanyProfile, long>();
|
||||
var before = await LoadAsync(uow, cancellationToken).ConfigureAwait(false);
|
||||
if (before is null)
|
||||
{
|
||||
profile.Id = await repository.InsertAsync(profile, cancellationToken).ConfigureAwait(false);
|
||||
await _audit.RecordAsync(uow, AuditAction.Insert, profile.Id, null, profile, actor.UserName, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
else
|
||||
{
|
||||
profile.Id = before.Id;
|
||||
await repository.UpdateAsync(profile, cancellationToken).ConfigureAwait(false);
|
||||
await _audit.RecordAsync(uow, AuditAction.Update, profile.Id, before, profile, actor.UserName, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
await _fiscal.InvalidateAsync(company, cancellationToken).ConfigureAwait(false);
|
||||
return profile;
|
||||
}
|
||||
|
||||
/// <summary>A new profile with the defaults of the instance (country from <c>KHAEMHAT_COUNTRY</c>).</summary>
|
||||
/// <param name="companyName">The name proposed.</param>
|
||||
/// <returns>The profile.</returns>
|
||||
public CompanyProfile NewProfile(string companyName) => new()
|
||||
{
|
||||
LegalName = companyName,
|
||||
Country = _fiscal.DefaultCountry.ToUpperInvariant(),
|
||||
AddressCountry = _fiscal.DefaultCountry.ToUpperInvariant(),
|
||||
CurrencyCode = "EUR",
|
||||
VatPeriodicity = VatPeriodicity.Monthly,
|
||||
LiquidationStatus = "LN",
|
||||
};
|
||||
|
||||
internal static Task<CompanyProfile?> LoadAsync(IUnitOfWork uow, CancellationToken cancellationToken) =>
|
||||
uow.Repository<CompanyProfile, long>().FindAsync(Query.For<CompanyProfile>().OrderBy(x => x.Id), cancellationToken);
|
||||
|
||||
private static void CheckTwoLetters(string? value, string field, List<TableProblem> problems, Action<string?> set)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(value))
|
||||
{
|
||||
set(null);
|
||||
return;
|
||||
}
|
||||
|
||||
var upper = value.Trim().ToUpperInvariant();
|
||||
set(upper);
|
||||
if (upper.Length != 2 || !upper.All(char.IsAsciiLetterUpper))
|
||||
{
|
||||
problems.Add(new(field, TwoLettersRequired));
|
||||
}
|
||||
}
|
||||
|
||||
[GeneratedRegex("^[A-Z0-9]{6,7}$", RegexOptions.CultureInvariant)]
|
||||
private static partial Regex RecipientCode();
|
||||
}
|
||||
|
||||
/// <summary>The common access check of the company services.</summary>
|
||||
internal static class CompanyGuard
|
||||
{
|
||||
/// <summary>Checks that the actor works in the company and has the permission.</summary>
|
||||
/// <param name="permissions">The permission service.</param>
|
||||
/// <param name="actor">Who acts.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="permission">The permission.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The normalized company code.</returns>
|
||||
public static async Task<string> DemandAsync(PermissionService permissions, Actor actor, string companyCode, string permission, CancellationToken cancellationToken)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(actor);
|
||||
var company = CompanyCodes.Normalize(companyCode);
|
||||
if (!actor.IsInstanceAccount && !string.Equals(actor.CompanyCode, company, StringComparison.Ordinal))
|
||||
{
|
||||
throw new AccessDeniedException(SecurityErrors.PermissionDenied, "A company user works only in its own company.");
|
||||
}
|
||||
|
||||
await permissions.DemandAsync(actor, permission, cancellationToken).ConfigureAwait(false);
|
||||
return company;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,212 @@
|
||||
using System.Globalization;
|
||||
using Khaemhat.Application.Audit;
|
||||
using Khaemhat.Application.Jobs;
|
||||
using Khaemhat.Application.Querying;
|
||||
using Khaemhat.Application.Security;
|
||||
using Khaemhat.Core.Instance;
|
||||
using Khaemhat.Core.Tables;
|
||||
using Khaemhat.Data;
|
||||
using Khaemhat.Data.Companies;
|
||||
using Khaemhat.Data.Querying;
|
||||
using Khaemhat.Infrastructure.Http;
|
||||
|
||||
namespace Khaemhat.Application.Tables;
|
||||
|
||||
/// <summary>
|
||||
/// The exchange rates of a company (SPEC §11.1): the ECB reference rates loaded by <see cref="EcbRatesJob"/> for the
|
||||
/// currencies of the table, and rates typed by hand. The rate of a day is the last one on or before it.
|
||||
/// </summary>
|
||||
public sealed class ExchangeRateService
|
||||
{
|
||||
/// <summary>The source of the ECB rates.</summary>
|
||||
public const string EcbSource = "ECB";
|
||||
|
||||
/// <summary>The source of the rates typed by hand.</summary>
|
||||
public const string ManualSource = "MANUAL";
|
||||
|
||||
/// <summary>Error: the rate is not positive.</summary>
|
||||
public const string RateInvalid = "tables.exchange-rate.invalid";
|
||||
|
||||
/// <summary>The fields of the grid.</summary>
|
||||
public static readonly ListFields<ExchangeRate> Fields = new ListFields<ExchangeRate>()
|
||||
.Add("currency", x => x.CurrencyCode, searchable: true)
|
||||
.Add("date", x => x.RateDate)
|
||||
.Add("rate", x => x.Rate)
|
||||
.Add("source", x => x.Source)
|
||||
.OrderByDefault(new ListSort("date", Descending: true), new ListSort("currency"));
|
||||
|
||||
private readonly IUnitOfWorkFactory _factory;
|
||||
private readonly PermissionService _permissions;
|
||||
private readonly AuditTrail _audit;
|
||||
|
||||
/// <summary>Creates the service.</summary>
|
||||
/// <param name="factory">Opens the company databases.</param>
|
||||
/// <param name="permissions">Checks permissions.</param>
|
||||
/// <param name="audit">Writes the history.</param>
|
||||
public ExchangeRateService(IUnitOfWorkFactory factory, PermissionService permissions, AuditTrail audit)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(factory);
|
||||
ArgumentNullException.ThrowIfNull(permissions);
|
||||
ArgumentNullException.ThrowIfNull(audit);
|
||||
_factory = factory;
|
||||
_permissions = permissions;
|
||||
_audit = audit;
|
||||
}
|
||||
|
||||
/// <summary>A page of rates.</summary>
|
||||
/// <param name="actor">Who reads.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="query">The request.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The page.</returns>
|
||||
public async Task<ListPage<ExchangeRate>> ListAsync(Actor actor, string companyCode, ListQuery query, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(query);
|
||||
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, TableService.ReadPermission, cancellationToken).ConfigureAwait(false);
|
||||
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
||||
var repository = uow.Repository<ExchangeRate, long>();
|
||||
var filtered = Fields.Apply(Query.For<ExchangeRate>(), query);
|
||||
var page = await repository.ListAsync(filtered, cancellationToken).ConfigureAwait(false);
|
||||
return new ListPage<ExchangeRate>(page.Items, page.TotalCount, new Dictionary<string, decimal>());
|
||||
}
|
||||
|
||||
/// <summary>The rate of a currency on a day: the last one on or before it; 1 for the euro.</summary>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="currency">The currency.</param>
|
||||
/// <param name="date">The day.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The rate, or <see langword="null"/> when none is known.</returns>
|
||||
public async Task<ExchangeRate?> RateOnAsync(string companyCode, string currency, DateOnly date, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(currency);
|
||||
var code = currency.Trim().ToUpperInvariant();
|
||||
if (code == "EUR")
|
||||
{
|
||||
return new ExchangeRate { CurrencyCode = code, RateDate = date, Rate = 1m, Source = EcbSource };
|
||||
}
|
||||
|
||||
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(CompanyCodes.Normalize(companyCode)), cancellationToken).ConfigureAwait(false);
|
||||
return await uow.Repository<ExchangeRate, long>()
|
||||
.FindAsync(Query.For<ExchangeRate>().Where(x => x.CurrencyCode == code && x.RateDate <= date).OrderByDescending(x => x.RateDate), cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>Saves a rate typed by hand (replacing the one of the same day).</summary>
|
||||
/// <param name="actor">Who saves.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="currency">The currency.</param>
|
||||
/// <param name="date">The day.</param>
|
||||
/// <param name="rate">Units of the currency for one euro.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The rate.</returns>
|
||||
/// <exception cref="ValidationFailedException">The rate is not positive or the currency is not in the table.</exception>
|
||||
public async Task<ExchangeRate> SetManualAsync(Actor actor, string companyCode, string currency, DateOnly date, decimal rate, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(currency);
|
||||
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, TableService.WritePermission, cancellationToken).ConfigureAwait(false);
|
||||
var code = currency.Trim().ToUpperInvariant();
|
||||
if (rate <= 0)
|
||||
{
|
||||
throw new ValidationFailedException([nameof(ExchangeRate.Rate) + ":" + RateInvalid]);
|
||||
}
|
||||
|
||||
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
||||
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
|
||||
if (await uow.Repository<Currency, long>().CountAsync(Query.For<Currency>().Where(x => x.Code == code), cancellationToken).ConfigureAwait(false) == 0)
|
||||
{
|
||||
throw new ValidationFailedException([nameof(ExchangeRate.CurrencyCode) + ":" + TableCatalog.ReferenceMissing]);
|
||||
}
|
||||
|
||||
var saved = await UpsertAsync(uow, new ExchangeRate { CurrencyCode = code, RateDate = date, Rate = rate, Source = ManualSource }, actor.UserName, cancellationToken).ConfigureAwait(false);
|
||||
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
|
||||
return saved;
|
||||
}
|
||||
|
||||
/// <summary>Stores ECB rates for the currencies of a company's table (manual rates of the same day are kept).</summary>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="rates">The ECB rates.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>How many rates were added or changed.</returns>
|
||||
public async Task<int> StoreEcbAsync(string companyCode, IReadOnlyList<EcbRate> rates, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(rates);
|
||||
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(CompanyCodes.Normalize(companyCode)), cancellationToken).ConfigureAwait(false);
|
||||
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
|
||||
var currencies = (await uow.Repository<Currency, long>().ListAsync(Query.For<Currency>().Where(x => !x.Disabled), cancellationToken).ConfigureAwait(false)).Items
|
||||
.Select(c => c.Code)
|
||||
.ToHashSet(StringComparer.Ordinal);
|
||||
var changed = 0;
|
||||
foreach (var rate in rates.Where(r => currencies.Contains(r.Currency)))
|
||||
{
|
||||
var existing = await FindAsync(uow, rate.Currency, rate.Date, cancellationToken).ConfigureAwait(false);
|
||||
if (existing is { Source: ManualSource } || existing?.Rate == rate.Rate)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
await UpsertAsync(uow, new ExchangeRate { CurrencyCode = rate.Currency, RateDate = rate.Date, Rate = rate.Rate, Source = EcbSource }, "system", cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
changed++;
|
||||
}
|
||||
|
||||
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
|
||||
return changed;
|
||||
}
|
||||
|
||||
private static Task<ExchangeRate?> FindAsync(IUnitOfWork uow, string currency, DateOnly date, CancellationToken cancellationToken) =>
|
||||
uow.Repository<ExchangeRate, long>().FindAsync(Query.For<ExchangeRate>().Where(x => x.CurrencyCode == currency && x.RateDate == date), cancellationToken);
|
||||
|
||||
private async Task<ExchangeRate> UpsertAsync(IUnitOfWork uow, ExchangeRate rate, string userName, CancellationToken cancellationToken)
|
||||
{
|
||||
var repository = uow.Repository<ExchangeRate, long>();
|
||||
var existing = await FindAsync(uow, rate.CurrencyCode, rate.RateDate, cancellationToken).ConfigureAwait(false);
|
||||
if (existing is null)
|
||||
{
|
||||
rate.Id = await repository.InsertAsync(rate, cancellationToken).ConfigureAwait(false);
|
||||
await _audit.RecordAsync(uow, AuditAction.Insert, rate.Id, null, rate, userName, cancellationToken).ConfigureAwait(false);
|
||||
return rate;
|
||||
}
|
||||
|
||||
var before = new ExchangeRate { Id = existing.Id, CurrencyCode = existing.CurrencyCode, RateDate = existing.RateDate, Rate = existing.Rate, Source = existing.Source };
|
||||
existing.Rate = rate.Rate;
|
||||
existing.Source = rate.Source;
|
||||
await repository.UpdateAsync(existing, cancellationToken).ConfigureAwait(false);
|
||||
await _audit.RecordAsync(uow, AuditAction.Update, existing.Id, before, existing, userName, cancellationToken).ConfigureAwait(false);
|
||||
return existing;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Loads the ECB reference rates into every active company (SPEC §11.12 "cambi BCE"), on working days; a company that
|
||||
/// switched the option off in its preferences is skipped.
|
||||
/// </summary>
|
||||
/// <param name="client">The ECB client.</param>
|
||||
/// <param name="rates">The exchange rates.</param>
|
||||
/// <param name="companies">The companies.</param>
|
||||
/// <param name="autoFill">The automatic filling options.</param>
|
||||
public sealed class EcbRatesJob(EcbRatesClient client, ExchangeRateService rates, ICompanyRegistry companies, AutoFillService autoFill) : IScheduledJob
|
||||
{
|
||||
/// <summary>The job type.</summary>
|
||||
public const string JobType = "tables.ecb-rates";
|
||||
|
||||
/// <inheritdoc />
|
||||
public string Type => JobType;
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<string?> RunAsync(JobContext context, CancellationToken cancellationToken)
|
||||
{
|
||||
// The 90-day file also fills the days missed while the instance was stopped.
|
||||
var downloaded = await client.GetAsync(last90Days: true, cancellationToken).ConfigureAwait(false);
|
||||
var changed = 0;
|
||||
foreach (var company in await companies.ListAsync(cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
if (company.Status is CompanyStatus.Active && await autoFill.IsOnAsync(company.Code, AutoFillService.EcbRates, cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
changed += await rates.StoreEcbAsync(company.Code, downloaded, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
var last = downloaded.Max(r => r.Date);
|
||||
return string.Create(CultureInfo.InvariantCulture, $"Cambi BCE del {last:dd/MM/yyyy}: {changed} valori aggiornati.");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,321 @@
|
||||
using System.Globalization;
|
||||
using Khaemhat.Application.Audit;
|
||||
using Khaemhat.Application.Security;
|
||||
using Khaemhat.Core.Caching;
|
||||
using Khaemhat.Core.Tables;
|
||||
using Khaemhat.Data;
|
||||
using Khaemhat.Data.Querying;
|
||||
|
||||
namespace Khaemhat.Application.Tables;
|
||||
|
||||
/// <summary>A fiscal year with its months, as mockup 052 shows it.</summary>
|
||||
/// <param name="Year">The year.</param>
|
||||
/// <param name="Periods">The months, in order.</param>
|
||||
public sealed record FiscalYearView(FiscalYear Year, IReadOnlyList<FiscalPeriod> Periods);
|
||||
|
||||
/// <summary>What a date may receive.</summary>
|
||||
public enum PeriodUse
|
||||
{
|
||||
/// <summary>A document or entry without VAT (warehouse, quotations, orders).</summary>
|
||||
NoVat = 0,
|
||||
|
||||
/// <summary>A document or entry with VAT: refused once the VAT of the period is settled.</summary>
|
||||
Vat = 1,
|
||||
}
|
||||
|
||||
/// <summary>Why a date is refused (or <see cref="Open"/>).</summary>
|
||||
public enum PeriodState
|
||||
{
|
||||
/// <summary>The date is in an open period.</summary>
|
||||
Open = 0,
|
||||
|
||||
/// <summary>No fiscal year contains the date.</summary>
|
||||
NoYear = 1,
|
||||
|
||||
/// <summary>The year is closed or being closed.</summary>
|
||||
YearClosed = 2,
|
||||
|
||||
/// <summary>The month is locked.</summary>
|
||||
Locked = 3,
|
||||
|
||||
/// <summary>The VAT of the month was settled (only for <see cref="PeriodUse.Vat"/>).</summary>
|
||||
Settled = 4,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Fiscal years and their months (SPEC §11.1, mockup 052): creation of the next year with its twelve months, lock and
|
||||
/// unlock of months, and the check that a date can receive documents and entries (<see cref="CheckAsync"/>), used by
|
||||
/// every service that writes dated records. Years and months are cached per company.
|
||||
/// </summary>
|
||||
public sealed class FiscalYearService
|
||||
{
|
||||
/// <summary>Error: the date of the new year overlaps an existing year.</summary>
|
||||
public const string Overlap = "fiscal.year.overlap";
|
||||
|
||||
/// <summary>Error: the year is closed: its months cannot change.</summary>
|
||||
public const string YearClosedError = "fiscal.year.closed";
|
||||
|
||||
/// <summary>Error: the month cannot become open again because the VAT is settled (reopened with the settlement, M7).</summary>
|
||||
public const string SettledError = "fiscal.period.settled";
|
||||
|
||||
/// <summary>The error code thrown by <see cref="DemandOpenAsync"/>, followed by the <see cref="PeriodState"/>.</summary>
|
||||
public const string DateRefused = "fiscal.date.";
|
||||
|
||||
private static readonly TimeSpan CacheTime = TimeSpan.FromHours(1);
|
||||
|
||||
private readonly IUnitOfWorkFactory _factory;
|
||||
private readonly PermissionService _permissions;
|
||||
private readonly AuditTrail _audit;
|
||||
private readonly ICacheProvider _cache;
|
||||
|
||||
/// <summary>Creates the service.</summary>
|
||||
/// <param name="factory">Opens the company databases.</param>
|
||||
/// <param name="permissions">Checks permissions.</param>
|
||||
/// <param name="audit">Writes the history.</param>
|
||||
/// <param name="cache">The cache.</param>
|
||||
public FiscalYearService(IUnitOfWorkFactory factory, PermissionService permissions, AuditTrail audit, ICacheProvider cache)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(factory);
|
||||
ArgumentNullException.ThrowIfNull(permissions);
|
||||
ArgumentNullException.ThrowIfNull(audit);
|
||||
ArgumentNullException.ThrowIfNull(cache);
|
||||
_factory = factory;
|
||||
_permissions = permissions;
|
||||
_audit = audit;
|
||||
_cache = cache;
|
||||
}
|
||||
|
||||
/// <summary>The years, newest first, with their months.</summary>
|
||||
/// <param name="actor">Who reads.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The years.</returns>
|
||||
public async Task<IReadOnlyList<FiscalYearView>> ListAsync(Actor actor, string companyCode, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, TableService.ReadPermission, cancellationToken).ConfigureAwait(false);
|
||||
return [.. (await CalendarAsync(company, cancellationToken).ConfigureAwait(false)).OrderByDescending(y => y.Year.StartDate)];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a year with its months: after the last year, or the one containing <paramref name="day"/> when there are
|
||||
/// none (starting in the month of the profile).
|
||||
/// </summary>
|
||||
/// <param name="actor">Who creates.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="day">A day of the first year, when the company has none.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The new year.</returns>
|
||||
public async Task<FiscalYearView> CreateNextAsync(Actor actor, string companyCode, DateOnly day, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, TableService.WritePermission, cancellationToken).ConfigureAwait(false);
|
||||
FiscalYearView created;
|
||||
await using (var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
|
||||
created = await CreateAsync(uow, day, actor.UserName, cancellationToken).ConfigureAwait(false);
|
||||
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
await InvalidateAsync(company, cancellationToken).ConfigureAwait(false);
|
||||
return created;
|
||||
}
|
||||
|
||||
/// <summary>Locks or unlocks a month (unlocking a settled month is refused).</summary>
|
||||
/// <param name="actor">Who changes it.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="periodId">The month.</param>
|
||||
/// <param name="locked">Lock or unlock.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The month.</returns>
|
||||
/// <exception cref="ValidationFailedException">The year is closed, or the month is settled.</exception>
|
||||
public async Task<FiscalPeriod> SetLockedAsync(Actor actor, string companyCode, long periodId, bool locked, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, TableService.WritePermission, cancellationToken).ConfigureAwait(false);
|
||||
FiscalPeriod period;
|
||||
await using (var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
|
||||
var periods = uow.Repository<FiscalPeriod, long>();
|
||||
period = await periods.GetAsync(periodId, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(TableService.NotFound);
|
||||
var year = await uow.Repository<FiscalYear, long>().GetAsync(period.FiscalYearId, cancellationToken).ConfigureAwait(false)
|
||||
?? throw new KeyNotFoundException(TableService.NotFound);
|
||||
if (year.Status != FiscalYearStatus.Open)
|
||||
{
|
||||
throw new ValidationFailedException([YearClosedError]);
|
||||
}
|
||||
|
||||
if (period.Status == FiscalPeriodStatus.Settled && !locked)
|
||||
{
|
||||
throw new ValidationFailedException([SettledError]);
|
||||
}
|
||||
|
||||
var target = locked ? FiscalPeriodStatus.Locked : FiscalPeriodStatus.Open;
|
||||
if (period.Status != target)
|
||||
{
|
||||
var before = Copy(period);
|
||||
period.Status = target;
|
||||
await periods.UpdateAsync(period, cancellationToken).ConfigureAwait(false);
|
||||
await _audit.RecordAsync(uow, AuditAction.Update, period.Id, before, period, actor.UserName, cancellationToken).ConfigureAwait(false);
|
||||
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
await InvalidateAsync(company, cancellationToken).ConfigureAwait(false);
|
||||
return period;
|
||||
}
|
||||
|
||||
/// <summary>Whether a date can receive a document or entry.</summary>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="date">The date.</param>
|
||||
/// <param name="use">With or without VAT.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The state of the date.</returns>
|
||||
public async Task<PeriodState> CheckAsync(string companyCode, DateOnly date, PeriodUse use, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var calendar = await CalendarAsync(CompanyCodes.Normalize(companyCode), cancellationToken).ConfigureAwait(false);
|
||||
return StateOf(calendar, date, use);
|
||||
}
|
||||
|
||||
/// <summary>Throws when a date cannot receive a document or entry.</summary>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="date">The date.</param>
|
||||
/// <param name="use">With or without VAT.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>A task.</returns>
|
||||
/// <exception cref="ValidationFailedException">The date is refused: <c>fiscal.date.locked</c> and similar.</exception>
|
||||
public async Task DemandOpenAsync(string companyCode, DateOnly date, PeriodUse use, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var state = await CheckAsync(companyCode, date, use, cancellationToken).ConfigureAwait(false);
|
||||
if (state != PeriodState.Open)
|
||||
{
|
||||
throw new ValidationFailedException([ErrorOf(state)]);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The error code of a refused date, such as <c>fiscal.date.locked</c>.</summary>
|
||||
/// <param name="state">The state.</param>
|
||||
/// <returns>The code.</returns>
|
||||
public static string ErrorOf(PeriodState state) => state switch
|
||||
{
|
||||
PeriodState.NoYear => DateRefused + "no-year",
|
||||
PeriodState.YearClosed => DateRefused + "year-closed",
|
||||
PeriodState.Locked => DateRefused + "locked",
|
||||
PeriodState.Settled => DateRefused + "settled",
|
||||
_ => DateRefused + "open",
|
||||
};
|
||||
|
||||
/// <summary>The state of a date in a calendar.</summary>
|
||||
/// <param name="calendar">The years with their months.</param>
|
||||
/// <param name="date">The date.</param>
|
||||
/// <param name="use">With or without VAT.</param>
|
||||
/// <returns>The state.</returns>
|
||||
public static PeriodState StateOf(IEnumerable<FiscalYearView> calendar, DateOnly date, PeriodUse use)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(calendar);
|
||||
var year = calendar.FirstOrDefault(y => y.Year.StartDate <= date && date <= y.Year.EndDate);
|
||||
if (year is null)
|
||||
{
|
||||
return PeriodState.NoYear;
|
||||
}
|
||||
|
||||
if (year.Year.Status != FiscalYearStatus.Open)
|
||||
{
|
||||
return PeriodState.YearClosed;
|
||||
}
|
||||
|
||||
var period = year.Periods.FirstOrDefault(p => p.StartDate <= date && date <= p.EndDate);
|
||||
return period?.Status switch
|
||||
{
|
||||
FiscalPeriodStatus.Locked => PeriodState.Locked,
|
||||
FiscalPeriodStatus.Settled when use == PeriodUse.Vat => PeriodState.Settled,
|
||||
_ => PeriodState.Open,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a year with its months inside a unit of work (the seeder uses it for the current year): after the last
|
||||
/// year, or the one containing <paramref name="day"/> when there are none.
|
||||
/// </summary>
|
||||
/// <param name="uow">The company unit of work.</param>
|
||||
/// <param name="day">A day of the first year.</param>
|
||||
/// <param name="userName">Who creates.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The new year.</returns>
|
||||
internal async Task<FiscalYearView> CreateAsync(IUnitOfWork uow, DateOnly day, string userName, CancellationToken cancellationToken)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(uow);
|
||||
var years = uow.Repository<FiscalYear, long>();
|
||||
var last = await years.FindAsync(Query.For<FiscalYear>().OrderByDescending(x => x.StartDate), cancellationToken).ConfigureAwait(false);
|
||||
DateOnly start;
|
||||
if (last is not null)
|
||||
{
|
||||
start = last.EndDate.AddDays(1);
|
||||
}
|
||||
else
|
||||
{
|
||||
var profile = await CompanyProfileService.LoadAsync(uow, cancellationToken).ConfigureAwait(false);
|
||||
var month = profile?.FiscalYearStartMonth ?? 1;
|
||||
start = new DateOnly(day.Month >= month ? day.Year : day.Year - 1, month, 1);
|
||||
}
|
||||
|
||||
var end = start.AddYears(1).AddDays(-1);
|
||||
if (await years.CountAsync(Query.For<FiscalYear>().Where(x => x.StartDate <= end && x.EndDate >= start), cancellationToken).ConfigureAwait(false) > 0)
|
||||
{
|
||||
throw new ValidationFailedException([Overlap]);
|
||||
}
|
||||
|
||||
var year = new FiscalYear
|
||||
{
|
||||
Code = start.Year == end.Year
|
||||
? start.Year.ToString(CultureInfo.InvariantCulture)
|
||||
: string.Create(CultureInfo.InvariantCulture, $"{start.Year}/{end.Year % 100:00}"),
|
||||
StartDate = start,
|
||||
EndDate = end,
|
||||
};
|
||||
year.Id = await years.InsertAsync(year, cancellationToken).ConfigureAwait(false);
|
||||
await _audit.RecordAsync(uow, AuditAction.Insert, year.Id, null, year, userName, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
var periods = new List<FiscalPeriod>();
|
||||
var repository = uow.Repository<FiscalPeriod, long>();
|
||||
for (var i = 0; i < 12; i++)
|
||||
{
|
||||
var first = start.AddMonths(i);
|
||||
var period = new FiscalPeriod { FiscalYearId = year.Id, Number = i + 1, StartDate = first, EndDate = first.AddMonths(1).AddDays(-1) };
|
||||
period.Id = await repository.InsertAsync(period, cancellationToken).ConfigureAwait(false);
|
||||
periods.Add(period);
|
||||
}
|
||||
|
||||
return new FiscalYearView(year, periods);
|
||||
}
|
||||
|
||||
/// <summary>Forgets the cached calendar of a company.</summary>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>A task.</returns>
|
||||
public ValueTask InvalidateAsync(string companyCode, CancellationToken cancellationToken = default) =>
|
||||
_cache.PublishInvalidationAsync(CacheKeys.For(CompanyCodes.Normalize(companyCode), "fiscal", "calendar"), cancellationToken);
|
||||
|
||||
private static FiscalPeriod Copy(FiscalPeriod period) => new()
|
||||
{
|
||||
Id = period.Id,
|
||||
FiscalYearId = period.FiscalYearId,
|
||||
Number = period.Number,
|
||||
StartDate = period.StartDate,
|
||||
EndDate = period.EndDate,
|
||||
Status = period.Status,
|
||||
RowVersion = period.RowVersion,
|
||||
};
|
||||
|
||||
private async Task<IReadOnlyList<FiscalYearView>> CalendarAsync(string company, CancellationToken cancellationToken) =>
|
||||
await _cache.GetOrCreateAsync<List<FiscalYearView>>(
|
||||
CacheKeys.For(company, "fiscal", "calendar"),
|
||||
async ct =>
|
||||
{
|
||||
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), ct).ConfigureAwait(false);
|
||||
var years = (await uow.Repository<FiscalYear, long>().ListAsync(Query.For<FiscalYear>().OrderBy(x => x.StartDate), ct).ConfigureAwait(false)).Items;
|
||||
var periods = (await uow.Repository<FiscalPeriod, long>().ListAsync(Query.For<FiscalPeriod>().OrderBy(x => x.StartDate), ct).ConfigureAwait(false)).Items;
|
||||
return [.. years.Select(y => new FiscalYearView(y, [.. periods.Where(p => p.FiscalYearId == y.Id)]))];
|
||||
},
|
||||
CacheTime,
|
||||
cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
@@ -0,0 +1,159 @@
|
||||
using Khaemhat.Application.Audit;
|
||||
using Khaemhat.Application.Security;
|
||||
using Khaemhat.Core.Caching;
|
||||
using Khaemhat.Core.Tables;
|
||||
using Khaemhat.Data;
|
||||
using Khaemhat.Data.Querying;
|
||||
|
||||
namespace Khaemhat.Application.Tables;
|
||||
|
||||
/// <summary>
|
||||
/// The installments of a payment term (SPEC §11.1): days from the document date, end of month, fixed day and share of
|
||||
/// the amount. They are saved all together, because only the whole set has to add up to 100%.
|
||||
/// </summary>
|
||||
public sealed class PaymentTermService
|
||||
{
|
||||
/// <summary>The installments do not add up to 100%.</summary>
|
||||
public const string PercentTotal = "tables.payment-term.percent-total";
|
||||
|
||||
/// <summary>A payment term needs at least one installment.</summary>
|
||||
public const string LinesRequired = "tables.payment-term.lines-required";
|
||||
|
||||
/// <summary>The days are negative or beyond a year and a half.</summary>
|
||||
public const string DaysRange = "tables.payment-term.days";
|
||||
|
||||
/// <summary>The fixed day is not a day of the month.</summary>
|
||||
public const string FixedDayRange = "tables.payment-term.fixed-day";
|
||||
|
||||
/// <summary>The field the errors of the installments are reported on.</summary>
|
||||
public const string LinesField = "Lines";
|
||||
|
||||
private const int MaxDays = 540;
|
||||
|
||||
private readonly IUnitOfWorkFactory _factory;
|
||||
private readonly PermissionService _permissions;
|
||||
private readonly AuditTrail _audit;
|
||||
private readonly ICacheProvider _cache;
|
||||
|
||||
/// <summary>Creates the service.</summary>
|
||||
/// <param name="factory">The units of work.</param>
|
||||
/// <param name="permissions">The permissions.</param>
|
||||
/// <param name="audit">The audit trail.</param>
|
||||
/// <param name="cache">The cache of the tables.</param>
|
||||
public PaymentTermService(IUnitOfWorkFactory factory, PermissionService permissions, AuditTrail audit, ICacheProvider cache)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(factory);
|
||||
ArgumentNullException.ThrowIfNull(permissions);
|
||||
ArgumentNullException.ThrowIfNull(audit);
|
||||
ArgumentNullException.ThrowIfNull(cache);
|
||||
_factory = factory;
|
||||
_permissions = permissions;
|
||||
_audit = audit;
|
||||
_cache = cache;
|
||||
}
|
||||
|
||||
/// <summary>The installments of a payment term, in order.</summary>
|
||||
/// <param name="actor">Who reads.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="paymentTermId">The payment term.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The installments.</returns>
|
||||
public async Task<IReadOnlyList<PaymentTermLine>> LinesAsync(Actor actor, string companyCode, long paymentTermId, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, TableService.ReadPermission, cancellationToken).ConfigureAwait(false);
|
||||
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
||||
return await ReadAsync(uow, paymentTermId, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>Checks a set of installments.</summary>
|
||||
/// <param name="lines">The installments.</param>
|
||||
/// <returns>The errors, on <see cref="LinesField"/>.</returns>
|
||||
public static IReadOnlyList<TableProblem> Validate(IReadOnlyList<PaymentTermLine> lines)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(lines);
|
||||
var problems = new List<TableProblem>();
|
||||
if (lines.Count == 0)
|
||||
{
|
||||
problems.Add(new(LinesField, LinesRequired));
|
||||
return problems;
|
||||
}
|
||||
|
||||
if (lines.Any(l => l.Days < 0 || l.Days > MaxDays))
|
||||
{
|
||||
problems.Add(new(LinesField, DaysRange));
|
||||
}
|
||||
|
||||
if (lines.Any(l => l.FixedDay is < 1 or > 31))
|
||||
{
|
||||
problems.Add(new(LinesField, FixedDayRange));
|
||||
}
|
||||
|
||||
if (lines.Any(l => l.Percent <= 0) || lines.Sum(l => l.Percent) != 100m)
|
||||
{
|
||||
problems.Add(new(LinesField, PercentTotal));
|
||||
}
|
||||
|
||||
return problems;
|
||||
}
|
||||
|
||||
/// <summary>Replaces the installments of a payment term, numbering them 1, 2, 3 in the given order.</summary>
|
||||
/// <param name="actor">Who saves.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="paymentTermId">The payment term.</param>
|
||||
/// <param name="lines">The installments.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The saved installments.</returns>
|
||||
/// <exception cref="ValidationFailedException">The installments are not valid (<c>Lines:code</c>).</exception>
|
||||
public async Task<IReadOnlyList<PaymentTermLine>> SaveLinesAsync(Actor actor, string companyCode, long paymentTermId, IReadOnlyList<PaymentTermLine> lines,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(lines);
|
||||
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, TableService.WritePermission, cancellationToken).ConfigureAwait(false);
|
||||
var problems = Validate(lines);
|
||||
if (problems.Count > 0)
|
||||
{
|
||||
throw new ValidationFailedException([.. problems.Select(p => p.Field + ":" + p.Code)]);
|
||||
}
|
||||
|
||||
IReadOnlyList<PaymentTermLine> saved;
|
||||
await using (var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
|
||||
_ = await uow.Repository<PaymentTerm, long>().GetAsync(paymentTermId, cancellationToken).ConfigureAwait(false)
|
||||
?? throw new KeyNotFoundException(TableService.NotFound);
|
||||
var repository = uow.Repository<PaymentTermLine, long>();
|
||||
foreach (var old in await ReadAsync(uow, paymentTermId, cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
await repository.DeleteAsync(old.Id, cancellationToken).ConfigureAwait(false);
|
||||
await _audit.RecordAsync(uow, AuditAction.Delete, old.Id, old, null, actor.UserName, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
var number = 0;
|
||||
foreach (var line in lines)
|
||||
{
|
||||
var row = new PaymentTermLine
|
||||
{
|
||||
PaymentTermId = paymentTermId,
|
||||
Number = ++number,
|
||||
Days = line.Days,
|
||||
EndOfMonth = line.EndOfMonth,
|
||||
FixedDay = line.FixedDay,
|
||||
Percent = line.Percent,
|
||||
};
|
||||
var id = await repository.InsertAsync(row, cancellationToken).ConfigureAwait(false);
|
||||
await _audit.RecordAsync(uow, AuditAction.Insert, id, null, row, actor.UserName, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
saved = await ReadAsync(uow, paymentTermId, cancellationToken).ConfigureAwait(false);
|
||||
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
await _cache.PublishInvalidationAsync(CacheKeys.Prefix(company, "tables"), cancellationToken).ConfigureAwait(false);
|
||||
return saved;
|
||||
}
|
||||
|
||||
private static async Task<IReadOnlyList<PaymentTermLine>> ReadAsync(IUnitOfWork uow, long paymentTermId, CancellationToken cancellationToken) =>
|
||||
(await uow.Repository<PaymentTermLine, long>()
|
||||
.ListAsync(Query.For<PaymentTermLine>().Where(x => x.PaymentTermId == paymentTermId).OrderBy(x => x.Number), cancellationToken)
|
||||
.ConfigureAwait(false)).Items;
|
||||
}
|
||||
@@ -0,0 +1,520 @@
|
||||
using System.Globalization;
|
||||
using System.Text.RegularExpressions;
|
||||
using Khaemhat.Core.Tables;
|
||||
using Khaemhat.Core.Validation;
|
||||
using Khaemhat.Fiscal.Abstractions;
|
||||
|
||||
namespace Khaemhat.Application.Tables;
|
||||
|
||||
/// <summary>
|
||||
/// The company tables of SPEC §11.1 handled by <see cref="TableService"/>, each with its rules. Keys are in English
|
||||
/// (<c>tax-codes</c>); the interface gives them Italian addresses and names through the resources.
|
||||
/// </summary>
|
||||
public sealed partial class TableCatalog
|
||||
{
|
||||
/// <summary>Error: a percentage outside 0-100.</summary>
|
||||
public const string PercentRange = "tables.percent.range";
|
||||
|
||||
/// <summary>Error: the end of validity is before the start.</summary>
|
||||
public const string ValidityOrder = "tables.validity.order";
|
||||
|
||||
/// <summary>Error: the code does not follow the pattern of the table.</summary>
|
||||
public const string CodePattern = "tables.code.pattern";
|
||||
|
||||
/// <summary>Error: a value not in the fiscal pack's code list.</summary>
|
||||
public const string NotInCodeList = "tables.code-list.unknown";
|
||||
|
||||
/// <summary>Warning: a value that the code list marks obsolete.</summary>
|
||||
public const string ObsoleteInCodeList = "tables.code-list.obsolete";
|
||||
|
||||
/// <summary>Error: decimals outside the allowed range.</summary>
|
||||
public const string DecimalsRange = "tables.decimals.range";
|
||||
|
||||
/// <summary>Error: the IBAN is not valid.</summary>
|
||||
public const string IbanInvalid = "tables.iban.invalid";
|
||||
|
||||
/// <summary>Error: the BIC is not valid.</summary>
|
||||
public const string BicInvalid = "tables.bic.invalid";
|
||||
|
||||
/// <summary>Error: the e-mail address is not valid.</summary>
|
||||
public const string EmailInvalid = "tables.email.invalid";
|
||||
|
||||
/// <summary>Error: the VAT number is not valid.</summary>
|
||||
public const string VatNumberInvalid = "tables.vat-number.invalid";
|
||||
|
||||
/// <summary>Error: the parent does not exist, is the row itself or is too deep.</summary>
|
||||
public const string ParentInvalid = "tables.parent.invalid";
|
||||
|
||||
/// <summary>Error: a referenced row does not exist.</summary>
|
||||
public const string ReferenceMissing = "tables.reference.missing";
|
||||
|
||||
/// <summary>Error: the discount formula cannot be read.</summary>
|
||||
public const string FormulaInvalid = "tables.discount.formula";
|
||||
|
||||
/// <summary>Error: the numerator format has no <c>{number}</c>.</summary>
|
||||
public const string FormatInvalid = "tables.numerator.format";
|
||||
|
||||
/// <summary>Error: the year is outside 2000-2100.</summary>
|
||||
public const string YearRange = "tables.year.range";
|
||||
|
||||
/// <summary>Error: the last number is negative.</summary>
|
||||
public const string NumberRange = "tables.number.range";
|
||||
|
||||
/// <summary>Error: a transfer reason must not change quantities by itself.</summary>
|
||||
public const string TransferEffect = "tables.inventory-reason.transfer";
|
||||
|
||||
/// <summary>Error: another price list is already the base one.</summary>
|
||||
public const string BaseDuplicate = "tables.price-list.base-duplicate";
|
||||
|
||||
/// <summary>The maximum depth of item categories.</summary>
|
||||
public const int MaxCategoryLevel = 3;
|
||||
|
||||
private readonly Dictionary<Type, TableDefinition> _byType = [];
|
||||
private readonly Dictionary<string, TableDefinition> _byKey = new(StringComparer.Ordinal);
|
||||
|
||||
/// <summary>Creates the catalog.</summary>
|
||||
public TableCatalog()
|
||||
{
|
||||
Add(new TableDefinition<Country>("countries", "countries") { CodeLength = 2 }
|
||||
.Field("eu", x => x.EuMember)
|
||||
.Rule((x, c) => Pattern(x.Code, TwoLetters(), c))
|
||||
.Rule((x, c) =>
|
||||
{
|
||||
if (x.VatPrefix is { Length: > 0 } && !TwoLetters().IsMatch(x.VatPrefix))
|
||||
{
|
||||
c.Error(nameof(Country.VatPrefix), CodePattern);
|
||||
}
|
||||
}));
|
||||
Add(new TableDefinition<Province>("provinces", "provinces") { CodeLength = 2 }
|
||||
.Field("region", x => x.Region, searchable: true)
|
||||
.Rule((x, c) => Pattern(x.Code, TwoLetters(), c)));
|
||||
Add(new TableDefinition<Municipality>("municipalities", "municipalities") { CodeLength = 4 }
|
||||
.Field("province", x => x.ProvinceCode, searchable: true)
|
||||
.Field("postal-codes", x => x.PostalCodes, searchable: true)
|
||||
.Rule((x, c) => Pattern(x.Code, CadastralCode(), c))
|
||||
.Rule((x, c) =>
|
||||
{
|
||||
x.ProvinceCode = x.ProvinceCode.Trim().ToUpperInvariant();
|
||||
if (!TwoLetters().IsMatch(x.ProvinceCode))
|
||||
{
|
||||
c.Error(nameof(Municipality.ProvinceCode), CodePattern);
|
||||
}
|
||||
}));
|
||||
Add(new TableDefinition<Currency>("currencies", "currencies") { CodeLength = 3 }
|
||||
.Rule((x, c) => Pattern(x.Code, ThreeLetters(), c))
|
||||
.Rule((x, c) => Decimals(x.Decimals, 0, 4, nameof(Currency.Decimals), c)));
|
||||
Add(new TableDefinition<UnitOfMeasure>("units", "units_of_measure")
|
||||
.Rule((x, c) => Decimals(x.Decimals, 0, 6, nameof(UnitOfMeasure.Decimals), c)));
|
||||
Add(new TableDefinition<TaxCode>("tax-codes", "tax_codes")
|
||||
{
|
||||
Complete = (x, pack) =>
|
||||
{
|
||||
x.Nature = string.IsNullOrWhiteSpace(x.Nature) ? null : x.Nature.Trim().ToUpperInvariant();
|
||||
x.Kind = pack.TaxCodes.KindOf(x.Rate, x.Nature);
|
||||
},
|
||||
}
|
||||
.Field("rate", x => x.Rate)
|
||||
.Field("nature", x => x.Nature, searchable: true)
|
||||
.Field("kind", x => x.Kind)
|
||||
.Rule((x, c) =>
|
||||
{
|
||||
var definition = new TaxCodeDefinition(x.Code, x.Description, x.Rate, x.Nature, x.Exigibility, x.NonDeductiblePercent, x.LegalReference);
|
||||
foreach (var problem in c.Pack.TaxCodes.Validate(definition))
|
||||
{
|
||||
if (problem.Severity == FiscalProblemSeverity.Error)
|
||||
{
|
||||
c.Error(problem.Field, problem.Code);
|
||||
}
|
||||
else
|
||||
{
|
||||
c.Warning(problem.Field, problem.Code);
|
||||
}
|
||||
}
|
||||
|
||||
Validity(x.ValidFrom, x.ValidTo, nameof(TaxCode.ValidTo), c);
|
||||
}));
|
||||
Add(new TableDefinition<PaymentMethod>("payment-methods", "payment_methods")
|
||||
.Field("einvoice", x => x.EInvoiceCode)
|
||||
.Rule((x, c) => InCodeList(x.EInvoiceCode, c.Pack.GetFeature<IEInvoiceFormat>()?.PaymentMethods, nameof(PaymentMethod.EInvoiceCode), c)));
|
||||
Add(new TableDefinition<PaymentTerm>("payment-terms", "payment_terms")
|
||||
.Field("condition", x => x.Condition)
|
||||
.Rule((x, c) => InCodeList(x.Condition, c.Pack.GetFeature<IEInvoiceFormat>()?.PaymentConditions, nameof(PaymentTerm.Condition), c))
|
||||
.Rule(async (x, c, ct) =>
|
||||
{
|
||||
if (x.PaymentMethodId is { } id && await c.GetAsync<PaymentMethod>(id, ct).ConfigureAwait(false) is null)
|
||||
{
|
||||
c.Error(nameof(PaymentTerm.PaymentMethodId), ReferenceMissing);
|
||||
}
|
||||
}));
|
||||
Add(new TableDefinition<BankAccount>("bank-accounts", "bank_accounts") { SingleDefault = x => x.IsDefault }
|
||||
.Field("iban", x => x.Iban, searchable: true)
|
||||
.Field("default", x => x.IsDefault)
|
||||
.Rule((x, c) =>
|
||||
{
|
||||
if (!string.IsNullOrWhiteSpace(x.Iban))
|
||||
{
|
||||
x.Iban = IbanValidator.Normalize(x.Iban);
|
||||
if (!IbanValidator.IsValid(x.Iban))
|
||||
{
|
||||
c.Error(nameof(BankAccount.Iban), IbanInvalid);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
x.Iban = null;
|
||||
}
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(x.Bic))
|
||||
{
|
||||
x.Bic = x.Bic.Trim().ToUpperInvariant();
|
||||
if (!Bic().IsMatch(x.Bic))
|
||||
{
|
||||
c.Error(nameof(BankAccount.Bic), BicInvalid);
|
||||
}
|
||||
}
|
||||
}));
|
||||
Add(new TableDefinition<Salesperson>("salespeople", "salespeople")
|
||||
.Field("commission", x => x.CommissionPercent)
|
||||
.Rule((x, c) =>
|
||||
{
|
||||
Percent(x.CommissionPercent, nameof(Salesperson.CommissionPercent), c);
|
||||
Email(x.Email, nameof(Salesperson.Email), c);
|
||||
}));
|
||||
Add(new TableDefinition<Carrier>("carriers", "carriers")
|
||||
.Field("vat-number", x => x.VatNumber, searchable: true)
|
||||
.Rule((x, c) =>
|
||||
{
|
||||
Email(x.Email, nameof(Carrier.Email), c);
|
||||
if (!string.IsNullOrWhiteSpace(x.VatNumber) && c.Pack.GetFeature<ITaxIdentifierRules>() is { } rules)
|
||||
{
|
||||
x.VatNumber = rules.NormalizeVatNumber(x.VatNumber);
|
||||
if (!rules.IsValidVatNumber(x.VatNumber))
|
||||
{
|
||||
c.Error(nameof(Carrier.VatNumber), VatNumberInvalid);
|
||||
}
|
||||
}
|
||||
}));
|
||||
Add(new TableDefinition<ShippingTerm>("shipping-terms", "shipping_terms"));
|
||||
Add(new TableDefinition<TransportMean>("transport-means", "transport_means"));
|
||||
Add(new TableDefinition<GoodsAppearance>("goods-appearances", "goods_appearances"));
|
||||
Add(new TableDefinition<DeliveryTerm>("delivery-terms", "delivery_terms"));
|
||||
Add(new TableDefinition<TransportReason>("transport-reasons", "transport_reasons"));
|
||||
Add(new TableDefinition<InventoryReason>("inventory-reasons", "inventory_reasons")
|
||||
.Field("effect", x => x.Effect)
|
||||
.Rule((x, c) =>
|
||||
{
|
||||
if (x.IsTransfer && x.Effect != StockEffect.None)
|
||||
{
|
||||
c.Error(nameof(InventoryReason.Effect), TransferEffect);
|
||||
}
|
||||
}));
|
||||
Add(new TableDefinition<Warehouse>("warehouses", "warehouses") { SingleDefault = x => x.IsDefault }
|
||||
.Field("default", x => x.IsDefault));
|
||||
Add(new TableDefinition<ItemCategory>("item-categories", "item_categories") { CodeLength = 20 }
|
||||
.Field("level", x => x.Level)
|
||||
.Rule(async (x, c, ct) =>
|
||||
{
|
||||
x.Level = 1;
|
||||
if (x.ParentId is not { } parentId)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var parent = parentId == x.Id ? null : await c.GetAsync<ItemCategory>(parentId, ct).ConfigureAwait(false);
|
||||
if (parent is null || parent.Level >= MaxCategoryLevel)
|
||||
{
|
||||
c.Error(nameof(ItemCategory.ParentId), ParentInvalid);
|
||||
return;
|
||||
}
|
||||
|
||||
x.Level = parent.Level + 1;
|
||||
}));
|
||||
Add(new TableDefinition<PartyCategory>("party-categories", "party_categories"));
|
||||
Add(new TableDefinition<PriceList>("price-lists", "price_lists")
|
||||
.Field("currency", x => x.CurrencyCode)
|
||||
.Rule(async (x, c, ct) =>
|
||||
{
|
||||
x.CurrencyCode = x.CurrencyCode.Trim().ToUpperInvariant();
|
||||
if (!ThreeLetters().IsMatch(x.CurrencyCode))
|
||||
{
|
||||
c.Error(nameof(PriceList.CurrencyCode), CodePattern);
|
||||
}
|
||||
|
||||
Validity(x.ValidFrom, x.ValidTo, nameof(PriceList.ValidTo), c);
|
||||
if (x.RoundingStep < 0)
|
||||
{
|
||||
c.Error(nameof(PriceList.RoundingStep), NumberRange);
|
||||
}
|
||||
|
||||
if (x.BasePriceListId is { } baseId && (baseId == x.Id || await c.GetAsync<PriceList>(baseId, ct).ConfigureAwait(false) is null))
|
||||
{
|
||||
c.Error(nameof(PriceList.BasePriceListId), ParentInvalid);
|
||||
}
|
||||
|
||||
var id = x.Id;
|
||||
if (x.IsBase && await c.CountAsync<PriceList>(p => p.IsBase && p.Id != id, ct).ConfigureAwait(false) > 0)
|
||||
{
|
||||
c.Error(nameof(PriceList.IsBase), BaseDuplicate);
|
||||
}
|
||||
}));
|
||||
Add(new TableDefinition<DiscountPolicy>("discount-policies", "discount_policies")
|
||||
.Field("formula", x => x.Formula)
|
||||
.Rule((x, c) =>
|
||||
{
|
||||
if (DiscountFormula.TryParse(x.Formula, out var steps))
|
||||
{
|
||||
x.Formula = DiscountFormula.Format(steps);
|
||||
}
|
||||
else
|
||||
{
|
||||
c.Error(nameof(DiscountPolicy.Formula), FormulaInvalid);
|
||||
}
|
||||
}));
|
||||
Add(new TableDefinition<DocumentNumerator>("numerators", "document_numerators") { SameKey = row => x => x.Year == row.Year }
|
||||
.Field("year", x => x.Year)
|
||||
.Field("kind", x => x.Kind)
|
||||
.Field("section", x => x.Section)
|
||||
.Field("last", x => x.LastNumber)
|
||||
.Rule((x, c) =>
|
||||
{
|
||||
if (x.Year is < 2000 or > 2100)
|
||||
{
|
||||
c.Error(nameof(DocumentNumerator.Year), YearRange);
|
||||
}
|
||||
|
||||
if (x.LastNumber < 0)
|
||||
{
|
||||
c.Error(nameof(DocumentNumerator.LastNumber), NumberRange);
|
||||
}
|
||||
|
||||
if (!DocumentNumberFormat.IsValid(x.Format))
|
||||
{
|
||||
c.Error(nameof(DocumentNumerator.Format), FormatInvalid);
|
||||
}
|
||||
|
||||
// Invoices, credit notes and final entries are numbered without gaps (SPEC §11.1).
|
||||
if (x.Kind is NumeratorKind.SalesInvoice or NumeratorKind.Journal)
|
||||
{
|
||||
x.GapsAllowed = false;
|
||||
}
|
||||
}));
|
||||
Add(new TableDefinition<DocumentType>("document-types", "document_types")
|
||||
.Field("kind", x => x.Kind)
|
||||
.Field("einvoice", x => x.EInvoiceType)
|
||||
.Rule(async (x, c, ct) =>
|
||||
{
|
||||
if (!string.IsNullOrWhiteSpace(x.EInvoiceType))
|
||||
{
|
||||
x.EInvoiceType = x.EInvoiceType.Trim().ToUpperInvariant();
|
||||
InCodeList(x.EInvoiceType, c.Pack.GetFeature<IEInvoiceFormat>()?.DocumentTypes, nameof(DocumentType.EInvoiceType), c);
|
||||
}
|
||||
else
|
||||
{
|
||||
x.EInvoiceType = null;
|
||||
}
|
||||
|
||||
if (x.NumeratorId is { } numeratorId && await c.GetAsync<DocumentNumerator>(numeratorId, ct).ConfigureAwait(false) is null)
|
||||
{
|
||||
c.Error(nameof(DocumentType.NumeratorId), ReferenceMissing);
|
||||
}
|
||||
|
||||
if (x.InventoryReasonId is { } reasonId && await c.GetAsync<InventoryReason>(reasonId, ct).ConfigureAwait(false) is null)
|
||||
{
|
||||
c.Error(nameof(DocumentType.InventoryReasonId), ReferenceMissing);
|
||||
}
|
||||
}));
|
||||
Add(new TableDefinition<CostCenter>("cost-centers", "cost_centers") { CodeLength = 20 }
|
||||
.Rule(async (x, c, ct) =>
|
||||
{
|
||||
if (x.ParentId is { } parentId && (parentId == x.Id || await c.GetAsync<CostCenter>(parentId, ct).ConfigureAwait(false) is null))
|
||||
{
|
||||
c.Error(nameof(CostCenter.ParentId), ParentInvalid);
|
||||
}
|
||||
}));
|
||||
Add(new TableDefinition<Job>("jobs", "jobs") { CodeLength = 20 }
|
||||
.Field("status", x => x.Status)
|
||||
.Rule((x, c) => Validity(x.StartDate, x.EndDate, nameof(Job.EndDate), c)));
|
||||
}
|
||||
|
||||
/// <summary>Every table, in the order of SPEC §11.1.</summary>
|
||||
public IEnumerable<TableDefinition> All => _byKey.Values;
|
||||
|
||||
/// <summary>The definition of an entity.</summary>
|
||||
/// <typeparam name="T">The entity.</typeparam>
|
||||
/// <returns>The definition.</returns>
|
||||
public TableDefinition<T> Get<T>()
|
||||
where T : CodedEntity, new() =>
|
||||
(TableDefinition<T>)(_byType.GetValueOrDefault(typeof(T)) ?? throw new InvalidOperationException($"{typeof(T).Name} is not a company table."));
|
||||
|
||||
/// <summary>A definition by key.</summary>
|
||||
/// <param name="key">The key, such as <c>tax-codes</c>.</param>
|
||||
/// <returns>The definition, or <see langword="null"/>.</returns>
|
||||
public TableDefinition? Find(string key) => _byKey.GetValueOrDefault(key);
|
||||
|
||||
private static void Pattern(string code, Regex pattern, TableRuleContext context)
|
||||
{
|
||||
if (code.Length > 0 && !pattern.IsMatch(code))
|
||||
{
|
||||
context.Error(nameof(CodedEntity.Code), CodePattern);
|
||||
}
|
||||
}
|
||||
|
||||
private static void Decimals(int value, int min, int max, string field, TableRuleContext context)
|
||||
{
|
||||
if (value < min || value > max)
|
||||
{
|
||||
context.Error(field, DecimalsRange);
|
||||
}
|
||||
}
|
||||
|
||||
private static void Percent(decimal value, string field, TableRuleContext context)
|
||||
{
|
||||
if (value is < 0 or > 100)
|
||||
{
|
||||
context.Error(field, PercentRange);
|
||||
}
|
||||
}
|
||||
|
||||
private static void Email(string? value, string field, TableRuleContext context)
|
||||
{
|
||||
if (!string.IsNullOrWhiteSpace(value) && !EmailValidator.IsValid(value))
|
||||
{
|
||||
context.Error(field, EmailInvalid);
|
||||
}
|
||||
}
|
||||
|
||||
private static void Validity(DateOnly? from, DateOnly? to, string field, TableRuleContext context)
|
||||
{
|
||||
if (from is { } start && to is { } end && end < start)
|
||||
{
|
||||
context.Error(field, ValidityOrder);
|
||||
}
|
||||
}
|
||||
|
||||
private static void InCodeList(string? value, CodeList? list, string field, TableRuleContext context)
|
||||
{
|
||||
if (list is null || string.IsNullOrEmpty(value))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var entry = list.Find(value);
|
||||
if (entry is null)
|
||||
{
|
||||
context.Error(field, NotInCodeList);
|
||||
}
|
||||
else if (entry.Obsolete)
|
||||
{
|
||||
context.Warning(field, ObsoleteInCodeList);
|
||||
}
|
||||
}
|
||||
|
||||
[GeneratedRegex("^[A-Z]{2}$", RegexOptions.CultureInvariant)]
|
||||
private static partial Regex TwoLetters();
|
||||
|
||||
[GeneratedRegex("^[A-Z]{3}$", RegexOptions.CultureInvariant)]
|
||||
private static partial Regex ThreeLetters();
|
||||
|
||||
[GeneratedRegex("^[A-Z][0-9]{3}$", RegexOptions.CultureInvariant)]
|
||||
private static partial Regex CadastralCode();
|
||||
|
||||
[GeneratedRegex("^[A-Z]{6}[A-Z0-9]{2}([A-Z0-9]{3})?$", RegexOptions.CultureInvariant)]
|
||||
private static partial Regex Bic();
|
||||
|
||||
private void Add<T>(TableDefinition<T> definition)
|
||||
where T : CodedEntity, new()
|
||||
{
|
||||
_byType.Add(typeof(T), definition);
|
||||
_byKey.Add(definition.Key, definition);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A chain of discounts such as <c>10+5</c>: each step applies to what the previous left.</summary>
|
||||
public static class DiscountFormula
|
||||
{
|
||||
/// <summary>Reads a formula: percentages 0-100 separated by <c>+</c>, decimal comma or point.</summary>
|
||||
/// <param name="formula">The formula.</param>
|
||||
/// <param name="steps">The percentages.</param>
|
||||
/// <returns>Whether it could be read.</returns>
|
||||
public static bool TryParse(string? formula, out IReadOnlyList<decimal> steps)
|
||||
{
|
||||
steps = [];
|
||||
if (string.IsNullOrWhiteSpace(formula))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var result = new List<decimal>();
|
||||
foreach (var part in formula.Split('+', StringSplitOptions.TrimEntries))
|
||||
{
|
||||
if (!decimal.TryParse(part.Replace(',', '.'), NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out var step) || step > 100)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
result.Add(step);
|
||||
}
|
||||
|
||||
steps = result;
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>Writes a formula in the Italian form, such as <c>10+5,5</c>.</summary>
|
||||
/// <param name="steps">The percentages.</param>
|
||||
/// <returns>The formula.</returns>
|
||||
public static string Format(IEnumerable<decimal> steps) =>
|
||||
string.Join('+', steps.Select(s => s.ToString("0.##", CultureInfo.GetCultureInfo("it-IT"))));
|
||||
|
||||
/// <summary>The single discount equal to the chain: 10+5 is 14.5%.</summary>
|
||||
/// <param name="steps">The percentages.</param>
|
||||
/// <returns>The equivalent percentage.</returns>
|
||||
public static decimal Equivalent(IEnumerable<decimal> steps) =>
|
||||
100m - (steps.Aggregate(1m, (left, step) => left * (1 - (step / 100m))) * 100m);
|
||||
}
|
||||
|
||||
/// <summary>The format of document numbers: <c>{prefix}</c>, <c>{year}</c>, <c>{section}</c> and <c>{number}</c> (with <c>:D6</c> and similar).</summary>
|
||||
public static partial class DocumentNumberFormat
|
||||
{
|
||||
/// <summary>Whether a format has the number and only known placeholders.</summary>
|
||||
/// <param name="format">The format.</param>
|
||||
/// <returns>Whether it is valid.</returns>
|
||||
public static bool IsValid(string? format) =>
|
||||
!string.IsNullOrWhiteSpace(format) && format.Length <= 60 && NumberPlaceholder().IsMatch(format) &&
|
||||
Placeholder().Matches(format).All(m => Known().IsMatch(m.Value));
|
||||
|
||||
/// <summary>Writes a number with a format.</summary>
|
||||
/// <param name="format">The format.</param>
|
||||
/// <param name="number">The number.</param>
|
||||
/// <param name="year">The year.</param>
|
||||
/// <param name="prefix">The prefix.</param>
|
||||
/// <param name="section">The section.</param>
|
||||
/// <returns>The document number, such as <c>FV/2026/000123</c>.</returns>
|
||||
public static string Apply(string format, long number, int year, string? prefix, string? section)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(format);
|
||||
return Placeholder().Replace(format, m =>
|
||||
{
|
||||
var token = m.Value[1..^1];
|
||||
var colon = token.IndexOf(':', StringComparison.Ordinal);
|
||||
var name = colon < 0 ? token : token[..colon];
|
||||
var spec = colon < 0 ? null : token[(colon + 1)..];
|
||||
return name switch
|
||||
{
|
||||
"number" => number.ToString(spec, CultureInfo.InvariantCulture),
|
||||
"year" => year.ToString(CultureInfo.InvariantCulture),
|
||||
"prefix" => prefix ?? string.Empty,
|
||||
"section" => section ?? string.Empty,
|
||||
_ => m.Value,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
[GeneratedRegex(@"\{number(:D[1-9])?\}", RegexOptions.CultureInvariant)]
|
||||
private static partial Regex NumberPlaceholder();
|
||||
|
||||
[GeneratedRegex(@"\{[^}]*\}", RegexOptions.CultureInvariant)]
|
||||
private static partial Regex Placeholder();
|
||||
|
||||
[GeneratedRegex(@"^\{(number(:D[1-9])?|year|prefix|section)\}$", RegexOptions.CultureInvariant)]
|
||||
private static partial Regex Known();
|
||||
}
|
||||
@@ -0,0 +1,214 @@
|
||||
using System.Globalization;
|
||||
using System.Linq.Expressions;
|
||||
using System.Reflection;
|
||||
using System.Text.RegularExpressions;
|
||||
using Khaemhat.Application.Querying;
|
||||
using Khaemhat.Core.Entities;
|
||||
using Khaemhat.Core.Tables;
|
||||
using Khaemhat.Data;
|
||||
using Khaemhat.Data.Querying;
|
||||
using Khaemhat.Fiscal.Abstractions;
|
||||
|
||||
namespace Khaemhat.Application.Tables;
|
||||
|
||||
/// <summary>A problem found on a field of a table row: an error blocks the save, a warning does not.</summary>
|
||||
/// <param name="Field">The property, such as <c>Code</c>.</param>
|
||||
/// <param name="Code">The stable code, translated by the interface (<c>tables.code.required</c>).</param>
|
||||
/// <param name="IsWarning">Whether it is only a warning.</param>
|
||||
public sealed record TableProblem(string Field, string Code, bool IsWarning = false);
|
||||
|
||||
/// <summary>What the rules of a table can use: the fiscal pack of the company and the other rows.</summary>
|
||||
public sealed class TableRuleContext
|
||||
{
|
||||
private readonly IUnitOfWork _unitOfWork;
|
||||
private readonly List<TableProblem> _problems = [];
|
||||
|
||||
internal TableRuleContext(IUnitOfWork unitOfWork, IFiscalPack pack)
|
||||
{
|
||||
_unitOfWork = unitOfWork;
|
||||
Pack = pack;
|
||||
}
|
||||
|
||||
/// <summary>The fiscal pack of the company's country.</summary>
|
||||
public IFiscalPack Pack { get; }
|
||||
|
||||
/// <summary>The problems found so far.</summary>
|
||||
public IReadOnlyList<TableProblem> Problems => _problems;
|
||||
|
||||
/// <summary>Adds an error.</summary>
|
||||
/// <param name="field">The property.</param>
|
||||
/// <param name="code">The code.</param>
|
||||
public void Error(string field, string code) => _problems.Add(new TableProblem(field, code));
|
||||
|
||||
/// <summary>Adds a warning.</summary>
|
||||
/// <param name="field">The property.</param>
|
||||
/// <param name="code">The code.</param>
|
||||
public void Warning(string field, string code) => _problems.Add(new TableProblem(field, code, IsWarning: true));
|
||||
|
||||
/// <summary>Reads another row by id.</summary>
|
||||
/// <typeparam name="TOther">The entity.</typeparam>
|
||||
/// <param name="id">The id.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The row, or <see langword="null"/>.</returns>
|
||||
public Task<TOther?> GetAsync<TOther>(long id, CancellationToken cancellationToken)
|
||||
where TOther : class, IEntity<long>, new() =>
|
||||
_unitOfWork.Repository<TOther, long>().GetAsync(id, cancellationToken);
|
||||
|
||||
/// <summary>Counts the rows of another table that match.</summary>
|
||||
/// <typeparam name="TOther">The other table.</typeparam>
|
||||
/// <param name="where">The condition.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>How many rows match.</returns>
|
||||
public Task<int> CountAsync<TOther>(System.Linq.Expressions.Expression<Func<TOther, bool>> where, CancellationToken cancellationToken)
|
||||
where TOther : class, IEntity<long>, new() =>
|
||||
_unitOfWork.Repository<TOther, long>().CountAsync(Query.For<TOther>().Where(where), cancellationToken);
|
||||
|
||||
/// <summary>Whether a coded row with a code exists.</summary>
|
||||
/// <typeparam name="TOther">The entity.</typeparam>
|
||||
/// <param name="code">The code.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>Whether it exists.</returns>
|
||||
public async Task<bool> ExistsAsync<TOther>(string? code, CancellationToken cancellationToken)
|
||||
where TOther : CodedEntity, new() =>
|
||||
!string.IsNullOrEmpty(code) &&
|
||||
await _unitOfWork.Repository<TOther, long>().CountAsync(Query.For<TOther>().Where(x => x.Code == code), cancellationToken).ConfigureAwait(false) > 0;
|
||||
}
|
||||
|
||||
/// <summary>A company table that the generic maschera and service handle (SPEC §11.1, mockup 076).</summary>
|
||||
public abstract class TableDefinition
|
||||
{
|
||||
/// <summary>Creates the definition.</summary>
|
||||
/// <param name="key">The key used in addresses and resources, such as <c>tax-codes</c>.</param>
|
||||
/// <param name="table">The database table.</param>
|
||||
protected TableDefinition(string key, string table)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(key);
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(table);
|
||||
Key = key;
|
||||
Table = table;
|
||||
}
|
||||
|
||||
/// <summary>The key, such as <c>tax-codes</c>.</summary>
|
||||
public string Key { get; }
|
||||
|
||||
/// <summary>The database table, such as <c>tax_codes</c>.</summary>
|
||||
public string Table { get; }
|
||||
|
||||
/// <summary>The entity type.</summary>
|
||||
public abstract Type EntityType { get; }
|
||||
|
||||
/// <summary>The maximum length of the code.</summary>
|
||||
public int CodeLength { get; init; } = 10;
|
||||
|
||||
/// <summary>Whether codes are kept as typed instead of upper case (municipality names are not codes).</summary>
|
||||
public bool KeepCodeCase { get; init; }
|
||||
|
||||
/// <summary>The CSV columns: header and property.</summary>
|
||||
public abstract IReadOnlyList<TableCsvColumn> CsvColumns { get; }
|
||||
}
|
||||
|
||||
/// <summary>A CSV column of a table: the snake_case header and the property.</summary>
|
||||
/// <param name="Header">The header.</param>
|
||||
/// <param name="Property">The property.</param>
|
||||
public sealed record TableCsvColumn(string Header, PropertyInfo Property);
|
||||
|
||||
/// <summary>A company table of <typeparamref name="T"/>.</summary>
|
||||
/// <typeparam name="T">The entity.</typeparam>
|
||||
public sealed partial class TableDefinition<T> : TableDefinition
|
||||
where T : CodedEntity, new()
|
||||
{
|
||||
private static readonly HashSet<string> NotInCsv = new(StringComparer.Ordinal)
|
||||
{
|
||||
nameof(Entity<long>.Id), nameof(IAuditable.CreatedAt), nameof(IAuditable.CreatedBy), nameof(IAuditable.UpdatedAt), nameof(IAuditable.UpdatedBy),
|
||||
nameof(IAuditable.RowVersion), nameof(CodedEntity.IsDemo),
|
||||
};
|
||||
|
||||
private readonly List<Func<T, TableRuleContext, CancellationToken, Task>> _rules = [];
|
||||
private IReadOnlyList<TableCsvColumn>? _csv;
|
||||
|
||||
/// <summary>Creates the definition with the list fields <c>code</c>, <c>description</c>, <c>disabled</c>.</summary>
|
||||
/// <param name="key">The key, such as <c>tax-codes</c>.</param>
|
||||
/// <param name="table">The database table.</param>
|
||||
public TableDefinition(string key, string table)
|
||||
: base(key, table)
|
||||
{
|
||||
Fields = new ListFields<T>()
|
||||
.Add("code", x => x.Code, searchable: true)
|
||||
.Add("description", x => x.Description, searchable: true)
|
||||
.Add("disabled", x => x.Disabled)
|
||||
.OrderByDefault(new ListSort("code"));
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public override Type EntityType => typeof(T);
|
||||
|
||||
/// <summary>The fields of the grid: filters, search and ordering.</summary>
|
||||
public ListFields<T> Fields { get; }
|
||||
|
||||
/// <summary>The rules run before every save, after the common ones (code and description).</summary>
|
||||
public IReadOnlyList<Func<T, TableRuleContext, CancellationToken, Task>> Rules => _rules;
|
||||
|
||||
/// <summary>The flag that only one row may have (the default bank account, the default warehouse).</summary>
|
||||
public Expression<Func<T, bool>>? SingleDefault { get; init; }
|
||||
|
||||
/// <summary>The other fields that, with the code, make a row unique (the year of a numerator).</summary>
|
||||
public Func<T, Expression<Func<T, bool>>>? SameKey { get; init; }
|
||||
|
||||
/// <summary>Called before the rules, to fill derived fields (the kind of a VAT code).</summary>
|
||||
public Action<T, IFiscalPack>? Complete { get; init; }
|
||||
|
||||
/// <inheritdoc />
|
||||
public override IReadOnlyList<TableCsvColumn> CsvColumns => _csv ??=
|
||||
[
|
||||
.. typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance)
|
||||
.Where(p => p.CanWrite && !NotInCsv.Contains(p.Name) && !p.Name.EndsWith("Id", StringComparison.Ordinal))
|
||||
.OrderBy(p => p.Name switch { nameof(CodedEntity.Code) => 0, nameof(CodedEntity.Description) => 1, _ => 2 })
|
||||
.ThenBy(p => p.MetadataToken)
|
||||
.Select(p => new TableCsvColumn(SnakeCase(p.Name), p)),
|
||||
];
|
||||
|
||||
/// <summary>Adds a rule.</summary>
|
||||
/// <param name="rule">The rule.</param>
|
||||
/// <returns>This, to chain.</returns>
|
||||
public TableDefinition<T> Rule(Func<T, TableRuleContext, CancellationToken, Task> rule)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(rule);
|
||||
_rules.Add(rule);
|
||||
return this;
|
||||
}
|
||||
|
||||
/// <summary>Adds a rule that needs no other rows.</summary>
|
||||
/// <param name="rule">The rule.</param>
|
||||
/// <returns>This, to chain.</returns>
|
||||
public TableDefinition<T> Rule(Action<T, TableRuleContext> rule)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(rule);
|
||||
_rules.Add((row, context, _) =>
|
||||
{
|
||||
rule(row, context);
|
||||
return Task.CompletedTask;
|
||||
});
|
||||
return this;
|
||||
}
|
||||
|
||||
/// <summary>Adds a grid field.</summary>
|
||||
/// <typeparam name="TValue">The type.</typeparam>
|
||||
/// <param name="id">The id.</param>
|
||||
/// <param name="selector">The property.</param>
|
||||
/// <param name="searchable">Whether the search box looks in it.</param>
|
||||
/// <returns>This, to chain.</returns>
|
||||
public TableDefinition<T> Field<TValue>(string id, Expression<Func<T, TValue>> selector, bool searchable = false)
|
||||
{
|
||||
Fields.Add(id, selector, searchable);
|
||||
return this;
|
||||
}
|
||||
|
||||
internal static string SnakeCase(string name) =>
|
||||
LowerUpper().Replace(UpperUpperLower().Replace(name, "$1_$2"), "$1_$2").ToLower(CultureInfo.InvariantCulture);
|
||||
|
||||
[GeneratedRegex("([A-Z])([A-Z][a-z])")]
|
||||
private static partial Regex UpperUpperLower();
|
||||
|
||||
[GeneratedRegex("([a-z0-9])([A-Z])")]
|
||||
private static partial Regex LowerUpper();
|
||||
}
|
||||
@@ -0,0 +1,622 @@
|
||||
using System.Data.Common;
|
||||
using System.Globalization;
|
||||
using System.Reflection;
|
||||
using Khaemhat.Application.Audit;
|
||||
using Khaemhat.Application.Querying;
|
||||
using Khaemhat.Application.Security;
|
||||
using Khaemhat.Core.Caching;
|
||||
using Khaemhat.Core.Tables;
|
||||
using Khaemhat.Data;
|
||||
using Khaemhat.Data.Querying;
|
||||
using Khaemhat.Fiscal.Abstractions;
|
||||
using Khaemhat.Infrastructure.Files;
|
||||
|
||||
namespace Khaemhat.Application.Tables;
|
||||
|
||||
/// <summary>What a delete did.</summary>
|
||||
public enum TableDeleteOutcome
|
||||
{
|
||||
/// <summary>The row is gone.</summary>
|
||||
Deleted = 0,
|
||||
|
||||
/// <summary>The row is used elsewhere: it was disabled instead.</summary>
|
||||
Disabled = 1,
|
||||
}
|
||||
|
||||
/// <summary>A row of a CSV import that could not be read or saved.</summary>
|
||||
/// <param name="Row">The row number in the file, from 2 (1 is the header).</param>
|
||||
/// <param name="Field">The column, or <see langword="null"/> for the whole row.</param>
|
||||
/// <param name="Code">The problem.</param>
|
||||
public sealed record TableImportError(int Row, string? Field, string Code);
|
||||
|
||||
/// <summary>The result of a CSV import: nothing is saved when there are errors.</summary>
|
||||
/// <param name="Inserted">New rows.</param>
|
||||
/// <param name="Updated">Rows changed (found by code).</param>
|
||||
/// <param name="Errors">The errors.</param>
|
||||
public sealed record TableImportResult(int Inserted, int Updated, IReadOnlyList<TableImportError> Errors)
|
||||
{
|
||||
/// <summary>Whether the import was saved.</summary>
|
||||
public bool Succeeded => Errors.Count == 0;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The company tables of SPEC §11.1 through one service (wiki <i>Tabelle azienda</i>): list, read, save with the common
|
||||
/// rules (code and description required, unique code) and those of the table, delete (or disable when the row is used),
|
||||
/// CSV export and import. The rows of each table are cached per company and invalidated on every change, also on the
|
||||
/// other instances when Redis is configured.
|
||||
/// </summary>
|
||||
/// <remarks>Reading needs <c>company.settings.read</c>, changing <c>company.settings.write</c>.</remarks>
|
||||
public sealed class TableService
|
||||
{
|
||||
/// <summary>Permission to see the tables.</summary>
|
||||
public const string ReadPermission = "company.settings.read";
|
||||
|
||||
/// <summary>Permission to change the tables.</summary>
|
||||
public const string WritePermission = "company.settings.write";
|
||||
|
||||
/// <summary>Error: the code is missing.</summary>
|
||||
public const string CodeRequired = "tables.code.required";
|
||||
|
||||
/// <summary>Error: the code is too long.</summary>
|
||||
public const string CodeTooLong = "tables.code.too-long";
|
||||
|
||||
/// <summary>Error: another row has the code.</summary>
|
||||
public const string CodeDuplicate = "tables.code.duplicate";
|
||||
|
||||
/// <summary>Error: the description is missing.</summary>
|
||||
public const string DescriptionRequired = "tables.description.required";
|
||||
|
||||
/// <summary>Error: the row changed or was deleted meanwhile.</summary>
|
||||
public const string NotFound = "tables.not-found";
|
||||
|
||||
/// <summary>Import error: the header has no <c>code</c> column.</summary>
|
||||
public const string CsvNoCode = "tables.csv.no-code";
|
||||
|
||||
/// <summary>Import error: a value cannot be read.</summary>
|
||||
public const string CsvBadValue = "tables.csv.bad-value";
|
||||
|
||||
/// <summary>Import error: unknown column (a warning in the result: the column is ignored).</summary>
|
||||
public const string CsvUnknownColumn = "tables.csv.unknown-column";
|
||||
|
||||
private static readonly TimeSpan CacheTime = TimeSpan.FromHours(1);
|
||||
private static readonly NullabilityInfoContext Nullability = new();
|
||||
|
||||
private readonly IUnitOfWorkFactory _factory;
|
||||
private readonly PermissionService _permissions;
|
||||
private readonly AuditTrail _audit;
|
||||
private readonly ICacheProvider _cache;
|
||||
private readonly CompanyFiscalContext _fiscal;
|
||||
private readonly TableCatalog _catalog;
|
||||
|
||||
/// <summary>Creates the service.</summary>
|
||||
/// <param name="factory">Opens the company databases.</param>
|
||||
/// <param name="permissions">Checks permissions.</param>
|
||||
/// <param name="audit">Writes the history.</param>
|
||||
/// <param name="cache">The cache of the rows.</param>
|
||||
/// <param name="fiscal">The fiscal pack of each company.</param>
|
||||
/// <param name="catalog">The tables.</param>
|
||||
public TableService(IUnitOfWorkFactory factory, PermissionService permissions, AuditTrail audit, ICacheProvider cache, CompanyFiscalContext fiscal, TableCatalog catalog)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(factory);
|
||||
ArgumentNullException.ThrowIfNull(permissions);
|
||||
ArgumentNullException.ThrowIfNull(audit);
|
||||
ArgumentNullException.ThrowIfNull(cache);
|
||||
ArgumentNullException.ThrowIfNull(fiscal);
|
||||
ArgumentNullException.ThrowIfNull(catalog);
|
||||
_factory = factory;
|
||||
_permissions = permissions;
|
||||
_audit = audit;
|
||||
_cache = cache;
|
||||
_fiscal = fiscal;
|
||||
_catalog = catalog;
|
||||
}
|
||||
|
||||
/// <summary>The tables.</summary>
|
||||
public TableCatalog Catalog => _catalog;
|
||||
|
||||
/// <summary>Every row of a table, from the cache (disabled ones included), ordered by code.</summary>
|
||||
/// <typeparam name="T">The entity.</typeparam>
|
||||
/// <param name="actor">Who reads.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The rows.</returns>
|
||||
public async Task<IReadOnlyList<T>> AllAsync<T>(Actor actor, string companyCode, CancellationToken cancellationToken = default)
|
||||
where T : CodedEntity, new()
|
||||
{
|
||||
var company = await DemandAsync(actor, companyCode, ReadPermission, cancellationToken).ConfigureAwait(false);
|
||||
return await RowsAsync(company, _catalog.Get<T>(), cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>The rows still in use (not disabled), for the choices on other records.</summary>
|
||||
/// <typeparam name="T">The entity.</typeparam>
|
||||
/// <param name="actor">Who reads.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The rows.</returns>
|
||||
public async Task<IReadOnlyList<T>> ActiveAsync<T>(Actor actor, string companyCode, CancellationToken cancellationToken = default)
|
||||
where T : CodedEntity, new() =>
|
||||
[.. (await AllAsync<T>(actor, companyCode, cancellationToken).ConfigureAwait(false)).Where(r => !r.Disabled)];
|
||||
|
||||
/// <summary>A page of a table for the grid.</summary>
|
||||
/// <typeparam name="T">The entity.</typeparam>
|
||||
/// <param name="actor">Who reads.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="query">Search, filters, ordering and page.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The page.</returns>
|
||||
public async Task<ListPage<T>> ListAsync<T>(Actor actor, string companyCode, ListQuery query, CancellationToken cancellationToken = default)
|
||||
where T : CodedEntity, new()
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(query);
|
||||
var rows = await AllAsync<T>(actor, companyCode, cancellationToken).ConfigureAwait(false);
|
||||
return _catalog.Get<T>().Fields.Apply(rows, query);
|
||||
}
|
||||
|
||||
/// <summary>One row, read from the database.</summary>
|
||||
/// <typeparam name="T">The entity.</typeparam>
|
||||
/// <param name="actor">Who reads.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="id">The id.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The row, or <see langword="null"/>.</returns>
|
||||
public async Task<T?> GetAsync<T>(Actor actor, string companyCode, long id, CancellationToken cancellationToken = default)
|
||||
where T : CodedEntity, new()
|
||||
{
|
||||
var company = await DemandAsync(actor, companyCode, ReadPermission, cancellationToken).ConfigureAwait(false);
|
||||
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
||||
return await uow.Repository<T, long>().GetAsync(id, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>Checks a row without saving it: the messages next to the fields.</summary>
|
||||
/// <typeparam name="T">The entity.</typeparam>
|
||||
/// <param name="actor">Who checks.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="row">The row (normalized in place: trimmed code in upper case, derived fields).</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>Errors and warnings.</returns>
|
||||
public async Task<IReadOnlyList<TableProblem>> ValidateAsync<T>(Actor actor, string companyCode, T row, CancellationToken cancellationToken = default)
|
||||
where T : CodedEntity, new()
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(row);
|
||||
var company = await DemandAsync(actor, companyCode, ReadPermission, cancellationToken).ConfigureAwait(false);
|
||||
var pack = await _fiscal.PackOfAsync(company, cancellationToken).ConfigureAwait(false);
|
||||
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
||||
return await CheckAsync(uow, pack, _catalog.Get<T>(), row, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>Saves a row: inserts it when <see cref="Core.Entities.Entity{TKey}.Id"/> is 0, updates it otherwise.</summary>
|
||||
/// <typeparam name="T">The entity.</typeparam>
|
||||
/// <param name="actor">Who saves.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="row">The row.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The saved row, with its id and new row version.</returns>
|
||||
/// <exception cref="ValidationFailedException">A rule failed; <see cref="ValidationFailedException.Errors"/> has <c>Field:code</c>.</exception>
|
||||
/// <exception cref="Core.Common.ConcurrencyException">Someone else changed the row meanwhile.</exception>
|
||||
public async Task<T> SaveAsync<T>(Actor actor, string companyCode, T row, CancellationToken cancellationToken = default)
|
||||
where T : CodedEntity, new()
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(row);
|
||||
var company = await DemandAsync(actor, companyCode, WritePermission, cancellationToken).ConfigureAwait(false);
|
||||
var definition = _catalog.Get<T>();
|
||||
var pack = await _fiscal.PackOfAsync(company, cancellationToken).ConfigureAwait(false);
|
||||
await using (var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
|
||||
Throw(await CheckAsync(uow, pack, definition, row, cancellationToken).ConfigureAwait(false));
|
||||
await WriteAsync(uow, definition, row, actor.UserName, cancellationToken).ConfigureAwait(false);
|
||||
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
await InvalidateAsync(company, definition, cancellationToken).ConfigureAwait(false);
|
||||
return row;
|
||||
}
|
||||
|
||||
/// <summary>Deletes a row, or disables it when other records use it.</summary>
|
||||
/// <typeparam name="T">The entity.</typeparam>
|
||||
/// <param name="actor">Who deletes.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="id">The row.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>What happened.</returns>
|
||||
/// <exception cref="KeyNotFoundException">No such row.</exception>
|
||||
public async Task<TableDeleteOutcome> DeleteAsync<T>(Actor actor, string companyCode, long id, CancellationToken cancellationToken = default)
|
||||
where T : CodedEntity, new()
|
||||
{
|
||||
var company = await DemandAsync(actor, companyCode, WritePermission, cancellationToken).ConfigureAwait(false);
|
||||
var definition = _catalog.Get<T>();
|
||||
var outcome = TableDeleteOutcome.Deleted;
|
||||
try
|
||||
{
|
||||
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
||||
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
|
||||
var repository = uow.Repository<T, long>();
|
||||
var before = await repository.GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(NotFound);
|
||||
await repository.DeleteAsync(id, cancellationToken).ConfigureAwait(false);
|
||||
await _audit.RecordAsync(uow, AuditAction.Delete, id, before, null, actor.UserName, cancellationToken).ConfigureAwait(false);
|
||||
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
catch (DbException)
|
||||
{
|
||||
// A foreign key refused the delete: the row is used, so it is only hidden from new choices.
|
||||
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
||||
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
|
||||
var repository = uow.Repository<T, long>();
|
||||
var row = await repository.GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(NotFound);
|
||||
if (!row.Disabled)
|
||||
{
|
||||
var before = Clone(row);
|
||||
row.Disabled = true;
|
||||
await repository.UpdateAsync(row, cancellationToken).ConfigureAwait(false);
|
||||
await _audit.RecordAsync(uow, AuditAction.Update, id, before, row, actor.UserName, cancellationToken).ConfigureAwait(false);
|
||||
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
outcome = TableDeleteOutcome.Disabled;
|
||||
}
|
||||
|
||||
await InvalidateAsync(company, definition, cancellationToken).ConfigureAwait(false);
|
||||
return outcome;
|
||||
}
|
||||
|
||||
/// <summary>Writes a table as CSV (Italian format: <c>;</c>, decimal comma, byte order mark).</summary>
|
||||
/// <typeparam name="T">The entity.</typeparam>
|
||||
/// <param name="actor">Who exports.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="output">The stream; left open.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The rows written.</returns>
|
||||
public async Task<int> ExportCsvAsync<T>(Actor actor, string companyCode, Stream output, CancellationToken cancellationToken = default)
|
||||
where T : CodedEntity, new()
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(output);
|
||||
var rows = await AllAsync<T>(actor, companyCode, cancellationToken).ConfigureAwait(false);
|
||||
var columns = _catalog.Get<T>().CsvColumns;
|
||||
await using var writer = new CsvWriter(output, CsvOptions.Italian, leaveOpen: true);
|
||||
await writer.WriteRowAsync(columns.Select(c => (object?)c.Header), cancellationToken).ConfigureAwait(false);
|
||||
foreach (var row in rows)
|
||||
{
|
||||
await writer.WriteRowAsync(columns.Select(c => Export(c.Property.GetValue(row))), cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
return rows.Count;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Imports a CSV with the columns of the export (any order, missing columns keep their value): rows are matched by
|
||||
/// code, new codes are inserted. Nothing is saved unless every row passes the rules.
|
||||
/// </summary>
|
||||
/// <typeparam name="T">The entity.</typeparam>
|
||||
/// <param name="actor">Who imports.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="content">The CSV.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>Counts and errors.</returns>
|
||||
public async Task<TableImportResult> ImportCsvAsync<T>(Actor actor, string companyCode, Stream content, CancellationToken cancellationToken = default)
|
||||
where T : CodedEntity, new()
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(content);
|
||||
var company = await DemandAsync(actor, companyCode, WritePermission, cancellationToken).ConfigureAwait(false);
|
||||
var definition = _catalog.Get<T>();
|
||||
var lines = await CsvReader.ReadAsync(content, null, cancellationToken).ConfigureAwait(false);
|
||||
if (lines.Count == 0)
|
||||
{
|
||||
return new TableImportResult(0, 0, [new TableImportError(1, null, CsvNoCode)]);
|
||||
}
|
||||
|
||||
var byHeader = definition.CsvColumns.ToDictionary(c => c.Header, StringComparer.OrdinalIgnoreCase);
|
||||
var header = lines[0].Select(h => byHeader.GetValueOrDefault(h.Trim())).ToArray();
|
||||
if (!header.Any(c => c?.Property.Name == nameof(CodedEntity.Code)))
|
||||
{
|
||||
return new TableImportResult(0, 0, [new TableImportError(1, null, CsvNoCode)]);
|
||||
}
|
||||
|
||||
var pack = await _fiscal.PackOfAsync(company, cancellationToken).ConfigureAwait(false);
|
||||
var errors = new List<TableImportError>();
|
||||
var inserted = 0;
|
||||
var updated = 0;
|
||||
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
||||
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
|
||||
var existing = (await uow.Repository<T, long>().ListAsync(Query.For<T>(), cancellationToken).ConfigureAwait(false)).Items
|
||||
.GroupBy(r => r.Code, StringComparer.OrdinalIgnoreCase)
|
||||
.ToDictionary(g => g.Key, g => g.First(), StringComparer.OrdinalIgnoreCase);
|
||||
var seen = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
|
||||
var pending = new List<T>();
|
||||
|
||||
for (var i = 1; i < lines.Count; i++)
|
||||
{
|
||||
var line = lines[i];
|
||||
var rowNumber = i + 1;
|
||||
var codeIndex = Array.FindIndex(header, c => c?.Property.Name == nameof(CodedEntity.Code));
|
||||
var code = codeIndex < line.Count ? line[codeIndex].Trim() : string.Empty;
|
||||
var row = existing.TryGetValue(code, out var found) ? found : new T();
|
||||
var rowErrors = false;
|
||||
for (var c = 0; c < header.Length && c < line.Count; c++)
|
||||
{
|
||||
if (header[c] is not { } column)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
if (TryParse(line[c], column.Property, out var value))
|
||||
{
|
||||
column.Property.SetValue(row, value);
|
||||
}
|
||||
else
|
||||
{
|
||||
errors.Add(new TableImportError(rowNumber, column.Header, CsvBadValue));
|
||||
rowErrors = true;
|
||||
}
|
||||
}
|
||||
|
||||
if (!seen.Add(row.Code.Trim()))
|
||||
{
|
||||
errors.Add(new TableImportError(rowNumber, "code", CodeDuplicate));
|
||||
continue;
|
||||
}
|
||||
|
||||
if (rowErrors)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var problems = await CheckAsync(uow, pack, definition, row, cancellationToken).ConfigureAwait(false);
|
||||
errors.AddRange(problems.Where(p => !p.IsWarning).Select(p => new TableImportError(rowNumber, TableDefinition<T>.SnakeCase(p.Field), p.Code)));
|
||||
pending.Add(row);
|
||||
}
|
||||
|
||||
if (errors.Count > 0)
|
||||
{
|
||||
return new TableImportResult(0, 0, errors);
|
||||
}
|
||||
|
||||
foreach (var row in pending)
|
||||
{
|
||||
if (row.Id == 0)
|
||||
{
|
||||
inserted++;
|
||||
}
|
||||
else
|
||||
{
|
||||
updated++;
|
||||
}
|
||||
|
||||
await WriteAsync(uow, definition, row, actor.UserName, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
|
||||
await InvalidateAsync(company, definition, cancellationToken).ConfigureAwait(false);
|
||||
return new TableImportResult(inserted, updated, []);
|
||||
}
|
||||
|
||||
/// <summary>Saves rows without permission checks or rules: the seeders (§14), inside their own unit of work.</summary>
|
||||
/// <typeparam name="T">The entity.</typeparam>
|
||||
/// <param name="unitOfWork">The company unit of work.</param>
|
||||
/// <param name="row">The row.</param>
|
||||
/// <param name="userName">Who writes, such as <c>system</c>.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>A task.</returns>
|
||||
internal Task WriteAsync<T>(IUnitOfWork unitOfWork, T row, string userName, CancellationToken cancellationToken)
|
||||
where T : CodedEntity, new() =>
|
||||
WriteAsync(unitOfWork, _catalog.Get<T>(), row, userName, cancellationToken);
|
||||
|
||||
/// <summary>Forgets the cached rows of every table of a company (after the seeders).</summary>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>A task.</returns>
|
||||
public ValueTask InvalidateAllAsync(string companyCode, CancellationToken cancellationToken = default) =>
|
||||
_cache.PublishInvalidationAsync(CacheKeys.Prefix(CompanyCodes.Normalize(companyCode), "tables"), cancellationToken);
|
||||
|
||||
private static async Task<IReadOnlyList<TableProblem>> CheckAsync<T>(
|
||||
IUnitOfWork uow, IFiscalPack pack, TableDefinition<T> definition, T row, CancellationToken cancellationToken)
|
||||
where T : CodedEntity, new()
|
||||
{
|
||||
row.Code = definition.KeepCodeCase ? row.Code.Trim() : row.Code.Trim().ToUpperInvariant();
|
||||
row.Description = row.Description.Trim();
|
||||
definition.Complete?.Invoke(row, pack);
|
||||
|
||||
var context = new TableRuleContext(uow, pack);
|
||||
if (row.Code.Length == 0)
|
||||
{
|
||||
context.Error(nameof(CodedEntity.Code), CodeRequired);
|
||||
}
|
||||
else if (row.Code.Length > definition.CodeLength)
|
||||
{
|
||||
context.Error(nameof(CodedEntity.Code), CodeTooLong);
|
||||
}
|
||||
else
|
||||
{
|
||||
var code = row.Code;
|
||||
var id = row.Id;
|
||||
var query = Query.For<T>().Where(x => x.Code == code && x.Id != id);
|
||||
if (definition.SameKey is { } sameKey)
|
||||
{
|
||||
query = query.Where(sameKey(row));
|
||||
}
|
||||
|
||||
if (await uow.Repository<T, long>().CountAsync(query, cancellationToken).ConfigureAwait(false) > 0)
|
||||
{
|
||||
context.Error(nameof(CodedEntity.Code), CodeDuplicate);
|
||||
}
|
||||
}
|
||||
|
||||
if (row.Description.Length == 0)
|
||||
{
|
||||
context.Error(nameof(CodedEntity.Description), DescriptionRequired);
|
||||
}
|
||||
|
||||
foreach (var rule in definition.Rules)
|
||||
{
|
||||
await rule(row, context, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
return context.Problems;
|
||||
}
|
||||
|
||||
private static void Throw(IReadOnlyList<TableProblem> problems)
|
||||
{
|
||||
var errors = problems.Where(p => !p.IsWarning).Select(p => p.Field + ":" + p.Code).ToList();
|
||||
if (errors.Count > 0)
|
||||
{
|
||||
throw new ValidationFailedException(errors);
|
||||
}
|
||||
}
|
||||
|
||||
private static T Clone<T>(T row)
|
||||
where T : class, new()
|
||||
{
|
||||
var copy = new T();
|
||||
foreach (var property in typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance).Where(p => p.CanRead && p.CanWrite))
|
||||
{
|
||||
property.SetValue(copy, property.GetValue(row));
|
||||
}
|
||||
|
||||
return copy;
|
||||
}
|
||||
|
||||
private static object? Export(object? value) => value switch
|
||||
{
|
||||
bool b => b ? "1" : "0",
|
||||
DateOnly d => d.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture),
|
||||
Enum e => e.ToString(),
|
||||
_ => value,
|
||||
};
|
||||
|
||||
private static bool TryParse(string text, PropertyInfo property, out object? value)
|
||||
{
|
||||
text = text.Trim();
|
||||
var type = property.PropertyType;
|
||||
var target = Nullable.GetUnderlyingType(type) ?? type;
|
||||
value = null;
|
||||
if (text.Length == 0)
|
||||
{
|
||||
if (target == typeof(string))
|
||||
{
|
||||
value = Nullability.Create(property).WriteState == NullabilityState.Nullable ? null : string.Empty;
|
||||
return true;
|
||||
}
|
||||
|
||||
if (Nullable.GetUnderlyingType(type) is null)
|
||||
{
|
||||
value = Activator.CreateInstance(target);
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
if (target == typeof(string))
|
||||
{
|
||||
value = text;
|
||||
return true;
|
||||
}
|
||||
|
||||
if (target == typeof(bool))
|
||||
{
|
||||
var lower = text.ToLowerInvariant();
|
||||
value = lower is "1" or "true" or "si" or "sì" or "s" or "x" or "vero";
|
||||
return value is true || lower is "0" or "false" or "no" or "n" or "falso";
|
||||
}
|
||||
|
||||
if (target == typeof(int) || target == typeof(long) || target == typeof(decimal))
|
||||
{
|
||||
// Italian (1.234,5) or invariant (1234.5): a comma is always the decimal point.
|
||||
var normalized = text.Contains(',', StringComparison.Ordinal) ? text.Replace(".", string.Empty, StringComparison.Ordinal).Replace(',', '.') : text;
|
||||
if (!decimal.TryParse(normalized, NumberStyles.Number, CultureInfo.InvariantCulture, out var number))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (target == typeof(decimal))
|
||||
{
|
||||
value = number;
|
||||
return true;
|
||||
}
|
||||
|
||||
if (decimal.Truncate(number) != number)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
value = target == typeof(int) ? (object)(int)number : (long)number;
|
||||
return true;
|
||||
}
|
||||
|
||||
if (target == typeof(DateOnly))
|
||||
{
|
||||
var ok = DateOnly.TryParseExact(text, ["yyyy-MM-dd", "dd/MM/yyyy", "d/M/yyyy"], CultureInfo.InvariantCulture, DateTimeStyles.None, out var date);
|
||||
value = date;
|
||||
return ok;
|
||||
}
|
||||
|
||||
if (target.IsEnum)
|
||||
{
|
||||
var ok = Enum.TryParse(target, text, ignoreCase: true, out var parsed) && Enum.IsDefined(target, parsed!);
|
||||
value = parsed;
|
||||
return ok;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private async Task WriteAsync<T>(IUnitOfWork uow, TableDefinition<T> definition, T row, string userName, CancellationToken cancellationToken)
|
||||
where T : CodedEntity, new()
|
||||
{
|
||||
var repository = uow.Repository<T, long>();
|
||||
if (definition.SingleDefault is { } flag && flag.Compile()(row))
|
||||
{
|
||||
await ClearOtherDefaultsAsync(repository, flag, row.Id, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
if (row.Id == 0)
|
||||
{
|
||||
row.Id = await repository.InsertAsync(row, cancellationToken).ConfigureAwait(false);
|
||||
await _audit.RecordAsync(uow, AuditAction.Insert, row.Id, null, row, userName, cancellationToken).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
|
||||
var before = await repository.GetAsync(row.Id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(NotFound);
|
||||
await repository.UpdateAsync(row, cancellationToken).ConfigureAwait(false);
|
||||
await _audit.RecordAsync(uow, AuditAction.Update, row.Id, before, row, userName, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private static async Task ClearOtherDefaultsAsync<T>(IRepository<T, long> repository, System.Linq.Expressions.Expression<Func<T, bool>> flag, long id, CancellationToken cancellationToken)
|
||||
where T : CodedEntity, new()
|
||||
{
|
||||
var others = await repository.ListAsync(Query.For<T>().Where(flag).Where(x => x.Id != id), cancellationToken).ConfigureAwait(false);
|
||||
var property = (PropertyInfo)((System.Linq.Expressions.MemberExpression)flag.Body).Member;
|
||||
foreach (var other in others.Items)
|
||||
{
|
||||
property.SetValue(other, false);
|
||||
await repository.UpdateAsync(other, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
private async Task<IReadOnlyList<T>> RowsAsync<T>(string company, TableDefinition<T> definition, CancellationToken cancellationToken)
|
||||
where T : CodedEntity, new() =>
|
||||
await _cache.GetOrCreateAsync<List<T>>(
|
||||
CacheKeys.For(company, "tables", definition.Key),
|
||||
async ct =>
|
||||
{
|
||||
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), ct).ConfigureAwait(false);
|
||||
var page = await uow.Repository<T, long>().ListAsync(Query.For<T>().OrderBy(x => x.Code), ct).ConfigureAwait(false);
|
||||
return [.. page.Items];
|
||||
},
|
||||
CacheTime,
|
||||
cancellationToken).ConfigureAwait(false);
|
||||
|
||||
private ValueTask InvalidateAsync(string company, TableDefinition definition, CancellationToken cancellationToken) =>
|
||||
_cache.PublishInvalidationAsync(CacheKeys.For(company, "tables", definition.Key), cancellationToken);
|
||||
|
||||
private async Task<string> DemandAsync(Actor actor, string companyCode, string permission, CancellationToken cancellationToken)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(actor);
|
||||
var company = CompanyCodes.Normalize(companyCode);
|
||||
if (!actor.IsInstanceAccount && !string.Equals(actor.CompanyCode, company, StringComparison.Ordinal))
|
||||
{
|
||||
throw new AccessDeniedException(SecurityErrors.PermissionDenied, "A company user works only in its own company.");
|
||||
}
|
||||
|
||||
await _permissions.DemandAsync(actor, permission, cancellationToken).ConfigureAwait(false);
|
||||
return company;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
namespace Khaemhat.Core.Accounting;
|
||||
|
||||
/// <summary>The nature of a ledger account: which statement it ends up in.</summary>
|
||||
public enum AccountNature
|
||||
{
|
||||
/// <summary>Balance sheet, assets.</summary>
|
||||
Asset = 0,
|
||||
|
||||
/// <summary>Balance sheet, liabilities and equity.</summary>
|
||||
Liability = 1,
|
||||
|
||||
/// <summary>Income statement, costs.</summary>
|
||||
Cost = 2,
|
||||
|
||||
/// <summary>Income statement, revenues.</summary>
|
||||
Revenue = 3,
|
||||
|
||||
/// <summary>Memorandum accounts (conti d'ordine), outside both statements.</summary>
|
||||
Memorandum = 4,
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
namespace Khaemhat.Core.Accounting;
|
||||
|
||||
/// <summary>What a ledger account is used for, beyond its nature: the accounts the automatic postings look for.</summary>
|
||||
public enum AccountType
|
||||
{
|
||||
/// <summary>Any other account.</summary>
|
||||
Generic = 0,
|
||||
|
||||
/// <summary>The customers control account, with a sub-ledger per customer.</summary>
|
||||
Customers = 1,
|
||||
|
||||
/// <summary>The suppliers control account, with a sub-ledger per supplier.</summary>
|
||||
Suppliers = 2,
|
||||
|
||||
/// <summary>A bank account.</summary>
|
||||
Bank = 3,
|
||||
|
||||
/// <summary>Cash.</summary>
|
||||
Cash = 4,
|
||||
|
||||
/// <summary>VAT on sales or purchases, or the VAT settlement.</summary>
|
||||
Vat = 5,
|
||||
|
||||
/// <summary>Amounts due to or from the tax authority (withholdings, taxes).</summary>
|
||||
Tax = 6,
|
||||
}
|
||||
@@ -0,0 +1,234 @@
|
||||
using Khaemhat.Core.Entities;
|
||||
|
||||
namespace Khaemhat.Core.Items;
|
||||
|
||||
/// <summary>What an item is (SPEC §11.2).</summary>
|
||||
public enum ItemKind
|
||||
{
|
||||
/// <summary>Goods bought or sold; kept in stock when <see cref="Item.Stocked"/>.</summary>
|
||||
Goods = 0,
|
||||
|
||||
/// <summary>A service, such as installation or hours of assistance.</summary>
|
||||
Service = 1,
|
||||
|
||||
/// <summary>An ancillary expense on invoices (transport, collection).</summary>
|
||||
Expense = 2,
|
||||
|
||||
/// <summary>A recurring descriptive line.</summary>
|
||||
Text = 3,
|
||||
|
||||
/// <summary>A fixed asset (linked to the asset register with the ASSET module).</summary>
|
||||
Asset = 4,
|
||||
}
|
||||
|
||||
/// <summary>Where the price proposed on a document line comes from (SPEC §11.3).</summary>
|
||||
public enum PriceSource
|
||||
{
|
||||
/// <summary>No price found.</summary>
|
||||
None = 0,
|
||||
|
||||
/// <summary>The net price agreed with the party for the item.</summary>
|
||||
PartyNet = 1,
|
||||
|
||||
/// <summary>The price list of the party (or of the document).</summary>
|
||||
PartyPriceList = 2,
|
||||
|
||||
/// <summary>The base price list of the company.</summary>
|
||||
BasePriceList = 3,
|
||||
|
||||
/// <summary>The price written on the item.</summary>
|
||||
Item = 4,
|
||||
}
|
||||
|
||||
/// <summary>An item (<c>items</c>, mockup 017).</summary>
|
||||
public sealed class Item : Entity<long>, IDemoMarkable
|
||||
{
|
||||
/// <summary>The code, automatic (ADR 0027, mask <c>{categoria}-{seq:0000}</c>).</summary>
|
||||
public string Code { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>What the item is.</summary>
|
||||
public ItemKind Kind { get; set; }
|
||||
|
||||
/// <summary>The description used on documents.</summary>
|
||||
public string Description { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>A longer description.</summary>
|
||||
public string? ExtendedDescription { get; set; }
|
||||
|
||||
/// <summary>The category (<c>item_categories</c>).</summary>
|
||||
public long? CategoryId { get; set; }
|
||||
|
||||
/// <summary>The base unit of measure (<c>units_of_measure</c>).</summary>
|
||||
public long? UnitOfMeasureId { get; set; }
|
||||
|
||||
/// <summary>The VAT code of sales (<c>tax_codes</c>).</summary>
|
||||
public long? SalesTaxCodeId { get; set; }
|
||||
|
||||
/// <summary>The VAT code of purchases (<c>tax_codes</c>).</summary>
|
||||
public long? PurchaseTaxCodeId { get; set; }
|
||||
|
||||
/// <summary>The main bar code (EAN/GTIN).</summary>
|
||||
public string? Barcode { get; set; }
|
||||
|
||||
/// <summary>The combined nomenclature code (NC8, Intrastat).</summary>
|
||||
public string? CustomsCode { get; set; }
|
||||
|
||||
/// <summary>The manufacturer.</summary>
|
||||
public string? Manufacturer { get; set; }
|
||||
|
||||
/// <summary>The brand.</summary>
|
||||
public string? Brand { get; set; }
|
||||
|
||||
/// <summary>Net weight in kilograms.</summary>
|
||||
public decimal? NetWeight { get; set; }
|
||||
|
||||
/// <summary>Gross weight in kilograms.</summary>
|
||||
public decimal? GrossWeight { get; set; }
|
||||
|
||||
/// <summary>The item is kept in stock (movements, balances, reorder from M6).</summary>
|
||||
public bool Stocked { get; set; }
|
||||
|
||||
/// <summary>The usual warehouse (<c>warehouses</c>).</summary>
|
||||
public long? WarehouseId { get; set; }
|
||||
|
||||
/// <summary>The minimum stock.</summary>
|
||||
public decimal? MinimumStock { get; set; }
|
||||
|
||||
/// <summary>The reorder point: below it the item is proposed for an order.</summary>
|
||||
public decimal? ReorderPoint { get; set; }
|
||||
|
||||
/// <summary>The reorder lot: orders are proposed in multiples of it.</summary>
|
||||
public decimal? ReorderLot { get; set; }
|
||||
|
||||
/// <summary>The price written on the item, the last fallback of the price search.</summary>
|
||||
public decimal? Price { get; set; }
|
||||
|
||||
/// <summary>The standard cost, set by hand.</summary>
|
||||
public decimal? StandardCost { get; set; }
|
||||
|
||||
/// <summary>The last purchase cost (updated by the receipts, M6).</summary>
|
||||
public decimal? LastCost { get; set; }
|
||||
|
||||
/// <summary>The weighted average cost (updated by the receipts, M6).</summary>
|
||||
public decimal? AverageCost { get; set; }
|
||||
|
||||
/// <summary>The revenue account (chart of accounts, M7).</summary>
|
||||
public string? RevenueAccountCode { get; set; }
|
||||
|
||||
/// <summary>The cost account (chart of accounts, M7).</summary>
|
||||
public string? CostAccountCode { get; set; }
|
||||
|
||||
/// <summary>Free notes.</summary>
|
||||
public string? Notes { get; set; }
|
||||
|
||||
/// <summary>Disabled: no longer proposed in new documents.</summary>
|
||||
public bool Disabled { get; set; }
|
||||
|
||||
/// <inheritdoc />
|
||||
public bool IsDemo { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>An alternative unit of measure of an item (<c>item_uoms</c>): a box of 10 pieces has factor 10.</summary>
|
||||
public sealed class ItemUnit : Entity<long>
|
||||
{
|
||||
/// <summary>The item.</summary>
|
||||
public long ItemId { get; set; }
|
||||
|
||||
/// <summary>The unit (<c>units_of_measure</c>).</summary>
|
||||
public long UnitOfMeasureId { get; set; }
|
||||
|
||||
/// <summary>How many base units one of this unit holds.</summary>
|
||||
public decimal Factor { get; set; } = 1m;
|
||||
|
||||
/// <summary>The bar code of the package.</summary>
|
||||
public string? Barcode { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>An alternative code of an item (<c>item_barcodes</c>): another EAN or an internal code.</summary>
|
||||
public sealed class ItemBarcode : Entity<long>
|
||||
{
|
||||
/// <summary>The item.</summary>
|
||||
public long ItemId { get; set; }
|
||||
|
||||
/// <summary>The code.</summary>
|
||||
public string Code { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>What the code is, such as <i>confezione</i> or <i>codice interno</i>.</summary>
|
||||
public string? Description { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A price of an item (<c>item_prices</c>): in a price list, or net for a party. A price is valid from a date (none:
|
||||
/// always); the price at a date is the one with the latest start not after it, so old prices stay for old documents.
|
||||
/// </summary>
|
||||
public sealed class ItemPrice : Entity<long>
|
||||
{
|
||||
/// <summary>The item.</summary>
|
||||
public long ItemId { get; set; }
|
||||
|
||||
/// <summary>The price list (<c>price_lists</c>), or none for a net price of a party.</summary>
|
||||
public long? PriceListId { get; set; }
|
||||
|
||||
/// <summary>The party of a net price (<c>parties</c>), or none for a price list.</summary>
|
||||
public long? PartyId { get; set; }
|
||||
|
||||
/// <summary>The price.</summary>
|
||||
public decimal Price { get; set; }
|
||||
|
||||
/// <summary>The price is valid from this day (none: always).</summary>
|
||||
public DateOnly? ValidFrom { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>A supplier of an item (<c>item_suppliers</c>) with its code and price; one is the usual one.</summary>
|
||||
public sealed class ItemSupplier : Entity<long>
|
||||
{
|
||||
/// <summary>The item.</summary>
|
||||
public long ItemId { get; set; }
|
||||
|
||||
/// <summary>The supplier (<c>parties</c>).</summary>
|
||||
public long PartyId { get; set; }
|
||||
|
||||
/// <summary>The code of the item at the supplier.</summary>
|
||||
public string? SupplierCode { get; set; }
|
||||
|
||||
/// <summary>The purchase price.</summary>
|
||||
public decimal? Price { get; set; }
|
||||
|
||||
/// <summary>The lead time in days.</summary>
|
||||
public int? LeadTimeDays { get; set; }
|
||||
|
||||
/// <summary>The minimum quantity of an order.</summary>
|
||||
public decimal? MinimumQuantity { get; set; }
|
||||
|
||||
/// <summary>The usual supplier, used by the reorder proposal.</summary>
|
||||
public bool IsDefault { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>An equivalent item proposed when this one is missing (<c>item_substitutes</c>).</summary>
|
||||
public sealed class ItemSubstitute : Entity<long>
|
||||
{
|
||||
/// <summary>The item.</summary>
|
||||
public long ItemId { get; set; }
|
||||
|
||||
/// <summary>The substitute (<c>items</c>).</summary>
|
||||
public long SubstituteId { get; set; }
|
||||
|
||||
/// <summary>Notes, such as the differences.</summary>
|
||||
public string? Notes { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>The code a customer or a supplier uses for one of our items (<c>party_item_codes</c>).</summary>
|
||||
public sealed class PartyItemCode : Entity<long>
|
||||
{
|
||||
/// <summary>The party.</summary>
|
||||
public long PartyId { get; set; }
|
||||
|
||||
/// <summary>The item.</summary>
|
||||
public long ItemId { get; set; }
|
||||
|
||||
/// <summary>The code of the party.</summary>
|
||||
public string Code { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>The description of the party.</summary>
|
||||
public string? Description { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
namespace Khaemhat.Core.Items;
|
||||
|
||||
/// <summary>How a price is rounded to a step.</summary>
|
||||
public enum RoundingDirection
|
||||
{
|
||||
/// <summary>To the nearest step, halves away from zero.</summary>
|
||||
Nearest = 0,
|
||||
|
||||
/// <summary>Up to the next step (per eccesso).</summary>
|
||||
Up = 1,
|
||||
|
||||
/// <summary>Down to the previous step (per difetto).</summary>
|
||||
Down = 2,
|
||||
}
|
||||
|
||||
/// <summary>The arithmetic of prices: percent changes and rounding to a step such as 0,10, 0,50 or 1,00.</summary>
|
||||
public static class PriceRounding
|
||||
{
|
||||
/// <summary>Rounds a price to a step; with no step, to the cent.</summary>
|
||||
/// <param name="value">The price.</param>
|
||||
/// <param name="step">The step, such as 0.10; zero or less means cents.</param>
|
||||
/// <param name="direction">Nearest, up or down.</param>
|
||||
/// <returns>The rounded price.</returns>
|
||||
public static decimal Round(decimal value, decimal step, RoundingDirection direction = RoundingDirection.Nearest)
|
||||
{
|
||||
if (step <= 0)
|
||||
{
|
||||
step = 0.01m;
|
||||
}
|
||||
|
||||
var units = value / step;
|
||||
units = direction switch
|
||||
{
|
||||
RoundingDirection.Up => decimal.Ceiling(Math.Round(units, 10)),
|
||||
RoundingDirection.Down => decimal.Floor(Math.Round(units, 10)),
|
||||
_ => Math.Round(units, MidpointRounding.AwayFromZero),
|
||||
};
|
||||
return Normalize(units * step);
|
||||
}
|
||||
|
||||
/// <summary>Applies a percent change: +10 adds a tenth, -5 takes off a twentieth.</summary>
|
||||
/// <param name="value">The price.</param>
|
||||
/// <param name="percent">The change in percent.</param>
|
||||
/// <returns>The changed price, not rounded.</returns>
|
||||
public static decimal Change(decimal value, decimal percent) => value * (1m + (percent / 100m));
|
||||
|
||||
/// <summary>The margin of a price over a cost, in percent of the price.</summary>
|
||||
/// <param name="price">The price.</param>
|
||||
/// <param name="cost">The cost.</param>
|
||||
/// <returns>The margin, or none without a positive price or a cost.</returns>
|
||||
public static decimal? Margin(decimal? price, decimal? cost) =>
|
||||
price is > 0 && cost is { } c ? Math.Round((price.Value - c) / price.Value * 100m, 1, MidpointRounding.AwayFromZero) : null;
|
||||
|
||||
// Four decimals at most, and two when the rest are zeros (12.3000 becomes 12.30).
|
||||
private static decimal Normalize(decimal value)
|
||||
{
|
||||
var rounded = Math.Round(value, 4, MidpointRounding.AwayFromZero);
|
||||
return rounded == Math.Round(rounded, 2) ? Math.Round(rounded, 2) : rounded;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,475 @@
|
||||
using Khaemhat.Core.Entities;
|
||||
|
||||
namespace Khaemhat.Core.Parties;
|
||||
|
||||
/// <summary>What a party is to the company (SPEC §11.2): the archive and the code mask follow from it.</summary>
|
||||
public enum PartyKind
|
||||
{
|
||||
/// <summary>A customer (it may also be a supplier).</summary>
|
||||
Customer = 0,
|
||||
|
||||
/// <summary>A supplier that is not a customer.</summary>
|
||||
Supplier = 1,
|
||||
|
||||
/// <summary>A qualified potential customer, without fiscal documents.</summary>
|
||||
Prospect = 2,
|
||||
|
||||
/// <summary>A commercial contact still to qualify (CRM).</summary>
|
||||
Lead = 3,
|
||||
}
|
||||
|
||||
/// <summary>The kind of subject: it decides the checks and the values proposed (SDI code, split payment, VAT number).</summary>
|
||||
public enum SubjectType
|
||||
{
|
||||
/// <summary>A domestic business.</summary>
|
||||
Company = 0,
|
||||
|
||||
/// <summary>A private person (consumer).</summary>
|
||||
Person = 1,
|
||||
|
||||
/// <summary>A public administration (split payment, office code of 6 characters).</summary>
|
||||
PublicAdministration = 2,
|
||||
|
||||
/// <summary>A business in another EU member state (VIES).</summary>
|
||||
EuCompany = 3,
|
||||
|
||||
/// <summary>A business outside the EU.</summary>
|
||||
NonEuCompany = 4,
|
||||
|
||||
/// <summary>A domestic business under the flat-rate scheme (no VAT charged, stamp duty).</summary>
|
||||
FlatRate = 5,
|
||||
}
|
||||
|
||||
/// <summary>The outcome of the last check of the VAT number on VIES, saved on the party.</summary>
|
||||
public enum VatCheckStatus
|
||||
{
|
||||
/// <summary>Not checked.</summary>
|
||||
None = 0,
|
||||
|
||||
/// <summary>Registered for intra-EU operations.</summary>
|
||||
Valid = 1,
|
||||
|
||||
/// <summary>Not registered.</summary>
|
||||
Invalid = 2,
|
||||
|
||||
/// <summary>The service could not answer; to repeat.</summary>
|
||||
Unavailable = 3,
|
||||
}
|
||||
|
||||
/// <summary>How the documents are sent to a customer.</summary>
|
||||
public enum DocumentDelivery
|
||||
{
|
||||
/// <summary>Not sent: printed or downloaded.</summary>
|
||||
None = 0,
|
||||
|
||||
/// <summary>By e-mail.</summary>
|
||||
Email = 1,
|
||||
|
||||
/// <summary>By certified e-mail (PEC).</summary>
|
||||
Pec = 2,
|
||||
}
|
||||
|
||||
/// <summary>What an address of a party is used for.</summary>
|
||||
public enum PartyAddressKind
|
||||
{
|
||||
/// <summary>Delivery address (destination of delivery notes).</summary>
|
||||
Delivery = 0,
|
||||
|
||||
/// <summary>Address for invoices, when different from the registered office.</summary>
|
||||
Billing = 1,
|
||||
|
||||
/// <summary>A building site or a branch.</summary>
|
||||
Site = 2,
|
||||
|
||||
/// <summary>Another address.</summary>
|
||||
Other = 3,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A party (SPEC §11.2, wiki <i>Anagrafiche</i>): customer, supplier, prospect or lead, registered once. The code follows
|
||||
/// the mask of its kind (ADR 0027); converting a lead or prospect into a customer gives it a customer code and keeps the
|
||||
/// old one in <see cref="PreviousCode"/>.
|
||||
/// </summary>
|
||||
public sealed class Party : Entity<long>, IDemoMarkable
|
||||
{
|
||||
/// <summary>The code, unique among the parties.</summary>
|
||||
public string Code { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>The code it had before a conversion.</summary>
|
||||
public string? PreviousCode { get; set; }
|
||||
|
||||
/// <summary>What the party is.</summary>
|
||||
public PartyKind Kind { get; set; }
|
||||
|
||||
/// <summary>A customer that also sells to the company.</summary>
|
||||
public bool IsAlsoSupplier { get; set; }
|
||||
|
||||
/// <summary>The kind of subject.</summary>
|
||||
public SubjectType SubjectType { get; set; }
|
||||
|
||||
/// <summary>The business name, or "last name first name" for a person.</summary>
|
||||
public string Name { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>The first name of a person.</summary>
|
||||
public string? FirstName { get; set; }
|
||||
|
||||
/// <summary>The last name of a person.</summary>
|
||||
public string? LastName { get; set; }
|
||||
|
||||
/// <summary>The name on fiscal documents, when different.</summary>
|
||||
public string? FiscalName { get; set; }
|
||||
|
||||
/// <summary>The VAT number, compact, without the country prefix.</summary>
|
||||
public string? VatNumber { get; set; }
|
||||
|
||||
/// <summary>The tax code.</summary>
|
||||
public string? TaxCode { get; set; }
|
||||
|
||||
/// <summary>The registration in the companies register (REA).</summary>
|
||||
public string? Rea { get; set; }
|
||||
|
||||
/// <summary>The category (<c>party_categories</c>).</summary>
|
||||
public long? CategoryId { get; set; }
|
||||
|
||||
/// <summary>Street of the registered office.</summary>
|
||||
public string? Address { get; set; }
|
||||
|
||||
/// <summary>Street number.</summary>
|
||||
public string? StreetNumber { get; set; }
|
||||
|
||||
/// <summary>Postal code.</summary>
|
||||
public string? PostalCode { get; set; }
|
||||
|
||||
/// <summary>Municipality or city.</summary>
|
||||
public string? City { get; set; }
|
||||
|
||||
/// <summary>Province abbreviation (or region abroad).</summary>
|
||||
public string? Province { get; set; }
|
||||
|
||||
/// <summary>Country (ISO 3166-1 alpha-2).</summary>
|
||||
public string CountryCode { get; set; } = "IT";
|
||||
|
||||
/// <summary>Phone.</summary>
|
||||
public string? Phone { get; set; }
|
||||
|
||||
/// <summary>E-mail.</summary>
|
||||
public string? Email { get; set; }
|
||||
|
||||
/// <summary>Certified e-mail (PEC).</summary>
|
||||
public string? Pec { get; set; }
|
||||
|
||||
/// <summary>Web site.</summary>
|
||||
public string? Website { get; set; }
|
||||
|
||||
/// <summary>The salesperson (<c>salespeople</c>).</summary>
|
||||
public long? SalespersonId { get; set; }
|
||||
|
||||
/// <summary>Language of the documents (ISO 639-1).</summary>
|
||||
public string Language { get; set; } = "it";
|
||||
|
||||
/// <summary>Currency of the documents (ISO 4217).</summary>
|
||||
public string CurrencyCode { get; set; } = "EUR";
|
||||
|
||||
/// <summary>Start of the relationship.</summary>
|
||||
public DateOnly? Since { get; set; }
|
||||
|
||||
/// <summary>Privacy notice accepted.</summary>
|
||||
public bool PrivacyAccepted { get; set; }
|
||||
|
||||
/// <summary>Consent to marketing.</summary>
|
||||
public bool Marketing { get; set; }
|
||||
|
||||
/// <summary>Notes.</summary>
|
||||
public string? Notes { get; set; }
|
||||
|
||||
/// <summary>Last VIES outcome.</summary>
|
||||
public VatCheckStatus VatCheck { get; set; }
|
||||
|
||||
/// <summary>When VIES answered (or failed), UTC.</summary>
|
||||
public DateTime? VatCheckedAt { get; set; }
|
||||
|
||||
/// <summary>The customer sub-account of the ledger, created at the first posting (M7).</summary>
|
||||
public string? CustomerAccountCode { get; set; }
|
||||
|
||||
/// <summary>The supplier sub-account of the ledger, created at the first posting (M7).</summary>
|
||||
public string? SupplierAccountCode { get; set; }
|
||||
|
||||
/// <summary>Hidden from new documents and default searches; kept with its documents.</summary>
|
||||
public bool Disabled { get; set; }
|
||||
|
||||
/// <inheritdoc />
|
||||
public bool IsDemo { get; set; }
|
||||
|
||||
/// <summary>Whether the party is a customer (also a supplier that is a customer).</summary>
|
||||
public bool IsCustomer => Kind == PartyKind.Customer;
|
||||
|
||||
/// <summary>Whether the party is a supplier, alone or also a customer.</summary>
|
||||
public bool IsSupplier => Kind == PartyKind.Supplier || (Kind == PartyKind.Customer && IsAlsoSupplier);
|
||||
}
|
||||
|
||||
/// <summary>An address of a party besides the registered office.</summary>
|
||||
public sealed class PartyAddress : Entity<long>
|
||||
{
|
||||
/// <summary>The party.</summary>
|
||||
public long PartyId { get; set; }
|
||||
|
||||
/// <summary>What it is used for.</summary>
|
||||
public PartyAddressKind Kind { get; set; }
|
||||
|
||||
/// <summary>The name shown on documents (site, branch).</summary>
|
||||
public string Name { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>Street.</summary>
|
||||
public string? Address { get; set; }
|
||||
|
||||
/// <summary>Street number.</summary>
|
||||
public string? StreetNumber { get; set; }
|
||||
|
||||
/// <summary>Postal code.</summary>
|
||||
public string? PostalCode { get; set; }
|
||||
|
||||
/// <summary>City.</summary>
|
||||
public string? City { get; set; }
|
||||
|
||||
/// <summary>Province.</summary>
|
||||
public string? Province { get; set; }
|
||||
|
||||
/// <summary>Country (ISO 3166-1 alpha-2).</summary>
|
||||
public string CountryCode { get; set; } = "IT";
|
||||
|
||||
/// <summary>The address proposed first for its kind.</summary>
|
||||
public bool IsDefault { get; set; }
|
||||
|
||||
/// <summary>Notes (opening hours, how to reach it).</summary>
|
||||
public string? Notes { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>A contact person of a party.</summary>
|
||||
public sealed class PartyContact : Entity<long>
|
||||
{
|
||||
/// <summary>The party.</summary>
|
||||
public long PartyId { get; set; }
|
||||
|
||||
/// <summary>Name and surname.</summary>
|
||||
public string Name { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>Role (purchasing, administration...).</summary>
|
||||
public string? Role { get; set; }
|
||||
|
||||
/// <summary>Phone.</summary>
|
||||
public string? Phone { get; set; }
|
||||
|
||||
/// <summary>Mobile phone.</summary>
|
||||
public string? Mobile { get; set; }
|
||||
|
||||
/// <summary>E-mail.</summary>
|
||||
public string? Email { get; set; }
|
||||
|
||||
/// <summary>The main contact.</summary>
|
||||
public bool IsDefault { get; set; }
|
||||
|
||||
/// <summary>Notes.</summary>
|
||||
public string? Notes { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>A bank account of a party: the bank of its RiBa, or where the company pays it.</summary>
|
||||
public sealed class PartyBankAccount : Entity<long>
|
||||
{
|
||||
/// <summary>The party.</summary>
|
||||
public long PartyId { get; set; }
|
||||
|
||||
/// <summary>The IBAN, compact.</summary>
|
||||
public string Iban { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>The BIC.</summary>
|
||||
public string? Bic { get; set; }
|
||||
|
||||
/// <summary>The bank.</summary>
|
||||
public string? BankName { get; set; }
|
||||
|
||||
/// <summary>The national bank code (ABI), read from the IBAN.</summary>
|
||||
public string? BankCode { get; set; }
|
||||
|
||||
/// <summary>The branch code (CAB), read from the IBAN.</summary>
|
||||
public string? BranchCode { get; set; }
|
||||
|
||||
/// <summary>The account proposed on documents.</summary>
|
||||
public bool IsDefault { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>The sales terms of a customer, proposed on its documents (M5).</summary>
|
||||
public sealed class PartySalesTerms : Entity<long>
|
||||
{
|
||||
/// <summary>The party (one row per party).</summary>
|
||||
public long PartyId { get; set; }
|
||||
|
||||
/// <summary>The price list (<c>price_lists</c>).</summary>
|
||||
public long? PriceListId { get; set; }
|
||||
|
||||
/// <summary>First discount, percent.</summary>
|
||||
public decimal? Discount1 { get; set; }
|
||||
|
||||
/// <summary>Second discount, percent.</summary>
|
||||
public decimal? Discount2 { get; set; }
|
||||
|
||||
/// <summary>The payment terms (<c>payment_terms</c>).</summary>
|
||||
public long? PaymentTermId { get; set; }
|
||||
|
||||
/// <summary>The account of the company where the customer pays (<c>bank_accounts</c>).</summary>
|
||||
public long? CompanyBankAccountId { get; set; }
|
||||
|
||||
/// <summary>The carrier (<c>carriers</c>).</summary>
|
||||
public long? CarrierId { get; set; }
|
||||
|
||||
/// <summary>The shipping terms (<c>shipping_terms</c>).</summary>
|
||||
public long? ShippingTermId { get; set; }
|
||||
|
||||
/// <summary>The warehouse goods leave from (<c>warehouses</c>).</summary>
|
||||
public long? WarehouseId { get; set; }
|
||||
|
||||
/// <summary>The credit limit: the most the customer may owe.</summary>
|
||||
public decimal? CreditLimit { get; set; }
|
||||
|
||||
/// <summary>Orders and deliveries are blocked.</summary>
|
||||
public bool Blocked { get; set; }
|
||||
|
||||
/// <summary>Delivery notes are grouped into one deferred invoice.</summary>
|
||||
public bool GroupDeliveryNotes { get; set; } = true;
|
||||
|
||||
/// <summary>The day of the month the deferred invoices are issued, if fixed.</summary>
|
||||
public int? InvoiceDay { get; set; }
|
||||
|
||||
/// <summary>How the documents are sent.</summary>
|
||||
public DocumentDelivery SendDocuments { get; set; }
|
||||
|
||||
/// <summary>Where the documents are sent, when not the main e-mail or PEC.</summary>
|
||||
public string? DocumentsEmail { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>The purchase terms of a supplier, proposed on its orders (M6).</summary>
|
||||
public sealed class PartyPurchaseTerms : Entity<long>
|
||||
{
|
||||
/// <summary>The party (one row per party).</summary>
|
||||
public long PartyId { get; set; }
|
||||
|
||||
/// <summary>The payment terms (<c>payment_terms</c>).</summary>
|
||||
public long? PaymentTermId { get; set; }
|
||||
|
||||
/// <summary>Days between order and delivery.</summary>
|
||||
public int? LeadTimeDays { get; set; }
|
||||
|
||||
/// <summary>The smallest order accepted.</summary>
|
||||
public decimal? MinimumOrder { get; set; }
|
||||
|
||||
/// <summary>Discount, percent.</summary>
|
||||
public decimal? Discount { get; set; }
|
||||
|
||||
/// <summary>The shipping terms (<c>shipping_terms</c>).</summary>
|
||||
public long? ShippingTermId { get; set; }
|
||||
|
||||
/// <summary>The VAT register of the purchases (M7).</summary>
|
||||
public string? VatRegisterCode { get; set; }
|
||||
|
||||
/// <summary>The cost account proposed (M7).</summary>
|
||||
public string? CostAccountCode { get; set; }
|
||||
|
||||
/// <summary>The e-mail for the orders.</summary>
|
||||
public string? OrdersEmail { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The fiscal data of a party (mockup 015, 016): e-invoicing, VAT regime, withholding and contributions, the declaration
|
||||
/// of intent of a habitual exporter and the identifiers.
|
||||
/// </summary>
|
||||
public sealed class PartyFiscal : Entity<long>
|
||||
{
|
||||
/// <summary>The party (one row per party).</summary>
|
||||
public long PartyId { get; set; }
|
||||
|
||||
/// <summary>The SDI recipient code (7 characters, 6 for a public administration).</summary>
|
||||
public string? RecipientCode { get; set; }
|
||||
|
||||
/// <summary>The PEC the e-invoices go to, without a recipient code.</summary>
|
||||
public string? RecipientPec { get; set; }
|
||||
|
||||
/// <summary>The reference of the administration (public administrations).</summary>
|
||||
public string? AdministrationReference { get; set; }
|
||||
|
||||
/// <summary>A courtesy PDF goes with the e-invoice.</summary>
|
||||
public bool AttachPdf { get; set; } = true;
|
||||
|
||||
/// <summary>A copy is sent by e-mail when the invoice is issued.</summary>
|
||||
public bool SendCopy { get; set; }
|
||||
|
||||
/// <summary>Split payment (art. 17-ter DPR 633/72).</summary>
|
||||
public bool SplitPayment { get; set; }
|
||||
|
||||
/// <summary>Reverse charge by default.</summary>
|
||||
public bool ReverseCharge { get; set; }
|
||||
|
||||
/// <summary>The VAT code proposed (<c>tax_codes</c>).</summary>
|
||||
public long? TaxCodeId { get; set; }
|
||||
|
||||
/// <summary>VAT exigibility: <c>I</c> immediate, <c>D</c> deferred, <c>S</c> split payment.</summary>
|
||||
public string? Exigibility { get; set; }
|
||||
|
||||
/// <summary>The stamp duty is charged to the customer.</summary>
|
||||
public bool StampDutyCharged { get; set; } = true;
|
||||
|
||||
/// <summary>Subject to withholding tax (professionals).</summary>
|
||||
public bool Withholding { get; set; }
|
||||
|
||||
/// <summary>Withholding rate, percent.</summary>
|
||||
public decimal? WithholdingRate { get; set; }
|
||||
|
||||
/// <summary>Withholding reason of the e-invoice (A, M, Q...).</summary>
|
||||
public string? WithholdingReason { get; set; }
|
||||
|
||||
/// <summary>Pension fund of the e-invoice (TC01-TC22).</summary>
|
||||
public string? PensionFund { get; set; }
|
||||
|
||||
/// <summary>Pension fund rate, percent.</summary>
|
||||
public decimal? PensionFundRate { get; set; }
|
||||
|
||||
/// <summary>Agent subject to ENASARCO.</summary>
|
||||
public bool Enasarco { get; set; }
|
||||
|
||||
/// <summary>Declaration of intent active.</summary>
|
||||
public bool IntentActive { get; set; }
|
||||
|
||||
/// <summary>Number of the declaration.</summary>
|
||||
public string? IntentNumber { get; set; }
|
||||
|
||||
/// <summary>Date of the declaration.</summary>
|
||||
public DateOnly? IntentDate { get; set; }
|
||||
|
||||
/// <summary>Protocol of the revenue agency.</summary>
|
||||
public string? IntentProtocol { get; set; }
|
||||
|
||||
/// <summary>The non-taxable VAT code used under the declaration (<c>tax_codes</c>, nature N3.5).</summary>
|
||||
public long? IntentTaxCodeId { get; set; }
|
||||
|
||||
/// <summary>The ceiling of the declaration.</summary>
|
||||
public decimal? IntentCeiling { get; set; }
|
||||
|
||||
/// <summary>The amount already invoiced under the declaration (updated by the invoices, M5).</summary>
|
||||
public decimal IntentUsed { get; set; }
|
||||
|
||||
/// <summary>The declaration is valid from.</summary>
|
||||
public DateOnly? IntentFrom { get; set; }
|
||||
|
||||
/// <summary>The declaration is valid until.</summary>
|
||||
public DateOnly? IntentTo { get; set; }
|
||||
|
||||
/// <summary>Global location number.</summary>
|
||||
public string? Gln { get; set; }
|
||||
|
||||
/// <summary>Economic operators registration and identification number (customs).</summary>
|
||||
public string? Eori { get; set; }
|
||||
|
||||
/// <summary>The code of the company at the party.</summary>
|
||||
public string? OurCode { get; set; }
|
||||
|
||||
/// <summary>What remains of the ceiling of the declaration.</summary>
|
||||
public decimal? IntentRemaining => IntentCeiling is { } ceiling ? ceiling - IntentUsed : null;
|
||||
}
|
||||
@@ -0,0 +1,472 @@
|
||||
using Khaemhat.Core.Entities;
|
||||
using Khaemhat.Core.Tax;
|
||||
|
||||
namespace Khaemhat.Core.Tables;
|
||||
|
||||
/// <summary>A row of a company table with a code the users type and a description (SPEC §11.1).</summary>
|
||||
public interface ICodedRecord : IEntity<long>
|
||||
{
|
||||
/// <summary>The code, unique in the table.</summary>
|
||||
string Code { get; set; }
|
||||
|
||||
/// <summary>The description (or the name).</summary>
|
||||
string Description { get; set; }
|
||||
|
||||
/// <summary>Hidden from choices on new records; kept for old ones.</summary>
|
||||
bool Disabled { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>Base class of the coded tables.</summary>
|
||||
public abstract class CodedEntity : Entity<long>, ICodedRecord, IDemoMarkable
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public string Code { get; set; } = string.Empty;
|
||||
|
||||
/// <inheritdoc />
|
||||
public string Description { get; set; } = string.Empty;
|
||||
|
||||
/// <inheritdoc />
|
||||
public bool Disabled { get; set; }
|
||||
|
||||
/// <inheritdoc />
|
||||
public bool IsDemo { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>A country (ISO 3166-1).</summary>
|
||||
public sealed class Country : CodedEntity
|
||||
{
|
||||
/// <summary>ISO 3166-1 alpha-3 code.</summary>
|
||||
public string? Iso3 { get; set; }
|
||||
|
||||
/// <summary>Member of the European Union (VIES, Intrastat, intra-EU VAT).</summary>
|
||||
public bool EuMember { get; set; }
|
||||
|
||||
/// <summary>The prefix of VAT numbers, when different from the code (Greece: <c>EL</c>).</summary>
|
||||
public string? VatPrefix { get; set; }
|
||||
|
||||
/// <summary>The usual currency (ISO 4217).</summary>
|
||||
public string? CurrencyCode { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>An Italian province (code = the two-letter abbreviation).</summary>
|
||||
public sealed class Province : CodedEntity
|
||||
{
|
||||
/// <summary>The region.</summary>
|
||||
public string? Region { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>An Italian municipality (code = cadastral code, used by the fiscal code).</summary>
|
||||
public sealed class Municipality : CodedEntity
|
||||
{
|
||||
/// <summary>The province abbreviation.</summary>
|
||||
public string ProvinceCode { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>The region.</summary>
|
||||
public string? Region { get; set; }
|
||||
|
||||
/// <summary>The ISTAT code (6 digits).</summary>
|
||||
public string? IstatCode { get; set; }
|
||||
|
||||
/// <summary>The postal codes, comma separated (one for most municipalities, a range for large cities).</summary>
|
||||
public string? PostalCodes { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>A currency (ISO 4217).</summary>
|
||||
public sealed class Currency : CodedEntity
|
||||
{
|
||||
/// <summary>The symbol, such as €.</summary>
|
||||
public string? Symbol { get; set; }
|
||||
|
||||
/// <summary>Decimals of amounts.</summary>
|
||||
public int Decimals { get; set; } = 2;
|
||||
}
|
||||
|
||||
/// <summary>An exchange rate: units of the currency for one euro on a day (ECB reference rate or manual).</summary>
|
||||
public sealed class ExchangeRate : Entity<long>
|
||||
{
|
||||
/// <summary>The currency (ISO 4217).</summary>
|
||||
public string CurrencyCode { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>The day.</summary>
|
||||
public DateOnly RateDate { get; set; }
|
||||
|
||||
/// <summary>Units of the currency for one euro.</summary>
|
||||
public decimal Rate { get; set; }
|
||||
|
||||
/// <summary>Where the rate comes from: <c>ECB</c> or <c>MANUAL</c>.</summary>
|
||||
public string Source { get; set; } = "MANUAL";
|
||||
}
|
||||
|
||||
/// <summary>A unit of measure.</summary>
|
||||
public sealed class UnitOfMeasure : CodedEntity
|
||||
{
|
||||
/// <summary>Decimals allowed in quantities.</summary>
|
||||
public int Decimals { get; set; }
|
||||
|
||||
/// <summary>The text written in <c>UnitaMisura</c> of the e-invoice, when different from the code.</summary>
|
||||
public string? EInvoiceCode { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>A VAT code (mockup 076).</summary>
|
||||
public sealed class TaxCode : CodedEntity
|
||||
{
|
||||
/// <summary>The rate in percent.</summary>
|
||||
public decimal Rate { get; set; }
|
||||
|
||||
/// <summary>The nature for zero-rate operations (N1...N7).</summary>
|
||||
public string? Nature { get; set; }
|
||||
|
||||
/// <summary>The kind of operation, from rate and nature.</summary>
|
||||
public TaxCodeKind Kind { get; set; }
|
||||
|
||||
/// <summary>When the tax becomes due.</summary>
|
||||
public TaxExigibility Exigibility { get; set; }
|
||||
|
||||
/// <summary>Share of the purchase tax that cannot be deducted.</summary>
|
||||
public decimal NonDeductiblePercent { get; set; }
|
||||
|
||||
/// <summary>The law printed on the invoice.</summary>
|
||||
public string? LegalReference { get; set; }
|
||||
|
||||
/// <summary>First day of validity.</summary>
|
||||
public DateOnly? ValidFrom { get; set; }
|
||||
|
||||
/// <summary>Last day of validity.</summary>
|
||||
public DateOnly? ValidTo { get; set; }
|
||||
|
||||
/// <summary>The VAT account for sales (ledger, M7).</summary>
|
||||
public string? SalesAccountCode { get; set; }
|
||||
|
||||
/// <summary>The VAT account for purchases (ledger, M7).</summary>
|
||||
public string? PurchaseAccountCode { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>A payment method (MP01...MP23).</summary>
|
||||
public sealed class PaymentMethod : CodedEntity
|
||||
{
|
||||
/// <summary>The FatturaPA code, such as <c>MP05</c>.</summary>
|
||||
public string EInvoiceCode { get; set; } = "MP05";
|
||||
|
||||
/// <summary>Whether a bank of the customer (RiBa, direct debit) or of the company (transfer) is needed.</summary>
|
||||
public bool NeedsBank { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>Payment terms with their installments (lines).</summary>
|
||||
public sealed class PaymentTerm : CodedEntity
|
||||
{
|
||||
/// <summary>The payment method.</summary>
|
||||
public long? PaymentMethodId { get; set; }
|
||||
|
||||
/// <summary>The FatturaPA condition: TP01 installments, TP02 full, TP03 advance.</summary>
|
||||
public string Condition { get; set; } = "TP02";
|
||||
|
||||
/// <summary>All the VAT on the first installment.</summary>
|
||||
public bool VatOnFirstInstallment { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>An installment of payment terms.</summary>
|
||||
public sealed class PaymentTermLine : Entity<long>
|
||||
{
|
||||
/// <summary>The payment terms.</summary>
|
||||
public long PaymentTermId { get; set; }
|
||||
|
||||
/// <summary>The order of the installment, from 1.</summary>
|
||||
public int Number { get; set; }
|
||||
|
||||
/// <summary>Days from the document date.</summary>
|
||||
public int Days { get; set; }
|
||||
|
||||
/// <summary>Move the due date to the end of the month.</summary>
|
||||
public bool EndOfMonth { get; set; }
|
||||
|
||||
/// <summary>A fixed day of the month after the end-of-month move, such as 10.</summary>
|
||||
public int? FixedDay { get; set; }
|
||||
|
||||
/// <summary>Share of the amount, in percent.</summary>
|
||||
public decimal Percent { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>A bank account of the company.</summary>
|
||||
public sealed class BankAccount : CodedEntity
|
||||
{
|
||||
/// <summary>The bank.</summary>
|
||||
public string? BankName { get; set; }
|
||||
|
||||
/// <summary>The IBAN, compact.</summary>
|
||||
public string? Iban { get; set; }
|
||||
|
||||
/// <summary>The BIC.</summary>
|
||||
public string? Bic { get; set; }
|
||||
|
||||
/// <summary>The SIA code for RiBa files.</summary>
|
||||
public string? SiaCode { get; set; }
|
||||
|
||||
/// <summary>The CBI CUC code.</summary>
|
||||
public string? CucCode { get; set; }
|
||||
|
||||
/// <summary>The ledger account (M7).</summary>
|
||||
public string? AccountCode { get; set; }
|
||||
|
||||
/// <summary>The account proposed on documents.</summary>
|
||||
public bool IsDefault { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>A sales agent (code + name in <see cref="CodedEntity.Description"/>).</summary>
|
||||
public sealed class Salesperson : CodedEntity
|
||||
{
|
||||
/// <summary>The e-mail address.</summary>
|
||||
public string? Email { get; set; }
|
||||
|
||||
/// <summary>The phone.</summary>
|
||||
public string? Phone { get; set; }
|
||||
|
||||
/// <summary>The usual commission, in percent.</summary>
|
||||
public decimal CommissionPercent { get; set; }
|
||||
|
||||
/// <summary>Subject to ENASARCO contributions.</summary>
|
||||
public bool Enasarco { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>A carrier (code + name).</summary>
|
||||
public sealed class Carrier : CodedEntity
|
||||
{
|
||||
/// <summary>The VAT number.</summary>
|
||||
public string? VatNumber { get; set; }
|
||||
|
||||
/// <summary>The address.</summary>
|
||||
public string? Address { get; set; }
|
||||
|
||||
/// <summary>The town.</summary>
|
||||
public string? City { get; set; }
|
||||
|
||||
/// <summary>The phone.</summary>
|
||||
public string? Phone { get; set; }
|
||||
|
||||
/// <summary>The e-mail address.</summary>
|
||||
public string? Email { get; set; }
|
||||
|
||||
/// <summary>The registration number in the haulage register.</summary>
|
||||
public string? RegisterNumber { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>Who pays the transport (porto: franco, assegnato...).</summary>
|
||||
public sealed class ShippingTerm : CodedEntity;
|
||||
|
||||
/// <summary>Who carries the goods (mittente, destinatario, vettore).</summary>
|
||||
public sealed class TransportMean : CodedEntity;
|
||||
|
||||
/// <summary>The appearance of the goods on the delivery note (cartoni, bancali...).</summary>
|
||||
public sealed class GoodsAppearance : CodedEntity;
|
||||
|
||||
/// <summary>An Incoterms rule.</summary>
|
||||
public sealed class DeliveryTerm : CodedEntity;
|
||||
|
||||
/// <summary>The reason of the transport (vendita, conto visione...).</summary>
|
||||
public sealed class TransportReason : CodedEntity;
|
||||
|
||||
/// <summary>What a stock movement does to the quantity on hand.</summary>
|
||||
public enum StockEffect
|
||||
{
|
||||
/// <summary>No effect on quantities.</summary>
|
||||
None = 0,
|
||||
|
||||
/// <summary>Increases the stock (load).</summary>
|
||||
Load = 1,
|
||||
|
||||
/// <summary>Decreases the stock (unload).</summary>
|
||||
Unload = 2,
|
||||
}
|
||||
|
||||
/// <summary>A warehouse movement reason.</summary>
|
||||
public sealed class InventoryReason : CodedEntity
|
||||
{
|
||||
/// <summary>The effect on the quantity.</summary>
|
||||
public StockEffect Effect { get; set; }
|
||||
|
||||
/// <summary>Whether it changes the stock value (purchases, sales) or only quantities (transfers).</summary>
|
||||
public bool AffectsValue { get; set; } = true;
|
||||
|
||||
/// <summary>Whether it is a transfer between warehouses (needs a destination).</summary>
|
||||
public bool IsTransfer { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>A warehouse.</summary>
|
||||
public sealed class Warehouse : CodedEntity
|
||||
{
|
||||
/// <summary>The address.</summary>
|
||||
public string? Address { get; set; }
|
||||
|
||||
/// <summary>The town.</summary>
|
||||
public string? City { get; set; }
|
||||
|
||||
/// <summary>The province abbreviation.</summary>
|
||||
public string? ProvinceCode { get; set; }
|
||||
|
||||
/// <summary>The warehouse proposed on documents.</summary>
|
||||
public bool IsDefault { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>A category of items, on up to three levels.</summary>
|
||||
public sealed class ItemCategory : CodedEntity
|
||||
{
|
||||
/// <summary>The parent category.</summary>
|
||||
public long? ParentId { get; set; }
|
||||
|
||||
/// <summary>The level, 1 to 3.</summary>
|
||||
public int Level { get; set; } = 1;
|
||||
}
|
||||
|
||||
/// <summary>A category of customers and suppliers.</summary>
|
||||
public sealed class PartyCategory : CodedEntity;
|
||||
|
||||
/// <summary>A price list (the prices are in <c>item_prices</c>, mockup 018).</summary>
|
||||
public sealed class PriceList : CodedEntity
|
||||
{
|
||||
/// <summary>The currency (ISO 4217).</summary>
|
||||
public string CurrencyCode { get; set; } = "EUR";
|
||||
|
||||
/// <summary>Prices include VAT (retail).</summary>
|
||||
public bool VatIncluded { get; set; }
|
||||
|
||||
/// <summary>First day of validity.</summary>
|
||||
public DateOnly? ValidFrom { get; set; }
|
||||
|
||||
/// <summary>Last day of validity.</summary>
|
||||
public DateOnly? ValidTo { get; set; }
|
||||
|
||||
/// <summary>The list this one derives from.</summary>
|
||||
public long? BasePriceListId { get; set; }
|
||||
|
||||
/// <summary>Change applied to the base list, in percent (negative for a discount).</summary>
|
||||
public decimal MarkupPercent { get; set; }
|
||||
|
||||
/// <summary>Rounding step of derived prices, such as 0.05; zero for none.</summary>
|
||||
public decimal RoundingStep { get; set; }
|
||||
|
||||
/// <summary>The base price list of the company: the third step of the price search (SPEC §11.3, ADR 0030).</summary>
|
||||
public bool IsBase { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>A discount policy: a chain of discounts such as <c>10+5</c>.</summary>
|
||||
public sealed class DiscountPolicy : CodedEntity
|
||||
{
|
||||
/// <summary>The chain of discounts in percent, separated by +.</summary>
|
||||
public string Formula { get; set; } = string.Empty;
|
||||
}
|
||||
|
||||
/// <summary>The family of a document numerator.</summary>
|
||||
public enum NumeratorKind
|
||||
{
|
||||
/// <summary>Quotations.</summary>
|
||||
Quotation = 0,
|
||||
|
||||
/// <summary>Customer orders.</summary>
|
||||
SalesOrder = 1,
|
||||
|
||||
/// <summary>Delivery notes.</summary>
|
||||
DeliveryNote = 2,
|
||||
|
||||
/// <summary>Sales invoices and credit notes (no gaps).</summary>
|
||||
SalesInvoice = 3,
|
||||
|
||||
/// <summary>Supplier orders.</summary>
|
||||
PurchaseOrder = 4,
|
||||
|
||||
/// <summary>Purchase protocol.</summary>
|
||||
PurchaseInvoice = 5,
|
||||
|
||||
/// <summary>Warehouse movements.</summary>
|
||||
Inventory = 6,
|
||||
|
||||
/// <summary>Journal entries (no gaps).</summary>
|
||||
Journal = 7,
|
||||
|
||||
/// <summary>Anything else.</summary>
|
||||
Other = 8,
|
||||
}
|
||||
|
||||
/// <summary>A document numerator for a year (assignment at confirmation arrives with the documents, M5).</summary>
|
||||
public sealed class DocumentNumerator : CodedEntity
|
||||
{
|
||||
/// <summary>The family.</summary>
|
||||
public NumeratorKind Kind { get; set; }
|
||||
|
||||
/// <summary>The section (sezionale), such as <c>A</c>; empty for the main one.</summary>
|
||||
public string? Section { get; set; }
|
||||
|
||||
/// <summary>The year.</summary>
|
||||
public int Year { get; set; }
|
||||
|
||||
/// <summary>The prefix.</summary>
|
||||
public string? Prefix { get; set; }
|
||||
|
||||
/// <summary>The format, such as <c>{prefix}/{year}/{number:D6}</c>.</summary>
|
||||
public string Format { get; set; } = "{number}/{year}";
|
||||
|
||||
/// <summary>The last number assigned.</summary>
|
||||
public long LastNumber { get; set; }
|
||||
|
||||
/// <summary>Whether gaps are allowed (never for invoices, credit notes and final entries).</summary>
|
||||
public bool GapsAllowed { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>A type of document: the links between a document and its numerator, warehouse reason and SDI type.</summary>
|
||||
public sealed class DocumentType : CodedEntity
|
||||
{
|
||||
/// <summary>The family of document.</summary>
|
||||
public NumeratorKind Kind { get; set; }
|
||||
|
||||
/// <summary>The numerator.</summary>
|
||||
public long? NumeratorId { get; set; }
|
||||
|
||||
/// <summary>The warehouse reason.</summary>
|
||||
public long? InventoryReasonId { get; set; }
|
||||
|
||||
/// <summary>The SDI document type (TD01...).</summary>
|
||||
public string? EInvoiceType { get; set; }
|
||||
|
||||
/// <summary>The journal template (ledger, M7).</summary>
|
||||
public string? JournalTemplateCode { get; set; }
|
||||
|
||||
/// <summary>The VAT register (ledger, M7).</summary>
|
||||
public string? VatRegisterCode { get; set; }
|
||||
|
||||
/// <summary>The print template.</summary>
|
||||
public string? PrintTemplate { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>A cost centre.</summary>
|
||||
public sealed class CostCenter : CodedEntity
|
||||
{
|
||||
/// <summary>The parent cost centre.</summary>
|
||||
public long? ParentId { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>The state of a job.</summary>
|
||||
public enum JobStatus
|
||||
{
|
||||
/// <summary>Open.</summary>
|
||||
Open = 0,
|
||||
|
||||
/// <summary>Suspended.</summary>
|
||||
Suspended = 1,
|
||||
|
||||
/// <summary>Closed.</summary>
|
||||
Closed = 2,
|
||||
}
|
||||
|
||||
/// <summary>A job (commessa).</summary>
|
||||
public sealed class Job : CodedEntity
|
||||
{
|
||||
/// <summary>The customer, when the job is for one.</summary>
|
||||
public long? PartyId { get; set; }
|
||||
|
||||
/// <summary>The start.</summary>
|
||||
public DateOnly? StartDate { get; set; }
|
||||
|
||||
/// <summary>The end.</summary>
|
||||
public DateOnly? EndDate { get; set; }
|
||||
|
||||
/// <summary>The state.</summary>
|
||||
public JobStatus Status { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,268 @@
|
||||
using System.Globalization;
|
||||
using System.Text;
|
||||
using Khaemhat.Core.Entities;
|
||||
|
||||
namespace Khaemhat.Core.Tables;
|
||||
|
||||
/// <summary>
|
||||
/// The last number given by an automatic code sequence (<c>code_sequences</c>, SPEC §11.12). One row per rule and,
|
||||
/// when the mask asks for it, per year and per category: the key is <c>items:VALV</c> or <c>leads:2026</c>.
|
||||
/// </summary>
|
||||
public sealed class CodeSequence : Entity<long>
|
||||
{
|
||||
/// <summary>The key of the sequence, see <see cref="CodeMask.SequenceKey"/>.</summary>
|
||||
public string Key { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>The last number given; the next code uses this plus one.</summary>
|
||||
public long LastValue { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A mask of automatic codes (SPEC §11.12, mockup 074), such as <c>C{seq:000000}</c> or <c>{categoria}-{seq:0000}</c>:
|
||||
/// letters, digits and <c>- _ / .</c> written as they are, plus the placeholders <c>{seq:000}</c> (the progressive
|
||||
/// number with as many digits as zeros; <c>{seq}</c> without zeros in front), <c>{anno}</c> (the year, four digits; also
|
||||
/// <c>{year}</c>) and <c>{categoria}</c> (the code of the category; also <c>{category}</c>). The number restarts every
|
||||
/// year when the mask has the year, and runs separately per category when it has the category.
|
||||
/// </summary>
|
||||
public sealed record CodeMask
|
||||
{
|
||||
/// <summary>Error: the mask needs exactly one <c>{seq}</c>.</summary>
|
||||
public const string SequenceRequired = "codes.mask.sequence";
|
||||
|
||||
/// <summary>Error: a placeholder is not known.</summary>
|
||||
public const string UnknownPlaceholder = "codes.mask.placeholder";
|
||||
|
||||
/// <summary>Error: the mask has characters not allowed in a code.</summary>
|
||||
public const string InvalidCharacter = "codes.mask.character";
|
||||
|
||||
/// <summary>Error: the codes of the mask are longer than the code column.</summary>
|
||||
public const string TooLong = "codes.mask.too-long";
|
||||
|
||||
/// <summary>Error: the mask uses the category for a table without categories.</summary>
|
||||
public const string CategoryNotAllowed = "codes.mask.category";
|
||||
|
||||
private const string AllowedLiterals = "-_/.";
|
||||
|
||||
private readonly IReadOnlyList<Part> _parts;
|
||||
|
||||
private CodeMask(string text, IReadOnlyList<Part> parts)
|
||||
{
|
||||
Text = text;
|
||||
_parts = parts;
|
||||
Digits = parts.First(p => p.Kind == PartKind.Sequence).Digits;
|
||||
UsesYear = parts.Any(p => p.Kind == PartKind.Year);
|
||||
UsesCategory = parts.Any(p => p.Kind == PartKind.Category);
|
||||
FixedLength = parts.Sum(p => p.Kind switch
|
||||
{
|
||||
PartKind.Literal => p.Text.Length,
|
||||
PartKind.Year => 4,
|
||||
PartKind.Sequence => Math.Max(1, p.Digits),
|
||||
_ => 0,
|
||||
});
|
||||
}
|
||||
|
||||
private enum PartKind
|
||||
{
|
||||
Literal,
|
||||
Sequence,
|
||||
Year,
|
||||
Category,
|
||||
}
|
||||
|
||||
/// <summary>The mask, with the written characters in upper case.</summary>
|
||||
public string Text { get; }
|
||||
|
||||
/// <summary>The digits of the number (0: as many as needed).</summary>
|
||||
public int Digits { get; }
|
||||
|
||||
/// <summary>Whether the number restarts every year.</summary>
|
||||
public bool UsesYear { get; }
|
||||
|
||||
/// <summary>Whether the code contains the category and the number runs per category.</summary>
|
||||
public bool UsesCategory { get; }
|
||||
|
||||
/// <summary>The length of a code without the category, with the number at its minimum width.</summary>
|
||||
public int FixedLength { get; }
|
||||
|
||||
/// <summary>Reads a mask.</summary>
|
||||
/// <param name="text">The mask as typed.</param>
|
||||
/// <param name="mask">The mask, when valid.</param>
|
||||
/// <param name="error">The error code, when not.</param>
|
||||
/// <returns><see langword="true"/> when valid.</returns>
|
||||
public static bool TryParse(string? text, out CodeMask? mask, out string? error)
|
||||
{
|
||||
mask = null;
|
||||
error = null;
|
||||
var value = text?.Trim() ?? string.Empty;
|
||||
var parts = new List<Part>();
|
||||
var literal = new StringBuilder();
|
||||
var i = 0;
|
||||
while (i < value.Length)
|
||||
{
|
||||
var c = value[i];
|
||||
if (c == '{')
|
||||
{
|
||||
var end = value.IndexOf('}', i);
|
||||
if (end < 0)
|
||||
{
|
||||
error = UnknownPlaceholder;
|
||||
return false;
|
||||
}
|
||||
|
||||
if (literal.Length > 0)
|
||||
{
|
||||
parts.Add(new Part(PartKind.Literal, literal.ToString(), 0));
|
||||
literal.Clear();
|
||||
}
|
||||
|
||||
if (!TryReadPlaceholder(value[(i + 1)..end], out var part))
|
||||
{
|
||||
error = UnknownPlaceholder;
|
||||
return false;
|
||||
}
|
||||
|
||||
parts.Add(part);
|
||||
i = end + 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
var upper = char.ToUpperInvariant(c);
|
||||
if (!(upper is >= 'A' and <= 'Z' or >= '0' and <= '9') && !AllowedLiterals.Contains(upper, StringComparison.Ordinal))
|
||||
{
|
||||
error = InvalidCharacter;
|
||||
return false;
|
||||
}
|
||||
|
||||
literal.Append(upper);
|
||||
i++;
|
||||
}
|
||||
|
||||
if (literal.Length > 0)
|
||||
{
|
||||
parts.Add(new Part(PartKind.Literal, literal.ToString(), 0));
|
||||
}
|
||||
|
||||
if (parts.Count(p => p.Kind == PartKind.Sequence) != 1)
|
||||
{
|
||||
error = SequenceRequired;
|
||||
return false;
|
||||
}
|
||||
|
||||
mask = new CodeMask(string.Concat(parts.Select(p => p.ToMask())), parts);
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>Reads a mask that is known to be valid.</summary>
|
||||
/// <param name="text">The mask.</param>
|
||||
/// <returns>The mask.</returns>
|
||||
/// <exception cref="FormatException">The mask is not valid.</exception>
|
||||
public static CodeMask Parse(string text) =>
|
||||
TryParse(text, out var mask, out var error) ? mask! : throw new FormatException(error);
|
||||
|
||||
/// <summary>The checks of a mask for a table.</summary>
|
||||
/// <param name="text">The mask as typed.</param>
|
||||
/// <param name="maxLength">The longest code the table accepts.</param>
|
||||
/// <param name="categoriesAllowed">Whether the table has categories.</param>
|
||||
/// <returns>The error code, or <see langword="null"/> when the mask can be used.</returns>
|
||||
public static string? Check(string? text, int maxLength, bool categoriesAllowed)
|
||||
{
|
||||
if (!TryParse(text, out var mask, out var error))
|
||||
{
|
||||
return error;
|
||||
}
|
||||
|
||||
if (mask!.UsesCategory && !categoriesAllowed)
|
||||
{
|
||||
return CategoryNotAllowed;
|
||||
}
|
||||
|
||||
// A category adds at least one character.
|
||||
return mask.FixedLength + (mask.UsesCategory ? 1 : 0) > maxLength ? TooLong : null;
|
||||
}
|
||||
|
||||
/// <summary>The key of the sequence a code of this mask takes its number from.</summary>
|
||||
/// <param name="rule">The rule, such as <c>customers</c>.</param>
|
||||
/// <param name="year">The year of the record.</param>
|
||||
/// <param name="category">The category code, for masks with the category.</param>
|
||||
/// <returns>The key, such as <c>items:VALV</c> or <c>leads:2026</c>.</returns>
|
||||
public string SequenceKey(string rule, int year, string? category)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(rule);
|
||||
var key = new StringBuilder(rule);
|
||||
if (UsesYear)
|
||||
{
|
||||
key.Append(':').Append(year.ToString("D4", CultureInfo.InvariantCulture));
|
||||
}
|
||||
|
||||
if (UsesCategory)
|
||||
{
|
||||
key.Append(':').Append(Normalize(category));
|
||||
}
|
||||
|
||||
return key.ToString();
|
||||
}
|
||||
|
||||
/// <summary>Writes a code.</summary>
|
||||
/// <param name="number">The progressive number.</param>
|
||||
/// <param name="year">The year.</param>
|
||||
/// <param name="category">The category code, for masks with the category.</param>
|
||||
/// <returns>The code.</returns>
|
||||
public string Format(long number, int year, string? category)
|
||||
{
|
||||
ArgumentOutOfRangeException.ThrowIfNegative(number);
|
||||
var code = new StringBuilder();
|
||||
foreach (var part in _parts)
|
||||
{
|
||||
code.Append(part.Kind switch
|
||||
{
|
||||
PartKind.Sequence => number.ToString(part.Digits > 0 ? "D" + part.Digits.ToString(CultureInfo.InvariantCulture) : "D", CultureInfo.InvariantCulture),
|
||||
PartKind.Year => year.ToString("D4", CultureInfo.InvariantCulture),
|
||||
PartKind.Category => Normalize(category),
|
||||
_ => part.Text,
|
||||
});
|
||||
}
|
||||
|
||||
return code.ToString();
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public override string ToString() => Text;
|
||||
|
||||
private static string Normalize(string? category) => (category ?? string.Empty).Trim().ToUpperInvariant();
|
||||
|
||||
private static bool TryReadPlaceholder(string body, out Part part)
|
||||
{
|
||||
var colon = body.IndexOf(':', StringComparison.Ordinal);
|
||||
var name = (colon < 0 ? body : body[..colon]).Trim().ToUpperInvariant();
|
||||
var format = colon < 0 ? null : body[(colon + 1)..].Trim();
|
||||
part = default;
|
||||
switch (name)
|
||||
{
|
||||
case "SEQ" when format is null:
|
||||
part = new Part(PartKind.Sequence, string.Empty, 0);
|
||||
return true;
|
||||
case "SEQ" when format.Length is > 0 and <= 12 && format.All(c => c == '0'):
|
||||
part = new Part(PartKind.Sequence, string.Empty, format.Length);
|
||||
return true;
|
||||
case "ANNO" or "YEAR" when format is null:
|
||||
part = new Part(PartKind.Year, string.Empty, 0);
|
||||
return true;
|
||||
case "CATEGORIA" or "CATEGORY" when format is null:
|
||||
part = new Part(PartKind.Category, string.Empty, 0);
|
||||
return true;
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private readonly record struct Part(PartKind Kind, string Text, int Digits)
|
||||
{
|
||||
public string ToMask() => Kind switch
|
||||
{
|
||||
PartKind.Sequence => Digits > 0 ? "{seq:" + new string('0', Digits) + "}" : "{seq}",
|
||||
PartKind.Year => "{anno}",
|
||||
PartKind.Category => "{categoria}",
|
||||
_ => Text,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,180 @@
|
||||
using Khaemhat.Core.Entities;
|
||||
using Khaemhat.Core.Tax;
|
||||
|
||||
namespace Khaemhat.Core.Tables;
|
||||
|
||||
/// <summary>The data of the company itself, one row per company database (SPEC §11.1, mockup 075).</summary>
|
||||
public sealed class CompanyProfile : Entity<long>
|
||||
{
|
||||
/// <summary>The company name.</summary>
|
||||
public string LegalName { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>The name written on fiscal documents, when different.</summary>
|
||||
public string? FiscalName { get; set; }
|
||||
|
||||
/// <summary>The VAT number, without the country prefix.</summary>
|
||||
public string? VatNumber { get; set; }
|
||||
|
||||
/// <summary>The tax code.</summary>
|
||||
public string? TaxCode { get; set; }
|
||||
|
||||
/// <summary>The province of the business register (REA).</summary>
|
||||
public string? ReaOffice { get; set; }
|
||||
|
||||
/// <summary>The number in the business register (REA).</summary>
|
||||
public string? ReaNumber { get; set; }
|
||||
|
||||
/// <summary>The share capital.</summary>
|
||||
public decimal? ShareCapital { get; set; }
|
||||
|
||||
/// <summary>Sole shareholder: <c>SU</c> one, <c>SM</c> more; empty when it does not apply.</summary>
|
||||
public string? Shareholders { get; set; }
|
||||
|
||||
/// <summary>Liquidation: <c>LN</c> not in liquidation, <c>LS</c> in liquidation.</summary>
|
||||
public string? LiquidationStatus { get; set; }
|
||||
|
||||
/// <summary>The street.</summary>
|
||||
public string? Address { get; set; }
|
||||
|
||||
/// <summary>The street number.</summary>
|
||||
public string? StreetNumber { get; set; }
|
||||
|
||||
/// <summary>The postal code.</summary>
|
||||
public string? PostalCode { get; set; }
|
||||
|
||||
/// <summary>The town.</summary>
|
||||
public string? City { get; set; }
|
||||
|
||||
/// <summary>The province abbreviation.</summary>
|
||||
public string? ProvinceCode { get; set; }
|
||||
|
||||
/// <summary>The country of the address (ISO 3166-1).</summary>
|
||||
public string? AddressCountry { get; set; }
|
||||
|
||||
/// <summary>The phone.</summary>
|
||||
public string? Phone { get; set; }
|
||||
|
||||
/// <summary>The e-mail address.</summary>
|
||||
public string? Email { get; set; }
|
||||
|
||||
/// <summary>The certified e-mail address.</summary>
|
||||
public string? Pec { get; set; }
|
||||
|
||||
/// <summary>The web site.</summary>
|
||||
public string? Website { get; set; }
|
||||
|
||||
/// <summary>The tax regime, such as <c>RF01</c>.</summary>
|
||||
public string TaxRegime { get; set; } = "RF01";
|
||||
|
||||
/// <summary>The company's own recipient code for incoming e-invoices.</summary>
|
||||
public string? RecipientCode { get; set; }
|
||||
|
||||
/// <summary>The logo (an attachment of entity <c>company_profile</c>).</summary>
|
||||
public long? LogoAttachmentId { get; set; }
|
||||
|
||||
/// <summary>The bank account proposed on documents.</summary>
|
||||
public long? DefaultBankAccountId { get; set; }
|
||||
|
||||
/// <summary>The accounting currency (ISO 4217).</summary>
|
||||
public string CurrencyCode { get; set; } = "EUR";
|
||||
|
||||
/// <summary>The country whose fiscal pack applies (ISO 3166-1), from <c>KHAEMHAT_COUNTRY</c> at creation.</summary>
|
||||
public string Country { get; set; } = "IT";
|
||||
|
||||
/// <summary>The VAT settlement periodicity.</summary>
|
||||
public VatPeriodicity VatPeriodicity { get; set; }
|
||||
|
||||
/// <summary>The deductible share for companies with exempt operations (pro-rata), in percent; 100 when it does not apply.</summary>
|
||||
public decimal ProRataPercent { get; set; } = 100m;
|
||||
|
||||
/// <summary>VAT on cash basis (art. 32-bis DL 83/2012).</summary>
|
||||
public bool CashVat { get; set; }
|
||||
|
||||
/// <summary>The first month of the fiscal year (1 for calendar years).</summary>
|
||||
public int FiscalYearStartMonth { get; set; } = 1;
|
||||
|
||||
/// <summary>The transmitter of e-invoices, when not the company: country.</summary>
|
||||
public string? TransmitterCountry { get; set; }
|
||||
|
||||
/// <summary>The transmitter of e-invoices: tax identifier.</summary>
|
||||
public string? TransmitterId { get; set; }
|
||||
|
||||
/// <summary>The intermediary that sends the returns (LIPE, F24): name.</summary>
|
||||
public string? IntermediaryName { get; set; }
|
||||
|
||||
/// <summary>The intermediary: tax code.</summary>
|
||||
public string? IntermediaryTaxCode { get; set; }
|
||||
|
||||
/// <summary>The text printed at the bottom of documents.</summary>
|
||||
public string? FooterNotes { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>The state of a fiscal year (SPEC §11.1, mockup 052).</summary>
|
||||
public enum FiscalYearStatus
|
||||
{
|
||||
/// <summary>Entries allowed.</summary>
|
||||
Open = 0,
|
||||
|
||||
/// <summary>Closing entries in progress: only closing entries.</summary>
|
||||
Closing = 1,
|
||||
|
||||
/// <summary>Read only.</summary>
|
||||
Closed = 2,
|
||||
}
|
||||
|
||||
/// <summary>A fiscal year.</summary>
|
||||
public sealed class FiscalYear : Entity<long>
|
||||
{
|
||||
/// <summary>The code, such as <c>2026</c> or <c>2026/27</c>.</summary>
|
||||
public string Code { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>The first day.</summary>
|
||||
public DateOnly StartDate { get; set; }
|
||||
|
||||
/// <summary>The last day.</summary>
|
||||
public DateOnly EndDate { get; set; }
|
||||
|
||||
/// <summary>The state.</summary>
|
||||
public FiscalYearStatus Status { get; set; }
|
||||
|
||||
/// <summary>The first page number of the journal printed for this year.</summary>
|
||||
public int JournalFirstPage { get; set; } = 1;
|
||||
|
||||
/// <summary>The number of the last final journal entry.</summary>
|
||||
public long LastFinalEntryNumber { get; set; }
|
||||
|
||||
/// <summary>The date of the last final journal entry.</summary>
|
||||
public DateOnly? LastFinalEntryDate { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>The state of a fiscal period.</summary>
|
||||
public enum FiscalPeriodStatus
|
||||
{
|
||||
/// <summary>Documents and entries allowed.</summary>
|
||||
Open = 0,
|
||||
|
||||
/// <summary>The VAT of the period was settled: no new entries with VAT.</summary>
|
||||
Settled = 1,
|
||||
|
||||
/// <summary>Locked: no new documents or entries dated in the period.</summary>
|
||||
Locked = 2,
|
||||
}
|
||||
|
||||
/// <summary>A month of a fiscal year.</summary>
|
||||
public sealed class FiscalPeriod : Entity<long>
|
||||
{
|
||||
/// <summary>The fiscal year.</summary>
|
||||
public long FiscalYearId { get; set; }
|
||||
|
||||
/// <summary>The number in the year, from 1.</summary>
|
||||
public int Number { get; set; }
|
||||
|
||||
/// <summary>The first day.</summary>
|
||||
public DateOnly StartDate { get; set; }
|
||||
|
||||
/// <summary>The last day.</summary>
|
||||
public DateOnly EndDate { get; set; }
|
||||
|
||||
/// <summary>The state.</summary>
|
||||
public FiscalPeriodStatus Status { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
namespace Khaemhat.Core.Tax;
|
||||
|
||||
/// <summary>When the VAT of an operation becomes due (FatturaPA <c>EsigibilitaIVA</c>: I, D, S).</summary>
|
||||
public enum TaxExigibility
|
||||
{
|
||||
/// <summary>Due when the invoice is issued (I).</summary>
|
||||
Immediate = 0,
|
||||
|
||||
/// <summary>Due when the invoice is paid, as with cash VAT or deferred VAT for public bodies (D).</summary>
|
||||
Deferred = 1,
|
||||
|
||||
/// <summary>Paid by the public body that buys (split payment, S).</summary>
|
||||
SplitPayment = 2,
|
||||
}
|
||||
|
||||
/// <summary>What a tax code means for the VAT return, independent of the country's code for it.</summary>
|
||||
public enum TaxCodeKind
|
||||
{
|
||||
/// <summary>Taxable with a rate above zero.</summary>
|
||||
Taxable = 0,
|
||||
|
||||
/// <summary>Not taxable (exports, intra-EU supplies, letters of intent).</summary>
|
||||
NonTaxable = 1,
|
||||
|
||||
/// <summary>Exempt.</summary>
|
||||
Exempt = 2,
|
||||
|
||||
/// <summary>Excluded from the taxable amount.</summary>
|
||||
Excluded = 3,
|
||||
|
||||
/// <summary>Outside the scope of VAT.</summary>
|
||||
NotSubject = 4,
|
||||
|
||||
/// <summary>VAT paid by the buyer (reverse charge).</summary>
|
||||
ReverseCharge = 5,
|
||||
|
||||
/// <summary>Margin scheme: VAT not shown on the invoice.</summary>
|
||||
Margin = 6,
|
||||
|
||||
/// <summary>VAT paid in another EU country.</summary>
|
||||
OtherEuVat = 7,
|
||||
}
|
||||
|
||||
/// <summary>How often the company settles VAT.</summary>
|
||||
public enum VatPeriodicity
|
||||
{
|
||||
/// <summary>Every month.</summary>
|
||||
Monthly = 0,
|
||||
|
||||
/// <summary>Every quarter, with interest where the country requires it.</summary>
|
||||
Quarterly = 1,
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
using System.Globalization;
|
||||
using System.Text;
|
||||
|
||||
namespace Khaemhat.Core.Validation;
|
||||
|
||||
/// <summary>
|
||||
/// International Bank Account Numbers (ISO 13616): country, length of the country and the mod-97 check. Spaces and
|
||||
/// case do not matter.
|
||||
/// </summary>
|
||||
public static class IbanValidator
|
||||
{
|
||||
// Lengths of the SEPA countries and their neighbours; other countries are checked for 15-34 characters only.
|
||||
private static readonly Dictionary<string, int> Lengths = new(StringComparer.Ordinal)
|
||||
{
|
||||
["AD"] = 24, ["AT"] = 20, ["BE"] = 16, ["BG"] = 22, ["CH"] = 21, ["CY"] = 28, ["CZ"] = 24, ["DE"] = 22,
|
||||
["DK"] = 18, ["EE"] = 20, ["ES"] = 24, ["FI"] = 18, ["FR"] = 27, ["GB"] = 22, ["GI"] = 23, ["GR"] = 27,
|
||||
["HR"] = 21, ["HU"] = 28, ["IE"] = 22, ["IS"] = 26, ["IT"] = 27, ["LI"] = 21, ["LT"] = 20, ["LU"] = 20,
|
||||
["LV"] = 21, ["MC"] = 27, ["MT"] = 31, ["NL"] = 18, ["NO"] = 15, ["PL"] = 28, ["PT"] = 25, ["RO"] = 24,
|
||||
["SE"] = 24, ["SI"] = 19, ["SK"] = 24, ["SM"] = 27, ["VA"] = 22,
|
||||
};
|
||||
|
||||
/// <summary>The IBAN without spaces, in capitals.</summary>
|
||||
/// <param name="iban">The IBAN as typed.</param>
|
||||
/// <returns>The compact form, or an empty string.</returns>
|
||||
public static string Normalize(string? iban) =>
|
||||
iban is null ? string.Empty : string.Concat(iban.Where(c => !char.IsWhiteSpace(c))).ToUpperInvariant();
|
||||
|
||||
/// <summary>The IBAN in groups of four characters, as printed.</summary>
|
||||
/// <param name="iban">The IBAN.</param>
|
||||
/// <returns>The printed form.</returns>
|
||||
public static string Format(string? iban)
|
||||
{
|
||||
var compact = Normalize(iban);
|
||||
var builder = new StringBuilder(compact.Length + (compact.Length / 4));
|
||||
for (var i = 0; i < compact.Length; i++)
|
||||
{
|
||||
if (i > 0 && i % 4 == 0)
|
||||
{
|
||||
builder.Append(' ');
|
||||
}
|
||||
|
||||
builder.Append(compact[i]);
|
||||
}
|
||||
|
||||
return builder.ToString();
|
||||
}
|
||||
|
||||
/// <summary>Whether an IBAN is well formed and its check digits are right.</summary>
|
||||
/// <param name="iban">The IBAN, with or without spaces.</param>
|
||||
/// <returns><see langword="true"/> for a valid IBAN.</returns>
|
||||
public static bool IsValid(string? iban)
|
||||
{
|
||||
var value = Normalize(iban);
|
||||
if (value.Length is < 15 or > 34 || !char.IsAsciiLetterUpper(value[0]) || !char.IsAsciiLetterUpper(value[1])
|
||||
|| !char.IsAsciiDigit(value[2]) || !char.IsAsciiDigit(value[3]) || !value.All(char.IsAsciiLetterOrDigit))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (Lengths.TryGetValue(value[..2], out var length) && value.Length != length)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
// Move the first four characters to the end, turn letters into 10-35 and compute mod 97 digit by digit.
|
||||
var remainder = 0;
|
||||
foreach (var c in value[4..] + value[..4])
|
||||
{
|
||||
var digits = char.IsAsciiDigit(c) ? (c - '0').ToString(CultureInfo.InvariantCulture) : (c - 'A' + 10).ToString(CultureInfo.InvariantCulture);
|
||||
foreach (var d in digits)
|
||||
{
|
||||
remainder = ((remainder * 10) + (d - '0')) % 97;
|
||||
}
|
||||
}
|
||||
|
||||
return remainder == 1;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>GTIN barcodes: EAN-8, UPC-A (12), EAN-13 and GTIN-14, with the mod-10 check digit.</summary>
|
||||
public static class EanValidator
|
||||
{
|
||||
/// <summary>Whether a barcode has a valid length and check digit.</summary>
|
||||
/// <param name="code">The digits of the barcode.</param>
|
||||
/// <returns><see langword="true"/> for a valid code.</returns>
|
||||
public static bool IsValid(string? code)
|
||||
{
|
||||
var value = code?.Trim() ?? string.Empty;
|
||||
if (value.Length is not (8 or 12 or 13 or 14) || !value.All(char.IsAsciiDigit))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
return CheckDigit(value[..^1]) == value[^1] - '0';
|
||||
}
|
||||
|
||||
/// <summary>The check digit for the digits of a code without it.</summary>
|
||||
/// <param name="digits">The digits before the check digit.</param>
|
||||
/// <returns>The check digit, 0-9.</returns>
|
||||
public static int CheckDigit(string digits)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(digits);
|
||||
var sum = 0;
|
||||
|
||||
// Weights 3 and 1 alternate starting from the rightmost digit.
|
||||
for (var i = 0; i < digits.Length; i++)
|
||||
{
|
||||
var digit = digits[digits.Length - 1 - i] - '0';
|
||||
sum += i % 2 == 0 ? digit * 3 : digit;
|
||||
}
|
||||
|
||||
return (10 - (sum % 10)) % 10;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// E-mail addresses as people type them for invoices and reminders: one <c>@</c>, a local part of up to 64 characters
|
||||
/// and a domain with at least one dot. Quoted local parts and IP literals are refused on purpose.
|
||||
/// </summary>
|
||||
public static class EmailValidator
|
||||
{
|
||||
private const string LocalSpecials = ".!#$%&'*+/=?^_`{|}~-";
|
||||
|
||||
/// <summary>Whether an address is acceptable.</summary>
|
||||
/// <param name="address">The address.</param>
|
||||
/// <returns><see langword="true"/> for a valid address.</returns>
|
||||
public static bool IsValid(string? address)
|
||||
{
|
||||
var value = address?.Trim() ?? string.Empty;
|
||||
var at = value.IndexOf('@', StringComparison.Ordinal);
|
||||
if (value.Length > 254 || at <= 0 || at != value.LastIndexOf('@'))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var local = value[..at];
|
||||
var domain = value[(at + 1)..];
|
||||
if (local.Length > 64 || local[0] == '.' || local[^1] == '.' || local.Contains("..", StringComparison.Ordinal)
|
||||
|| !local.All(c => char.IsAsciiLetterOrDigit(c) || LocalSpecials.Contains(c, StringComparison.Ordinal)))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var labels = domain.Split('.');
|
||||
return labels.Length >= 2
|
||||
&& labels.All(l => l.Length is > 0 and <= 63 && l[0] != '-' && l[^1] != '-' && l.All(c => char.IsLetterOrDigit(c) || c == '-'))
|
||||
&& labels[^1].Length >= 2 && !labels[^1].All(char.IsAsciiDigit);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
using Khaemhat.Core.Items;
|
||||
using Khaemhat.Data.Mapping;
|
||||
|
||||
namespace Khaemhat.Data.CompanyDatabase;
|
||||
|
||||
/// <summary>Map of <see cref="Item"/> to <c>items</c>.</summary>
|
||||
public sealed class ItemMap : EntityMap<Item>
|
||||
{
|
||||
/// <summary>Creates the map.</summary>
|
||||
public ItemMap()
|
||||
{
|
||||
ToTable("items");
|
||||
Map(x => x.Code).MaxLength(30);
|
||||
Map(x => x.Description).MaxLength(200);
|
||||
Map(x => x.Barcode).MaxLength(20);
|
||||
Map(x => x.CustomsCode).MaxLength(10);
|
||||
Map(x => x.Manufacturer).MaxLength(100);
|
||||
Map(x => x.Brand).MaxLength(100);
|
||||
Map(x => x.RevenueAccountCode).MaxLength(20);
|
||||
Map(x => x.CostAccountCode).MaxLength(20);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Map of <see cref="ItemUnit"/> to <c>item_uoms</c>.</summary>
|
||||
public sealed class ItemUnitMap : EntityMap<ItemUnit>
|
||||
{
|
||||
/// <summary>Creates the map.</summary>
|
||||
public ItemUnitMap()
|
||||
{
|
||||
ToTable("item_uoms");
|
||||
Map(x => x.Barcode).MaxLength(20);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Map of <see cref="ItemBarcode"/> to <c>item_barcodes</c>.</summary>
|
||||
public sealed class ItemBarcodeMap : EntityMap<ItemBarcode>
|
||||
{
|
||||
/// <summary>Creates the map.</summary>
|
||||
public ItemBarcodeMap()
|
||||
{
|
||||
ToTable("item_barcodes");
|
||||
Map(x => x.Code).MaxLength(40);
|
||||
Map(x => x.Description).MaxLength(100);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Map of <see cref="ItemPrice"/> to <c>item_prices</c>.</summary>
|
||||
public sealed class ItemPriceMap : EntityMap<ItemPrice>
|
||||
{
|
||||
/// <summary>Creates the map.</summary>
|
||||
public ItemPriceMap() => ToTable("item_prices");
|
||||
}
|
||||
|
||||
/// <summary>Map of <see cref="ItemSupplier"/> to <c>item_suppliers</c>.</summary>
|
||||
public sealed class ItemSupplierMap : EntityMap<ItemSupplier>
|
||||
{
|
||||
/// <summary>Creates the map.</summary>
|
||||
public ItemSupplierMap()
|
||||
{
|
||||
ToTable("item_suppliers");
|
||||
Map(x => x.SupplierCode).MaxLength(40);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Map of <see cref="ItemSubstitute"/> to <c>item_substitutes</c>.</summary>
|
||||
public sealed class ItemSubstituteMap : EntityMap<ItemSubstitute>
|
||||
{
|
||||
/// <summary>Creates the map.</summary>
|
||||
public ItemSubstituteMap()
|
||||
{
|
||||
ToTable("item_substitutes");
|
||||
Map(x => x.Notes).MaxLength(200);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Map of <see cref="PartyItemCode"/> to <c>party_item_codes</c>.</summary>
|
||||
public sealed class PartyItemCodeMap : EntityMap<PartyItemCode>
|
||||
{
|
||||
/// <summary>Creates the map.</summary>
|
||||
public PartyItemCodeMap()
|
||||
{
|
||||
ToTable("party_item_codes");
|
||||
Map(x => x.Code).MaxLength(40);
|
||||
Map(x => x.Description).MaxLength(200);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
using Khaemhat.Data.Migrations;
|
||||
using Khaemhat.Data.Schema;
|
||||
|
||||
namespace Khaemhat.Data.CompanyDatabase.Migrations;
|
||||
|
||||
/// <summary>The company data and the fiscal years with their periods (SPEC §11.1, mockup 075 and 052).</summary>
|
||||
[Migration(20261111_010, "create_company_profile")]
|
||||
public sealed class M20261111_010_CreateCompanyProfile : IMigration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public void Up(ISchemaBuilder schema)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(schema);
|
||||
schema.CreateTable("company_profile", t =>
|
||||
{
|
||||
t.Id();
|
||||
t.String("legal_name", 200).NotNull();
|
||||
t.String("fiscal_name", 200);
|
||||
t.String("vat_number", 28);
|
||||
t.String("tax_code", 16);
|
||||
t.String("rea_office", 2);
|
||||
t.String("rea_number", 20);
|
||||
t.Decimal("share_capital");
|
||||
t.String("shareholders", 2);
|
||||
t.String("liquidation_status", 2);
|
||||
t.String("address", 200);
|
||||
t.String("street_number", 8);
|
||||
t.String("postal_code", 10);
|
||||
t.String("city", 100);
|
||||
t.String("province_code", 2);
|
||||
t.String("address_country", 2);
|
||||
t.String("phone", 30);
|
||||
t.String("email", 254);
|
||||
t.String("pec", 254);
|
||||
t.String("website", 200);
|
||||
t.String("tax_regime", 4).NotNull();
|
||||
t.String("recipient_code", 7);
|
||||
t.Int64("logo_attachment_id");
|
||||
t.Int64("default_bank_account_id");
|
||||
t.String("currency_code", 3).NotNull();
|
||||
t.String("country", 2).NotNull();
|
||||
t.String("vat_periodicity", 40).NotNull();
|
||||
t.Decimal("pro_rata_percent").NotNull();
|
||||
t.Bool("cash_vat").NotNull().Default(false);
|
||||
t.Int32("fiscal_year_start_month").NotNull();
|
||||
t.String("transmitter_country", 2);
|
||||
t.String("transmitter_id", 28);
|
||||
t.String("intermediary_name", 200);
|
||||
t.String("intermediary_tax_code", 16);
|
||||
t.Text("footer_notes");
|
||||
t.AuditColumns();
|
||||
});
|
||||
|
||||
schema.CreateTable("fiscal_years", t =>
|
||||
{
|
||||
t.Id();
|
||||
t.String("code", 10).NotNull();
|
||||
t.Date("start_date").NotNull();
|
||||
t.Date("end_date").NotNull();
|
||||
t.String("status", 40).NotNull();
|
||||
t.Int32("journal_first_page").NotNull();
|
||||
t.Int64("last_final_entry_number").NotNull();
|
||||
t.Date("last_final_entry_date");
|
||||
t.AuditColumns();
|
||||
t.Unique("ux_fiscal_years_code", "code");
|
||||
t.Unique("ux_fiscal_years_start_date", "start_date");
|
||||
});
|
||||
|
||||
schema.CreateTable("fiscal_periods", t =>
|
||||
{
|
||||
t.Id();
|
||||
t.Int64("fiscal_year_id").NotNull();
|
||||
t.Int32("number").NotNull();
|
||||
t.Date("start_date").NotNull();
|
||||
t.Date("end_date").NotNull();
|
||||
t.String("status", 40).NotNull();
|
||||
t.AuditColumns();
|
||||
t.Unique("ux_fiscal_periods_fiscal_year_id_number", "fiscal_year_id", "number");
|
||||
t.Index("ix_fiscal_periods_start_date", "start_date");
|
||||
t.ForeignKey("fk_fiscal_periods_fiscal_year", "fiscal_year_id", "fiscal_years", ReferentialAction.Cascade);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
using Khaemhat.Data.Migrations;
|
||||
using Khaemhat.Data.Schema;
|
||||
|
||||
namespace Khaemhat.Data.CompanyDatabase.Migrations;
|
||||
|
||||
/// <summary>Countries, provinces, municipalities, currencies, exchange rates and units of measure (SPEC §11.1).</summary>
|
||||
[Migration(20261111_011, "create_geography_and_currencies")]
|
||||
public sealed class M20261111_011_CreateGeographyAndCurrencies : IMigration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public void Up(ISchemaBuilder schema)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(schema);
|
||||
schema.CreateTable("countries", t =>
|
||||
{
|
||||
t.Id();
|
||||
t.String("code", 2).NotNull();
|
||||
t.String("description", 100).NotNull();
|
||||
t.Bool("disabled").NotNull().Default(false);
|
||||
t.String("iso3", 3);
|
||||
t.Bool("eu_member").NotNull().Default(false);
|
||||
t.String("vat_prefix", 2);
|
||||
t.String("currency_code", 3);
|
||||
t.DemoColumn();
|
||||
t.AuditColumns();
|
||||
t.Unique("ux_countries_code", "code");
|
||||
});
|
||||
|
||||
schema.CreateTable("provinces", t =>
|
||||
{
|
||||
t.Id();
|
||||
t.String("code", 2).NotNull();
|
||||
t.String("description", 100).NotNull();
|
||||
t.Bool("disabled").NotNull().Default(false);
|
||||
t.String("region", 60);
|
||||
t.DemoColumn();
|
||||
t.AuditColumns();
|
||||
t.Unique("ux_provinces_code", "code");
|
||||
});
|
||||
|
||||
schema.CreateTable("municipalities", t =>
|
||||
{
|
||||
t.Id();
|
||||
t.String("code", 4).NotNull();
|
||||
t.String("description", 100).NotNull();
|
||||
t.Bool("disabled").NotNull().Default(false);
|
||||
t.String("province_code", 2).NotNull();
|
||||
t.String("region", 60);
|
||||
t.String("istat_code", 6);
|
||||
t.String("postal_codes", 400);
|
||||
t.DemoColumn();
|
||||
t.AuditColumns();
|
||||
t.Unique("ux_municipalities_code", "code");
|
||||
t.Index("ix_municipalities_description", "description");
|
||||
t.Index("ix_municipalities_province_code", "province_code");
|
||||
});
|
||||
|
||||
schema.CreateTable("currencies", t =>
|
||||
{
|
||||
t.Id();
|
||||
t.String("code", 3).NotNull();
|
||||
t.String("description", 100).NotNull();
|
||||
t.Bool("disabled").NotNull().Default(false);
|
||||
t.String("symbol", 5);
|
||||
t.Int32("decimals").NotNull();
|
||||
t.DemoColumn();
|
||||
t.AuditColumns();
|
||||
t.Unique("ux_currencies_code", "code");
|
||||
});
|
||||
|
||||
schema.CreateTable("exchange_rates", t =>
|
||||
{
|
||||
t.Id();
|
||||
t.String("currency_code", 3).NotNull();
|
||||
t.Date("rate_date").NotNull();
|
||||
t.Decimal("rate").NotNull();
|
||||
t.String("source", 10).NotNull();
|
||||
t.AuditColumns();
|
||||
t.Unique("ux_exchange_rates_currency_code_rate_date", "currency_code", "rate_date");
|
||||
});
|
||||
|
||||
schema.CreateTable("units_of_measure", t =>
|
||||
{
|
||||
t.Id();
|
||||
t.String("code", 10).NotNull();
|
||||
t.String("description", 100).NotNull();
|
||||
t.Bool("disabled").NotNull().Default(false);
|
||||
t.Int32("decimals").NotNull();
|
||||
t.String("e_invoice_code", 10);
|
||||
t.DemoColumn();
|
||||
t.AuditColumns();
|
||||
t.Unique("ux_units_of_measure_code", "code");
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
using Khaemhat.Data.Migrations;
|
||||
using Khaemhat.Data.Schema;
|
||||
|
||||
namespace Khaemhat.Data.CompanyDatabase.Migrations;
|
||||
|
||||
/// <summary>VAT codes, payment methods and terms, bank accounts and salespeople (SPEC §11.1, mockup 076).</summary>
|
||||
[Migration(20261111_012, "create_tax_and_payment_tables")]
|
||||
public sealed class M20261111_012_CreateTaxAndPaymentTables : IMigration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public void Up(ISchemaBuilder schema)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(schema);
|
||||
schema.CreateTable("tax_codes", t =>
|
||||
{
|
||||
t.Id();
|
||||
t.String("code", 10).NotNull();
|
||||
t.String("description", 100).NotNull();
|
||||
t.Bool("disabled").NotNull().Default(false);
|
||||
t.Decimal("rate").NotNull();
|
||||
t.String("nature", 5);
|
||||
t.String("kind", 40).NotNull();
|
||||
t.String("exigibility", 40).NotNull();
|
||||
t.Decimal("non_deductible_percent").NotNull();
|
||||
t.String("legal_reference", 200);
|
||||
t.Date("valid_from");
|
||||
t.Date("valid_to");
|
||||
t.String("sales_account_code", 20);
|
||||
t.String("purchase_account_code", 20);
|
||||
t.DemoColumn();
|
||||
t.AuditColumns();
|
||||
t.Unique("ux_tax_codes_code", "code");
|
||||
});
|
||||
|
||||
schema.CreateTable("payment_methods", t =>
|
||||
{
|
||||
t.Id();
|
||||
t.String("code", 10).NotNull();
|
||||
t.String("description", 100).NotNull();
|
||||
t.Bool("disabled").NotNull().Default(false);
|
||||
t.String("e_invoice_code", 4).NotNull();
|
||||
t.Bool("needs_bank").NotNull().Default(false);
|
||||
t.DemoColumn();
|
||||
t.AuditColumns();
|
||||
t.Unique("ux_payment_methods_code", "code");
|
||||
});
|
||||
|
||||
schema.CreateTable("payment_terms", t =>
|
||||
{
|
||||
t.Id();
|
||||
t.String("code", 10).NotNull();
|
||||
t.String("description", 100).NotNull();
|
||||
t.Bool("disabled").NotNull().Default(false);
|
||||
t.Int64("payment_method_id");
|
||||
t.String("condition", 4).NotNull();
|
||||
t.Bool("vat_on_first_installment").NotNull().Default(false);
|
||||
t.DemoColumn();
|
||||
t.AuditColumns();
|
||||
t.Unique("ux_payment_terms_code", "code");
|
||||
t.ForeignKey("fk_payment_terms_payment_method", "payment_method_id", "payment_methods", ReferentialAction.Restrict);
|
||||
});
|
||||
|
||||
schema.CreateTable("payment_term_lines", t =>
|
||||
{
|
||||
t.Id();
|
||||
t.Int64("payment_term_id").NotNull();
|
||||
t.Int32("number").NotNull();
|
||||
t.Int32("days").NotNull();
|
||||
t.Bool("end_of_month").NotNull().Default(false);
|
||||
t.Int32("fixed_day");
|
||||
t.Decimal("percent").NotNull();
|
||||
t.AuditColumns();
|
||||
t.Unique("ux_payment_term_lines_payment_term_id_number", "payment_term_id", "number");
|
||||
t.ForeignKey("fk_payment_term_lines_payment_term", "payment_term_id", "payment_terms", ReferentialAction.Cascade);
|
||||
});
|
||||
|
||||
schema.CreateTable("bank_accounts", t =>
|
||||
{
|
||||
t.Id();
|
||||
t.String("code", 10).NotNull();
|
||||
t.String("description", 100).NotNull();
|
||||
t.Bool("disabled").NotNull().Default(false);
|
||||
t.String("bank_name", 100);
|
||||
t.String("iban", 34);
|
||||
t.String("bic", 11);
|
||||
t.String("sia_code", 5);
|
||||
t.String("cuc_code", 8);
|
||||
t.String("account_code", 20);
|
||||
t.Bool("is_default").NotNull().Default(false);
|
||||
t.DemoColumn();
|
||||
t.AuditColumns();
|
||||
t.Unique("ux_bank_accounts_code", "code");
|
||||
});
|
||||
|
||||
schema.CreateTable("salespeople", t =>
|
||||
{
|
||||
t.Id();
|
||||
t.String("code", 10).NotNull();
|
||||
t.String("description", 100).NotNull();
|
||||
t.Bool("disabled").NotNull().Default(false);
|
||||
t.String("email", 254);
|
||||
t.String("phone", 30);
|
||||
t.Decimal("commission_percent").NotNull();
|
||||
t.Bool("enasarco").NotNull().Default(false);
|
||||
t.DemoColumn();
|
||||
t.AuditColumns();
|
||||
t.Unique("ux_salespeople_code", "code");
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
using Khaemhat.Data.Migrations;
|
||||
using Khaemhat.Data.Schema;
|
||||
|
||||
namespace Khaemhat.Data.CompanyDatabase.Migrations;
|
||||
|
||||
/// <summary>Carriers, transport tables, warehouse reasons and warehouses (SPEC §11.1).</summary>
|
||||
[Migration(20261111_013, "create_logistics_tables")]
|
||||
public sealed class M20261111_013_CreateLogisticsTables : IMigration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public void Up(ISchemaBuilder schema)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(schema);
|
||||
schema.CreateTable("carriers", t =>
|
||||
{
|
||||
t.Id();
|
||||
t.String("code", 10).NotNull();
|
||||
t.String("description", 100).NotNull();
|
||||
t.Bool("disabled").NotNull().Default(false);
|
||||
t.String("vat_number", 28);
|
||||
t.String("address", 200);
|
||||
t.String("city", 100);
|
||||
t.String("phone", 30);
|
||||
t.String("email", 254);
|
||||
t.String("register_number", 30);
|
||||
t.DemoColumn();
|
||||
t.AuditColumns();
|
||||
t.Unique("ux_carriers_code", "code");
|
||||
});
|
||||
|
||||
schema.CreateTable("shipping_terms", t =>
|
||||
{
|
||||
t.Id();
|
||||
t.String("code", 10).NotNull();
|
||||
t.String("description", 100).NotNull();
|
||||
t.Bool("disabled").NotNull().Default(false);
|
||||
t.DemoColumn();
|
||||
t.AuditColumns();
|
||||
t.Unique("ux_shipping_terms_code", "code");
|
||||
});
|
||||
|
||||
schema.CreateTable("transport_means", t =>
|
||||
{
|
||||
t.Id();
|
||||
t.String("code", 10).NotNull();
|
||||
t.String("description", 100).NotNull();
|
||||
t.Bool("disabled").NotNull().Default(false);
|
||||
t.DemoColumn();
|
||||
t.AuditColumns();
|
||||
t.Unique("ux_transport_means_code", "code");
|
||||
});
|
||||
|
||||
schema.CreateTable("goods_appearances", t =>
|
||||
{
|
||||
t.Id();
|
||||
t.String("code", 10).NotNull();
|
||||
t.String("description", 100).NotNull();
|
||||
t.Bool("disabled").NotNull().Default(false);
|
||||
t.DemoColumn();
|
||||
t.AuditColumns();
|
||||
t.Unique("ux_goods_appearances_code", "code");
|
||||
});
|
||||
|
||||
schema.CreateTable("delivery_terms", t =>
|
||||
{
|
||||
t.Id();
|
||||
t.String("code", 10).NotNull();
|
||||
t.String("description", 100).NotNull();
|
||||
t.Bool("disabled").NotNull().Default(false);
|
||||
t.DemoColumn();
|
||||
t.AuditColumns();
|
||||
t.Unique("ux_delivery_terms_code", "code");
|
||||
});
|
||||
|
||||
schema.CreateTable("transport_reasons", t =>
|
||||
{
|
||||
t.Id();
|
||||
t.String("code", 10).NotNull();
|
||||
t.String("description", 100).NotNull();
|
||||
t.Bool("disabled").NotNull().Default(false);
|
||||
t.DemoColumn();
|
||||
t.AuditColumns();
|
||||
t.Unique("ux_transport_reasons_code", "code");
|
||||
});
|
||||
|
||||
schema.CreateTable("inventory_reasons", t =>
|
||||
{
|
||||
t.Id();
|
||||
t.String("code", 10).NotNull();
|
||||
t.String("description", 100).NotNull();
|
||||
t.Bool("disabled").NotNull().Default(false);
|
||||
t.String("effect", 40).NotNull();
|
||||
t.Bool("affects_value").NotNull().Default(false);
|
||||
t.Bool("is_transfer").NotNull().Default(false);
|
||||
t.DemoColumn();
|
||||
t.AuditColumns();
|
||||
t.Unique("ux_inventory_reasons_code", "code");
|
||||
});
|
||||
|
||||
schema.CreateTable("warehouses", t =>
|
||||
{
|
||||
t.Id();
|
||||
t.String("code", 10).NotNull();
|
||||
t.String("description", 100).NotNull();
|
||||
t.Bool("disabled").NotNull().Default(false);
|
||||
t.String("address", 200);
|
||||
t.String("city", 100);
|
||||
t.String("province_code", 2);
|
||||
t.Bool("is_default").NotNull().Default(false);
|
||||
t.DemoColumn();
|
||||
t.AuditColumns();
|
||||
t.Unique("ux_warehouses_code", "code");
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
using Khaemhat.Data.Migrations;
|
||||
using Khaemhat.Data.Schema;
|
||||
|
||||
namespace Khaemhat.Data.CompanyDatabase.Migrations;
|
||||
|
||||
/// <summary>Categories, price lists, discounts, numerators, document types, cost centres and jobs (SPEC §11.1).</summary>
|
||||
[Migration(20261111_014, "create_catalog_tables")]
|
||||
public sealed class M20261111_014_CreateCatalogTables : IMigration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public void Up(ISchemaBuilder schema)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(schema);
|
||||
schema.CreateTable("item_categories", t =>
|
||||
{
|
||||
t.Id();
|
||||
t.String("code", 20).NotNull();
|
||||
t.String("description", 100).NotNull();
|
||||
t.Bool("disabled").NotNull().Default(false);
|
||||
t.Int64("parent_id");
|
||||
t.Int32("level").NotNull();
|
||||
t.DemoColumn();
|
||||
t.AuditColumns();
|
||||
t.Unique("ux_item_categories_code", "code");
|
||||
t.ForeignKey("fk_item_categories_parent", "parent_id", "item_categories", ReferentialAction.Restrict);
|
||||
});
|
||||
|
||||
schema.CreateTable("party_categories", t =>
|
||||
{
|
||||
t.Id();
|
||||
t.String("code", 10).NotNull();
|
||||
t.String("description", 100).NotNull();
|
||||
t.Bool("disabled").NotNull().Default(false);
|
||||
t.DemoColumn();
|
||||
t.AuditColumns();
|
||||
t.Unique("ux_party_categories_code", "code");
|
||||
});
|
||||
|
||||
schema.CreateTable("price_lists", t =>
|
||||
{
|
||||
t.Id();
|
||||
t.String("code", 10).NotNull();
|
||||
t.String("description", 100).NotNull();
|
||||
t.Bool("disabled").NotNull().Default(false);
|
||||
t.String("currency_code", 3).NotNull();
|
||||
t.Bool("vat_included").NotNull().Default(false);
|
||||
t.Date("valid_from");
|
||||
t.Date("valid_to");
|
||||
t.Int64("base_price_list_id");
|
||||
t.Decimal("markup_percent").NotNull();
|
||||
t.Decimal("rounding_step").NotNull();
|
||||
t.DemoColumn();
|
||||
t.AuditColumns();
|
||||
t.Unique("ux_price_lists_code", "code");
|
||||
t.ForeignKey("fk_price_lists_base_price_list", "base_price_list_id", "price_lists", ReferentialAction.Restrict);
|
||||
});
|
||||
|
||||
schema.CreateTable("discount_policies", t =>
|
||||
{
|
||||
t.Id();
|
||||
t.String("code", 10).NotNull();
|
||||
t.String("description", 100).NotNull();
|
||||
t.Bool("disabled").NotNull().Default(false);
|
||||
t.String("formula", 60).NotNull();
|
||||
t.DemoColumn();
|
||||
t.AuditColumns();
|
||||
t.Unique("ux_discount_policies_code", "code");
|
||||
});
|
||||
|
||||
schema.CreateTable("document_numerators", t =>
|
||||
{
|
||||
t.Id();
|
||||
t.String("code", 10).NotNull();
|
||||
t.String("description", 100).NotNull();
|
||||
t.Bool("disabled").NotNull().Default(false);
|
||||
t.String("kind", 40).NotNull();
|
||||
t.String("section", 10);
|
||||
t.Int32("year").NotNull();
|
||||
t.String("prefix", 10);
|
||||
t.String("format", 60).NotNull();
|
||||
t.Int64("last_number").NotNull();
|
||||
t.Bool("gaps_allowed").NotNull().Default(false);
|
||||
t.DemoColumn();
|
||||
t.AuditColumns();
|
||||
t.Unique("ux_document_numerators_code_year", "code", "year");
|
||||
});
|
||||
|
||||
schema.CreateTable("document_types", t =>
|
||||
{
|
||||
t.Id();
|
||||
t.String("code", 10).NotNull();
|
||||
t.String("description", 100).NotNull();
|
||||
t.Bool("disabled").NotNull().Default(false);
|
||||
t.String("kind", 40).NotNull();
|
||||
t.Int64("numerator_id");
|
||||
t.Int64("inventory_reason_id");
|
||||
t.String("e_invoice_type", 4);
|
||||
t.String("journal_template_code", 10);
|
||||
t.String("vat_register_code", 10);
|
||||
t.String("print_template", 60);
|
||||
t.DemoColumn();
|
||||
t.AuditColumns();
|
||||
t.Unique("ux_document_types_code", "code");
|
||||
t.ForeignKey("fk_document_types_inventory_reason", "inventory_reason_id", "inventory_reasons", ReferentialAction.Restrict);
|
||||
});
|
||||
|
||||
schema.CreateTable("cost_centers", t =>
|
||||
{
|
||||
t.Id();
|
||||
t.String("code", 20).NotNull();
|
||||
t.String("description", 100).NotNull();
|
||||
t.Bool("disabled").NotNull().Default(false);
|
||||
t.Int64("parent_id");
|
||||
t.DemoColumn();
|
||||
t.AuditColumns();
|
||||
t.Unique("ux_cost_centers_code", "code");
|
||||
t.ForeignKey("fk_cost_centers_parent", "parent_id", "cost_centers", ReferentialAction.Restrict);
|
||||
});
|
||||
|
||||
schema.CreateTable("jobs", t =>
|
||||
{
|
||||
t.Id();
|
||||
t.String("code", 20).NotNull();
|
||||
t.String("description", 100).NotNull();
|
||||
t.Bool("disabled").NotNull().Default(false);
|
||||
t.Int64("party_id");
|
||||
t.Date("start_date");
|
||||
t.Date("end_date");
|
||||
t.String("status", 40).NotNull();
|
||||
t.DemoColumn();
|
||||
t.AuditColumns();
|
||||
t.Unique("ux_jobs_code", "code");
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
using Khaemhat.Data.Migrations;
|
||||
using Khaemhat.Data.Schema;
|
||||
|
||||
namespace Khaemhat.Data.CompanyDatabase.Migrations;
|
||||
|
||||
/// <summary>The sequences of the automatic codes (SPEC §11.12): one row per rule, year and category.</summary>
|
||||
[Migration(20261111_015, "create_code_sequences")]
|
||||
public sealed class M20261111_015_CreateCodeSequences : IMigration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public void Up(ISchemaBuilder schema)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(schema);
|
||||
schema.CreateTable("code_sequences", t =>
|
||||
{
|
||||
t.Id();
|
||||
t.String("key", 100).NotNull();
|
||||
t.Int64("last_value").NotNull();
|
||||
t.AuditColumns();
|
||||
t.Unique("ux_code_sequences_key", "key");
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,203 @@
|
||||
using Khaemhat.Data.Migrations;
|
||||
using Khaemhat.Data.Schema;
|
||||
|
||||
namespace Khaemhat.Data.CompanyDatabase.Migrations;
|
||||
|
||||
/// <summary>
|
||||
/// Parties and their details (SPEC §11.2, issue #41): addresses, contacts, bank accounts, sales and purchase terms and
|
||||
/// fiscal data. The details go with the party; the company tables they point to cannot be deleted while used.
|
||||
/// </summary>
|
||||
[Migration(20261112_001, "create_parties")]
|
||||
public sealed class M20261112_001_CreateParties : IMigration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public void Up(ISchemaBuilder schema)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(schema);
|
||||
schema.CreateTable("parties", t =>
|
||||
{
|
||||
t.Id();
|
||||
t.String("code", 30).NotNull();
|
||||
t.String("previous_code", 30);
|
||||
t.String("kind", 40).NotNull();
|
||||
t.Bool("is_also_supplier").NotNull().Default(false);
|
||||
t.String("subject_type", 40).NotNull();
|
||||
t.String("name", 200).NotNull();
|
||||
t.String("first_name", 80);
|
||||
t.String("last_name", 80);
|
||||
t.String("fiscal_name", 200);
|
||||
t.String("vat_number", 30);
|
||||
t.String("tax_code", 30);
|
||||
t.String("rea", 20);
|
||||
t.Int64("category_id");
|
||||
t.String("address", 200);
|
||||
t.String("street_number", 20);
|
||||
t.String("postal_code", 10);
|
||||
t.String("city", 100);
|
||||
t.String("province", 10);
|
||||
t.String("country_code", 2).NotNull();
|
||||
t.String("phone", 40);
|
||||
t.String("email", 200);
|
||||
t.String("pec", 200);
|
||||
t.String("website", 200);
|
||||
t.Int64("salesperson_id");
|
||||
t.String("language", 5).NotNull();
|
||||
t.String("currency_code", 3).NotNull();
|
||||
t.Date("since");
|
||||
t.Bool("privacy_accepted").NotNull().Default(false);
|
||||
t.Bool("marketing").NotNull().Default(false);
|
||||
t.Text("notes");
|
||||
t.String("vat_check", 40).NotNull();
|
||||
t.DateTimeUtc("vat_checked_at");
|
||||
t.String("customer_account_code", 20);
|
||||
t.String("supplier_account_code", 20);
|
||||
t.Bool("disabled").NotNull().Default(false);
|
||||
t.DemoColumn();
|
||||
t.AuditColumns();
|
||||
t.Unique("ux_parties_code", "code");
|
||||
t.Index("ix_parties_name", "name");
|
||||
t.Index("ix_parties_vat_number", "vat_number");
|
||||
t.Index("ix_parties_tax_code", "tax_code");
|
||||
t.Index("ix_parties_kind", "kind");
|
||||
t.ForeignKey("fk_parties_category", "category_id", "party_categories", ReferentialAction.Restrict);
|
||||
t.ForeignKey("fk_parties_salesperson", "salesperson_id", "salespeople", ReferentialAction.Restrict);
|
||||
});
|
||||
|
||||
schema.CreateTable("party_addresses", t =>
|
||||
{
|
||||
t.Id();
|
||||
t.Int64("party_id").NotNull();
|
||||
t.String("kind", 40).NotNull();
|
||||
t.String("name", 200).NotNull();
|
||||
t.String("address", 200);
|
||||
t.String("street_number", 20);
|
||||
t.String("postal_code", 10);
|
||||
t.String("city", 100);
|
||||
t.String("province", 10);
|
||||
t.String("country_code", 2).NotNull();
|
||||
t.Bool("is_default").NotNull().Default(false);
|
||||
t.Text("notes");
|
||||
t.AuditColumns();
|
||||
t.Index("ix_party_addresses_party", "party_id");
|
||||
t.ForeignKey("fk_party_addresses_party", "party_id", "parties", ReferentialAction.Cascade);
|
||||
});
|
||||
|
||||
schema.CreateTable("party_contacts", t =>
|
||||
{
|
||||
t.Id();
|
||||
t.Int64("party_id").NotNull();
|
||||
t.String("name", 120).NotNull();
|
||||
t.String("role", 80);
|
||||
t.String("phone", 40);
|
||||
t.String("mobile", 40);
|
||||
t.String("email", 200);
|
||||
t.Bool("is_default").NotNull().Default(false);
|
||||
t.Text("notes");
|
||||
t.AuditColumns();
|
||||
t.Index("ix_party_contacts_party", "party_id");
|
||||
t.ForeignKey("fk_party_contacts_party", "party_id", "parties", ReferentialAction.Cascade);
|
||||
});
|
||||
|
||||
schema.CreateTable("party_bank_accounts", t =>
|
||||
{
|
||||
t.Id();
|
||||
t.Int64("party_id").NotNull();
|
||||
t.String("iban", 34).NotNull();
|
||||
t.String("bic", 11);
|
||||
t.String("bank_name", 100);
|
||||
t.String("bank_code", 10);
|
||||
t.String("branch_code", 10);
|
||||
t.Bool("is_default").NotNull().Default(false);
|
||||
t.AuditColumns();
|
||||
t.Index("ix_party_bank_accounts_party", "party_id");
|
||||
t.ForeignKey("fk_party_bank_accounts_party", "party_id", "parties", ReferentialAction.Cascade);
|
||||
});
|
||||
|
||||
schema.CreateTable("party_sales_terms", t =>
|
||||
{
|
||||
t.Id();
|
||||
t.Int64("party_id").NotNull();
|
||||
t.Int64("price_list_id");
|
||||
t.Decimal("discount1");
|
||||
t.Decimal("discount2");
|
||||
t.Int64("payment_term_id");
|
||||
t.Int64("company_bank_account_id");
|
||||
t.Int64("carrier_id");
|
||||
t.Int64("shipping_term_id");
|
||||
t.Int64("warehouse_id");
|
||||
t.Decimal("credit_limit");
|
||||
t.Bool("blocked").NotNull().Default(false);
|
||||
t.Bool("group_delivery_notes").NotNull().Default(true);
|
||||
t.Int32("invoice_day");
|
||||
t.String("send_documents", 40).NotNull();
|
||||
t.String("documents_email", 200);
|
||||
t.AuditColumns();
|
||||
t.Unique("ux_party_sales_terms_party", "party_id");
|
||||
t.ForeignKey("fk_party_sales_terms_party", "party_id", "parties", ReferentialAction.Cascade);
|
||||
t.ForeignKey("fk_party_sales_terms_price_list", "price_list_id", "price_lists", ReferentialAction.Restrict);
|
||||
t.ForeignKey("fk_party_sales_terms_payment_term", "payment_term_id", "payment_terms", ReferentialAction.Restrict);
|
||||
t.ForeignKey("fk_party_sales_terms_bank_account", "company_bank_account_id", "bank_accounts", ReferentialAction.Restrict);
|
||||
t.ForeignKey("fk_party_sales_terms_carrier", "carrier_id", "carriers", ReferentialAction.Restrict);
|
||||
t.ForeignKey("fk_party_sales_terms_shipping_term", "shipping_term_id", "shipping_terms", ReferentialAction.Restrict);
|
||||
t.ForeignKey("fk_party_sales_terms_warehouse", "warehouse_id", "warehouses", ReferentialAction.Restrict);
|
||||
});
|
||||
|
||||
schema.CreateTable("party_purchase_terms", t =>
|
||||
{
|
||||
t.Id();
|
||||
t.Int64("party_id").NotNull();
|
||||
t.Int64("payment_term_id");
|
||||
t.Int32("lead_time_days");
|
||||
t.Decimal("minimum_order");
|
||||
t.Decimal("discount");
|
||||
t.Int64("shipping_term_id");
|
||||
t.String("vat_register_code", 10);
|
||||
t.String("cost_account_code", 20);
|
||||
t.String("orders_email", 200);
|
||||
t.AuditColumns();
|
||||
t.Unique("ux_party_purchase_terms_party", "party_id");
|
||||
t.ForeignKey("fk_party_purchase_terms_party", "party_id", "parties", ReferentialAction.Cascade);
|
||||
t.ForeignKey("fk_party_purchase_terms_payment_term", "payment_term_id", "payment_terms", ReferentialAction.Restrict);
|
||||
t.ForeignKey("fk_party_purchase_terms_shipping_term", "shipping_term_id", "shipping_terms", ReferentialAction.Restrict);
|
||||
});
|
||||
|
||||
schema.CreateTable("party_fiscal", t =>
|
||||
{
|
||||
t.Id();
|
||||
t.Int64("party_id").NotNull();
|
||||
t.String("recipient_code", 7);
|
||||
t.String("recipient_pec", 200);
|
||||
t.String("administration_reference", 20);
|
||||
t.Bool("attach_pdf").NotNull().Default(true);
|
||||
t.Bool("send_copy").NotNull().Default(false);
|
||||
t.Bool("split_payment").NotNull().Default(false);
|
||||
t.Bool("reverse_charge").NotNull().Default(false);
|
||||
t.Int64("tax_code_id");
|
||||
t.String("exigibility", 1);
|
||||
t.Bool("stamp_duty_charged").NotNull().Default(true);
|
||||
t.Bool("withholding").NotNull().Default(false);
|
||||
t.Decimal("withholding_rate");
|
||||
t.String("withholding_reason", 4);
|
||||
t.String("pension_fund", 4);
|
||||
t.Decimal("pension_fund_rate");
|
||||
t.Bool("enasarco").NotNull().Default(false);
|
||||
t.Bool("intent_active").NotNull().Default(false);
|
||||
t.String("intent_number", 40);
|
||||
t.Date("intent_date");
|
||||
t.String("intent_protocol", 40);
|
||||
t.Int64("intent_tax_code_id");
|
||||
t.Decimal("intent_ceiling");
|
||||
t.Decimal("intent_used").NotNull().Default(0m);
|
||||
t.Date("intent_from");
|
||||
t.Date("intent_to");
|
||||
t.String("gln", 13);
|
||||
t.String("eori", 17);
|
||||
t.String("our_code", 40);
|
||||
t.AuditColumns();
|
||||
t.Unique("ux_party_fiscal_party", "party_id");
|
||||
t.ForeignKey("fk_party_fiscal_party", "party_id", "parties", ReferentialAction.Cascade);
|
||||
t.ForeignKey("fk_party_fiscal_tax_code", "tax_code_id", "tax_codes", ReferentialAction.Restrict);
|
||||
t.ForeignKey("fk_party_fiscal_intent_tax_code", "intent_tax_code_id", "tax_codes", ReferentialAction.Restrict);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
using Khaemhat.Data.Migrations;
|
||||
using Khaemhat.Data.Schema;
|
||||
|
||||
namespace Khaemhat.Data.CompanyDatabase.Migrations;
|
||||
|
||||
/// <summary>
|
||||
/// Items and their details (SPEC §11.2, issue #42): alternative units and codes, prices of the price lists and net
|
||||
/// prices of the parties, suppliers, substitutes, and the codes the parties use for our items. The details go with the
|
||||
/// item; an item used as a substitute or a party with prices cannot be deleted.
|
||||
/// </summary>
|
||||
[Migration(20261112_002, "create_items")]
|
||||
public sealed class M20261112_002_CreateItems : IMigration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public void Up(ISchemaBuilder schema)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(schema);
|
||||
schema.AlterTable("price_lists", t => t.Bool("is_base").NotNull().Default(false));
|
||||
schema.Sql(d => "UPDATE price_lists SET is_base = " + d.Literal(true, ColumnType.Bool) + " WHERE code = 'BASE'");
|
||||
schema.CreateTable("items", t =>
|
||||
{
|
||||
t.Id();
|
||||
t.String("code", 30).NotNull();
|
||||
t.String("kind", 40).NotNull();
|
||||
t.String("description", 200).NotNull();
|
||||
t.Text("extended_description");
|
||||
t.Int64("category_id");
|
||||
t.Int64("unit_of_measure_id");
|
||||
t.Int64("sales_tax_code_id");
|
||||
t.Int64("purchase_tax_code_id");
|
||||
t.String("barcode", 20);
|
||||
t.String("customs_code", 10);
|
||||
t.String("manufacturer", 100);
|
||||
t.String("brand", 100);
|
||||
t.Decimal("net_weight");
|
||||
t.Decimal("gross_weight");
|
||||
t.Bool("stocked").NotNull().Default(false);
|
||||
t.Int64("warehouse_id");
|
||||
t.Decimal("minimum_stock");
|
||||
t.Decimal("reorder_point");
|
||||
t.Decimal("reorder_lot");
|
||||
t.Decimal("price");
|
||||
t.Decimal("standard_cost");
|
||||
t.Decimal("last_cost");
|
||||
t.Decimal("average_cost");
|
||||
t.String("revenue_account_code", 20);
|
||||
t.String("cost_account_code", 20);
|
||||
t.Text("notes");
|
||||
t.Bool("disabled").NotNull().Default(false);
|
||||
t.DemoColumn();
|
||||
t.AuditColumns();
|
||||
t.Unique("ux_items_code", "code");
|
||||
t.Index("ix_items_description", "description");
|
||||
t.Index("ix_items_barcode", "barcode");
|
||||
t.Index("ix_items_category", "category_id");
|
||||
t.ForeignKey("fk_items_category", "category_id", "item_categories", ReferentialAction.Restrict);
|
||||
t.ForeignKey("fk_items_unit", "unit_of_measure_id", "units_of_measure", ReferentialAction.Restrict);
|
||||
t.ForeignKey("fk_items_sales_tax_code", "sales_tax_code_id", "tax_codes", ReferentialAction.Restrict);
|
||||
t.ForeignKey("fk_items_purchase_tax_code", "purchase_tax_code_id", "tax_codes", ReferentialAction.Restrict);
|
||||
t.ForeignKey("fk_items_warehouse", "warehouse_id", "warehouses", ReferentialAction.Restrict);
|
||||
});
|
||||
|
||||
schema.CreateTable("item_uoms", t =>
|
||||
{
|
||||
t.Id();
|
||||
t.Int64("item_id").NotNull();
|
||||
t.Int64("unit_of_measure_id").NotNull();
|
||||
t.Decimal("factor").NotNull().Default(1m);
|
||||
t.String("barcode", 20);
|
||||
t.AuditColumns();
|
||||
t.Unique("ux_item_uoms_item_unit", "item_id", "unit_of_measure_id");
|
||||
t.ForeignKey("fk_item_uoms_item", "item_id", "items", ReferentialAction.Cascade);
|
||||
t.ForeignKey("fk_item_uoms_unit", "unit_of_measure_id", "units_of_measure", ReferentialAction.Restrict);
|
||||
});
|
||||
|
||||
schema.CreateTable("item_barcodes", t =>
|
||||
{
|
||||
t.Id();
|
||||
t.Int64("item_id").NotNull();
|
||||
t.String("code", 40).NotNull();
|
||||
t.String("description", 100);
|
||||
t.AuditColumns();
|
||||
t.Index("ix_item_barcodes_code", "code");
|
||||
t.ForeignKey("fk_item_barcodes_item", "item_id", "items", ReferentialAction.Cascade);
|
||||
});
|
||||
|
||||
schema.CreateTable("item_prices", t =>
|
||||
{
|
||||
t.Id();
|
||||
t.Int64("item_id").NotNull();
|
||||
t.Int64("price_list_id");
|
||||
t.Int64("party_id");
|
||||
t.Decimal("price").NotNull();
|
||||
t.Date("valid_from");
|
||||
t.AuditColumns();
|
||||
t.Index("ix_item_prices_item", "item_id");
|
||||
t.Index("ix_item_prices_price_list", "price_list_id");
|
||||
t.Index("ix_item_prices_party", "party_id");
|
||||
t.ForeignKey("fk_item_prices_item", "item_id", "items", ReferentialAction.Cascade);
|
||||
t.ForeignKey("fk_item_prices_price_list", "price_list_id", "price_lists", ReferentialAction.Restrict);
|
||||
t.ForeignKey("fk_item_prices_party", "party_id", "parties", ReferentialAction.Restrict);
|
||||
});
|
||||
|
||||
schema.CreateTable("item_suppliers", t =>
|
||||
{
|
||||
t.Id();
|
||||
t.Int64("item_id").NotNull();
|
||||
t.Int64("party_id").NotNull();
|
||||
t.String("supplier_code", 40);
|
||||
t.Decimal("price");
|
||||
t.Int32("lead_time_days");
|
||||
t.Decimal("minimum_quantity");
|
||||
t.Bool("is_default").NotNull().Default(false);
|
||||
t.AuditColumns();
|
||||
t.Unique("ux_item_suppliers_item_party", "item_id", "party_id");
|
||||
t.ForeignKey("fk_item_suppliers_item", "item_id", "items", ReferentialAction.Cascade);
|
||||
t.ForeignKey("fk_item_suppliers_party", "party_id", "parties", ReferentialAction.Restrict);
|
||||
});
|
||||
|
||||
schema.CreateTable("item_substitutes", t =>
|
||||
{
|
||||
t.Id();
|
||||
t.Int64("item_id").NotNull();
|
||||
t.Int64("substitute_id").NotNull();
|
||||
t.String("notes", 200);
|
||||
t.AuditColumns();
|
||||
t.Unique("ux_item_substitutes_pair", "item_id", "substitute_id");
|
||||
t.ForeignKey("fk_item_substitutes_item", "item_id", "items", ReferentialAction.Cascade);
|
||||
t.ForeignKey("fk_item_substitutes_substitute", "substitute_id", "items", ReferentialAction.Restrict);
|
||||
});
|
||||
|
||||
schema.CreateTable("party_item_codes", t =>
|
||||
{
|
||||
t.Id();
|
||||
t.Int64("party_id").NotNull();
|
||||
t.Int64("item_id").NotNull();
|
||||
t.String("code", 40).NotNull();
|
||||
t.String("description", 200);
|
||||
t.AuditColumns();
|
||||
t.Unique("ux_party_item_codes_party_code", "party_id", "code");
|
||||
t.Index("ix_party_item_codes_item", "item_id");
|
||||
t.ForeignKey("fk_party_item_codes_party", "party_id", "parties", ReferentialAction.Cascade);
|
||||
t.ForeignKey("fk_party_item_codes_item", "item_id", "items", ReferentialAction.Cascade);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
using Khaemhat.Core.Parties;
|
||||
using Khaemhat.Data.Mapping;
|
||||
|
||||
namespace Khaemhat.Data.CompanyDatabase;
|
||||
|
||||
/// <summary>Map of <see cref="Party"/> to <c>parties</c>.</summary>
|
||||
public sealed class PartyMap : EntityMap<Party>
|
||||
{
|
||||
/// <summary>Creates the map.</summary>
|
||||
public PartyMap()
|
||||
{
|
||||
ToTable("parties");
|
||||
Map(x => x.Code).MaxLength(30);
|
||||
Map(x => x.PreviousCode).MaxLength(30);
|
||||
Map(x => x.Name).MaxLength(200);
|
||||
Map(x => x.FirstName).MaxLength(80);
|
||||
Map(x => x.LastName).MaxLength(80);
|
||||
Map(x => x.FiscalName).MaxLength(200);
|
||||
Map(x => x.VatNumber).MaxLength(30);
|
||||
Map(x => x.TaxCode).MaxLength(30);
|
||||
Map(x => x.Rea).MaxLength(20);
|
||||
Map(x => x.Address).MaxLength(200);
|
||||
Map(x => x.StreetNumber).MaxLength(20);
|
||||
Map(x => x.PostalCode).MaxLength(10);
|
||||
Map(x => x.City).MaxLength(100);
|
||||
Map(x => x.Province).MaxLength(10);
|
||||
Map(x => x.CountryCode).MaxLength(2);
|
||||
Map(x => x.Phone).MaxLength(40);
|
||||
Map(x => x.Email).MaxLength(200);
|
||||
Map(x => x.Pec).MaxLength(200);
|
||||
Map(x => x.Website).MaxLength(200);
|
||||
Map(x => x.Language).MaxLength(5);
|
||||
Map(x => x.CurrencyCode).MaxLength(3);
|
||||
Map(x => x.CustomerAccountCode).MaxLength(20);
|
||||
Map(x => x.SupplierAccountCode).MaxLength(20);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Map of <see cref="PartyAddress"/> to <c>party_addresses</c>.</summary>
|
||||
public sealed class PartyAddressMap : EntityMap<PartyAddress>
|
||||
{
|
||||
/// <summary>Creates the map.</summary>
|
||||
public PartyAddressMap()
|
||||
{
|
||||
ToTable("party_addresses");
|
||||
Map(x => x.Name).MaxLength(200);
|
||||
Map(x => x.Address).MaxLength(200);
|
||||
Map(x => x.StreetNumber).MaxLength(20);
|
||||
Map(x => x.PostalCode).MaxLength(10);
|
||||
Map(x => x.City).MaxLength(100);
|
||||
Map(x => x.Province).MaxLength(10);
|
||||
Map(x => x.CountryCode).MaxLength(2);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Map of <see cref="PartyContact"/> to <c>party_contacts</c>.</summary>
|
||||
public sealed class PartyContactMap : EntityMap<PartyContact>
|
||||
{
|
||||
/// <summary>Creates the map.</summary>
|
||||
public PartyContactMap()
|
||||
{
|
||||
ToTable("party_contacts");
|
||||
Map(x => x.Name).MaxLength(120);
|
||||
Map(x => x.Role).MaxLength(80);
|
||||
Map(x => x.Phone).MaxLength(40);
|
||||
Map(x => x.Mobile).MaxLength(40);
|
||||
Map(x => x.Email).MaxLength(200);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Map of <see cref="PartyBankAccount"/> to <c>party_bank_accounts</c>.</summary>
|
||||
public sealed class PartyBankAccountMap : EntityMap<PartyBankAccount>
|
||||
{
|
||||
/// <summary>Creates the map.</summary>
|
||||
public PartyBankAccountMap()
|
||||
{
|
||||
ToTable("party_bank_accounts");
|
||||
Map(x => x.Iban).MaxLength(34);
|
||||
Map(x => x.Bic).MaxLength(11);
|
||||
Map(x => x.BankName).MaxLength(100);
|
||||
Map(x => x.BankCode).MaxLength(10);
|
||||
Map(x => x.BranchCode).MaxLength(10);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Map of <see cref="PartySalesTerms"/> to <c>party_sales_terms</c>.</summary>
|
||||
public sealed class PartySalesTermsMap : EntityMap<PartySalesTerms>
|
||||
{
|
||||
/// <summary>Creates the map.</summary>
|
||||
public PartySalesTermsMap()
|
||||
{
|
||||
ToTable("party_sales_terms");
|
||||
Map(x => x.DocumentsEmail).MaxLength(200);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Map of <see cref="PartyPurchaseTerms"/> to <c>party_purchase_terms</c>.</summary>
|
||||
public sealed class PartyPurchaseTermsMap : EntityMap<PartyPurchaseTerms>
|
||||
{
|
||||
/// <summary>Creates the map.</summary>
|
||||
public PartyPurchaseTermsMap()
|
||||
{
|
||||
ToTable("party_purchase_terms");
|
||||
Map(x => x.VatRegisterCode).MaxLength(10);
|
||||
Map(x => x.CostAccountCode).MaxLength(20);
|
||||
Map(x => x.OrdersEmail).MaxLength(200);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Map of <see cref="PartyFiscal"/> to <c>party_fiscal</c>.</summary>
|
||||
public sealed class PartyFiscalMap : EntityMap<PartyFiscal>
|
||||
{
|
||||
/// <summary>Creates the map.</summary>
|
||||
public PartyFiscalMap()
|
||||
{
|
||||
ToTable("party_fiscal");
|
||||
Map(x => x.RecipientCode).MaxLength(7);
|
||||
Map(x => x.RecipientPec).MaxLength(200);
|
||||
Map(x => x.AdministrationReference).MaxLength(20);
|
||||
Map(x => x.Exigibility).MaxLength(1);
|
||||
Map(x => x.WithholdingReason).MaxLength(4);
|
||||
Map(x => x.PensionFund).MaxLength(4);
|
||||
Map(x => x.IntentNumber).MaxLength(40);
|
||||
Map(x => x.IntentProtocol).MaxLength(40);
|
||||
Map(x => x.Gln).MaxLength(13);
|
||||
Map(x => x.Eori).MaxLength(17);
|
||||
Map(x => x.OurCode).MaxLength(40);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,448 @@
|
||||
using Khaemhat.Core.Tables;
|
||||
using Khaemhat.Data.Mapping;
|
||||
|
||||
namespace Khaemhat.Data.CompanyDatabase;
|
||||
|
||||
/// <summary>Map of <see cref="CompanyProfile"/> to <c>company_profile</c>.</summary>
|
||||
public sealed class CompanyProfileMap : EntityMap<CompanyProfile>
|
||||
{
|
||||
/// <summary>Creates the map.</summary>
|
||||
public CompanyProfileMap()
|
||||
{
|
||||
ToTable("company_profile");
|
||||
Map(x => x.LegalName).MaxLength(200);
|
||||
Map(x => x.FiscalName).MaxLength(200);
|
||||
Map(x => x.VatNumber).MaxLength(28);
|
||||
Map(x => x.TaxCode).MaxLength(16);
|
||||
Map(x => x.ReaOffice).MaxLength(2);
|
||||
Map(x => x.ReaNumber).MaxLength(20);
|
||||
Map(x => x.Shareholders).MaxLength(2);
|
||||
Map(x => x.LiquidationStatus).MaxLength(2);
|
||||
Map(x => x.Address).MaxLength(200);
|
||||
Map(x => x.StreetNumber).MaxLength(8);
|
||||
Map(x => x.PostalCode).MaxLength(10);
|
||||
Map(x => x.City).MaxLength(100);
|
||||
Map(x => x.ProvinceCode).MaxLength(2);
|
||||
Map(x => x.AddressCountry).MaxLength(2);
|
||||
Map(x => x.Phone).MaxLength(30);
|
||||
Map(x => x.Email).MaxLength(254);
|
||||
Map(x => x.Pec).MaxLength(254);
|
||||
Map(x => x.Website).MaxLength(200);
|
||||
Map(x => x.TaxRegime).MaxLength(4);
|
||||
Map(x => x.RecipientCode).MaxLength(7);
|
||||
Map(x => x.CurrencyCode).MaxLength(3);
|
||||
Map(x => x.Country).MaxLength(2);
|
||||
Map(x => x.TransmitterCountry).MaxLength(2);
|
||||
Map(x => x.TransmitterId).MaxLength(28);
|
||||
Map(x => x.IntermediaryName).MaxLength(200);
|
||||
Map(x => x.IntermediaryTaxCode).MaxLength(16);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Map of <see cref="FiscalYear"/> to <c>fiscal_years</c>.</summary>
|
||||
public sealed class FiscalYearMap : EntityMap<FiscalYear>
|
||||
{
|
||||
/// <summary>Creates the map.</summary>
|
||||
public FiscalYearMap()
|
||||
{
|
||||
ToTable("fiscal_years");
|
||||
Map(x => x.Code).MaxLength(10);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Map of <see cref="FiscalPeriod"/> to <c>fiscal_periods</c>.</summary>
|
||||
public sealed class FiscalPeriodMap : EntityMap<FiscalPeriod>
|
||||
{
|
||||
/// <summary>Creates the map.</summary>
|
||||
public FiscalPeriodMap()
|
||||
{
|
||||
ToTable("fiscal_periods");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Map of <see cref="Country"/> to <c>countries</c>.</summary>
|
||||
public sealed class CountryMap : EntityMap<Country>
|
||||
{
|
||||
/// <summary>Creates the map.</summary>
|
||||
public CountryMap()
|
||||
{
|
||||
ToTable("countries");
|
||||
Map(x => x.Code).MaxLength(2);
|
||||
Map(x => x.Description).MaxLength(100);
|
||||
Map(x => x.Iso3).MaxLength(3);
|
||||
Map(x => x.VatPrefix).MaxLength(2);
|
||||
Map(x => x.CurrencyCode).MaxLength(3);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Map of <see cref="Province"/> to <c>provinces</c>.</summary>
|
||||
public sealed class ProvinceMap : EntityMap<Province>
|
||||
{
|
||||
/// <summary>Creates the map.</summary>
|
||||
public ProvinceMap()
|
||||
{
|
||||
ToTable("provinces");
|
||||
Map(x => x.Code).MaxLength(2);
|
||||
Map(x => x.Description).MaxLength(100);
|
||||
Map(x => x.Region).MaxLength(60);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Map of <see cref="Municipality"/> to <c>municipalities</c>.</summary>
|
||||
public sealed class MunicipalityMap : EntityMap<Municipality>
|
||||
{
|
||||
/// <summary>Creates the map.</summary>
|
||||
public MunicipalityMap()
|
||||
{
|
||||
ToTable("municipalities");
|
||||
Map(x => x.Code).MaxLength(4);
|
||||
Map(x => x.Description).MaxLength(100);
|
||||
Map(x => x.ProvinceCode).MaxLength(2);
|
||||
Map(x => x.Region).MaxLength(60);
|
||||
Map(x => x.IstatCode).MaxLength(6);
|
||||
Map(x => x.PostalCodes).MaxLength(400);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Map of <see cref="Currency"/> to <c>currencies</c>.</summary>
|
||||
public sealed class CurrencyMap : EntityMap<Currency>
|
||||
{
|
||||
/// <summary>Creates the map.</summary>
|
||||
public CurrencyMap()
|
||||
{
|
||||
ToTable("currencies");
|
||||
Map(x => x.Code).MaxLength(3);
|
||||
Map(x => x.Description).MaxLength(100);
|
||||
Map(x => x.Symbol).MaxLength(5);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Map of <see cref="ExchangeRate"/> to <c>exchange_rates</c>.</summary>
|
||||
public sealed class ExchangeRateMap : EntityMap<ExchangeRate>
|
||||
{
|
||||
/// <summary>Creates the map.</summary>
|
||||
public ExchangeRateMap()
|
||||
{
|
||||
ToTable("exchange_rates");
|
||||
Map(x => x.CurrencyCode).MaxLength(3);
|
||||
Map(x => x.Source).MaxLength(10);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Map of <see cref="UnitOfMeasure"/> to <c>units_of_measure</c>.</summary>
|
||||
public sealed class UnitOfMeasureMap : EntityMap<UnitOfMeasure>
|
||||
{
|
||||
/// <summary>Creates the map.</summary>
|
||||
public UnitOfMeasureMap()
|
||||
{
|
||||
ToTable("units_of_measure");
|
||||
Map(x => x.Code).MaxLength(10);
|
||||
Map(x => x.Description).MaxLength(100);
|
||||
Map(x => x.EInvoiceCode).MaxLength(10);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Map of <see cref="TaxCode"/> to <c>tax_codes</c>.</summary>
|
||||
public sealed class TaxCodeMap : EntityMap<TaxCode>
|
||||
{
|
||||
/// <summary>Creates the map.</summary>
|
||||
public TaxCodeMap()
|
||||
{
|
||||
ToTable("tax_codes");
|
||||
Map(x => x.Code).MaxLength(10);
|
||||
Map(x => x.Description).MaxLength(100);
|
||||
Map(x => x.Nature).MaxLength(5);
|
||||
Map(x => x.LegalReference).MaxLength(200);
|
||||
Map(x => x.SalesAccountCode).MaxLength(20);
|
||||
Map(x => x.PurchaseAccountCode).MaxLength(20);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Map of <see cref="PaymentMethod"/> to <c>payment_methods</c>.</summary>
|
||||
public sealed class PaymentMethodMap : EntityMap<PaymentMethod>
|
||||
{
|
||||
/// <summary>Creates the map.</summary>
|
||||
public PaymentMethodMap()
|
||||
{
|
||||
ToTable("payment_methods");
|
||||
Map(x => x.Code).MaxLength(10);
|
||||
Map(x => x.Description).MaxLength(100);
|
||||
Map(x => x.EInvoiceCode).MaxLength(4);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Map of <see cref="PaymentTerm"/> to <c>payment_terms</c>.</summary>
|
||||
public sealed class PaymentTermMap : EntityMap<PaymentTerm>
|
||||
{
|
||||
/// <summary>Creates the map.</summary>
|
||||
public PaymentTermMap()
|
||||
{
|
||||
ToTable("payment_terms");
|
||||
Map(x => x.Code).MaxLength(10);
|
||||
Map(x => x.Description).MaxLength(100);
|
||||
Map(x => x.Condition).MaxLength(4);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Map of <see cref="PaymentTermLine"/> to <c>payment_term_lines</c>.</summary>
|
||||
public sealed class PaymentTermLineMap : EntityMap<PaymentTermLine>
|
||||
{
|
||||
/// <summary>Creates the map.</summary>
|
||||
public PaymentTermLineMap()
|
||||
{
|
||||
ToTable("payment_term_lines");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Map of <see cref="BankAccount"/> to <c>bank_accounts</c>.</summary>
|
||||
public sealed class BankAccountMap : EntityMap<BankAccount>
|
||||
{
|
||||
/// <summary>Creates the map.</summary>
|
||||
public BankAccountMap()
|
||||
{
|
||||
ToTable("bank_accounts");
|
||||
Map(x => x.Code).MaxLength(10);
|
||||
Map(x => x.Description).MaxLength(100);
|
||||
Map(x => x.BankName).MaxLength(100);
|
||||
Map(x => x.Iban).MaxLength(34);
|
||||
Map(x => x.Bic).MaxLength(11);
|
||||
Map(x => x.SiaCode).MaxLength(5);
|
||||
Map(x => x.CucCode).MaxLength(8);
|
||||
Map(x => x.AccountCode).MaxLength(20);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Map of <see cref="Salesperson"/> to <c>salespeople</c>.</summary>
|
||||
public sealed class SalespersonMap : EntityMap<Salesperson>
|
||||
{
|
||||
/// <summary>Creates the map.</summary>
|
||||
public SalespersonMap()
|
||||
{
|
||||
ToTable("salespeople");
|
||||
Map(x => x.Code).MaxLength(10);
|
||||
Map(x => x.Description).MaxLength(100);
|
||||
Map(x => x.Email).MaxLength(254);
|
||||
Map(x => x.Phone).MaxLength(30);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Map of <see cref="Carrier"/> to <c>carriers</c>.</summary>
|
||||
public sealed class CarrierMap : EntityMap<Carrier>
|
||||
{
|
||||
/// <summary>Creates the map.</summary>
|
||||
public CarrierMap()
|
||||
{
|
||||
ToTable("carriers");
|
||||
Map(x => x.Code).MaxLength(10);
|
||||
Map(x => x.Description).MaxLength(100);
|
||||
Map(x => x.VatNumber).MaxLength(28);
|
||||
Map(x => x.Address).MaxLength(200);
|
||||
Map(x => x.City).MaxLength(100);
|
||||
Map(x => x.Phone).MaxLength(30);
|
||||
Map(x => x.Email).MaxLength(254);
|
||||
Map(x => x.RegisterNumber).MaxLength(30);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Map of <see cref="ShippingTerm"/> to <c>shipping_terms</c>.</summary>
|
||||
public sealed class ShippingTermMap : EntityMap<ShippingTerm>
|
||||
{
|
||||
/// <summary>Creates the map.</summary>
|
||||
public ShippingTermMap()
|
||||
{
|
||||
ToTable("shipping_terms");
|
||||
Map(x => x.Code).MaxLength(10);
|
||||
Map(x => x.Description).MaxLength(100);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Map of <see cref="TransportMean"/> to <c>transport_means</c>.</summary>
|
||||
public sealed class TransportMeanMap : EntityMap<TransportMean>
|
||||
{
|
||||
/// <summary>Creates the map.</summary>
|
||||
public TransportMeanMap()
|
||||
{
|
||||
ToTable("transport_means");
|
||||
Map(x => x.Code).MaxLength(10);
|
||||
Map(x => x.Description).MaxLength(100);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Map of <see cref="GoodsAppearance"/> to <c>goods_appearances</c>.</summary>
|
||||
public sealed class GoodsAppearanceMap : EntityMap<GoodsAppearance>
|
||||
{
|
||||
/// <summary>Creates the map.</summary>
|
||||
public GoodsAppearanceMap()
|
||||
{
|
||||
ToTable("goods_appearances");
|
||||
Map(x => x.Code).MaxLength(10);
|
||||
Map(x => x.Description).MaxLength(100);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Map of <see cref="DeliveryTerm"/> to <c>delivery_terms</c>.</summary>
|
||||
public sealed class DeliveryTermMap : EntityMap<DeliveryTerm>
|
||||
{
|
||||
/// <summary>Creates the map.</summary>
|
||||
public DeliveryTermMap()
|
||||
{
|
||||
ToTable("delivery_terms");
|
||||
Map(x => x.Code).MaxLength(10);
|
||||
Map(x => x.Description).MaxLength(100);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Map of <see cref="TransportReason"/> to <c>transport_reasons</c>.</summary>
|
||||
public sealed class TransportReasonMap : EntityMap<TransportReason>
|
||||
{
|
||||
/// <summary>Creates the map.</summary>
|
||||
public TransportReasonMap()
|
||||
{
|
||||
ToTable("transport_reasons");
|
||||
Map(x => x.Code).MaxLength(10);
|
||||
Map(x => x.Description).MaxLength(100);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Map of <see cref="InventoryReason"/> to <c>inventory_reasons</c>.</summary>
|
||||
public sealed class InventoryReasonMap : EntityMap<InventoryReason>
|
||||
{
|
||||
/// <summary>Creates the map.</summary>
|
||||
public InventoryReasonMap()
|
||||
{
|
||||
ToTable("inventory_reasons");
|
||||
Map(x => x.Code).MaxLength(10);
|
||||
Map(x => x.Description).MaxLength(100);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Map of <see cref="Warehouse"/> to <c>warehouses</c>.</summary>
|
||||
public sealed class WarehouseMap : EntityMap<Warehouse>
|
||||
{
|
||||
/// <summary>Creates the map.</summary>
|
||||
public WarehouseMap()
|
||||
{
|
||||
ToTable("warehouses");
|
||||
Map(x => x.Code).MaxLength(10);
|
||||
Map(x => x.Description).MaxLength(100);
|
||||
Map(x => x.Address).MaxLength(200);
|
||||
Map(x => x.City).MaxLength(100);
|
||||
Map(x => x.ProvinceCode).MaxLength(2);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Map of <see cref="ItemCategory"/> to <c>item_categories</c>.</summary>
|
||||
public sealed class ItemCategoryMap : EntityMap<ItemCategory>
|
||||
{
|
||||
/// <summary>Creates the map.</summary>
|
||||
public ItemCategoryMap()
|
||||
{
|
||||
ToTable("item_categories");
|
||||
Map(x => x.Code).MaxLength(20);
|
||||
Map(x => x.Description).MaxLength(100);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Map of <see cref="PartyCategory"/> to <c>party_categories</c>.</summary>
|
||||
public sealed class PartyCategoryMap : EntityMap<PartyCategory>
|
||||
{
|
||||
/// <summary>Creates the map.</summary>
|
||||
public PartyCategoryMap()
|
||||
{
|
||||
ToTable("party_categories");
|
||||
Map(x => x.Code).MaxLength(10);
|
||||
Map(x => x.Description).MaxLength(100);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Map of <see cref="PriceList"/> to <c>price_lists</c>.</summary>
|
||||
public sealed class PriceListMap : EntityMap<PriceList>
|
||||
{
|
||||
/// <summary>Creates the map.</summary>
|
||||
public PriceListMap()
|
||||
{
|
||||
ToTable("price_lists");
|
||||
Map(x => x.Code).MaxLength(10);
|
||||
Map(x => x.Description).MaxLength(100);
|
||||
Map(x => x.CurrencyCode).MaxLength(3);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Map of <see cref="DiscountPolicy"/> to <c>discount_policies</c>.</summary>
|
||||
public sealed class DiscountPolicyMap : EntityMap<DiscountPolicy>
|
||||
{
|
||||
/// <summary>Creates the map.</summary>
|
||||
public DiscountPolicyMap()
|
||||
{
|
||||
ToTable("discount_policies");
|
||||
Map(x => x.Code).MaxLength(10);
|
||||
Map(x => x.Description).MaxLength(100);
|
||||
Map(x => x.Formula).MaxLength(60);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Map of <see cref="DocumentNumerator"/> to <c>document_numerators</c>.</summary>
|
||||
public sealed class DocumentNumeratorMap : EntityMap<DocumentNumerator>
|
||||
{
|
||||
/// <summary>Creates the map.</summary>
|
||||
public DocumentNumeratorMap()
|
||||
{
|
||||
ToTable("document_numerators");
|
||||
Map(x => x.Code).MaxLength(10);
|
||||
Map(x => x.Description).MaxLength(100);
|
||||
Map(x => x.Section).MaxLength(10);
|
||||
Map(x => x.Prefix).MaxLength(10);
|
||||
Map(x => x.Format).MaxLength(60);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Map of <see cref="DocumentType"/> to <c>document_types</c>.</summary>
|
||||
public sealed class DocumentTypeMap : EntityMap<DocumentType>
|
||||
{
|
||||
/// <summary>Creates the map.</summary>
|
||||
public DocumentTypeMap()
|
||||
{
|
||||
ToTable("document_types");
|
||||
Map(x => x.Code).MaxLength(10);
|
||||
Map(x => x.Description).MaxLength(100);
|
||||
Map(x => x.EInvoiceType).MaxLength(4);
|
||||
Map(x => x.JournalTemplateCode).MaxLength(10);
|
||||
Map(x => x.VatRegisterCode).MaxLength(10);
|
||||
Map(x => x.PrintTemplate).MaxLength(60);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Map of <see cref="CostCenter"/> to <c>cost_centers</c>.</summary>
|
||||
public sealed class CostCenterMap : EntityMap<CostCenter>
|
||||
{
|
||||
/// <summary>Creates the map.</summary>
|
||||
public CostCenterMap()
|
||||
{
|
||||
ToTable("cost_centers");
|
||||
Map(x => x.Code).MaxLength(20);
|
||||
Map(x => x.Description).MaxLength(100);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Map of <see cref="Job"/> to <c>jobs</c>.</summary>
|
||||
public sealed class JobMap : EntityMap<Job>
|
||||
{
|
||||
/// <summary>Creates the map.</summary>
|
||||
public JobMap()
|
||||
{
|
||||
ToTable("jobs");
|
||||
Map(x => x.Code).MaxLength(20);
|
||||
Map(x => x.Description).MaxLength(100);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Map of <see cref="CodeSequence"/> to <c>code_sequences</c>.</summary>
|
||||
public sealed class CodeSequenceMap : EntityMap<CodeSequence>
|
||||
{
|
||||
/// <summary>Creates the map.</summary>
|
||||
public CodeSequenceMap()
|
||||
{
|
||||
ToTable("code_sequences");
|
||||
Map(x => x.Key).MaxLength(100);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
using Khaemhat.Core.Tax;
|
||||
|
||||
namespace Khaemhat.Fiscal.Abstractions;
|
||||
|
||||
/// <summary>A tax period: a month or a quarter of a year.</summary>
|
||||
/// <param name="Year">The year.</param>
|
||||
/// <param name="Number">The month (1-12) or the quarter (1-4).</param>
|
||||
/// <param name="Periodicity">Monthly or quarterly.</param>
|
||||
/// <param name="Start">The first day.</param>
|
||||
/// <param name="End">The last day.</param>
|
||||
public sealed record TaxPeriod(int Year, int Number, VatPeriodicity Periodicity, DateOnly Start, DateOnly End)
|
||||
{
|
||||
/// <summary>The period of a periodicity that contains a date.</summary>
|
||||
/// <param name="date">The date.</param>
|
||||
/// <param name="periodicity">Monthly or quarterly.</param>
|
||||
/// <returns>The period.</returns>
|
||||
public static TaxPeriod Containing(DateOnly date, VatPeriodicity periodicity) =>
|
||||
periodicity == VatPeriodicity.Monthly
|
||||
? Of(date.Year, date.Month, periodicity)
|
||||
: Of(date.Year, ((date.Month - 1) / 3) + 1, periodicity);
|
||||
|
||||
/// <summary>A period by number.</summary>
|
||||
/// <param name="year">The year.</param>
|
||||
/// <param name="number">The month (1-12) or the quarter (1-4).</param>
|
||||
/// <param name="periodicity">Monthly or quarterly.</param>
|
||||
/// <returns>The period.</returns>
|
||||
public static TaxPeriod Of(int year, int number, VatPeriodicity periodicity)
|
||||
{
|
||||
var months = periodicity == VatPeriodicity.Monthly ? 1 : 3;
|
||||
ArgumentOutOfRangeException.ThrowIfLessThan(number, 1);
|
||||
ArgumentOutOfRangeException.ThrowIfGreaterThan(number, 12 / months);
|
||||
var start = new DateOnly(year, ((number - 1) * months) + 1, 1);
|
||||
return new TaxPeriod(year, number, periodicity, start, start.AddMonths(months).AddDays(-1));
|
||||
}
|
||||
|
||||
/// <summary>Every period of a year.</summary>
|
||||
/// <param name="year">The year.</param>
|
||||
/// <param name="periodicity">Monthly or quarterly.</param>
|
||||
/// <returns>12 months or 4 quarters.</returns>
|
||||
public static IReadOnlyList<TaxPeriod> OfYear(int year, VatPeriodicity periodicity) =>
|
||||
[.. Enumerable.Range(1, periodicity == VatPeriodicity.Monthly ? 12 : 4).Select(n => Of(year, n, periodicity))];
|
||||
|
||||
/// <summary>Whether a date falls in the period.</summary>
|
||||
/// <param name="date">The date.</param>
|
||||
/// <returns><see langword="true"/> inside the period.</returns>
|
||||
public bool Contains(DateOnly date) => date >= Start && date <= End;
|
||||
}
|
||||
|
||||
/// <summary>Tax deadlines and the days on which they move.</summary>
|
||||
public interface IFiscalCalendar
|
||||
{
|
||||
/// <summary>The day by which the VAT of a period must be paid, already moved past holidays.</summary>
|
||||
/// <param name="period">The period.</param>
|
||||
/// <returns>The due date.</returns>
|
||||
DateOnly VatPaymentDue(TaxPeriod period);
|
||||
|
||||
/// <summary>The interest added to the VAT of a period, in percent (Italy: 1% for quarterly payers).</summary>
|
||||
/// <param name="periodicity">Monthly or quarterly.</param>
|
||||
/// <returns>The rate in percent.</returns>
|
||||
decimal VatInterestRate(VatPeriodicity periodicity);
|
||||
|
||||
/// <summary>Whether no tax payment can fall on a day (weekend or public holiday).</summary>
|
||||
/// <param name="day">The day.</param>
|
||||
/// <returns><see langword="true"/> for a non-working day.</returns>
|
||||
bool IsNonWorkingDay(DateOnly day);
|
||||
|
||||
/// <summary>The day itself, or the next working day if it is not one.</summary>
|
||||
/// <param name="day">The day.</param>
|
||||
/// <returns>A working day.</returns>
|
||||
DateOnly NextWorkingDay(DateOnly day);
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
namespace Khaemhat.Fiscal.Abstractions;
|
||||
|
||||
/// <summary>One code of an official code list, such as <c>TD01</c> or <c>MP05</c>.</summary>
|
||||
/// <param name="Code">The code as written in files and messages.</param>
|
||||
/// <param name="Description">The official description, in the country's language.</param>
|
||||
/// <param name="Obsolete">Kept to read old documents; not accepted on new ones.</param>
|
||||
public sealed record CodeListEntry(string Code, string Description, bool Obsolete = false);
|
||||
|
||||
/// <summary>An official code list of a country (document types, payment methods, tax natures...).</summary>
|
||||
public sealed class CodeList
|
||||
{
|
||||
private readonly Dictionary<string, CodeListEntry> _byCode;
|
||||
|
||||
/// <summary>Creates the list.</summary>
|
||||
/// <param name="name">A stable name, such as <c>DocumentTypes</c>.</param>
|
||||
/// <param name="entries">The entries in their official order; codes are unique, compared without case.</param>
|
||||
public CodeList(string name, IEnumerable<CodeListEntry> entries)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(name);
|
||||
ArgumentNullException.ThrowIfNull(entries);
|
||||
Name = name;
|
||||
Entries = [.. entries];
|
||||
_byCode = new Dictionary<string, CodeListEntry>(StringComparer.OrdinalIgnoreCase);
|
||||
foreach (var entry in Entries)
|
||||
{
|
||||
if (!_byCode.TryAdd(entry.Code, entry))
|
||||
{
|
||||
throw new ArgumentException($"Code '{entry.Code}' appears twice in {name}.", nameof(entries));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The name of the list.</summary>
|
||||
public string Name { get; }
|
||||
|
||||
/// <summary>Every entry, obsolete ones included, in the official order.</summary>
|
||||
public IReadOnlyList<CodeListEntry> Entries { get; }
|
||||
|
||||
/// <summary>The entries accepted on new documents.</summary>
|
||||
public IEnumerable<CodeListEntry> Active => Entries.Where(e => !e.Obsolete);
|
||||
|
||||
/// <summary>An entry by code, obsolete ones included.</summary>
|
||||
/// <param name="code">The code, compared without case.</param>
|
||||
/// <returns>The entry, or <see langword="null"/>.</returns>
|
||||
public CodeListEntry? Find(string? code) =>
|
||||
code is not null && _byCode.TryGetValue(code.Trim(), out var entry) ? entry : null;
|
||||
|
||||
/// <summary>Whether a code exists and is accepted on new documents.</summary>
|
||||
/// <param name="code">The code.</param>
|
||||
/// <returns><see langword="true"/> for an active code.</returns>
|
||||
public bool IsActive(string? code) => Find(code) is { Obsolete: false };
|
||||
}
|
||||
|
||||
/// <summary>How serious a <see cref="FiscalProblem"/> is.</summary>
|
||||
public enum FiscalProblemSeverity
|
||||
{
|
||||
/// <summary>The record cannot be saved.</summary>
|
||||
Error = 0,
|
||||
|
||||
/// <summary>The record can be saved, but the user should check it.</summary>
|
||||
Warning = 1,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A rule of the country that a record breaks. <see cref="Code"/> is a stable key (such as
|
||||
/// <c>fiscal.tax.nature-required</c>) that the interface translates; <see cref="Field"/> names the property at fault.
|
||||
/// </summary>
|
||||
/// <param name="Field">The property name, such as <c>Nature</c>.</param>
|
||||
/// <param name="Code">The problem code.</param>
|
||||
/// <param name="Severity">Error or warning.</param>
|
||||
public sealed record FiscalProblem(string Field, string Code, FiscalProblemSeverity Severity = FiscalProblemSeverity.Error);
|
||||
@@ -0,0 +1,273 @@
|
||||
using Khaemhat.Core.Accounting;
|
||||
using Khaemhat.Core.Tax;
|
||||
|
||||
namespace Khaemhat.Fiscal.Abstractions;
|
||||
|
||||
// The optional features of a country pack. Each interface starts with what the current milestone needs and grows with
|
||||
// the milestone that uses it (writer and reader of e-invoices in M9, statements in M10...), see ADR 0025.
|
||||
|
||||
/// <summary>The country's electronic invoice format: version and code lists (Italy: FatturaPA).</summary>
|
||||
public interface IEInvoiceFormat
|
||||
{
|
||||
/// <summary>The name of the format, such as <c>FatturaPA</c>.</summary>
|
||||
string Name { get; }
|
||||
|
||||
/// <summary>The version of the official technical specifications that this pack follows.</summary>
|
||||
string SpecVersion { get; }
|
||||
|
||||
/// <summary>The transmission formats (Italy: <c>FPR12</c>, <c>FPA12</c>, <c>FSM10</c>).</summary>
|
||||
CodeList TransmissionFormats { get; }
|
||||
|
||||
/// <summary>The document types (Italy: <c>TD01</c>...).</summary>
|
||||
CodeList DocumentTypes { get; }
|
||||
|
||||
/// <summary>The payment methods (Italy: <c>MP01</c>...).</summary>
|
||||
CodeList PaymentMethods { get; }
|
||||
|
||||
/// <summary>The payment conditions (Italy: <c>TP01</c>...).</summary>
|
||||
CodeList PaymentConditions { get; }
|
||||
|
||||
/// <summary>The tax regimes of the seller (Italy: <c>RF01</c>...).</summary>
|
||||
CodeList TaxRegimes { get; }
|
||||
}
|
||||
|
||||
/// <summary>A kind of withholding tax the company applies or suffers.</summary>
|
||||
/// <param name="Code">A stable code, such as <c>PROF</c>.</param>
|
||||
/// <param name="Description">The description.</param>
|
||||
/// <param name="Rate">The rate in percent.</param>
|
||||
/// <param name="TaxableBasePercent">The share of the amount the rate applies to, in percent.</param>
|
||||
/// <param name="PaymentCode">The tax payment code (Italy: F24 <c>1040</c>).</param>
|
||||
/// <param name="InvoiceType">The type written in the e-invoice (Italy: <c>RT01</c>).</param>
|
||||
/// <param name="PaymentReason">The default reason written in the e-invoice (Italy: <c>A</c>).</param>
|
||||
public sealed record WithholdingKind(
|
||||
string Code,
|
||||
string Description,
|
||||
decimal Rate,
|
||||
decimal TaxableBasePercent,
|
||||
string PaymentCode,
|
||||
string InvoiceType,
|
||||
string PaymentReason);
|
||||
|
||||
/// <summary>Withholding taxes and social security funds.</summary>
|
||||
public interface IWithholdingRules
|
||||
{
|
||||
/// <summary>The usual kinds of withholding.</summary>
|
||||
IReadOnlyList<WithholdingKind> Kinds { get; }
|
||||
|
||||
/// <summary>The withholding types of the e-invoice (Italy: <c>RT01</c>...).</summary>
|
||||
CodeList InvoiceTypes { get; }
|
||||
|
||||
/// <summary>The payment reasons of the e-invoice (Italy: <c>A</c>, <c>B</c>... <c>ZO</c>).</summary>
|
||||
CodeList PaymentReasons { get; }
|
||||
|
||||
/// <summary>The social security funds (Italy: <c>TC01</c>...).</summary>
|
||||
CodeList SocialSecurityFunds { get; }
|
||||
|
||||
/// <summary>The tax withheld on an amount.</summary>
|
||||
/// <param name="amount">The amount the withholding is computed on (fee, commission).</param>
|
||||
/// <param name="kind">The kind of withholding.</param>
|
||||
/// <returns>The withheld tax, rounded to the cent.</returns>
|
||||
decimal Compute(decimal amount, WithholdingKind kind);
|
||||
}
|
||||
|
||||
/// <summary>Depreciation rules for fixed assets.</summary>
|
||||
public interface IFixedAssetRules
|
||||
{
|
||||
/// <summary>The share of the yearly rate allowed in the first year (Italy: 0.5).</summary>
|
||||
decimal FirstYearFactor { get; }
|
||||
|
||||
/// <summary>The cost up to which an asset may be expensed in one year (Italy: 516.46).</summary>
|
||||
decimal LowValueThreshold { get; }
|
||||
|
||||
/// <summary>The tax limit on the cost of a passenger car (Italy: 18,075.99).</summary>
|
||||
decimal PassengerCarCostLimit { get; }
|
||||
|
||||
/// <summary>The depreciation of one year, never more than what is left to depreciate.</summary>
|
||||
/// <param name="cost">The depreciable cost.</param>
|
||||
/// <param name="ratePercent">The yearly rate in percent.</param>
|
||||
/// <param name="firstYear">Whether this is the first year of use.</param>
|
||||
/// <param name="alreadyDepreciated">The depreciation of the previous years.</param>
|
||||
/// <returns>The depreciation, rounded to the cent.</returns>
|
||||
decimal YearlyDepreciation(decimal cost, decimal ratePercent, bool firstYear, decimal alreadyDepreciated);
|
||||
}
|
||||
|
||||
/// <summary>A tax payment code of the country's payment form (Italy: codice tributo F24).</summary>
|
||||
/// <param name="Code">The code, such as <c>6001</c>.</param>
|
||||
/// <param name="Description">What it pays.</param>
|
||||
public sealed record TaxPaymentCode(string Code, string Description);
|
||||
|
||||
/// <summary>The country's tax payment form (Italy: F24); the file export arrives with the VAT settlement (M7).</summary>
|
||||
public interface ITaxPaymentFormExporter
|
||||
{
|
||||
/// <summary>The name of the form, such as <c>F24</c>.</summary>
|
||||
string FormName { get; }
|
||||
|
||||
/// <summary>The payment codes the product uses.</summary>
|
||||
IReadOnlyList<TaxPaymentCode> Codes { get; }
|
||||
|
||||
/// <summary>The code for the VAT of a period.</summary>
|
||||
/// <param name="period">The period.</param>
|
||||
/// <returns>The payment code.</returns>
|
||||
string VatCode(TaxPeriod period);
|
||||
|
||||
/// <summary>The code for the VAT advance of December.</summary>
|
||||
/// <param name="periodicity">Monthly or quarterly.</param>
|
||||
/// <returns>The payment code.</returns>
|
||||
string VatAdvanceCode(VatPeriodicity periodicity);
|
||||
|
||||
/// <summary>The code for the stamp duty on e-invoices of a quarter.</summary>
|
||||
/// <param name="quarter">The quarter, 1-4.</param>
|
||||
/// <returns>The payment code.</returns>
|
||||
string StampDutyCode(int quarter);
|
||||
}
|
||||
|
||||
/// <summary>Which statement a schema line belongs to.</summary>
|
||||
public enum FinancialStatementKind
|
||||
{
|
||||
/// <summary>Balance sheet (Italy: art. 2424 c.c.).</summary>
|
||||
BalanceSheet = 0,
|
||||
|
||||
/// <summary>Income statement (Italy: art. 2425 c.c.).</summary>
|
||||
IncomeStatement = 1,
|
||||
}
|
||||
|
||||
/// <summary>A line of the legal financial statements.</summary>
|
||||
/// <param name="Code">The code of the line, such as <c>B.II.1</c>.</param>
|
||||
/// <param name="Description">The legal description.</param>
|
||||
/// <param name="ParentCode">The line it adds up into, if any.</param>
|
||||
/// <param name="Postable">Whether accounts can be mapped to it.</param>
|
||||
public sealed record FinancialStatementLine(string Code, string Description, string? ParentCode, bool Postable);
|
||||
|
||||
/// <summary>The legal schema of the financial statements (arrives with the statements, M10).</summary>
|
||||
public interface IFinancialStatementsSchema
|
||||
{
|
||||
/// <summary>The lines of a statement, in legal order.</summary>
|
||||
/// <param name="kind">The statement.</param>
|
||||
/// <returns>The lines.</returns>
|
||||
IReadOnlyList<FinancialStatementLine> Lines(FinancialStatementKind kind);
|
||||
}
|
||||
|
||||
/// <summary>An account of the country's model chart of accounts.</summary>
|
||||
/// <param name="Code">The hierarchical code, such as <c>01.01.001</c>.</param>
|
||||
/// <param name="Description">The description.</param>
|
||||
/// <param name="ParentCode">The parent account, if any.</param>
|
||||
/// <param name="Nature">The statement it ends up in.</param>
|
||||
/// <param name="StatementLine">The financial statement line it maps to, if any.</param>
|
||||
public sealed record AccountTemplate(string Code, string Description, string? ParentCode, AccountNature Nature, string? StatementLine);
|
||||
|
||||
/// <summary>The model chart of accounts loaded into a new company (arrives with the ledger, M7).</summary>
|
||||
public interface IChartOfAccountsTemplate
|
||||
{
|
||||
/// <summary>The name of the model, such as <c>PMI standard</c>.</summary>
|
||||
string Name { get; }
|
||||
|
||||
/// <summary>The accounts, parents before children.</summary>
|
||||
IReadOnlyList<AccountTemplate> Accounts { get; }
|
||||
}
|
||||
|
||||
/// <summary>A line of an Intrastat return.</summary>
|
||||
/// <param name="CountryCode">The country of the counterparty.</param>
|
||||
/// <param name="VatNumber">The VAT number of the counterparty, without country prefix.</param>
|
||||
/// <param name="Amount">The amount in euro.</param>
|
||||
/// <param name="NomenclatureCode">The combined nomenclature code (goods) or CPA code (services).</param>
|
||||
/// <param name="TransactionNature">The nature of the transaction.</param>
|
||||
public sealed record IntrastatLine(string CountryCode, string VatNumber, decimal Amount, string? NomenclatureCode, string? TransactionNature);
|
||||
|
||||
/// <summary>An Intrastat return of a period.</summary>
|
||||
/// <param name="Form">The form, such as <c>INTRA-1 bis</c>.</param>
|
||||
/// <param name="Period">The period.</param>
|
||||
/// <param name="Lines">The lines.</param>
|
||||
public sealed record IntrastatReturn(string Form, TaxPeriod Period, IReadOnlyList<IntrastatLine> Lines);
|
||||
|
||||
/// <summary>Writes Intrastat returns in the customs format (arrives with Intrastat, M10).</summary>
|
||||
public interface IIntrastatExporter
|
||||
{
|
||||
/// <summary>The forms the exporter writes.</summary>
|
||||
IReadOnlyList<string> Forms { get; }
|
||||
|
||||
/// <summary>Writes a return.</summary>
|
||||
/// <param name="intrastatReturn">The return.</param>
|
||||
/// <param name="output">The stream to write to.</param>
|
||||
/// <param name="cancellationToken">Cancels the write.</param>
|
||||
/// <returns>A task that completes when the file is written.</returns>
|
||||
Task WriteAsync(IntrastatReturn intrastatReturn, Stream output, CancellationToken cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>A payment method of the base data.</summary>
|
||||
/// <param name="Code">The code.</param>
|
||||
/// <param name="Description">The description.</param>
|
||||
/// <param name="EInvoiceCode">The code of the e-invoice format.</param>
|
||||
/// <param name="NeedsBank">Whether a bank is needed (transfer, bank receipt, direct debit).</param>
|
||||
public sealed record PaymentMethodTemplate(string Code, string Description, string EInvoiceCode, bool NeedsBank);
|
||||
|
||||
/// <summary>An installment of payment terms of the base data.</summary>
|
||||
/// <param name="Days">Days from the document date.</param>
|
||||
/// <param name="EndOfMonth">Whether the due date moves to the end of the month.</param>
|
||||
/// <param name="Percent">Share of the amount, in percent.</param>
|
||||
public sealed record InstallmentTemplate(int Days, bool EndOfMonth, decimal Percent);
|
||||
|
||||
/// <summary>Payment terms of the base data.</summary>
|
||||
/// <param name="Code">The code.</param>
|
||||
/// <param name="Description">The description.</param>
|
||||
/// <param name="PaymentMethodCode">The payment method (a <see cref="PaymentMethodTemplate.Code"/>).</param>
|
||||
/// <param name="Condition">The condition of the e-invoice format (installments, full, advance).</param>
|
||||
/// <param name="Installments">The installments.</param>
|
||||
public sealed record PaymentTermTemplate(string Code, string Description, string PaymentMethodCode, string Condition, IReadOnlyList<InstallmentTemplate> Installments);
|
||||
|
||||
/// <summary>A document type of the base data.</summary>
|
||||
/// <param name="Code">The code.</param>
|
||||
/// <param name="Description">The description.</param>
|
||||
/// <param name="Kind">The family.</param>
|
||||
/// <param name="NumeratorCode">The numerator of the base data (<c>FAT</c>, <c>DDT</c>...), if the document is numbered by the company.</param>
|
||||
/// <param name="InventoryReasonCode">The warehouse reason of the base data (<c>SCA</c>, <c>CAR</c>...), if the document moves goods.</param>
|
||||
/// <param name="EInvoiceType">The type of the e-invoice format, if the document is sent electronically.</param>
|
||||
public sealed record DocumentTypeTemplate(
|
||||
string Code, string Description, Khaemhat.Core.Tables.NumeratorKind Kind, string? NumeratorCode, string? InventoryReasonCode, string? EInvoiceType);
|
||||
|
||||
/// <summary>
|
||||
/// The rows of the base tables that depend on the country's rules (SPEC §14): payment methods and terms with the codes
|
||||
/// of the e-invoice format, and document types with their electronic type. The rest of the base data is the same in
|
||||
/// every country.
|
||||
/// </summary>
|
||||
public interface IBaseTablesTemplate
|
||||
{
|
||||
/// <summary>The payment methods.</summary>
|
||||
IReadOnlyList<PaymentMethodTemplate> PaymentMethods { get; }
|
||||
|
||||
/// <summary>The payment terms.</summary>
|
||||
IReadOnlyList<PaymentTermTemplate> PaymentTerms { get; }
|
||||
|
||||
/// <summary>The document types.</summary>
|
||||
IReadOnlyList<DocumentTypeTemplate> DocumentTypes { get; }
|
||||
}
|
||||
|
||||
/// <summary>A province (or equivalent first-level area) of the country's official list.</summary>
|
||||
/// <param name="Code">The abbreviation, such as <c>TO</c>.</param>
|
||||
/// <param name="Name">The name.</param>
|
||||
/// <param name="Region">The region.</param>
|
||||
public sealed record ProvinceTemplate(string Code, string Name, string Region);
|
||||
|
||||
/// <summary>A municipality of the country's official list.</summary>
|
||||
/// <param name="Code">The code used by the tax rules (the Italian cadastral code, such as <c>L219</c>).</param>
|
||||
/// <param name="Name">The name.</param>
|
||||
/// <param name="ProvinceCode">The province (a <see cref="ProvinceTemplate.Code"/>).</param>
|
||||
/// <param name="Region">The region.</param>
|
||||
/// <param name="StatisticalCode">The code of the national statistics office, if any.</param>
|
||||
/// <param name="PostalCodes">The postal codes, comma separated, when the list has them.</param>
|
||||
public sealed record MunicipalityTemplate(string Code, string Name, string ProvinceCode, string Region, string? StatisticalCode, string? PostalCodes);
|
||||
|
||||
/// <summary>
|
||||
/// The official list of provinces and municipalities shipped with the pack, loaded into the base tables (ADR 0026,
|
||||
/// ADR 0028). Like the rest of the base data it only adds the codes a company is missing.
|
||||
/// </summary>
|
||||
public interface IPlaceDirectory
|
||||
{
|
||||
/// <summary>Where the list comes from and its date, shown in the documentation and the logs.</summary>
|
||||
string Source { get; }
|
||||
|
||||
/// <summary>The provinces.</summary>
|
||||
IReadOnlyList<ProvinceTemplate> Provinces { get; }
|
||||
|
||||
/// <summary>The municipalities.</summary>
|
||||
IReadOnlyList<MunicipalityTemplate> Municipalities { get; }
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
namespace Khaemhat.Fiscal.Abstractions;
|
||||
|
||||
/// <summary>
|
||||
/// The country packs registered at start-up, found by country code. The composition root registers the concrete packs;
|
||||
/// application code receives this catalog and never names a country's implementation.
|
||||
/// </summary>
|
||||
public sealed class FiscalPackCatalog
|
||||
{
|
||||
private readonly Dictionary<string, IFiscalPack> _byCountry;
|
||||
|
||||
/// <summary>Creates the catalog.</summary>
|
||||
/// <param name="packs">The packs; two packs for the same country are a configuration error.</param>
|
||||
public FiscalPackCatalog(IEnumerable<IFiscalPack> packs)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(packs);
|
||||
_byCountry = new Dictionary<string, IFiscalPack>(StringComparer.OrdinalIgnoreCase);
|
||||
foreach (var pack in packs)
|
||||
{
|
||||
if (!_byCountry.TryAdd(pack.CountryCode, pack))
|
||||
{
|
||||
throw new ArgumentException($"Two fiscal packs for country '{pack.CountryCode}'.", nameof(packs));
|
||||
}
|
||||
}
|
||||
|
||||
Packs = [.. _byCountry.Values.OrderBy(p => p.CountryCode, StringComparer.Ordinal)];
|
||||
}
|
||||
|
||||
/// <summary>Every registered pack, by country code.</summary>
|
||||
public IReadOnlyList<IFiscalPack> Packs { get; }
|
||||
|
||||
/// <summary>The pack of a country.</summary>
|
||||
/// <param name="countryCode">ISO 3166-1 alpha-2 code, case-insensitive.</param>
|
||||
/// <returns>The pack.</returns>
|
||||
/// <exception cref="FiscalPackNotFoundException">No pack for that country.</exception>
|
||||
public IFiscalPack ForCountry(string? countryCode) =>
|
||||
TryForCountry(countryCode, out var pack) ? pack : throw new FiscalPackNotFoundException(countryCode ?? string.Empty);
|
||||
|
||||
/// <summary>The pack of a country, if registered.</summary>
|
||||
/// <param name="countryCode">ISO 3166-1 alpha-2 code, case-insensitive.</param>
|
||||
/// <param name="pack">The pack, when found.</param>
|
||||
/// <returns>Whether a pack was found.</returns>
|
||||
public bool TryForCountry(string? countryCode, out IFiscalPack pack)
|
||||
{
|
||||
if (!string.IsNullOrWhiteSpace(countryCode) && _byCountry.TryGetValue(countryCode.Trim(), out var found))
|
||||
{
|
||||
pack = found;
|
||||
return true;
|
||||
}
|
||||
|
||||
pack = null!;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>No fiscal pack is registered for the country of the company.</summary>
|
||||
public sealed class FiscalPackNotFoundException : Exception
|
||||
{
|
||||
/// <summary>Creates the exception.</summary>
|
||||
public FiscalPackNotFoundException()
|
||||
: this(string.Empty)
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>Creates the exception.</summary>
|
||||
/// <param name="countryCode">The country without a pack.</param>
|
||||
public FiscalPackNotFoundException(string countryCode)
|
||||
: base($"No fiscal pack for country '{countryCode}'.") => CountryCode = countryCode;
|
||||
|
||||
/// <summary>Creates the exception.</summary>
|
||||
/// <param name="message">The message.</param>
|
||||
/// <param name="innerException">The cause.</param>
|
||||
public FiscalPackNotFoundException(string message, Exception innerException)
|
||||
: base(message, innerException) => CountryCode = string.Empty;
|
||||
|
||||
/// <summary>The country without a pack.</summary>
|
||||
public string CountryCode { get; }
|
||||
}
|
||||
@@ -0,0 +1,157 @@
|
||||
namespace Khaemhat.Fiscal.Abstractions;
|
||||
|
||||
/// <summary>
|
||||
/// Everything a country's tax rules contribute (SPEC §1.10, §3, ADR 0007). The rest of the product talks to these
|
||||
/// interfaces only; the country's pack is chosen by <c>company_profile.country</c> through <see cref="FiscalPackCatalog"/>.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Taxes and a calendar exist everywhere, so they are properties. The other features (e-invoicing, withholding taxes,
|
||||
/// Intrastat...) depend on the country and on the milestone that delivers them: ask for them with
|
||||
/// <see cref="GetFeature{T}"/> or <see cref="FiscalPackExtensions.Require{T}(IFiscalPack)"/>.
|
||||
/// </remarks>
|
||||
public interface IFiscalPack
|
||||
{
|
||||
/// <summary>ISO 3166-1 alpha-2 code of the country, such as <c>IT</c>.</summary>
|
||||
string CountryCode { get; }
|
||||
|
||||
/// <summary>The name of the country in the interface language.</summary>
|
||||
string Name { get; }
|
||||
|
||||
/// <summary>The version of the pack's data (code lists, base tables), such as <c>IT 2026.2</c>.</summary>
|
||||
string DataVersion { get; }
|
||||
|
||||
/// <summary>Tax natures, base tax codes and their rules.</summary>
|
||||
ITaxCodeCatalog TaxCodes { get; }
|
||||
|
||||
/// <summary>Tax computation and rounding.</summary>
|
||||
ITaxEngine TaxEngine { get; }
|
||||
|
||||
/// <summary>Tax periods, deadlines and holidays.</summary>
|
||||
IFiscalCalendar Calendar { get; }
|
||||
|
||||
/// <summary>A feature of the pack, or <see langword="null"/> if the country (or this version) has none.</summary>
|
||||
/// <typeparam name="T">The feature interface, such as <see cref="IEInvoiceFormat"/>.</typeparam>
|
||||
/// <returns>The feature, or <see langword="null"/>.</returns>
|
||||
T? GetFeature<T>()
|
||||
where T : class;
|
||||
}
|
||||
|
||||
/// <summary>Helpers over <see cref="IFiscalPack"/>.</summary>
|
||||
public static class FiscalPackExtensions
|
||||
{
|
||||
/// <summary>A feature the caller cannot work without.</summary>
|
||||
/// <typeparam name="T">The feature interface.</typeparam>
|
||||
/// <param name="pack">The pack.</param>
|
||||
/// <returns>The feature.</returns>
|
||||
/// <exception cref="FiscalFeatureNotAvailableException">The pack has no such feature.</exception>
|
||||
public static T Require<T>(this IFiscalPack pack)
|
||||
where T : class
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(pack);
|
||||
return pack.GetFeature<T>() ?? throw new FiscalFeatureNotAvailableException(pack.CountryCode, typeof(T).Name);
|
||||
}
|
||||
|
||||
/// <summary>Whether the pack has a feature.</summary>
|
||||
/// <typeparam name="T">The feature interface.</typeparam>
|
||||
/// <param name="pack">The pack.</param>
|
||||
/// <returns><see langword="true"/> if <see cref="IFiscalPack.GetFeature{T}"/> returns it.</returns>
|
||||
public static bool Supports<T>(this IFiscalPack pack)
|
||||
where T : class
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(pack);
|
||||
return pack.GetFeature<T>() is not null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Base class for country packs: the three mandatory parts plus a table of optional features registered with
|
||||
/// <see cref="AddFeature{T}"/>.
|
||||
/// </summary>
|
||||
public abstract class FiscalPackBase : IFiscalPack
|
||||
{
|
||||
private readonly Dictionary<Type, object> _features = [];
|
||||
|
||||
/// <inheritdoc />
|
||||
public abstract string CountryCode { get; }
|
||||
|
||||
/// <inheritdoc />
|
||||
public abstract string Name { get; }
|
||||
|
||||
/// <inheritdoc />
|
||||
public abstract string DataVersion { get; }
|
||||
|
||||
/// <inheritdoc />
|
||||
public abstract ITaxCodeCatalog TaxCodes { get; }
|
||||
|
||||
/// <inheritdoc />
|
||||
public abstract ITaxEngine TaxEngine { get; }
|
||||
|
||||
/// <inheritdoc />
|
||||
public abstract IFiscalCalendar Calendar { get; }
|
||||
|
||||
/// <inheritdoc />
|
||||
public T? GetFeature<T>()
|
||||
where T : class
|
||||
{
|
||||
object? feature = typeof(T) == typeof(ITaxCodeCatalog) ? TaxCodes
|
||||
: typeof(T) == typeof(ITaxEngine) ? TaxEngine
|
||||
: typeof(T) == typeof(IFiscalCalendar) ? Calendar
|
||||
: _features.GetValueOrDefault(typeof(T));
|
||||
return feature as T;
|
||||
}
|
||||
|
||||
/// <summary>Registers an optional feature; call it from the constructor of the pack.</summary>
|
||||
/// <typeparam name="T">The feature interface.</typeparam>
|
||||
/// <param name="feature">The implementation.</param>
|
||||
protected void AddFeature<T>(T feature)
|
||||
where T : class
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(feature);
|
||||
_features[typeof(T)] = feature;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A feature the country's pack does not provide (yet).</summary>
|
||||
public sealed class FiscalFeatureNotAvailableException : Exception
|
||||
{
|
||||
/// <summary>Creates the exception.</summary>
|
||||
public FiscalFeatureNotAvailableException()
|
||||
: this(string.Empty, string.Empty)
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>Creates the exception.</summary>
|
||||
/// <param name="message">The message.</param>
|
||||
public FiscalFeatureNotAvailableException(string message)
|
||||
: base(message)
|
||||
{
|
||||
CountryCode = string.Empty;
|
||||
Feature = string.Empty;
|
||||
}
|
||||
|
||||
/// <summary>Creates the exception.</summary>
|
||||
/// <param name="message">The message.</param>
|
||||
/// <param name="innerException">The cause.</param>
|
||||
public FiscalFeatureNotAvailableException(string message, Exception innerException)
|
||||
: base(message, innerException)
|
||||
{
|
||||
CountryCode = string.Empty;
|
||||
Feature = string.Empty;
|
||||
}
|
||||
|
||||
/// <summary>Creates the exception.</summary>
|
||||
/// <param name="countryCode">The country of the pack.</param>
|
||||
/// <param name="feature">The name of the missing feature interface.</param>
|
||||
public FiscalFeatureNotAvailableException(string countryCode, string feature)
|
||||
: base($"The fiscal pack for '{countryCode}' has no {feature}.")
|
||||
{
|
||||
CountryCode = countryCode;
|
||||
Feature = feature;
|
||||
}
|
||||
|
||||
/// <summary>The country of the pack.</summary>
|
||||
public string CountryCode { get; }
|
||||
|
||||
/// <summary>The name of the missing feature interface.</summary>
|
||||
public string Feature { get; }
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
namespace Khaemhat.Fiscal.Abstractions;
|
||||
|
||||
/// <summary>The sex written in a personal tax code.</summary>
|
||||
public enum PersonSex
|
||||
{
|
||||
/// <summary>Male.</summary>
|
||||
Male = 0,
|
||||
|
||||
/// <summary>Female.</summary>
|
||||
Female = 1,
|
||||
}
|
||||
|
||||
/// <summary>What a personal tax code is computed from.</summary>
|
||||
/// <param name="Surname">The surname.</param>
|
||||
/// <param name="GivenName">The given name (all given names, as in the registry).</param>
|
||||
/// <param name="BirthDate">The date of birth.</param>
|
||||
/// <param name="Sex">The sex.</param>
|
||||
/// <param name="BirthPlaceCode">The code of the place of birth (Italy: cadastral code of the municipality, or Z... for a foreign country).</param>
|
||||
public sealed record PersonalTaxCodeData(string Surname, string GivenName, DateOnly BirthDate, PersonSex Sex, string BirthPlaceCode);
|
||||
|
||||
/// <summary>What can be read back from a personal tax code.</summary>
|
||||
/// <param name="BirthDate">The date of birth (century guessed from the reference date).</param>
|
||||
/// <param name="Sex">The sex.</param>
|
||||
/// <param name="BirthPlaceCode">The code of the place of birth.</param>
|
||||
public sealed record PersonalTaxCodeInfo(DateOnly BirthDate, PersonSex Sex, string BirthPlaceCode);
|
||||
|
||||
/// <summary>Who receives an e-invoice, for the recipient code rules.</summary>
|
||||
public enum RecipientKind
|
||||
{
|
||||
/// <summary>A business with its own channel, or without (then the default code).</summary>
|
||||
Business = 0,
|
||||
|
||||
/// <summary>A public administration (Italy: office code of 6 characters).</summary>
|
||||
PublicAdministration = 1,
|
||||
|
||||
/// <summary>A private consumer.</summary>
|
||||
Consumer = 2,
|
||||
|
||||
/// <summary>A customer abroad.</summary>
|
||||
Foreign = 3,
|
||||
}
|
||||
|
||||
/// <summary>The country's tax identifiers: VAT number, personal tax code and e-invoice recipient code.</summary>
|
||||
public interface ITaxIdentifierRules
|
||||
{
|
||||
/// <summary>The VAT number without spaces and without the country prefix.</summary>
|
||||
/// <param name="vatNumber">The number as typed.</param>
|
||||
/// <returns>The compact number.</returns>
|
||||
string NormalizeVatNumber(string? vatNumber);
|
||||
|
||||
/// <summary>Whether a domestic VAT number is valid (format and check digit).</summary>
|
||||
/// <param name="vatNumber">The number, with or without prefix.</param>
|
||||
/// <returns><see langword="true"/> when valid.</returns>
|
||||
bool IsValidVatNumber(string? vatNumber);
|
||||
|
||||
/// <summary>Whether a personal or company tax code is valid.</summary>
|
||||
/// <param name="taxCode">The code.</param>
|
||||
/// <returns><see langword="true"/> when valid.</returns>
|
||||
bool IsValidTaxCode(string? taxCode);
|
||||
|
||||
/// <summary>Computes the personal tax code of a person.</summary>
|
||||
/// <param name="data">The personal data.</param>
|
||||
/// <returns>The code.</returns>
|
||||
string ComputePersonalTaxCode(PersonalTaxCodeData data);
|
||||
|
||||
/// <summary>Reads birth date, sex and place back from a personal tax code.</summary>
|
||||
/// <param name="taxCode">The code.</param>
|
||||
/// <param name="today">The reference date that decides the century.</param>
|
||||
/// <returns>The data, or <see langword="null"/> if the code is not a valid personal code.</returns>
|
||||
PersonalTaxCodeInfo? DecodePersonalTaxCode(string? taxCode, DateOnly today);
|
||||
|
||||
/// <summary>The rules an e-invoice recipient code breaks for a kind of customer; empty when valid.</summary>
|
||||
/// <param name="recipientCode">The code.</param>
|
||||
/// <param name="kind">The kind of customer.</param>
|
||||
/// <returns>Errors and warnings with field <c>RecipientCode</c>.</returns>
|
||||
IReadOnlyList<FiscalProblem> CheckRecipientCode(string? recipientCode, RecipientKind kind);
|
||||
|
||||
/// <summary>The recipient code to propose for a kind of customer without one.</summary>
|
||||
/// <param name="kind">The kind of customer.</param>
|
||||
/// <returns>The default code, or <see langword="null"/> if the customer must give one.</returns>
|
||||
string? DefaultRecipientCode(RecipientKind kind);
|
||||
}
|
||||
|
||||
/// <summary>A bank found from its national code.</summary>
|
||||
/// <param name="BankCode">The national bank code (Italy: ABI).</param>
|
||||
/// <param name="Name">The name of the bank, <see langword="null"/> when the directory does not know it.</param>
|
||||
/// <param name="Bic">The BIC, when known.</param>
|
||||
/// <param name="BranchCode">The branch code (Italy: CAB), when the IBAN has one.</param>
|
||||
public sealed record BankInfo(string BankCode, string? Name, string? Bic, string? BranchCode);
|
||||
|
||||
/// <summary>The country's directory of banks, to fill bank name and BIC from an IBAN.</summary>
|
||||
public interface IBankDirectory
|
||||
{
|
||||
/// <summary>The bank of a domestic IBAN.</summary>
|
||||
/// <param name="iban">The IBAN.</param>
|
||||
/// <returns>The bank, or <see langword="null"/> if the IBAN is foreign, invalid or the bank unknown.</returns>
|
||||
BankInfo? FindByIban(string? iban);
|
||||
|
||||
/// <summary>The bank and branch codes of a domestic IBAN, with name and BIC when the directory knows the bank.</summary>
|
||||
/// <param name="iban">The IBAN.</param>
|
||||
/// <returns>The codes, or <see langword="null"/> if the IBAN is foreign or invalid.</returns>
|
||||
BankInfo? ReadIban(string? iban);
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
using Khaemhat.Core.Tax;
|
||||
|
||||
namespace Khaemhat.Fiscal.Abstractions;
|
||||
|
||||
/// <summary>
|
||||
/// The fiscal content of a tax code (SPEC §11.1, mockup 076): the parts the country's rules check. The table
|
||||
/// <c>tax_codes</c> adds validity, accounts and the other company data.
|
||||
/// </summary>
|
||||
/// <param name="Code">The company's code, such as <c>22</c> or <c>NI8</c>.</param>
|
||||
/// <param name="Description">The description shown on documents.</param>
|
||||
/// <param name="Rate">The rate in percent, such as 22.</param>
|
||||
/// <param name="Nature">The country's nature code for zero-rate operations (Italy: <c>N1</c>...<c>N7</c>).</param>
|
||||
/// <param name="Exigibility">When the tax becomes due.</param>
|
||||
/// <param name="NonDeductiblePercent">Share of the purchase tax that cannot be deducted, 0-100.</param>
|
||||
/// <param name="LegalReference">The law the operation is based on, printed on the invoice.</param>
|
||||
public sealed record TaxCodeDefinition(
|
||||
string Code,
|
||||
string Description,
|
||||
decimal Rate,
|
||||
string? Nature = null,
|
||||
TaxExigibility Exigibility = TaxExigibility.Immediate,
|
||||
decimal NonDeductiblePercent = 0m,
|
||||
string? LegalReference = null);
|
||||
|
||||
/// <summary>The country's tax natures and base tax codes, and the rules a tax code must follow.</summary>
|
||||
public interface ITaxCodeCatalog
|
||||
{
|
||||
/// <summary>The nature codes for operations without tax.</summary>
|
||||
CodeList Natures { get; }
|
||||
|
||||
/// <summary>The tax codes loaded by the base data (SPEC §14).</summary>
|
||||
IReadOnlyList<TaxCodeDefinition> BaseCodes { get; }
|
||||
|
||||
/// <summary>The kind of operation a rate and nature describe.</summary>
|
||||
/// <param name="rate">The rate in percent.</param>
|
||||
/// <param name="nature">The nature code, if any.</param>
|
||||
/// <returns>The kind.</returns>
|
||||
TaxCodeKind KindOf(decimal rate, string? nature);
|
||||
|
||||
/// <summary>The rules a tax code breaks; empty when it is valid.</summary>
|
||||
/// <param name="code">The tax code.</param>
|
||||
/// <returns>Errors and warnings.</returns>
|
||||
IReadOnlyList<FiscalProblem> Validate(TaxCodeDefinition code);
|
||||
}
|
||||
|
||||
/// <summary>An amount of a document subject to one tax code.</summary>
|
||||
/// <param name="Amount">The taxable amount, already net of discounts.</param>
|
||||
/// <param name="Rate">The rate in percent.</param>
|
||||
/// <param name="Nature">The nature code for zero-rate operations.</param>
|
||||
/// <param name="Exigibility">When the tax becomes due.</param>
|
||||
/// <param name="NonDeductiblePercent">Share of the tax that cannot be deducted (purchases).</param>
|
||||
public sealed record TaxableAmount(
|
||||
decimal Amount,
|
||||
decimal Rate,
|
||||
string? Nature = null,
|
||||
TaxExigibility Exigibility = TaxExigibility.Immediate,
|
||||
decimal NonDeductiblePercent = 0m);
|
||||
|
||||
/// <summary>One line of the tax summary of a document (castelletto IVA).</summary>
|
||||
/// <param name="Rate">The rate in percent.</param>
|
||||
/// <param name="Nature">The nature code, if any.</param>
|
||||
/// <param name="Exigibility">When the tax becomes due.</param>
|
||||
/// <param name="NonDeductiblePercent">Share of the tax that cannot be deducted.</param>
|
||||
/// <param name="Taxable">The sum of the taxable amounts.</param>
|
||||
/// <param name="Tax">The tax, rounded to the cent.</param>
|
||||
/// <param name="NonDeductibleTax">The part of <paramref name="Tax"/> that cannot be deducted.</param>
|
||||
public sealed record TaxSummaryLine(
|
||||
decimal Rate,
|
||||
string? Nature,
|
||||
TaxExigibility Exigibility,
|
||||
decimal NonDeductiblePercent,
|
||||
decimal Taxable,
|
||||
decimal Tax,
|
||||
decimal NonDeductibleTax);
|
||||
|
||||
/// <summary>Whether a document needs stamp duty, and how much.</summary>
|
||||
/// <param name="Required">The document must carry the duty.</param>
|
||||
/// <param name="Amount">The duty, zero when not required.</param>
|
||||
/// <param name="ExemptTotal">The sum of the amounts without tax that the rule counts.</param>
|
||||
/// <param name="Threshold">The amount above which the duty is due.</param>
|
||||
public sealed record StampDutyAssessment(bool Required, decimal Amount, decimal ExemptTotal, decimal Threshold);
|
||||
|
||||
/// <summary>Tax computation with the country's rounding rules.</summary>
|
||||
public interface ITaxEngine
|
||||
{
|
||||
/// <summary>Rounds an amount of money as the country's tax rules require.</summary>
|
||||
/// <param name="amount">The amount.</param>
|
||||
/// <returns>The amount rounded to the cent.</returns>
|
||||
decimal Round(decimal amount);
|
||||
|
||||
/// <summary>The tax on a taxable amount.</summary>
|
||||
/// <param name="taxable">The taxable amount.</param>
|
||||
/// <param name="rate">The rate in percent.</param>
|
||||
/// <returns>The tax, rounded.</returns>
|
||||
decimal ComputeTax(decimal taxable, decimal rate);
|
||||
|
||||
/// <summary>
|
||||
/// The tax summary of a document: one line per rate, nature, exigibility and non-deductible share, with the tax
|
||||
/// computed on the total of the line (not summed from the rows).
|
||||
/// </summary>
|
||||
/// <param name="amounts">The taxable amounts of the document rows.</param>
|
||||
/// <returns>The summary lines, by rate (highest first) and then by nature.</returns>
|
||||
IReadOnlyList<TaxSummaryLine> Summarize(IEnumerable<TaxableAmount> amounts);
|
||||
|
||||
/// <summary>Whether the document needs stamp duty.</summary>
|
||||
/// <param name="summary">The tax summary of the document.</param>
|
||||
/// <returns>The assessment.</returns>
|
||||
StampDutyAssessment AssessStampDuty(IEnumerable<TaxSummaryLine> summary);
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
sigla;denominazione;regione
|
||||
AG;Agrigento;Sicilia
|
||||
AL;Alessandria;Piemonte
|
||||
AN;Ancona;Marche
|
||||
AO;Valle d'Aosta/Vallée d'Aoste;Valle d'Aosta/Vallée d'Aoste
|
||||
AP;Ascoli Piceno;Marche
|
||||
AQ;L'Aquila;Abruzzo
|
||||
AR;Arezzo;Toscana
|
||||
AT;Asti;Piemonte
|
||||
AV;Avellino;Campania
|
||||
BA;Bari;Puglia
|
||||
BG;Bergamo;Lombardia
|
||||
BI;Biella;Piemonte
|
||||
BL;Belluno;Veneto
|
||||
BN;Benevento;Campania
|
||||
BO;Bologna;Emilia-Romagna
|
||||
BR;Brindisi;Puglia
|
||||
BS;Brescia;Lombardia
|
||||
BT;Barletta-Andria-Trani;Puglia
|
||||
BZ;Bolzano/Bozen;Trentino-Alto Adige/Südtirol
|
||||
CA;Cagliari;Sardegna
|
||||
CB;Campobasso;Molise
|
||||
CE;Caserta;Campania
|
||||
CH;Chieti;Abruzzo
|
||||
CI;Sulcis Iglesiente;Sardegna
|
||||
CL;Caltanissetta;Sicilia
|
||||
CN;Cuneo;Piemonte
|
||||
CO;Como;Lombardia
|
||||
CR;Cremona;Lombardia
|
||||
CS;Cosenza;Calabria
|
||||
CT;Catania;Sicilia
|
||||
CZ;Catanzaro;Calabria
|
||||
EN;Enna;Sicilia
|
||||
FC;Forlì-Cesena;Emilia-Romagna
|
||||
FE;Ferrara;Emilia-Romagna
|
||||
FG;Foggia;Puglia
|
||||
FI;Firenze;Toscana
|
||||
FM;Fermo;Marche
|
||||
FR;Frosinone;Lazio
|
||||
GE;Genova;Liguria
|
||||
GO;Gorizia;Friuli-Venezia Giulia
|
||||
GR;Grosseto;Toscana
|
||||
IM;Imperia;Liguria
|
||||
IS;Isernia;Molise
|
||||
KR;Crotone;Calabria
|
||||
LC;Lecco;Lombardia
|
||||
LE;Lecce;Puglia
|
||||
LI;Livorno;Toscana
|
||||
LO;Lodi;Lombardia
|
||||
LT;Latina;Lazio
|
||||
LU;Lucca;Toscana
|
||||
MB;Monza e della Brianza;Lombardia
|
||||
MC;Macerata;Marche
|
||||
ME;Messina;Sicilia
|
||||
MI;Milano;Lombardia
|
||||
MN;Mantova;Lombardia
|
||||
MO;Modena;Emilia-Romagna
|
||||
MS;Massa-Carrara;Toscana
|
||||
MT;Matera;Basilicata
|
||||
NA;Napoli;Campania
|
||||
NO;Novara;Piemonte
|
||||
NU;Nuoro;Sardegna
|
||||
OG;Ogliastra;Sardegna
|
||||
OR;Oristano;Sardegna
|
||||
OT;Gallura Nord-Est Sardegna;Sardegna
|
||||
PA;Palermo;Sicilia
|
||||
PC;Piacenza;Emilia-Romagna
|
||||
PD;Padova;Veneto
|
||||
PE;Pescara;Abruzzo
|
||||
PG;Perugia;Umbria
|
||||
PI;Pisa;Toscana
|
||||
PN;Pordenone;Friuli-Venezia Giulia
|
||||
PO;Prato;Toscana
|
||||
PR;Parma;Emilia-Romagna
|
||||
PT;Pistoia;Toscana
|
||||
PU;Pesaro e Urbino;Marche
|
||||
PV;Pavia;Lombardia
|
||||
PZ;Potenza;Basilicata
|
||||
RA;Ravenna;Emilia-Romagna
|
||||
RC;Reggio Calabria;Calabria
|
||||
RE;Reggio nell'Emilia;Emilia-Romagna
|
||||
RG;Ragusa;Sicilia
|
||||
RI;Rieti;Lazio
|
||||
RM;Roma;Lazio
|
||||
RN;Rimini;Emilia-Romagna
|
||||
RO;Rovigo;Veneto
|
||||
SA;Salerno;Campania
|
||||
SI;Siena;Toscana
|
||||
SO;Sondrio;Lombardia
|
||||
SP;La Spezia;Liguria
|
||||
SR;Siracusa;Sicilia
|
||||
SS;Sassari;Sardegna
|
||||
SV;Savona;Liguria
|
||||
TA;Taranto;Puglia
|
||||
TE;Teramo;Abruzzo
|
||||
TN;Trento;Trentino-Alto Adige/Südtirol
|
||||
TO;Torino;Piemonte
|
||||
TP;Trapani;Sicilia
|
||||
TR;Terni;Umbria
|
||||
TS;Trieste;Friuli-Venezia Giulia
|
||||
TV;Treviso;Veneto
|
||||
UD;Udine;Friuli-Venezia Giulia
|
||||
VA;Varese;Lombardia
|
||||
VB;Verbano-Cusio-Ossola;Piemonte
|
||||
VC;Vercelli;Piemonte
|
||||
VE;Venezia;Veneto
|
||||
VI;Vicenza;Veneto
|
||||
VR;Verona;Veneto
|
||||
VS;Medio Campidano;Sardegna
|
||||
VT;Viterbo;Lazio
|
||||
VV;Vibo Valentia;Calabria
|
||||
|
@@ -0,0 +1,198 @@
|
||||
using Khaemhat.Fiscal.Abstractions;
|
||||
|
||||
namespace Khaemhat.Fiscal.Italy;
|
||||
|
||||
/// <summary>
|
||||
/// The code lists of the FatturaPA technical specifications of the Agenzia delle Entrate (SPEC §11.9). Descriptions
|
||||
/// follow the official tables, shortened where the official text runs to several lines.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <see cref="SpecVersion"/> is the version checked at each release (ADR 0025): 1.9 (in force from 1 April 2025)
|
||||
/// added TD29 and redefined TD20; 1.9.1 (published 31 March 2026, in force from 15 May 2026) changed no code list.
|
||||
/// </remarks>
|
||||
public static class FatturaPaCodeLists
|
||||
{
|
||||
/// <summary>The version of the technical specifications that this pack follows.</summary>
|
||||
public const string SpecVersion = "1.9.1";
|
||||
|
||||
/// <summary>The date from which <see cref="SpecVersion"/> is in force.</summary>
|
||||
public static readonly DateOnly SpecInForceFrom = new(2026, 5, 15);
|
||||
|
||||
/// <summary>Transmission formats (<c>FormatoTrasmissione</c>).</summary>
|
||||
public static CodeList TransmissionFormats { get; } = new("TransmissionFormats",
|
||||
[
|
||||
new("FPA12", "Fattura verso pubbliche amministrazioni"),
|
||||
new("FPR12", "Fattura verso privati"),
|
||||
new("FSM10", "Fattura semplificata"),
|
||||
]);
|
||||
|
||||
/// <summary>Document types (<c>TipoDocumento</c>).</summary>
|
||||
public static CodeList DocumentTypes { get; } = new("DocumentTypes",
|
||||
[
|
||||
new("TD01", "Fattura"),
|
||||
new("TD02", "Acconto/anticipo su fattura"),
|
||||
new("TD03", "Acconto/anticipo su parcella"),
|
||||
new("TD04", "Nota di credito"),
|
||||
new("TD05", "Nota di debito"),
|
||||
new("TD06", "Parcella"),
|
||||
new("TD07", "Fattura semplificata"),
|
||||
new("TD08", "Nota di credito semplificata"),
|
||||
new("TD09", "Nota di debito semplificata"),
|
||||
new("TD16", "Integrazione fattura reverse charge interno"),
|
||||
new("TD17", "Integrazione/autofattura per acquisto servizi dall'estero"),
|
||||
new("TD18", "Integrazione per acquisto di beni intracomunitari"),
|
||||
new("TD19", "Integrazione/autofattura per acquisto di beni ex art. 17 c. 2 DPR 633/72"),
|
||||
new("TD20", "Autofattura per regolarizzazione e integrazione delle fatture (art. 6 c. 8 e 9-bis D.Lgs. 471/97 o art. 46 c. 5 DL 331/93)"),
|
||||
new("TD21", "Autofattura per splafonamento"),
|
||||
new("TD22", "Estrazione beni da deposito IVA"),
|
||||
new("TD23", "Estrazione beni da deposito IVA con versamento dell'IVA"),
|
||||
new("TD24", "Fattura differita di cui all'art. 21 c. 4 lett. a) DPR 633/72"),
|
||||
new("TD25", "Fattura differita di cui all'art. 21 c. 4 terzo periodo lett. b) DPR 633/72"),
|
||||
new("TD26", "Cessione di beni ammortizzabili e per passaggi interni (art. 36 DPR 633/72)"),
|
||||
new("TD27", "Fattura per autoconsumo o per cessioni gratuite senza rivalsa"),
|
||||
new("TD28", "Acquisti da San Marino con IVA (fattura cartacea)"),
|
||||
new("TD29", "Comunicazione per omessa o irregolare fatturazione (art. 6 c. 8 D.Lgs. 471/97)"),
|
||||
]);
|
||||
|
||||
/// <summary>Document types accepted only in the simplified format <c>FSM10</c>.</summary>
|
||||
public static IReadOnlySet<string> SimplifiedDocumentTypes { get; } = new HashSet<string>(StringComparer.Ordinal) { "TD07", "TD08", "TD09" };
|
||||
|
||||
/// <summary>Payment methods (<c>ModalitaPagamento</c>).</summary>
|
||||
public static CodeList PaymentMethods { get; } = new("PaymentMethods",
|
||||
[
|
||||
new("MP01", "Contanti"),
|
||||
new("MP02", "Assegno"),
|
||||
new("MP03", "Assegno circolare"),
|
||||
new("MP04", "Contanti presso Tesoreria"),
|
||||
new("MP05", "Bonifico"),
|
||||
new("MP06", "Vaglia cambiario"),
|
||||
new("MP07", "Bollettino bancario"),
|
||||
new("MP08", "Carta di pagamento"),
|
||||
new("MP09", "RID"),
|
||||
new("MP10", "RID utenze"),
|
||||
new("MP11", "RID veloce"),
|
||||
new("MP12", "RIBA"),
|
||||
new("MP13", "MAV"),
|
||||
new("MP14", "Quietanza erario"),
|
||||
new("MP15", "Giroconto su conti di contabilità speciale"),
|
||||
new("MP16", "Domiciliazione bancaria"),
|
||||
new("MP17", "Domiciliazione postale"),
|
||||
new("MP18", "Bollettino di c/c postale"),
|
||||
new("MP19", "SEPA Direct Debit"),
|
||||
new("MP20", "SEPA Direct Debit CORE"),
|
||||
new("MP21", "SEPA Direct Debit B2B"),
|
||||
new("MP22", "Trattenuta su somme già riscosse"),
|
||||
new("MP23", "PagoPA"),
|
||||
]);
|
||||
|
||||
/// <summary>Payment conditions (<c>CondizioniPagamento</c>).</summary>
|
||||
public static CodeList PaymentConditions { get; } = new("PaymentConditions",
|
||||
[
|
||||
new("TP01", "Pagamento a rate"),
|
||||
new("TP02", "Pagamento completo"),
|
||||
new("TP03", "Anticipo"),
|
||||
]);
|
||||
|
||||
/// <summary>Tax regimes of the seller (<c>RegimeFiscale</c>); RF03 no longer exists.</summary>
|
||||
public static CodeList TaxRegimes { get; } = new("TaxRegimes",
|
||||
[
|
||||
new("RF01", "Ordinario"),
|
||||
new("RF02", "Contribuenti minimi (art. 1 c. 96-117 L. 244/2007)"),
|
||||
new("RF03", "Nuove iniziative produttive (abrogato)", Obsolete: true),
|
||||
new("RF04", "Agricoltura e attività connesse e pesca (artt. 34 e 34-bis DPR 633/72)"),
|
||||
new("RF05", "Vendita sali e tabacchi (art. 74 c. 1 DPR 633/72)"),
|
||||
new("RF06", "Commercio dei fiammiferi (art. 74 c. 1 DPR 633/72)"),
|
||||
new("RF07", "Editoria (art. 74 c. 1 DPR 633/72)"),
|
||||
new("RF08", "Gestione di servizi di telefonia pubblica (art. 74 c. 1 DPR 633/72)"),
|
||||
new("RF09", "Rivendita di documenti di trasporto pubblico e di sosta (art. 74 c. 1 DPR 633/72)"),
|
||||
new("RF10", "Intrattenimenti, giochi e altre attività di cui alla tariffa allegata al DPR 640/72 (art. 74 c. 6 DPR 633/72)"),
|
||||
new("RF11", "Agenzie di viaggi e turismo (art. 74-ter DPR 633/72)"),
|
||||
new("RF12", "Agriturismo (art. 5 c. 2 L. 413/91)"),
|
||||
new("RF13", "Vendite a domicilio (art. 25-bis c. 6 DPR 600/73)"),
|
||||
new("RF14", "Rivendita di beni usati, oggetti d'arte, d'antiquariato o da collezione (art. 36 DL 41/95)"),
|
||||
new("RF15", "Agenzie di vendite all'asta di oggetti d'arte, antiquariato o da collezione (art. 40-bis DL 41/95)"),
|
||||
new("RF16", "IVA per cassa P.A. (art. 6 c. 5 DPR 633/72)"),
|
||||
new("RF17", "IVA per cassa (art. 32-bis DL 83/2012)"),
|
||||
new("RF18", "Altro"),
|
||||
new("RF19", "Regime forfettario (art. 1 c. 54-89 L. 190/2014)"),
|
||||
]);
|
||||
|
||||
/// <summary>Withholding types (<c>TipoRitenuta</c>).</summary>
|
||||
public static CodeList WithholdingTypes { get; } = new("WithholdingTypes",
|
||||
[
|
||||
new("RT01", "Ritenuta persone fisiche"),
|
||||
new("RT02", "Ritenuta persone giuridiche"),
|
||||
new("RT03", "Contributo INPS"),
|
||||
new("RT04", "Contributo ENASARCO"),
|
||||
new("RT05", "Contributo ENPAM"),
|
||||
new("RT06", "Altro contributo previdenziale"),
|
||||
]);
|
||||
|
||||
/// <summary>Payment reasons of the withholding (<c>CausalePagamento</c>, as in the CU form).</summary>
|
||||
public static CodeList WithholdingReasons { get; } = new("WithholdingReasons",
|
||||
[
|
||||
new("A", "Prestazioni di lavoro autonomo rientranti nell'esercizio di arte o professione abituale"),
|
||||
new("B", "Utilizzazione economica, da parte dell'autore o dell'inventore, di opere dell'ingegno"),
|
||||
new("C", "Utili derivanti da contratti di associazione in partecipazione e cointeressenza (solo apporto di lavoro)"),
|
||||
new("D", "Utili spettanti ai soci promotori e ai soci fondatori delle società di capitali"),
|
||||
new("E", "Levata di protesti cambiari da parte dei segretari comunali"),
|
||||
new("G", "Indennità corrisposte per la cessazione di attività sportiva professionale"),
|
||||
new("H", "Indennità corrisposte per la cessazione dei rapporti di agenzia"),
|
||||
new("I", "Indennità corrisposte per la cessazione da funzioni notarili"),
|
||||
new("L", "Utilizzazione economica di opere dell'ingegno da parte di soggetto diverso dall'autore"),
|
||||
new("L1", "Redditi da utilizzazione economica di opere dell'ingegno acquisiti a titolo oneroso"),
|
||||
new("M", "Prestazioni di lavoro autonomo non esercitate abitualmente"),
|
||||
new("M1", "Redditi derivanti dall'assunzione di obblighi di fare, non fare o permettere"),
|
||||
new("M2", "Prestazioni di lavoro autonomo non esercitate abitualmente con obbligo di iscrizione alla Gestione Separata ENPAPI"),
|
||||
new("N", "Indennità di trasferta, rimborsi forfetari, premi e compensi nell'esercizio diretto di attività sportive dilettantistiche"),
|
||||
new("O", "Prestazioni di lavoro autonomo non esercitate abitualmente, senza obbligo di iscrizione alla gestione separata"),
|
||||
new("O1", "Redditi da obblighi di fare, non fare o permettere, senza obbligo di iscrizione alla gestione separata"),
|
||||
new("P", "Compensi a soggetti non residenti privi di stabile organizzazione per l'uso di attrezzature"),
|
||||
new("Q", "Provvigioni ad agente o rappresentante di commercio monomandatario"),
|
||||
new("R", "Provvigioni ad agente o rappresentante di commercio plurimandatario"),
|
||||
new("S", "Provvigioni a commissionario"),
|
||||
new("T", "Provvigioni a mediatore"),
|
||||
new("U", "Provvigioni a procacciatore di affari"),
|
||||
new("V", "Provvigioni a incaricato per le vendite a domicilio o porta a porta"),
|
||||
new("V1", "Redditi derivanti da attività commerciali non esercitate abitualmente"),
|
||||
new("V2", "Prestazioni non esercitate abitualmente rese dagli incaricati alla vendita diretta a domicilio"),
|
||||
new("W", "Corrispettivi per prestazioni relative a contratti d'appalto (art. 25-ter DPR 600/73)"),
|
||||
new("X", "Canoni corrisposti nel 2004 da società o enti residenti (art. 26-quater DPR 600/73)"),
|
||||
new("Y", "Canoni corrisposti dal 2005 da società o enti residenti (art. 26-quater DPR 600/73)"),
|
||||
new("Z", "Titolo diverso dai precedenti (sostituito da ZO)", Obsolete: true),
|
||||
new("ZO", "Titolo diverso dai precedenti"),
|
||||
]);
|
||||
|
||||
/// <summary>Social security funds (<c>TipoCassa</c>).</summary>
|
||||
public static CodeList SocialSecurityFunds { get; } = new("SocialSecurityFunds",
|
||||
[
|
||||
new("TC01", "Cassa nazionale previdenza e assistenza avvocati e procuratori legali"),
|
||||
new("TC02", "Cassa previdenza dottori commercialisti"),
|
||||
new("TC03", "Cassa previdenza e assistenza geometri"),
|
||||
new("TC04", "Cassa nazionale previdenza e assistenza ingegneri e architetti liberi professionisti"),
|
||||
new("TC05", "Cassa nazionale del notariato"),
|
||||
new("TC06", "Cassa nazionale previdenza e assistenza ragionieri e periti commerciali"),
|
||||
new("TC07", "Ente nazionale assistenza agenti e rappresentanti di commercio (ENASARCO)"),
|
||||
new("TC08", "Ente nazionale previdenza e assistenza consulenti del lavoro (ENPACL)"),
|
||||
new("TC09", "Ente nazionale previdenza e assistenza medici (ENPAM)"),
|
||||
new("TC10", "Ente nazionale previdenza e assistenza farmacisti (ENPAF)"),
|
||||
new("TC11", "Ente nazionale previdenza e assistenza veterinari (ENPAV)"),
|
||||
new("TC12", "Ente nazionale previdenza e assistenza impiegati dell'agricoltura (ENPAIA)"),
|
||||
new("TC13", "Fondo previdenza impiegati imprese di spedizione e agenzie marittime"),
|
||||
new("TC14", "Istituto nazionale previdenza giornalisti italiani (INPGI)"),
|
||||
new("TC15", "Opera nazionale assistenza orfani sanitari italiani (ONAOSI)"),
|
||||
new("TC16", "Cassa autonoma assistenza integrativa giornalisti italiani (CASAGIT)"),
|
||||
new("TC17", "Ente previdenza periti industriali e periti industriali laureati (EPPI)"),
|
||||
new("TC18", "Ente previdenza e assistenza pluricategoriale (EPAP)"),
|
||||
new("TC19", "Ente nazionale previdenza e assistenza biologi (ENPAB)"),
|
||||
new("TC20", "Ente nazionale previdenza e assistenza professione infermieristica (ENPAPI)"),
|
||||
new("TC21", "Ente nazionale previdenza e assistenza psicologi (ENPAP)"),
|
||||
new("TC22", "INPS"),
|
||||
]);
|
||||
|
||||
/// <summary>Recipient code for consumers and companies without a channel.</summary>
|
||||
public const string RecipientCodeNone = "0000000";
|
||||
|
||||
/// <summary>Recipient code for foreign customers.</summary>
|
||||
public const string RecipientCodeForeign = "XXXXXXX";
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
using Khaemhat.Core.Tables;
|
||||
using Khaemhat.Fiscal.Abstractions;
|
||||
|
||||
namespace Khaemhat.Fiscal.Italy;
|
||||
|
||||
/// <summary>
|
||||
/// The Italian rows of the base tables (SPEC §14): payment methods with the FatturaPA codes MP, the usual payment terms
|
||||
/// (rimessa diretta, bonifico, RiBa at 30/60/90 days end of month) and the document types with their SDI type TD.
|
||||
/// </summary>
|
||||
public sealed class ItalianBaseTables : IBaseTablesTemplate
|
||||
{
|
||||
private static readonly InstallmentTemplate Now = new(0, false, 100m);
|
||||
|
||||
/// <inheritdoc />
|
||||
public IReadOnlyList<PaymentMethodTemplate> PaymentMethods { get; } =
|
||||
[
|
||||
new("CONT", "Contanti", "MP01", false),
|
||||
new("ASS", "Assegno", "MP02", false),
|
||||
new("BON", "Bonifico bancario", "MP05", true),
|
||||
new("CARTA", "Carta di pagamento", "MP08", false),
|
||||
new("RIBA", "Ricevuta bancaria (RiBa)", "MP12", true),
|
||||
new("MAV", "MAV", "MP13", true),
|
||||
new("DOM", "Domiciliazione bancaria", "MP16", true),
|
||||
new("SDD", "Addebito diretto SEPA (SDD Core)", "MP20", true),
|
||||
new("SDDB", "Addebito diretto SEPA B2B", "MP21", true),
|
||||
new("PAGOPA", "PagoPA", "MP23", false),
|
||||
];
|
||||
|
||||
/// <inheritdoc />
|
||||
public IReadOnlyList<PaymentTermTemplate> PaymentTerms { get; } =
|
||||
[
|
||||
new("RD", "Rimessa diretta", "BON", "TP02", [Now]),
|
||||
new("CONT", "Contanti alla consegna", "CONT", "TP02", [Now]),
|
||||
new("ANT", "Pagamento anticipato", "BON", "TP03", [Now]),
|
||||
new("BB30", "Bonifico 30 gg data fattura", "BON", "TP02", [new(30, false, 100m)]),
|
||||
new("BB30FM", "Bonifico 30 gg fine mese", "BON", "TP02", [new(30, true, 100m)]),
|
||||
new("BB60FM", "Bonifico 60 gg fine mese", "BON", "TP02", [new(60, true, 100m)]),
|
||||
new("BB3060FM", "Bonifico 30-60 gg fine mese", "BON", "TP01", [new(30, true, 50m), new(60, true, 50m)]),
|
||||
new("RB30FM", "RiBa 30 gg fine mese", "RIBA", "TP02", [new(30, true, 100m)]),
|
||||
new("RB60FM", "RiBa 60 gg fine mese", "RIBA", "TP02", [new(60, true, 100m)]),
|
||||
new("RB3060FM", "RiBa 30-60 gg fine mese", "RIBA", "TP01", [new(30, true, 50m), new(60, true, 50m)]),
|
||||
new("RB306090", "RiBa 30-60-90 gg fine mese", "RIBA", "TP01", [new(30, true, 33.33m), new(60, true, 33.33m), new(90, true, 33.34m)]),
|
||||
new("SDD30", "Addebito SEPA 30 gg data fattura", "SDD", "TP02", [new(30, false, 100m)]),
|
||||
];
|
||||
|
||||
/// <inheritdoc />
|
||||
public IReadOnlyList<DocumentTypeTemplate> DocumentTypes { get; } =
|
||||
[
|
||||
new("PRE", "Preventivo", NumeratorKind.Quotation, "PRE", null, null),
|
||||
new("OC", "Ordine cliente", NumeratorKind.SalesOrder, "ORD", null, null),
|
||||
new("DDT", "Documento di trasporto", NumeratorKind.DeliveryNote, "DDT", "SCA", null),
|
||||
new("FI", "Fattura immediata", NumeratorKind.SalesInvoice, "FAT", null, "TD01"),
|
||||
new("FA", "Fattura accompagnatoria", NumeratorKind.SalesInvoice, "FAT", "SCA", "TD01"),
|
||||
new("FD", "Fattura differita", NumeratorKind.SalesInvoice, "FAT", null, "TD24"),
|
||||
new("FACC", "Fattura di acconto", NumeratorKind.SalesInvoice, "FAT", null, "TD02"),
|
||||
new("NC", "Nota di credito", NumeratorKind.SalesInvoice, "FAT", null, "TD04"),
|
||||
new("ND", "Nota di debito", NumeratorKind.SalesInvoice, "FAT", null, "TD05"),
|
||||
new("PAR", "Parcella", NumeratorKind.SalesInvoice, "FAT", null, "TD06"),
|
||||
new("PF", "Fattura pro forma", NumeratorKind.Other, "PRF", null, null),
|
||||
new("AF16", "Integrazione reverse charge interno", NumeratorKind.SalesInvoice, "AUT", null, "TD16"),
|
||||
new("AF17", "Integrazione acquisto servizi dall'estero", NumeratorKind.SalesInvoice, "AUT", null, "TD17"),
|
||||
new("AF18", "Integrazione acquisto beni intracomunitari", NumeratorKind.SalesInvoice, "AUT", null, "TD18"),
|
||||
new("AF19", "Integrazione acquisto beni art. 17 c.2", NumeratorKind.SalesInvoice, "AUT", null, "TD19"),
|
||||
new("OF", "Ordine fornitore", NumeratorKind.PurchaseOrder, "ORF", null, null),
|
||||
new("DDTF", "DDT fornitore (carico)", NumeratorKind.Inventory, null, "CAR", null),
|
||||
new("FF", "Fattura fornitore", NumeratorKind.PurchaseInvoice, "PRA", null, null),
|
||||
new("NCF", "Nota di credito fornitore", NumeratorKind.PurchaseInvoice, "PRA", null, null),
|
||||
new("MM", "Movimento di magazzino", NumeratorKind.Inventory, "MAG", null, null),
|
||||
];
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
using Khaemhat.Core.Tax;
|
||||
using Khaemhat.Fiscal.Abstractions;
|
||||
|
||||
namespace Khaemhat.Fiscal.Italy;
|
||||
|
||||
/// <summary>
|
||||
/// Italian VAT deadlines (wiki <i>Fiscalità italiana</i>, "Scadenze e regole principali"):
|
||||
/// <list type="bullet">
|
||||
/// <item>monthly VAT by the 16th of the next month;</item>
|
||||
/// <item>quarterly VAT by the 16th of the second month after the quarter, with 1% interest; the fourth quarter is paid
|
||||
/// with the annual balance by 16 March;</item>
|
||||
/// <item>payments due from 1 to 20 August move to 20 August (art. 3-quater DL 16/2012);</item>
|
||||
/// <item>a deadline on a Saturday, Sunday or public holiday moves to the next working day (art. 7 DL 70/2011).</item>
|
||||
/// </list>
|
||||
/// </summary>
|
||||
public sealed class ItalianFiscalCalendar : IFiscalCalendar
|
||||
{
|
||||
/// <summary>Interest on quarterly VAT, in percent.</summary>
|
||||
public const decimal QuarterlyInterestRate = 1m;
|
||||
|
||||
/// <inheritdoc />
|
||||
public DateOnly VatPaymentDue(TaxPeriod period)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(period);
|
||||
DateOnly due;
|
||||
if (period.Periodicity == VatPeriodicity.Monthly)
|
||||
{
|
||||
due = new DateOnly(period.Year, period.Number, 16).AddMonths(1);
|
||||
}
|
||||
else if (period.Number == 4)
|
||||
{
|
||||
due = new DateOnly(period.Year + 1, 3, 16);
|
||||
}
|
||||
else
|
||||
{
|
||||
due = new DateOnly(period.End.Year, period.End.Month, 16).AddMonths(2);
|
||||
}
|
||||
|
||||
if (due.Month == 8 && due.Day <= 20)
|
||||
{
|
||||
due = new DateOnly(due.Year, 8, 20);
|
||||
}
|
||||
|
||||
return NextWorkingDay(due);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public decimal VatInterestRate(VatPeriodicity periodicity) =>
|
||||
periodicity == VatPeriodicity.Quarterly ? QuarterlyInterestRate : 0m;
|
||||
|
||||
/// <inheritdoc />
|
||||
public bool IsNonWorkingDay(DateOnly day) =>
|
||||
day.DayOfWeek is DayOfWeek.Saturday or DayOfWeek.Sunday || IsPublicHoliday(day);
|
||||
|
||||
/// <inheritdoc />
|
||||
public DateOnly NextWorkingDay(DateOnly day)
|
||||
{
|
||||
while (IsNonWorkingDay(day))
|
||||
{
|
||||
day = day.AddDays(1);
|
||||
}
|
||||
|
||||
return day;
|
||||
}
|
||||
|
||||
/// <summary>Whether a day is an Italian national public holiday.</summary>
|
||||
/// <param name="date">The day.</param>
|
||||
/// <returns><see langword="true"/> for a holiday.</returns>
|
||||
public static bool IsPublicHoliday(DateOnly date)
|
||||
{
|
||||
switch ((date.Month, date.Day))
|
||||
{
|
||||
case (1, 1): // Capodanno
|
||||
case (1, 6): // Epifania
|
||||
case (4, 25): // Liberazione
|
||||
case (5, 1): // Festa del lavoro
|
||||
case (6, 2): // Festa della Repubblica
|
||||
case (8, 15): // Ferragosto
|
||||
case (11, 1): // Ognissanti
|
||||
case (12, 8): // Immacolata
|
||||
case (12, 25): // Natale
|
||||
case (12, 26): // Santo Stefano
|
||||
return true;
|
||||
case (10, 4) when date.Year >= 2026: // San Francesco, national holiday again from 2026
|
||||
return true;
|
||||
default:
|
||||
return date == EasterSunday(date.Year).AddDays(1); // Lunedì dell'Angelo
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Easter Sunday of a year (Gregorian calendar, anonymous algorithm).</summary>
|
||||
/// <param name="year">The year.</param>
|
||||
/// <returns>The date.</returns>
|
||||
public static DateOnly EasterSunday(int year)
|
||||
{
|
||||
var a = year % 19;
|
||||
var b = year / 100;
|
||||
var c = year % 100;
|
||||
var d = b / 4;
|
||||
var e = b % 4;
|
||||
var f = (b + 8) / 25;
|
||||
var g = (b - f + 1) / 3;
|
||||
var h = ((19 * a) + b - d - g + 15) % 30;
|
||||
var i = c / 4;
|
||||
var k = c % 4;
|
||||
var l = (32 + (2 * e) + (2 * i) - h - k) % 7;
|
||||
var m = (a + (11 * h) + (22 * l)) / 451;
|
||||
var month = (h + l - (7 * m) + 114) / 31;
|
||||
var day = ((h + l - (7 * m) + 114) % 31) + 1;
|
||||
return new DateOnly(year, month, day);
|
||||
}
|
||||
}
|
||||