Compare commits
12
Commits
v0.3.0
..
3dbbaba86e
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3dbbaba86e | ||
|
|
c8241a414e | ||
|
|
3401271483 | ||
|
|
a9eda510f2 | ||
|
|
321aae7e81 | ||
|
|
07555de700 | ||
|
|
9bcf8c1082 | ||
|
|
34e196424f | ||
|
|
25f8a7ad30 | ||
|
|
49d2bb166b | ||
|
|
8079d3da69 | ||
|
|
f7c9cf6da8 |
No files matched your search
@@ -7,6 +7,72 @@ un'immagine `gitea.encke-hake.ts.net/balbosoft/khaemhat:X.Y.Z`.
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
### 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.
|
||||
|
||||
### Changed
|
||||
- Tabella *Listini*: nuovi campi *Listino base* (uno solo) e *Derivato da*; la migrazione marca come base il listino
|
||||
`BASE` esistente.
|
||||
|
||||
## [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
|
||||
+2
-2
@@ -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
|
||||
|
||||
+1046
-15
File diff suppressed because it is too large.
Load diff
+2
-1
@@ -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
|
||||
|
||||
+4
-2
@@ -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
|
||||
|
||||
|
||||
+12
-7
@@ -2,11 +2,16 @@
|
||||
|
||||
> 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.
|
||||
**Ultimo aggiornamento:** 2026-11-12
|
||||
**Milestone corrente:** M4 — Tabelle, anagrafiche, articoli (issue #37-#46), ramo `feat/37-tabelle-anagrafiche`.
|
||||
Fatti: pacchetto fiscale (#37), validatori e VIES (#40), tabelle azienda, profilo, esercizi e cambi con le maschere
|
||||
(#38, #39), dati di base e `scripts/seed.sh --base` (#45) con province e comuni ISTAT e CAP GeoNames (ADR 0028;
|
||||
mancano le banche ABI/CAB, senza fonte con licenza compatibile), codici automatici e compilazione automatica (#43), anagrafiche con radar, scheda, controlli, VIES e
|
||||
21 anagrafiche di esempio (#41, ADR 0029), articoli e listini con prezzi a validità, listini derivati,
|
||||
aggiornamento massivo, codici delle anagrafiche, 120 articoli di esempio e `seed --demo [--scale N]` (#42, ADR 0030).
|
||||
ADR 0025-0030.
|
||||
**Prossimo passo:** import/export guidato (#44), chiusura M4 come `v0.4.0` (#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
|
||||
filtro predefinito nei radar.
|
||||
@@ -14,7 +19,7 @@ filtro predefinito nei radar.
|
||||
## Fatto
|
||||
|
||||
- Specifica normativa in `docs/SPEC.md`; `CLAUDE.md` con emendamenti E1-E6.
|
||||
- ADR 0001-0024.
|
||||
- ADR 0001-0030.
|
||||
- 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 +45,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
|
||||
|
||||
@@ -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*.
|
||||
+98
-68
@@ -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:** bozza · **Ultima revisione:** 2026-11-12 · **Versione software:** non ancora rilasciata (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,15 +38,17 @@ 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*.
|
||||
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).
|
||||
|
||||
- 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**).
|
||||
- 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
|
||||
|
||||
@@ -51,39 +56,44 @@ stato è un badge: *Attivo*, *Disabilitato*, *PA · split*, *UE*, *Extra-UE*, *P
|
||||
*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**.
|
||||
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** 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.
|
||||
**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 +103,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 +112,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 +140,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 +153,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 +208,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.
|
||||
|
||||
|
||||
+140
-90
@@ -1,153 +1,203 @@
|
||||
# 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:** bozza · **Ultima revisione:** 2026-11-12 · **Versione software:** non ancora rilasciata (milestone M4)
|
||||
> **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.
|
||||
|
||||
## 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**.
|
||||
**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`).
|
||||
|
||||
**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.
|
||||
**Schede**:
|
||||
|
||||
**Schede**: *Dati principali*, *UM alternative*, *Codici alternativi*, *Listini*, *Fornitori*, *Sostitutivi*,
|
||||
*Movimenti*, *Immagini e allegati*.
|
||||
| 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**.
|
||||
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`).
|
||||
|
||||
- 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.
|
||||
### La griglia dei listini
|
||||
|
||||
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**.
|
||||
**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 @@
|
||||
# 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:** bozza · **Ultima revisione:** 2026-11-11 · **Versione software:** non ancora rilasciata (milestone M4; dati di esempio 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** |
|
||||
|
||||
@@ -10,6 +10,9 @@ 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*.
|
||||
|
||||
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). **In corso:** M4.
|
||||
|
||||
| # | 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:** bozza · **Ultima revisione:** 2026-11-11 · **Versione software:** non ancora rilasciata (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,47 @@ 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**.
|
||||
## 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 +76,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 +89,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,7 +108,7 @@ 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)) |
|
||||
| **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** | regole di sconto riutilizzabili (struttura definita in sviluppo) |
|
||||
| **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 |
|
||||
@@ -112,19 +143,23 @@ 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*.
|
||||
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,28 +177,44 @@ 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
|
||||
|
||||
@@ -188,8 +239,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
|
||||
|
||||
|
||||
+14
-6
@@ -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,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" />
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -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,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);
|
||||
});
|
||||
}
|
||||
}
|
||||
+95
@@ -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");
|
||||
});
|
||||
}
|
||||
}
|
||||
+110
@@ -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);
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,355 @@
|
||||
using System.Globalization;
|
||||
using System.Text;
|
||||
using Khaemhat.Core.Validation;
|
||||
using Khaemhat.Fiscal.Abstractions;
|
||||
|
||||
namespace Khaemhat.Fiscal.Italy;
|
||||
|
||||
/// <summary>
|
||||
/// Italian VAT numbers (partita IVA): 11 digits, the last a Luhn-like check digit; the first seven (the taxpayer
|
||||
/// number) cannot be all zeros.
|
||||
/// </summary>
|
||||
public static class ItalianVatNumberValidator
|
||||
{
|
||||
/// <summary>The number without spaces and without the <c>IT</c> prefix.</summary>
|
||||
/// <param name="vatNumber">The number as typed.</param>
|
||||
/// <returns>The compact number.</returns>
|
||||
public static string Normalize(string? vatNumber)
|
||||
{
|
||||
var compact = string.Concat((vatNumber ?? string.Empty).Where(c => !char.IsWhiteSpace(c) && c != '.' && c != '-')).ToUpperInvariant();
|
||||
return compact.StartsWith("IT", StringComparison.Ordinal) ? compact[2..] : compact;
|
||||
}
|
||||
|
||||
/// <summary>Whether a VAT number is valid.</summary>
|
||||
/// <param name="vatNumber">The number, with or without prefix.</param>
|
||||
/// <returns><see langword="true"/> when valid.</returns>
|
||||
public static bool IsValid(string? vatNumber)
|
||||
{
|
||||
var value = Normalize(vatNumber);
|
||||
if (value.Length != 11 || !value.All(char.IsAsciiDigit) || value.StartsWith("0000000", StringComparison.Ordinal))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
return CheckDigit(value[..10]) == value[10] - '0';
|
||||
}
|
||||
|
||||
/// <summary>The check digit for the first ten digits.</summary>
|
||||
/// <param name="digits">Ten digits.</param>
|
||||
/// <returns>The check digit.</returns>
|
||||
public static int CheckDigit(string digits)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(digits);
|
||||
var sum = 0;
|
||||
for (var i = 0; i < digits.Length; i++)
|
||||
{
|
||||
var d = digits[i] - '0';
|
||||
if (i % 2 == 1)
|
||||
{
|
||||
d *= 2;
|
||||
if (d > 9)
|
||||
{
|
||||
d -= 9;
|
||||
}
|
||||
}
|
||||
|
||||
sum += d;
|
||||
}
|
||||
|
||||
return (10 - (sum % 10)) % 10;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Italian personal tax codes (codice fiscale, DM 23/12/1976): 16 characters for people, with the omocodia
|
||||
/// substitutions accepted; companies use their 11-digit number.
|
||||
/// </summary>
|
||||
public static class FiscalCodeValidator
|
||||
{
|
||||
/// <summary>Letters that replace digits in omocodic codes: L=0, M=1... V=9.</summary>
|
||||
internal const string OmocodiaLetters = "LMNPQRSTUV";
|
||||
|
||||
/// <summary>Month letters: A=January... T=December.</summary>
|
||||
internal const string MonthLetters = "ABCDEHLMPRST";
|
||||
|
||||
// Positions (0-based) that hold digits, possibly replaced by omocodia letters.
|
||||
private static readonly int[] DigitPositions = [6, 7, 9, 10, 12, 13, 14];
|
||||
|
||||
// Values of characters in odd positions (1st, 3rd... 1-based) for the check character.
|
||||
private static readonly int[] OddValues = [1, 0, 5, 7, 9, 13, 15, 17, 19, 21, 2, 4, 18, 20, 11, 3, 6, 8, 12, 14, 16, 10, 22, 25, 24, 23];
|
||||
|
||||
/// <summary>The code without spaces, in capitals.</summary>
|
||||
/// <param name="code">The code as typed.</param>
|
||||
/// <returns>The compact code.</returns>
|
||||
public static string Normalize(string? code) =>
|
||||
string.Concat((code ?? string.Empty).Where(c => !char.IsWhiteSpace(c))).ToUpperInvariant();
|
||||
|
||||
/// <summary>Whether a tax code is valid: a 16-character personal code or an 11-digit company code.</summary>
|
||||
/// <param name="code">The code.</param>
|
||||
/// <returns><see langword="true"/> when valid.</returns>
|
||||
public static bool IsValid(string? code)
|
||||
{
|
||||
var value = Normalize(code);
|
||||
return value.Length == 11 ? ItalianVatNumberValidator.IsValid(value) : IsValidPersonal(value);
|
||||
}
|
||||
|
||||
/// <summary>Whether a 16-character personal code is valid.</summary>
|
||||
/// <param name="code">The code.</param>
|
||||
/// <returns><see langword="true"/> when valid.</returns>
|
||||
public static bool IsValidPersonal(string? code)
|
||||
{
|
||||
var value = Normalize(code);
|
||||
if (value.Length != 16 || !value.All(char.IsAsciiLetterOrDigit))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
for (var i = 0; i < 16; i++)
|
||||
{
|
||||
var isDigitPosition = Array.IndexOf(DigitPositions, i) >= 0;
|
||||
var c = value[i];
|
||||
var ok = isDigitPosition
|
||||
? char.IsAsciiDigit(c) || OmocodiaLetters.Contains(c, StringComparison.Ordinal)
|
||||
: char.IsAsciiLetterUpper(c);
|
||||
if (!ok)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
var plain = RemoveOmocodia(value);
|
||||
var day = int.Parse(plain.AsSpan(9, 2), CultureInfo.InvariantCulture);
|
||||
return MonthLetters.Contains(value[8], StringComparison.Ordinal)
|
||||
&& day is (>= 1 and <= 31) or (>= 41 and <= 71)
|
||||
&& CheckCharacter(value[..15]) == value[15];
|
||||
}
|
||||
|
||||
/// <summary>The check character of the first 15 characters.</summary>
|
||||
/// <param name="first15">The first 15 characters, in capitals.</param>
|
||||
/// <returns>The check character.</returns>
|
||||
public static char CheckCharacter(string first15)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(first15);
|
||||
var sum = 0;
|
||||
for (var i = 0; i < first15.Length; i++)
|
||||
{
|
||||
var c = first15[i];
|
||||
var index = char.IsAsciiDigit(c) ? c - '0' : c - 'A';
|
||||
sum += i % 2 == 0 ? OddValues[index] : index;
|
||||
}
|
||||
|
||||
return (char)('A' + (sum % 26));
|
||||
}
|
||||
|
||||
/// <summary>The code with omocodia letters turned back into digits.</summary>
|
||||
/// <param name="code">A 16-character code.</param>
|
||||
/// <returns>The code with digits in the digit positions.</returns>
|
||||
public static string RemoveOmocodia(string code)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(code);
|
||||
var chars = code.ToCharArray();
|
||||
foreach (var p in DigitPositions)
|
||||
{
|
||||
var i = OmocodiaLetters.IndexOf(chars[p], StringComparison.Ordinal);
|
||||
if (i >= 0)
|
||||
{
|
||||
chars[p] = (char)('0' + i);
|
||||
}
|
||||
}
|
||||
|
||||
return new string(chars);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Computes and decodes Italian personal tax codes.</summary>
|
||||
public static class FiscalCodeCalculator
|
||||
{
|
||||
/// <summary>The personal tax code of a person.</summary>
|
||||
/// <param name="data">Surname, name, birth date, sex and cadastral code of the birth place.</param>
|
||||
/// <returns>The 16-character code.</returns>
|
||||
public static string Compute(PersonalTaxCodeData data)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(data);
|
||||
var place = FiscalCodeValidator.Normalize(data.BirthPlaceCode);
|
||||
if (place.Length != 4 || !char.IsAsciiLetterUpper(place[0]) || !place[1..].All(char.IsAsciiDigit))
|
||||
{
|
||||
throw new ArgumentException("The birth place code must be a letter and three digits, such as H501.", nameof(data));
|
||||
}
|
||||
|
||||
var day = data.BirthDate.Day + (data.Sex == PersonSex.Female ? 40 : 0);
|
||||
var first15 = string.Concat(
|
||||
SurnamePart(data.Surname),
|
||||
NamePart(data.GivenName),
|
||||
(data.BirthDate.Year % 100).ToString("00", CultureInfo.InvariantCulture),
|
||||
FiscalCodeValidator.MonthLetters[data.BirthDate.Month - 1].ToString(),
|
||||
day.ToString("00", CultureInfo.InvariantCulture),
|
||||
place);
|
||||
return first15 + FiscalCodeValidator.CheckCharacter(first15);
|
||||
}
|
||||
|
||||
/// <summary>Reads birth date, sex and place from a personal code.</summary>
|
||||
/// <param name="code">The code.</param>
|
||||
/// <param name="today">The reference date: a two-digit year after it belongs to the previous century.</param>
|
||||
/// <returns>The data, or <see langword="null"/> for an invalid code.</returns>
|
||||
public static PersonalTaxCodeInfo? Decode(string? code, DateOnly today)
|
||||
{
|
||||
if (!FiscalCodeValidator.IsValidPersonal(code))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var plain = FiscalCodeValidator.RemoveOmocodia(FiscalCodeValidator.Normalize(code));
|
||||
var yy = int.Parse(plain.AsSpan(6, 2), CultureInfo.InvariantCulture);
|
||||
var month = FiscalCodeValidator.MonthLetters.IndexOf(plain[8], StringComparison.Ordinal) + 1;
|
||||
var day = int.Parse(plain.AsSpan(9, 2), CultureInfo.InvariantCulture);
|
||||
var sex = day > 40 ? PersonSex.Female : PersonSex.Male;
|
||||
day = day > 40 ? day - 40 : day;
|
||||
var year = (today.Year / 100 * 100) + yy;
|
||||
if (year > today.Year)
|
||||
{
|
||||
year -= 100;
|
||||
}
|
||||
|
||||
return day <= DateTime.DaysInMonth(year, month)
|
||||
? new PersonalTaxCodeInfo(new DateOnly(year, month, day), sex, plain[11..15])
|
||||
: null;
|
||||
}
|
||||
|
||||
private static string SurnamePart(string surname)
|
||||
{
|
||||
var (consonants, vowels) = Split(surname);
|
||||
return (consonants + vowels + "XXX")[..3];
|
||||
}
|
||||
|
||||
private static string NamePart(string name)
|
||||
{
|
||||
var (consonants, vowels) = Split(name);
|
||||
return consonants.Length >= 4
|
||||
? string.Concat(consonants[0], consonants[2], consonants[3])
|
||||
: (consonants + vowels + "XXX")[..3];
|
||||
}
|
||||
|
||||
private static (string Consonants, string Vowels) Split(string text)
|
||||
{
|
||||
var letters = Letters(text);
|
||||
return (
|
||||
string.Concat(letters.Where(c => !"AEIOU".Contains(c, StringComparison.Ordinal))),
|
||||
string.Concat(letters.Where(c => "AEIOU".Contains(c, StringComparison.Ordinal))));
|
||||
}
|
||||
|
||||
// Letters A-Z only: accents dropped (È -> E), apostrophes and spaces ignored.
|
||||
private static string Letters(string text)
|
||||
{
|
||||
var decomposed = (text ?? string.Empty).Normalize(NormalizationForm.FormD).ToUpperInvariant();
|
||||
return string.Concat(decomposed.Where(char.IsAsciiLetterUpper));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// E-invoice recipient codes (codice destinatario): 7 characters for businesses, 6 for public administrations (IPA
|
||||
/// office code), <c>0000000</c> for consumers and businesses without a channel, <c>XXXXXXX</c> abroad.
|
||||
/// </summary>
|
||||
public static class SdiRecipientCodeValidator
|
||||
{
|
||||
private const string Field = "RecipientCode";
|
||||
|
||||
/// <summary>The rules a recipient code breaks.</summary>
|
||||
/// <param name="code">The code.</param>
|
||||
/// <param name="kind">The kind of customer.</param>
|
||||
/// <returns>Errors and warnings.</returns>
|
||||
public static IReadOnlyList<FiscalProblem> Check(string? code, RecipientKind kind)
|
||||
{
|
||||
var value = FiscalCodeValidator.Normalize(code);
|
||||
if (value.Length == 0)
|
||||
{
|
||||
return kind == RecipientKind.PublicAdministration ? [new(Field, "fiscal.recipient.required")] : [];
|
||||
}
|
||||
|
||||
if (!value.All(char.IsAsciiLetterOrDigit))
|
||||
{
|
||||
return [new(Field, "fiscal.recipient.characters")];
|
||||
}
|
||||
|
||||
return kind switch
|
||||
{
|
||||
RecipientKind.PublicAdministration when value.Length != 6 => [new(Field, "fiscal.recipient.pa-length")],
|
||||
RecipientKind.Foreign when value != FatturaPaCodeLists.RecipientCodeForeign => [new(Field, "fiscal.recipient.foreign")],
|
||||
RecipientKind.Consumer when value != FatturaPaCodeLists.RecipientCodeNone => [new(Field, "fiscal.recipient.consumer", FiscalProblemSeverity.Warning)],
|
||||
RecipientKind.Business when value.Length != 7 => [new(Field, "fiscal.recipient.business-length")],
|
||||
RecipientKind.Business when value == FatturaPaCodeLists.RecipientCodeForeign => [new(Field, "fiscal.recipient.foreign-code-domestic")],
|
||||
_ => [],
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The Italian tax identifiers as a pack feature.</summary>
|
||||
public sealed class ItalianTaxIdentifierRules : ITaxIdentifierRules
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public string NormalizeVatNumber(string? vatNumber) => ItalianVatNumberValidator.Normalize(vatNumber);
|
||||
|
||||
/// <inheritdoc />
|
||||
public bool IsValidVatNumber(string? vatNumber) => ItalianVatNumberValidator.IsValid(vatNumber);
|
||||
|
||||
/// <inheritdoc />
|
||||
public bool IsValidTaxCode(string? taxCode) => FiscalCodeValidator.IsValid(taxCode);
|
||||
|
||||
/// <inheritdoc />
|
||||
public string ComputePersonalTaxCode(PersonalTaxCodeData data) => FiscalCodeCalculator.Compute(data);
|
||||
|
||||
/// <inheritdoc />
|
||||
public PersonalTaxCodeInfo? DecodePersonalTaxCode(string? taxCode, DateOnly today) => FiscalCodeCalculator.Decode(taxCode, today);
|
||||
|
||||
/// <inheritdoc />
|
||||
public IReadOnlyList<FiscalProblem> CheckRecipientCode(string? recipientCode, RecipientKind kind) =>
|
||||
SdiRecipientCodeValidator.Check(recipientCode, kind);
|
||||
|
||||
/// <inheritdoc />
|
||||
public string? DefaultRecipientCode(RecipientKind kind) => kind switch
|
||||
{
|
||||
RecipientKind.Foreign => FatturaPaCodeLists.RecipientCodeForeign,
|
||||
RecipientKind.PublicAdministration => null,
|
||||
_ => FatturaPaCodeLists.RecipientCodeNone,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Italian banks by ABI code, to fill bank name, BIC and CAB from an Italian IBAN
|
||||
/// (<c>IT</c> + check + CIN + ABI + CAB + account).
|
||||
/// </summary>
|
||||
public sealed class ItalianBankDirectory : IBankDirectory
|
||||
{
|
||||
private readonly Dictionary<string, BankInfo> _byAbi;
|
||||
|
||||
/// <summary>Creates the directory.</summary>
|
||||
/// <param name="banks">The banks, one per ABI code.</param>
|
||||
public ItalianBankDirectory(IEnumerable<BankInfo> banks)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(banks);
|
||||
_byAbi = banks.GroupBy(b => b.BankCode, StringComparer.Ordinal).ToDictionary(g => g.Key, g => g.First(), StringComparer.Ordinal);
|
||||
}
|
||||
|
||||
/// <summary>How many banks the directory knows.</summary>
|
||||
public int Count => _byAbi.Count;
|
||||
|
||||
/// <summary>ABI and CAB of an Italian IBAN.</summary>
|
||||
/// <param name="iban">The IBAN.</param>
|
||||
/// <returns>The codes, or <see langword="null"/> for an invalid or foreign IBAN.</returns>
|
||||
public static (string Abi, string Cab)? CodesOf(string? iban)
|
||||
{
|
||||
var value = IbanValidator.Normalize(iban);
|
||||
return IbanValidator.IsValid(value) && value.StartsWith("IT", StringComparison.Ordinal)
|
||||
? (value[5..10], value[10..15])
|
||||
: null;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public BankInfo? FindByIban(string? iban) =>
|
||||
CodesOf(iban) is { } codes && _byAbi.TryGetValue(codes.Abi, out var bank) ? bank with { BranchCode = codes.Cab } : null;
|
||||
|
||||
/// <inheritdoc />
|
||||
public BankInfo? ReadIban(string? iban) =>
|
||||
CodesOf(iban) is not { } codes ? null
|
||||
: _byAbi.TryGetValue(codes.Abi, out var bank) ? bank with { BranchCode = codes.Cab }
|
||||
: new BankInfo(codes.Abi, null, null, codes.Cab);
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
using Khaemhat.Fiscal.Abstractions;
|
||||
using Khaemhat.Infrastructure.Files;
|
||||
|
||||
namespace Khaemhat.Fiscal.Italy;
|
||||
|
||||
/// <summary>
|
||||
/// The Italian provinces and municipalities from the ISTAT list of municipality codes (ADR 0028): abbreviation, name and
|
||||
/// region of the 110 provinces, and cadastral code, name, province, region and ISTAT code of every municipality, with
|
||||
/// the postal codes of GeoNames where they match (about 98% of the municipalities). The files are rebuilt with
|
||||
/// <c>tools/Khaemhat.PlacesTool</c> and read once, the first time they are needed.
|
||||
/// </summary>
|
||||
public sealed class ItalianPlaces : IPlaceDirectory
|
||||
{
|
||||
/// <summary>The source of the embedded files.</summary>
|
||||
public const string ListSource =
|
||||
"ISTAT, Codici statistici delle unità amministrative territoriali, 26/02/2026 (CC BY 4.0); CAP: GeoNames, www.geonames.org (CC BY 4.0)";
|
||||
|
||||
private readonly Lazy<IReadOnlyList<ProvinceTemplate>> _provinces = new(ReadProvinces);
|
||||
private readonly Lazy<IReadOnlyList<MunicipalityTemplate>> _municipalities = new(ReadMunicipalities);
|
||||
|
||||
/// <inheritdoc />
|
||||
public string Source => ListSource;
|
||||
|
||||
/// <inheritdoc />
|
||||
public IReadOnlyList<ProvinceTemplate> Provinces => _provinces.Value;
|
||||
|
||||
/// <inheritdoc />
|
||||
public IReadOnlyList<MunicipalityTemplate> Municipalities => _municipalities.Value;
|
||||
|
||||
private static IReadOnlyList<ProvinceTemplate> ReadProvinces() =>
|
||||
[.. Read("province.csv").Select(l => new ProvinceTemplate(l[0], l[1], l[2]))];
|
||||
|
||||
private static IReadOnlyList<MunicipalityTemplate> ReadMunicipalities() =>
|
||||
[.. Read("comuni.csv").Select(l => new MunicipalityTemplate(l[0], l[1], l[2], l[3], l[4], l.Count > 5 && l[5].Length > 0 ? l[5] : null))];
|
||||
|
||||
private static List<IReadOnlyList<string>> Read(string file)
|
||||
{
|
||||
using var stream = typeof(ItalianPlaces).Assembly.GetManifestResourceStream("Khaemhat.Fiscal.Italy.Data." + file)
|
||||
?? throw new InvalidOperationException($"The file {file} is missing from the assembly.");
|
||||
using var reader = new StreamReader(stream);
|
||||
return [.. CsvReader.Parse(reader.ReadToEnd(), ';').Skip(1)];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,145 @@
|
||||
using Khaemhat.Core.Tax;
|
||||
using Khaemhat.Fiscal.Abstractions;
|
||||
|
||||
namespace Khaemhat.Fiscal.Italy;
|
||||
|
||||
/// <summary>The FatturaPA format: version of the specifications and code lists (writer and reader arrive in M9).</summary>
|
||||
public sealed class FatturaPaFormat : IEInvoiceFormat
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public string Name => "FatturaPA";
|
||||
|
||||
/// <inheritdoc />
|
||||
public string SpecVersion => FatturaPaCodeLists.SpecVersion;
|
||||
|
||||
/// <inheritdoc />
|
||||
public CodeList TransmissionFormats => FatturaPaCodeLists.TransmissionFormats;
|
||||
|
||||
/// <inheritdoc />
|
||||
public CodeList DocumentTypes => FatturaPaCodeLists.DocumentTypes;
|
||||
|
||||
/// <inheritdoc />
|
||||
public CodeList PaymentMethods => FatturaPaCodeLists.PaymentMethods;
|
||||
|
||||
/// <inheritdoc />
|
||||
public CodeList PaymentConditions => FatturaPaCodeLists.PaymentConditions;
|
||||
|
||||
/// <inheritdoc />
|
||||
public CodeList TaxRegimes => FatturaPaCodeLists.TaxRegimes;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Italian withholding taxes: fees of professionals (20% on the whole fee, F24 1040), commissions of agents (23% on 50%,
|
||||
/// or on 20% for agents with employees, F24 1038) and the 4% of condominiums (F24 1019).
|
||||
/// </summary>
|
||||
public sealed class WithholdingRulesIt : IWithholdingRules
|
||||
{
|
||||
private readonly ItalianTaxEngine _engine = new();
|
||||
|
||||
/// <inheritdoc />
|
||||
public IReadOnlyList<WithholdingKind> Kinds { get; } =
|
||||
[
|
||||
new("PROF", "Lavoro autonomo professionale", 20m, 100m, "1040", "RT01", "A"),
|
||||
new("OCC", "Lavoro autonomo occasionale", 20m, 100m, "1040", "RT01", "M"),
|
||||
new("AGEN", "Provvigioni ad agenti e rappresentanti", 23m, 50m, "1038", "RT01", "R"),
|
||||
new("AGEND", "Provvigioni ad agenti con dipendenti o terzi", 23m, 20m, "1038", "RT01", "R"),
|
||||
new("COND", "Ritenuta del condominio sugli appalti", 4m, 100m, "1019", "RT01", "W"),
|
||||
];
|
||||
|
||||
/// <inheritdoc />
|
||||
public CodeList InvoiceTypes => FatturaPaCodeLists.WithholdingTypes;
|
||||
|
||||
/// <inheritdoc />
|
||||
public CodeList PaymentReasons => FatturaPaCodeLists.WithholdingReasons;
|
||||
|
||||
/// <inheritdoc />
|
||||
public CodeList SocialSecurityFunds => FatturaPaCodeLists.SocialSecurityFunds;
|
||||
|
||||
/// <inheritdoc />
|
||||
public decimal Compute(decimal amount, WithholdingKind kind)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(kind);
|
||||
return _engine.Round(amount * kind.TaxableBasePercent / 100m * kind.Rate / 100m);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Italian depreciation rules (DM 31/12/1988 coefficients arrive with the asset register, M10).</summary>
|
||||
public sealed class FixedAssetRulesIt : IFixedAssetRules
|
||||
{
|
||||
private readonly ItalianTaxEngine _engine = new();
|
||||
|
||||
/// <inheritdoc />
|
||||
public decimal FirstYearFactor => 0.5m;
|
||||
|
||||
/// <inheritdoc />
|
||||
public decimal LowValueThreshold => 516.46m;
|
||||
|
||||
/// <inheritdoc />
|
||||
public decimal PassengerCarCostLimit => 18_075.99m;
|
||||
|
||||
/// <inheritdoc />
|
||||
public decimal YearlyDepreciation(decimal cost, decimal ratePercent, bool firstYear, decimal alreadyDepreciated)
|
||||
{
|
||||
var remaining = Math.Max(0m, cost - alreadyDepreciated);
|
||||
var amount = _engine.Round(cost * ratePercent / 100m * (firstYear ? FirstYearFactor : 1m));
|
||||
return Math.Min(amount, remaining);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The F24 payment codes Khaemhat proposes (the file export arrives with the VAT settlement, M7).</summary>
|
||||
public sealed class F24Exporter : ITaxPaymentFormExporter
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public string FormName => "F24";
|
||||
|
||||
/// <inheritdoc />
|
||||
public IReadOnlyList<TaxPaymentCode> Codes { get; } = BuildCodes();
|
||||
|
||||
/// <inheritdoc />
|
||||
public string VatCode(TaxPeriod period)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(period);
|
||||
return period.Periodicity == VatPeriodicity.Monthly
|
||||
? (6000 + period.Number).ToString(System.Globalization.CultureInfo.InvariantCulture)
|
||||
: (6030 + period.Number).ToString(System.Globalization.CultureInfo.InvariantCulture);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public string VatAdvanceCode(VatPeriodicity periodicity) => periodicity == VatPeriodicity.Monthly ? "6013" : "6035";
|
||||
|
||||
/// <inheritdoc />
|
||||
public string StampDutyCode(int quarter)
|
||||
{
|
||||
ArgumentOutOfRangeException.ThrowIfLessThan(quarter, 1);
|
||||
ArgumentOutOfRangeException.ThrowIfGreaterThan(quarter, 4);
|
||||
return (2520 + quarter).ToString(System.Globalization.CultureInfo.InvariantCulture);
|
||||
}
|
||||
|
||||
private static List<TaxPaymentCode> BuildCodes()
|
||||
{
|
||||
string[] months = ["gennaio", "febbraio", "marzo", "aprile", "maggio", "giugno", "luglio", "agosto", "settembre", "ottobre", "novembre", "dicembre"];
|
||||
var codes = new List<TaxPaymentCode>();
|
||||
for (var m = 1; m <= 12; m++)
|
||||
{
|
||||
codes.Add(new((6000 + m).ToString(System.Globalization.CultureInfo.InvariantCulture), "Versamento IVA mensile " + months[m - 1]));
|
||||
}
|
||||
|
||||
codes.Add(new("6013", "Versamento acconto IVA mensile"));
|
||||
for (var q = 1; q <= 4; q++)
|
||||
{
|
||||
codes.Add(new((6030 + q).ToString(System.Globalization.CultureInfo.InvariantCulture), $"Versamento IVA trimestrale {q}° trimestre"));
|
||||
}
|
||||
|
||||
codes.Add(new("6035", "Versamento IVA acconto trimestrali"));
|
||||
codes.Add(new("6099", "Versamento IVA sulla base della dichiarazione annuale"));
|
||||
codes.Add(new("1040", "Ritenute su redditi di lavoro autonomo"));
|
||||
codes.Add(new("1038", "Ritenute su provvigioni"));
|
||||
codes.Add(new("1019", "Ritenute del 4% operate dal condominio a titolo di acconto IRPEF"));
|
||||
for (var q = 1; q <= 4; q++)
|
||||
{
|
||||
codes.Add(new((2520 + q).ToString(System.Globalization.CultureInfo.InvariantCulture), $"Imposta di bollo sulle fatture elettroniche, {q}° trimestre"));
|
||||
}
|
||||
|
||||
return codes;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
using Khaemhat.Core.Tax;
|
||||
using Khaemhat.Fiscal.Abstractions;
|
||||
|
||||
namespace Khaemhat.Fiscal.Italy;
|
||||
|
||||
/// <summary>The Italian VAT natures, the base tax codes of SPEC §14 and the rules of a tax code (mockup 076).</summary>
|
||||
public sealed class ItalianTaxCodeCatalog : ITaxCodeCatalog
|
||||
{
|
||||
/// <summary>The rates of Italian VAT in percent (ordinary and reduced).</summary>
|
||||
public static IReadOnlySet<decimal> StandardRates { get; } = new HashSet<decimal> { 0m, 4m, 5m, 10m, 22m };
|
||||
|
||||
/// <inheritdoc />
|
||||
public CodeList Natures => VatNatures.All;
|
||||
|
||||
/// <inheritdoc />
|
||||
public IReadOnlyList<TaxCodeDefinition> BaseCodes { get; } =
|
||||
[
|
||||
new("22", "IVA 22%", 22m),
|
||||
new("10", "IVA 10%", 10m),
|
||||
new("5", "IVA 5%", 5m),
|
||||
new("4", "IVA 4%", 4m),
|
||||
new("22SP", "IVA 22% scissione dei pagamenti", 22m, Exigibility: TaxExigibility.SplitPayment, LegalReference: "Art. 17-ter DPR 633/72"),
|
||||
new("10SP", "IVA 10% scissione dei pagamenti", 10m, Exigibility: TaxExigibility.SplitPayment, LegalReference: "Art. 17-ter DPR 633/72"),
|
||||
new("22I50", "IVA 22% indetraibile al 50%", 22m, NonDeductiblePercent: 50m),
|
||||
new("22I100", "IVA 22% indetraibile", 22m, NonDeductiblePercent: 100m),
|
||||
new("ESC15", "Escluso art. 15", 0m, "N1", LegalReference: "Art. 15 DPR 633/72"),
|
||||
new("FC7", "Non soggetto artt. 7-7 septies", 0m, "N2.1", LegalReference: "Artt. 7-7-septies DPR 633/72"),
|
||||
new("NS", "Non soggetto, altri casi", 0m, "N2.2", LegalReference: "Art. 2 DPR 633/72"),
|
||||
new("FORF", "Operazione in regime forfettario", 0m, "N2.2", LegalReference: "Art. 1 c. 54-89 L. 190/2014"),
|
||||
new("NI8", "Non imponibile art. 8 (esportazioni)", 0m, "N3.1", LegalReference: "Art. 8 c. 1 lett. a) DPR 633/72"),
|
||||
new("NI41", "Non imponibile art. 41 (cessioni intracomunitarie)", 0m, "N3.2", LegalReference: "Art. 41 DL 331/93"),
|
||||
new("NI71", "Non imponibile art. 71 (San Marino)", 0m, "N3.3", LegalReference: "Art. 71 DPR 633/72"),
|
||||
new("NI8C", "Non imponibile art. 8 c. 1 lett. c) (dichiarazione d'intento)", 0m, "N3.5", LegalReference: "Art. 8 c. 1 lett. c) DPR 633/72"),
|
||||
new("ESE10", "Esente art. 10", 0m, "N4", LegalReference: "Art. 10 DPR 633/72"),
|
||||
new("RC74", "Inversione contabile, rottami", 0m, "N6.1", LegalReference: "Art. 74 c. 7 e 8 DPR 633/72"),
|
||||
new("RC17O", "Inversione contabile, oro e argento", 0m, "N6.2", LegalReference: "Art. 17 c. 5 DPR 633/72"),
|
||||
new("RC17A", "Inversione contabile, subappalto edile", 0m, "N6.3", LegalReference: "Art. 17 c. 6 lett. a) DPR 633/72"),
|
||||
new("RC17F", "Inversione contabile, cessione di fabbricati", 0m, "N6.4", LegalReference: "Art. 17 c. 6 lett. a-bis) DPR 633/72"),
|
||||
new("RC17B", "Inversione contabile, telefoni cellulari", 0m, "N6.5", LegalReference: "Art. 17 c. 6 lett. b) DPR 633/72"),
|
||||
new("RC17C", "Inversione contabile, prodotti elettronici", 0m, "N6.6", LegalReference: "Art. 17 c. 6 lett. c) DPR 633/72"),
|
||||
new("RC17E", "Inversione contabile, comparto edile e settori connessi", 0m, "N6.7", LegalReference: "Art. 17 c. 6 lett. a-ter) DPR 633/72"),
|
||||
new("RC17N", "Inversione contabile, settore energetico", 0m, "N6.8", LegalReference: "Art. 17 c. 6 lett. d-bis), d-ter), d-quater) DPR 633/72"),
|
||||
new("RC17", "Inversione contabile, altri casi", 0m, "N6.9", LegalReference: "Art. 17 DPR 633/72"),
|
||||
];
|
||||
|
||||
/// <inheritdoc />
|
||||
public TaxCodeKind KindOf(decimal rate, string? nature) =>
|
||||
string.IsNullOrWhiteSpace(nature) ? TaxCodeKind.Taxable : VatNatures.KindOf(nature);
|
||||
|
||||
/// <inheritdoc />
|
||||
public IReadOnlyList<FiscalProblem> Validate(TaxCodeDefinition code)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(code);
|
||||
var problems = new List<FiscalProblem>();
|
||||
var nature = string.IsNullOrWhiteSpace(code.Nature) ? null : code.Nature.Trim();
|
||||
|
||||
if (code.Rate is < 0m or > 100m)
|
||||
{
|
||||
problems.Add(new(nameof(code.Rate), "fiscal.tax.rate-range"));
|
||||
}
|
||||
else if (!StandardRates.Contains(code.Rate))
|
||||
{
|
||||
// Compensation rates of the agricultural regime are legal but rare: a warning, not an error.
|
||||
problems.Add(new(nameof(code.Rate), "fiscal.tax.rate-unusual", FiscalProblemSeverity.Warning));
|
||||
}
|
||||
|
||||
if (nature is null)
|
||||
{
|
||||
if (code.Rate == 0m)
|
||||
{
|
||||
problems.Add(new(nameof(code.Nature), "fiscal.tax.nature-required"));
|
||||
}
|
||||
}
|
||||
else if (Natures.Find(nature) is not { } entry)
|
||||
{
|
||||
problems.Add(new(nameof(code.Nature), "fiscal.tax.nature-unknown"));
|
||||
}
|
||||
else if (entry.Obsolete)
|
||||
{
|
||||
problems.Add(new(nameof(code.Nature), "fiscal.tax.nature-obsolete"));
|
||||
}
|
||||
else if (code.Rate != 0m)
|
||||
{
|
||||
problems.Add(new(nameof(code.Nature), "fiscal.tax.nature-with-rate"));
|
||||
}
|
||||
else if (string.IsNullOrWhiteSpace(code.LegalReference))
|
||||
{
|
||||
problems.Add(new(nameof(code.LegalReference), "fiscal.tax.legal-reference-missing", FiscalProblemSeverity.Warning));
|
||||
}
|
||||
|
||||
if (code.Exigibility == TaxExigibility.SplitPayment && code.Rate == 0m)
|
||||
{
|
||||
problems.Add(new(nameof(code.Exigibility), "fiscal.tax.split-needs-rate"));
|
||||
}
|
||||
|
||||
if (code.Exigibility != TaxExigibility.Immediate && VatNatures.IsReverseCharge(nature))
|
||||
{
|
||||
problems.Add(new(nameof(code.Exigibility), "fiscal.tax.reverse-charge-immediate"));
|
||||
}
|
||||
|
||||
if (code.NonDeductiblePercent is < 0m or > 100m)
|
||||
{
|
||||
problems.Add(new(nameof(code.NonDeductiblePercent), "fiscal.tax.non-deductible-range"));
|
||||
}
|
||||
|
||||
return problems;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
using Khaemhat.Fiscal.Abstractions;
|
||||
|
||||
namespace Khaemhat.Fiscal.Italy;
|
||||
|
||||
/// <summary>
|
||||
/// Italian VAT arithmetic: amounts to the cent, halves away from zero; the tax of the summary is computed on the total
|
||||
/// taxable of each line, as the FatturaPA <c>DatiRiepilogo</c> requires (tolerance of one cent on rows).
|
||||
/// </summary>
|
||||
public sealed class ItalianTaxEngine : ITaxEngine
|
||||
{
|
||||
/// <summary>The stamp duty on invoices without VAT (art. 13 of the tariff of DPR 642/72).</summary>
|
||||
public const decimal StampDutyAmount = 2.00m;
|
||||
|
||||
/// <summary>The amount without VAT above which the stamp duty is due.</summary>
|
||||
public const decimal StampDutyThreshold = 77.47m;
|
||||
|
||||
/// <inheritdoc />
|
||||
public decimal Round(decimal amount) => Math.Round(amount, 2, MidpointRounding.AwayFromZero);
|
||||
|
||||
/// <inheritdoc />
|
||||
public decimal ComputeTax(decimal taxable, decimal rate) => Round(taxable * rate / 100m);
|
||||
|
||||
/// <inheritdoc />
|
||||
public IReadOnlyList<TaxSummaryLine> Summarize(IEnumerable<TaxableAmount> amounts)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(amounts);
|
||||
return
|
||||
[
|
||||
.. amounts
|
||||
.GroupBy(a => (a.Rate, Nature: Normalize(a.Nature), a.Exigibility, a.NonDeductiblePercent))
|
||||
.Select(g =>
|
||||
{
|
||||
var taxable = Round(g.Sum(a => a.Amount));
|
||||
var tax = ComputeTax(taxable, g.Key.Rate);
|
||||
return new TaxSummaryLine(g.Key.Rate, g.Key.Nature, g.Key.Exigibility, g.Key.NonDeductiblePercent,
|
||||
taxable, tax, Round(tax * g.Key.NonDeductiblePercent / 100m));
|
||||
})
|
||||
.OrderByDescending(l => l.Rate)
|
||||
.ThenBy(l => l.Nature, StringComparer.Ordinal)
|
||||
.ThenBy(l => l.Exigibility)
|
||||
.ThenBy(l => l.NonDeductiblePercent),
|
||||
];
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public StampDutyAssessment AssessStampDuty(IEnumerable<TaxSummaryLine> summary)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(summary);
|
||||
var exempt = Round(summary.Where(l => l.Rate == 0m && VatNatures.CountsForStampDuty(l.Nature)).Sum(l => l.Taxable));
|
||||
var required = exempt > StampDutyThreshold;
|
||||
return new StampDutyAssessment(required, required ? StampDutyAmount : 0m, exempt, StampDutyThreshold);
|
||||
}
|
||||
|
||||
private static string? Normalize(string? nature) =>
|
||||
string.IsNullOrWhiteSpace(nature) ? null : nature.Trim().ToUpperInvariant();
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
using Khaemhat.Fiscal.Abstractions;
|
||||
|
||||
namespace Khaemhat.Fiscal.Italy;
|
||||
|
||||
/// <summary>
|
||||
/// The Italian fiscal pack (SPEC §1.10, ADR 0007, ADR 0025): chosen for companies whose <c>company_profile.country</c>
|
||||
/// is <c>IT</c>. Registered only by the composition root of <c>Khaemhat.Web</c>.
|
||||
/// </summary>
|
||||
public sealed class ItalyFiscalPack : FiscalPackBase
|
||||
{
|
||||
/// <summary>The version of the Italian base data and code lists.</summary>
|
||||
public const string Version = "IT 2026.3";
|
||||
|
||||
/// <summary>Creates the pack with every feature this version delivers.</summary>
|
||||
public ItalyFiscalPack()
|
||||
{
|
||||
AddFeature<IEInvoiceFormat>(new FatturaPaFormat());
|
||||
AddFeature<IWithholdingRules>(new WithholdingRulesIt());
|
||||
AddFeature<IFixedAssetRules>(new FixedAssetRulesIt());
|
||||
AddFeature<ITaxPaymentFormExporter>(new F24Exporter());
|
||||
AddFeature<ITaxIdentifierRules>(new ItalianTaxIdentifierRules());
|
||||
AddFeature<IBaseTablesTemplate>(new ItalianBaseTables());
|
||||
AddFeature<IPlaceDirectory>(new ItalianPlaces());
|
||||
|
||||
// ABI and CAB are read from every Italian IBAN; bank names and BICs arrive with the ABI list (ADR 0026).
|
||||
AddFeature<IBankDirectory>(new ItalianBankDirectory([]));
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public override string CountryCode => "IT";
|
||||
|
||||
/// <inheritdoc />
|
||||
public override string Name => "Italia";
|
||||
|
||||
/// <inheritdoc />
|
||||
public override string DataVersion => Version;
|
||||
|
||||
/// <inheritdoc />
|
||||
public override ITaxCodeCatalog TaxCodes { get; } = new ItalianTaxCodeCatalog();
|
||||
|
||||
/// <inheritdoc />
|
||||
public override ITaxEngine TaxEngine { get; } = new ItalianTaxEngine();
|
||||
|
||||
/// <inheritdoc />
|
||||
public override IFiscalCalendar Calendar { get; } = new ItalianFiscalCalendar();
|
||||
}
|
||||
@@ -4,6 +4,11 @@
|
||||
<RootNamespace>Khaemhat.Fiscal.Italy</RootNamespace>
|
||||
</PropertyGroup>
|
||||
|
||||
<!-- Provinces and municipalities from the ISTAT list (ADR 0028). -->
|
||||
<ItemGroup>
|
||||
<EmbeddedResource Include="Data/*.csv" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="../Khaemhat.Core/Khaemhat.Core.csproj" />
|
||||
<ProjectReference Include="../Khaemhat.Fiscal.Abstractions/Khaemhat.Fiscal.Abstractions.csproj" />
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
using Khaemhat.Core.Tax;
|
||||
using Khaemhat.Fiscal.Abstractions;
|
||||
|
||||
namespace Khaemhat.Fiscal.Italy;
|
||||
|
||||
/// <summary>
|
||||
/// The VAT natures of the FatturaPA specifications (<c>Natura</c>, N1-N7). Since 2021 the generic codes N2, N3 and N6
|
||||
/// are no longer accepted: only their sub-codes.
|
||||
/// </summary>
|
||||
public static class VatNatures
|
||||
{
|
||||
/// <summary>Every nature, obsolete ones included.</summary>
|
||||
public static CodeList All { get; } = new("VatNatures",
|
||||
[
|
||||
new("N1", "Escluse ex art. 15 DPR 633/72"),
|
||||
new("N2", "Non soggette", Obsolete: true),
|
||||
new("N2.1", "Non soggette ad IVA ai sensi degli artt. da 7 a 7-septies DPR 633/72"),
|
||||
new("N2.2", "Non soggette - altri casi"),
|
||||
new("N3", "Non imponibili", Obsolete: true),
|
||||
new("N3.1", "Non imponibili - esportazioni"),
|
||||
new("N3.2", "Non imponibili - cessioni intracomunitarie"),
|
||||
new("N3.3", "Non imponibili - cessioni verso San Marino"),
|
||||
new("N3.4", "Non imponibili - operazioni assimilate alle cessioni all'esportazione"),
|
||||
new("N3.5", "Non imponibili - a seguito di dichiarazioni d'intento"),
|
||||
new("N3.6", "Non imponibili - altre operazioni che non concorrono alla formazione del plafond"),
|
||||
new("N4", "Esenti"),
|
||||
new("N5", "Regime del margine / IVA non esposta in fattura"),
|
||||
new("N6", "Inversione contabile", Obsolete: true),
|
||||
new("N6.1", "Inversione contabile - cessione di rottami e altri materiali di recupero"),
|
||||
new("N6.2", "Inversione contabile - cessione di oro e argento ai sensi della L. 7/2000 nonché di oreficeria usata ad OPO"),
|
||||
new("N6.3", "Inversione contabile - subappalto nel settore edile"),
|
||||
new("N6.4", "Inversione contabile - cessione di fabbricati"),
|
||||
new("N6.5", "Inversione contabile - cessione di telefoni cellulari"),
|
||||
new("N6.6", "Inversione contabile - cessione di prodotti elettronici"),
|
||||
new("N6.7", "Inversione contabile - prestazioni comparto edile e settori connessi"),
|
||||
new("N6.8", "Inversione contabile - operazioni settore energetico"),
|
||||
new("N6.9", "Inversione contabile - altri casi"),
|
||||
new("N7", "IVA assolta in altro stato UE (art. 7-octies e art. 74-sexies DPR 633/72)"),
|
||||
]);
|
||||
|
||||
// Natures whose amounts count toward the stamp duty threshold: exports (N3.1), intra-EU supplies (N3.2), San Marino
|
||||
// (N3.3), operations assimilated to exports (N3.4), reverse charge (N6.x) and VAT paid in another EU state (N7) are
|
||||
// exempt from stamp duty (art. 15 of the table attached to DPR 642/72 and the Agenzia's guidance).
|
||||
private static readonly HashSet<string> StampDutyNatures = new(StringComparer.OrdinalIgnoreCase)
|
||||
{
|
||||
"N1", "N2.1", "N2.2", "N3.5", "N3.6", "N4", "N5",
|
||||
};
|
||||
|
||||
/// <summary>The kind of operation a nature describes; no nature means a taxable operation.</summary>
|
||||
/// <param name="nature">The nature code.</param>
|
||||
/// <returns>The kind.</returns>
|
||||
public static TaxCodeKind KindOf(string? nature)
|
||||
{
|
||||
var code = nature?.Trim().ToUpperInvariant() ?? string.Empty;
|
||||
return code switch
|
||||
{
|
||||
"" => TaxCodeKind.Taxable,
|
||||
"N1" => TaxCodeKind.Excluded,
|
||||
"N4" => TaxCodeKind.Exempt,
|
||||
"N5" => TaxCodeKind.Margin,
|
||||
"N7" => TaxCodeKind.OtherEuVat,
|
||||
_ when code.StartsWith("N2", StringComparison.Ordinal) => TaxCodeKind.NotSubject,
|
||||
_ when code.StartsWith("N3", StringComparison.Ordinal) => TaxCodeKind.NonTaxable,
|
||||
_ when code.StartsWith("N6", StringComparison.Ordinal) => TaxCodeKind.ReverseCharge,
|
||||
_ => throw new ArgumentException($"Unknown VAT nature '{nature}'.", nameof(nature)),
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>Whether an amount with this nature counts toward the stamp duty threshold.</summary>
|
||||
/// <param name="nature">The nature code.</param>
|
||||
/// <returns><see langword="true"/> when the stamp duty rule counts it.</returns>
|
||||
public static bool CountsForStampDuty(string? nature) => nature is not null && StampDutyNatures.Contains(nature.Trim());
|
||||
|
||||
/// <summary>Whether the nature is a reverse charge one (N6.x).</summary>
|
||||
/// <param name="nature">The nature code.</param>
|
||||
/// <returns><see langword="true"/> for reverse charge.</returns>
|
||||
public static bool IsReverseCharge(string? nature) =>
|
||||
nature is not null && nature.Trim().StartsWith("N6", StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
using System.Text;
|
||||
|
||||
namespace Khaemhat.Infrastructure.Files;
|
||||
|
||||
/// <summary>
|
||||
/// Reads CSV files written by <see cref="CsvWriter"/> or by spreadsheets (RFC 4180): quoted fields with doubled quotes,
|
||||
/// line breaks inside quotes, an optional UTF-8 byte order mark. The separator is guessed from the first line
|
||||
/// (<c>;</c>, <c>,</c> or tab) unless given.
|
||||
/// </summary>
|
||||
public static class CsvReader
|
||||
{
|
||||
/// <summary>The separators tried, in order of preference.</summary>
|
||||
private static readonly char[] Separators = [';', ',', '\t'];
|
||||
|
||||
/// <summary>Reads every row of a text.</summary>
|
||||
/// <param name="text">The content.</param>
|
||||
/// <param name="separator">The separator, or <see langword="null"/> to guess it.</param>
|
||||
/// <returns>The rows; empty lines are skipped.</returns>
|
||||
public static IReadOnlyList<IReadOnlyList<string>> Parse(string text, char? separator = null)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(text);
|
||||
if (text.Length > 0 && text[0] == '')
|
||||
{
|
||||
text = text[1..];
|
||||
}
|
||||
|
||||
var sep = separator ?? Guess(text);
|
||||
var rows = new List<IReadOnlyList<string>>();
|
||||
var row = new List<string>();
|
||||
var field = new StringBuilder();
|
||||
var quoted = false;
|
||||
var fieldStarted = false;
|
||||
|
||||
for (var i = 0; i < text.Length; i++)
|
||||
{
|
||||
var c = text[i];
|
||||
if (quoted)
|
||||
{
|
||||
if (c == '"')
|
||||
{
|
||||
if (i + 1 < text.Length && text[i + 1] == '"')
|
||||
{
|
||||
field.Append('"');
|
||||
i++;
|
||||
}
|
||||
else
|
||||
{
|
||||
quoted = false;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
field.Append(c);
|
||||
}
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if (c == '"' && field.Length == 0)
|
||||
{
|
||||
quoted = true;
|
||||
fieldStarted = true;
|
||||
}
|
||||
else if (c == sep)
|
||||
{
|
||||
row.Add(field.ToString());
|
||||
field.Clear();
|
||||
fieldStarted = true;
|
||||
}
|
||||
else if (c is '\r' or '\n')
|
||||
{
|
||||
if (c == '\r' && i + 1 < text.Length && text[i + 1] == '\n')
|
||||
{
|
||||
i++;
|
||||
}
|
||||
|
||||
EndRow();
|
||||
}
|
||||
else
|
||||
{
|
||||
field.Append(c);
|
||||
fieldStarted = true;
|
||||
}
|
||||
}
|
||||
|
||||
EndRow();
|
||||
return rows;
|
||||
|
||||
void EndRow()
|
||||
{
|
||||
if (fieldStarted || field.Length > 0 || row.Count > 0)
|
||||
{
|
||||
row.Add(field.ToString());
|
||||
if (row.Count > 1 || row[0].Length > 0)
|
||||
{
|
||||
rows.Add(row);
|
||||
}
|
||||
}
|
||||
|
||||
row = [];
|
||||
field.Clear();
|
||||
fieldStarted = false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Reads a stream as UTF-8 (the byte order mark is optional).</summary>
|
||||
/// <param name="content">The stream.</param>
|
||||
/// <param name="separator">The separator, or <see langword="null"/> to guess it.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The rows.</returns>
|
||||
public static async Task<IReadOnlyList<IReadOnlyList<string>>> ReadAsync(Stream content, char? separator = null, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(content);
|
||||
using var reader = new StreamReader(content, Encoding.UTF8, detectEncodingFromByteOrderMarks: true, leaveOpen: true);
|
||||
return Parse(await reader.ReadToEndAsync(cancellationToken).ConfigureAwait(false), separator);
|
||||
}
|
||||
|
||||
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();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
using System.Globalization;
|
||||
using System.Xml;
|
||||
using System.Xml.Linq;
|
||||
|
||||
namespace Khaemhat.Infrastructure.Http;
|
||||
|
||||
/// <summary>A reference rate of the European Central Bank: units of the currency for one euro.</summary>
|
||||
/// <param name="Currency">The currency (ISO 4217).</param>
|
||||
/// <param name="Date">The day of the rate.</param>
|
||||
/// <param name="Rate">Units of the currency for one euro.</param>
|
||||
public sealed record EcbRate(string Currency, DateOnly Date, decimal Rate);
|
||||
|
||||
/// <summary>
|
||||
/// The euro foreign exchange reference rates of the European Central Bank (SPEC §11.1, §11.12), published on working
|
||||
/// days around 16:00 CET as an XML file (<c>eurofxref-daily.xml</c>, or the last 90 days in <c>eurofxref-hist-90d.xml</c>).
|
||||
/// </summary>
|
||||
public sealed class EcbRatesClient
|
||||
{
|
||||
/// <summary>The address of the reference rates.</summary>
|
||||
public static readonly Uri DefaultBaseAddress = new("https://www.ecb.europa.eu/stats/eurofxref/");
|
||||
|
||||
private const string Namespace = "http://www.ecb.int/vocabulary/2002-08-01/eurofxref";
|
||||
|
||||
private readonly HttpClient _http;
|
||||
|
||||
/// <summary>Creates the client.</summary>
|
||||
/// <param name="http">The HTTP client (its base address defaults to <see cref="DefaultBaseAddress"/>).</param>
|
||||
public EcbRatesClient(HttpClient http)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(http);
|
||||
_http = http;
|
||||
_http.BaseAddress ??= DefaultBaseAddress;
|
||||
}
|
||||
|
||||
/// <summary>Reads the rates of the last working day, or of the last 90 days.</summary>
|
||||
/// <param name="last90Days">Whether to read the last 90 days (to fill gaps after a stop).</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The rates.</returns>
|
||||
/// <exception cref="HttpRequestException">The service did not answer.</exception>
|
||||
/// <exception cref="FormatException">The answer is not the expected XML.</exception>
|
||||
public async Task<IReadOnlyList<EcbRate>> GetAsync(bool last90Days = false, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var path = new Uri(last90Days ? "eurofxref-hist-90d.xml" : "eurofxref-daily.xml", UriKind.Relative);
|
||||
using var response = await _http.GetAsync(path, cancellationToken).ConfigureAwait(false);
|
||||
response.EnsureSuccessStatusCode();
|
||||
var content = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
|
||||
await using (content.ConfigureAwait(false))
|
||||
{
|
||||
return await ParseAsync(content, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Reads the ECB XML.</summary>
|
||||
/// <param name="xml">The XML.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The rates.</returns>
|
||||
/// <exception cref="FormatException">The XML is not the ECB format.</exception>
|
||||
public static async Task<IReadOnlyList<EcbRate>> ParseAsync(Stream xml, CancellationToken cancellationToken = default)
|
||||
{
|
||||
XDocument document;
|
||||
try
|
||||
{
|
||||
var settings = new XmlReaderSettings { Async = true, DtdProcessing = DtdProcessing.Prohibit, XmlResolver = null };
|
||||
using var reader = XmlReader.Create(xml, settings);
|
||||
document = await XDocument.LoadAsync(reader, LoadOptions.None, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
catch (XmlException ex)
|
||||
{
|
||||
throw new FormatException("The ECB answer is not XML.", ex);
|
||||
}
|
||||
|
||||
XNamespace ns = Namespace;
|
||||
var rates = new List<EcbRate>();
|
||||
foreach (var day in document.Descendants(ns + "Cube").Where(c => c.Attribute("time") is not null))
|
||||
{
|
||||
if (!DateOnly.TryParseExact(day.Attribute("time")!.Value, "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None, out var date))
|
||||
{
|
||||
throw new FormatException("The ECB answer has a date that cannot be read.");
|
||||
}
|
||||
|
||||
foreach (var cube in day.Elements(ns + "Cube"))
|
||||
{
|
||||
var currency = cube.Attribute("currency")?.Value;
|
||||
var text = cube.Attribute("rate")?.Value;
|
||||
if (currency is { Length: 3 } && decimal.TryParse(text, NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out var rate) && rate > 0)
|
||||
{
|
||||
rates.Add(new EcbRate(currency, date, rate));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (rates.Count == 0)
|
||||
{
|
||||
throw new FormatException("The ECB answer has no rates.");
|
||||
}
|
||||
|
||||
return rates;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,168 @@
|
||||
using System.Globalization;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace Khaemhat.Infrastructure.Http;
|
||||
|
||||
/// <summary>The outcome of a VIES check.</summary>
|
||||
public enum ViesStatus
|
||||
{
|
||||
/// <summary>The number is registered for intra-EU operations.</summary>
|
||||
Valid = 0,
|
||||
|
||||
/// <summary>The number is not registered (or not active for intra-EU operations).</summary>
|
||||
Invalid = 1,
|
||||
|
||||
/// <summary>The service or the member state could not answer; try again later.</summary>
|
||||
Unavailable = 2,
|
||||
|
||||
/// <summary>The request was refused as malformed (unknown country, wrong characters).</summary>
|
||||
InvalidInput = 3,
|
||||
}
|
||||
|
||||
/// <summary>The answer of VIES, as saved on the party (SPEC §11.2).</summary>
|
||||
/// <param name="Status">The outcome.</param>
|
||||
/// <param name="CountryCode">The member state code asked (Greece is <c>EL</c>).</param>
|
||||
/// <param name="VatNumber">The number asked, without prefix.</param>
|
||||
/// <param name="CheckedAt">When VIES answered (or when the call failed), UTC.</param>
|
||||
/// <param name="Name">The registered name, when the member state shares it.</param>
|
||||
/// <param name="Address">The registered address, when shared.</param>
|
||||
/// <param name="Error">The VIES error code for <see cref="ViesStatus.Unavailable"/> and <see cref="ViesStatus.InvalidInput"/>.</param>
|
||||
public sealed record ViesResult(
|
||||
ViesStatus Status,
|
||||
string CountryCode,
|
||||
string VatNumber,
|
||||
DateTimeOffset CheckedAt,
|
||||
string? Name,
|
||||
string? Address,
|
||||
string? Error);
|
||||
|
||||
/// <summary>
|
||||
/// Checks EU VAT numbers with the VIES REST service of the European Commission
|
||||
/// (<c>GET /taxation_customs/vies/rest-api/ms/{country}/vat/{number}</c>). Network errors and timeouts become
|
||||
/// <see cref="ViesStatus.Unavailable"/>: a check that could not be made is never reported as invalid.
|
||||
/// </summary>
|
||||
public sealed class ViesClient
|
||||
{
|
||||
/// <summary>The public service address.</summary>
|
||||
public static readonly Uri DefaultBaseAddress = new("https://ec.europa.eu/taxation_customs/vies/rest-api/");
|
||||
|
||||
private static readonly HashSet<string> MemberStates = new(StringComparer.Ordinal)
|
||||
{
|
||||
"AT", "BE", "BG", "CY", "CZ", "DE", "DK", "EE", "EL", "ES", "FI", "FR", "HR", "HU", "IE", "IT", "LT", "LU",
|
||||
"LV", "MT", "NL", "PL", "PT", "RO", "SE", "SI", "SK", "XI",
|
||||
};
|
||||
|
||||
private readonly HttpClient _http;
|
||||
private readonly TimeProvider _time;
|
||||
|
||||
/// <summary>Creates the client.</summary>
|
||||
/// <param name="http">The HTTP client; its base address defaults to <see cref="DefaultBaseAddress"/>.</param>
|
||||
/// <param name="time">The clock.</param>
|
||||
public ViesClient(HttpClient http, TimeProvider time)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(http);
|
||||
ArgumentNullException.ThrowIfNull(time);
|
||||
_http = http;
|
||||
_http.BaseAddress ??= DefaultBaseAddress;
|
||||
_time = time;
|
||||
}
|
||||
|
||||
/// <summary>The VIES member state code for an ISO country code (Greece: <c>GR</c> becomes <c>EL</c>).</summary>
|
||||
/// <param name="isoCountryCode">ISO 3166-1 alpha-2 code.</param>
|
||||
/// <returns>The VIES code, or <see langword="null"/> outside the EU.</returns>
|
||||
public static string? MemberStateCode(string? isoCountryCode)
|
||||
{
|
||||
var code = isoCountryCode?.Trim().ToUpperInvariant();
|
||||
code = code == "GR" ? "EL" : code;
|
||||
return code is not null && MemberStates.Contains(code) ? code : null;
|
||||
}
|
||||
|
||||
/// <summary>Checks a VAT number.</summary>
|
||||
/// <param name="countryCode">ISO or VIES country code.</param>
|
||||
/// <param name="vatNumber">The number, with or without the country prefix.</param>
|
||||
/// <param name="cancellationToken">Cancels the call.</param>
|
||||
/// <returns>The outcome.</returns>
|
||||
public async Task<ViesResult> CheckAsync(string countryCode, string vatNumber, CancellationToken cancellationToken)
|
||||
{
|
||||
var state = MemberStateCode(countryCode);
|
||||
var number = string.Concat((vatNumber ?? string.Empty).Where(char.IsAsciiLetterOrDigit)).ToUpperInvariant();
|
||||
if (state is not null && number.StartsWith(state, StringComparison.Ordinal))
|
||||
{
|
||||
number = number[state.Length..];
|
||||
}
|
||||
|
||||
if (state is null || number.Length == 0)
|
||||
{
|
||||
return new ViesResult(ViesStatus.InvalidInput, countryCode ?? string.Empty, number, _time.GetUtcNow(), null, null, "INVALID_INPUT");
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
using var response = await _http.GetAsync(new Uri($"ms/{state}/vat/{Uri.EscapeDataString(number)}", UriKind.Relative), cancellationToken).ConfigureAwait(false);
|
||||
if (!response.IsSuccessStatusCode)
|
||||
{
|
||||
var status = (int)response.StatusCode;
|
||||
return Failed(state, number, status is >= 400 and < 500 && status != 429 ? ViesStatus.InvalidInput : ViesStatus.Unavailable,
|
||||
"HTTP_" + status.ToString(CultureInfo.InvariantCulture));
|
||||
}
|
||||
|
||||
var answer = await response.Content.ReadFromJsonAsync<ViesAnswer>(cancellationToken).ConfigureAwait(false);
|
||||
if (answer is null)
|
||||
{
|
||||
return Failed(state, number, ViesStatus.Unavailable, "EMPTY_RESPONSE");
|
||||
}
|
||||
|
||||
var error = answer.UserError;
|
||||
if (answer.IsValid)
|
||||
{
|
||||
return new ViesResult(ViesStatus.Valid, state, number, answer.RequestDate ?? _time.GetUtcNow(), Clean(answer.Name), Clean(answer.Address), null);
|
||||
}
|
||||
|
||||
return error is null or "VALID" or "INVALID"
|
||||
? new ViesResult(ViesStatus.Invalid, state, number, answer.RequestDate ?? _time.GetUtcNow(), null, null, null)
|
||||
: Failed(state, number, error == "INVALID_INPUT" ? ViesStatus.InvalidInput : ViesStatus.Unavailable, error);
|
||||
}
|
||||
catch (HttpRequestException ex)
|
||||
{
|
||||
return Failed(state, number, ViesStatus.Unavailable, ex.HttpRequestError.ToString());
|
||||
}
|
||||
catch (TaskCanceledException) when (!cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
return Failed(state, number, ViesStatus.Unavailable, "TIMEOUT");
|
||||
}
|
||||
catch (JsonException)
|
||||
{
|
||||
return Failed(state, number, ViesStatus.Unavailable, "BAD_RESPONSE");
|
||||
}
|
||||
}
|
||||
|
||||
private ViesResult Failed(string state, string number, ViesStatus status, string error) =>
|
||||
new(status, state, number, _time.GetUtcNow(), null, null, error);
|
||||
|
||||
// Member states that do not share the data answer with "---".
|
||||
private static string? Clean(string? value)
|
||||
{
|
||||
var text = value?.Trim();
|
||||
return string.IsNullOrEmpty(text) || text == "---" ? null : text;
|
||||
}
|
||||
|
||||
private sealed class ViesAnswer
|
||||
{
|
||||
[JsonPropertyName("isValid")]
|
||||
public bool IsValid { get; set; }
|
||||
|
||||
[JsonPropertyName("requestDate")]
|
||||
public DateTimeOffset? RequestDate { get; set; }
|
||||
|
||||
[JsonPropertyName("userError")]
|
||||
public string? UserError { get; set; }
|
||||
|
||||
[JsonPropertyName("name")]
|
||||
public string? Name { get; set; }
|
||||
|
||||
[JsonPropertyName("address")]
|
||||
public string? Address { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -10,7 +10,6 @@
|
||||
@page "/servizi/{*Rest}"
|
||||
@page "/canali/{*Rest}"
|
||||
@page "/report/{*Rest}"
|
||||
@page "/tabelle/{*Rest}"
|
||||
@page "/automazioni/{*Rest}"
|
||||
@page "/amministrazione/{*Rest}"
|
||||
@attribute [Authorize]
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
@page "/anagrafiche/categorie"
|
||||
@attribute [Authorize]
|
||||
@using Khaemhat.Web.Items
|
||||
@inject NavigationManager Navigation
|
||||
|
||||
@* The menu entry Anagrafiche > Categorie: the item categories are a company table, kept with the others. *@
|
||||
@code {
|
||||
/// <inheritdoc />
|
||||
protected override void OnInitialized() => Navigation.NavigateTo(ItemScreens.CategoriesUrl, new NavigationOptions { ReplaceHistoryEntry = true });
|
||||
}
|
||||
@@ -0,0 +1,782 @@
|
||||
@page "/anagrafiche/articoli/nuovo"
|
||||
@page "/anagrafiche/articoli/{Id:long}"
|
||||
@attribute [Authorize]
|
||||
@inherits MasterDataPage<ItemRecord>
|
||||
@using Khaemhat.Application.Audit
|
||||
@using Khaemhat.Application.Items
|
||||
@using Khaemhat.Application.Parties
|
||||
@using Khaemhat.Application.Security
|
||||
@using Khaemhat.Application.Tables
|
||||
@using Khaemhat.Core.Common
|
||||
@using Khaemhat.Core.Items
|
||||
@using Khaemhat.Web.Items
|
||||
@using Khaemhat.Web.Parties
|
||||
@using Khaemhat.Web.Components.Pages.Parties
|
||||
@using Khaemhat.Web.Tables
|
||||
@inject ShellSession Session
|
||||
@inject ItemService Items
|
||||
@inject PriceListService PriceLists
|
||||
@inject PartyService Parties
|
||||
@inject TableService Tables
|
||||
@inject AttachmentService Attachments
|
||||
|
||||
@* The record of an item (SPEC §11.2, mockup 017): header with code, description and the base price today, tabs for
|
||||
main data, alternative units, alternative codes, prices of the lists and net prices of the customers, suppliers,
|
||||
substitutes, notes with attachments, history. Stock and movements per warehouse arrive with the warehouse (M6). The
|
||||
checks are those of ItemService: errors stop the save and open the tab of the first one, warnings show after saving. *@
|
||||
<KhPageTitle Text="@PageTitle" Icon="box" />
|
||||
|
||||
@if (!_loaded)
|
||||
{
|
||||
<p class="muted kh-pad">@T["Common.Loading"]</p>
|
||||
}
|
||||
else if (Session.Company is null)
|
||||
{
|
||||
<div class="kh-message"><KhIcon Name="building" Class="lg" /><h1>@T["Items.NoCompany"]</h1></div>
|
||||
}
|
||||
else if (!Session.Permissions.Allows(ItemService.ReadPermission))
|
||||
{
|
||||
<div class="kh-message">
|
||||
<KhIcon Name="lock" Class="lg" />
|
||||
<h1>@T["Pages.AccessDenied.Title"]</h1>
|
||||
<p class="lead">@T["Pages.AccessDenied.Lead"]</p>
|
||||
</div>
|
||||
}
|
||||
else if (Record is null)
|
||||
{
|
||||
<div class="kh-message">
|
||||
<KhIcon Name="alert" Class="lg" />
|
||||
<h1>@T["Items.NotFound"]</h1>
|
||||
<a class="btn" href="@ItemScreens.RadarUrl">@T["Items.Title"]</a>
|
||||
</div>
|
||||
}
|
||||
else
|
||||
{
|
||||
<KhRecordLayout Page="this">
|
||||
<Heading>
|
||||
<KhDocHead KindIcon="box" KindLabel="@T["Items.Kinds." + I.Kind]" Number="@(I.Code.Length > 0 ? I.Code : T["Items.CodeAuto"])"
|
||||
PartyName="@(I.Description.Length > 0 ? I.Description : T["Items.NewTitle"])" PartyLines="HeadLines"
|
||||
TotalLabel="@BaseLabel" TotalValue="@(BasePrice is { } price ? T.Money(price) : null)" SubValues="HeadStats">
|
||||
<State>
|
||||
@if (I.Disabled)
|
||||
{
|
||||
<KhBadge Tone="KhTone.Neutral">@T["Items.States.Disabled"]</KhBadge>
|
||||
}
|
||||
else if (!IsNew)
|
||||
{
|
||||
<KhBadge Tone="KhTone.Ok">@T["Items.States.Active"]</KhBadge>
|
||||
}
|
||||
@if (!I.Stocked)
|
||||
{
|
||||
<KhBadge Tone="KhTone.Info">@T["Items.States.NotStocked"]</KhBadge>
|
||||
}
|
||||
@if (I.IsDemo)
|
||||
{
|
||||
<KhBadge Tone="KhTone.Info">@T["Items.States.Demo"]</KhBadge>
|
||||
}
|
||||
@if (IsModified)
|
||||
{
|
||||
<KhBadge Tone="KhTone.Warning">@T["CompanyTables.Modified"]</KhBadge>
|
||||
}
|
||||
</State>
|
||||
<Chips>
|
||||
@if (PartyScreens.Describe(_lookups.Categories, I.CategoryId, full: true) is { } category)
|
||||
{
|
||||
<KhChip Icon="folder" Text="@T["Items.Fields.CategoryId"]" Value="@category" />
|
||||
}
|
||||
@if (PartyScreens.Describe(_lookups.Units, I.UnitOfMeasureId) is { } unit)
|
||||
{
|
||||
<KhChip Icon="layers" Text="@T["Items.Fields.UnitOfMeasureId"]" Value="@unit" />
|
||||
}
|
||||
@if (PartyScreens.Describe(_lookups.TaxCodes, I.SalesTaxCodeId) is { } tax)
|
||||
{
|
||||
<KhChip Icon="euro" Text="@T["Items.Fields.SalesTaxCodeId"]" Value="@tax" />
|
||||
}
|
||||
@if (Record.Suppliers.FirstOrDefault(s => s.IsDefault) is { } supplier && _parties.TryGetValue(supplier.PartyId, out var party))
|
||||
{
|
||||
<KhChip Icon="truck" Text="@T["Items.Fields.Supplier"]" Value="@party.Name" />
|
||||
}
|
||||
</Chips>
|
||||
</KhDocHead>
|
||||
</Heading>
|
||||
<ChildContent>
|
||||
<KhForm Validation="Validation" ReadOnly="IsReadOnly" Layout="KhFormLayout.Groups" @ref="Form">
|
||||
@switch (ActiveTab)
|
||||
{
|
||||
case ItemScreens.Tabs.Main:
|
||||
<KhFieldGroup Title="@T["Items.Groups.Identity"]" Icon="box">
|
||||
<KhTextBox Label="@T["Items.Fields.Code"]" Name="Code" Value="@I.Code" ValueChanged="v => Change(() => I.Code = v ?? string.Empty)" Mono="true"
|
||||
Placeholder="@T["Items.CodeAuto"]" Span="4" MaxLength="30" />
|
||||
<KhSelect TValue="string" Label="@T["Items.Fields.Kind"]" Name="Kind" Options="KindChoices" Value="@I.Kind.ToString()" Span="4" ValueChanged="SetKind" />
|
||||
<KhSelect TValue="string" Label="@T["Items.Fields.CategoryId"]" Name="CategoryId" Options="_lookups.Categories" Empty="" Span="4"
|
||||
Value="@PartyScreens.Text(I.CategoryId)" ValueChanged="v => Change(() => I.CategoryId = PartyScreens.Id(v))" />
|
||||
<KhTextBox Label="@T["Items.Fields.Description"]" Name="Description" Value="@I.Description" ValueChanged="v => Change(() => I.Description = v ?? string.Empty)"
|
||||
Span="12" MaxLength="200" Required="true" />
|
||||
<KhTextArea Label="@T["Items.Fields.ExtendedDescription"]" Name="ExtendedDescription" Value="@I.ExtendedDescription"
|
||||
ValueChanged="v => Change(() => I.ExtendedDescription = v)" Span="12" Rows="3" />
|
||||
<KhTextBox Label="@T["Items.Fields.Brand"]" Name="Brand" Value="@I.Brand" ValueChanged="v => Change(() => I.Brand = v)" Span="6" MaxLength="100" />
|
||||
<KhTextBox Label="@T["Items.Fields.Manufacturer"]" Name="Manufacturer" Value="@I.Manufacturer" ValueChanged="v => Change(() => I.Manufacturer = v)" Span="6" MaxLength="100" />
|
||||
<KhCheck Label="@T["Items.Fields.Disabled"]" Name="Disabled" Value="I.Disabled" ValueChanged="v => Change(() => I.Disabled = v)" Span="4" />
|
||||
</KhFieldGroup>
|
||||
<KhFieldGroup Title="@T["Items.Groups.Codes"]" Icon="key">
|
||||
<KhSelect TValue="string" Label="@T["Items.Fields.UnitOfMeasureId"]" Name="UnitOfMeasureId" Options="_lookups.Units" Empty="" Span="4"
|
||||
Value="@PartyScreens.Text(I.UnitOfMeasureId)" ValueChanged="v => Change(() => I.UnitOfMeasureId = PartyScreens.Id(v))" />
|
||||
<KhTextBox Label="@T["Items.Fields.Barcode"]" Name="Barcode" Value="@I.Barcode" ValueChanged="v => Change(() => I.Barcode = v)" Mono="true" Span="4" MaxLength="20" />
|
||||
<KhTextBox Label="@T["Items.Fields.CustomsCode"]" Name="CustomsCode" Value="@I.CustomsCode" ValueChanged="v => Change(() => I.CustomsCode = v)" Mono="true" Span="4" MaxLength="10" />
|
||||
<KhSelect TValue="string" Label="@T["Items.Fields.SalesTaxCodeId"]" Name="SalesTaxCodeId" Options="_lookups.TaxCodes" Empty="" Span="6"
|
||||
Value="@PartyScreens.Text(I.SalesTaxCodeId)" ValueChanged="v => Change(() => I.SalesTaxCodeId = PartyScreens.Id(v))" />
|
||||
<KhSelect TValue="string" Label="@T["Items.Fields.PurchaseTaxCodeId"]" Name="PurchaseTaxCodeId" Options="_lookups.TaxCodes" Empty="" Span="6"
|
||||
Value="@PartyScreens.Text(I.PurchaseTaxCodeId)" ValueChanged="v => Change(() => I.PurchaseTaxCodeId = PartyScreens.Id(v))" />
|
||||
<KhNumberBox Label="@T["Items.Fields.NetWeight"]" Name="NetWeight" Value="I.NetWeight" ValueChanged="v => Change(() => I.NetWeight = v)" Min="0" Decimals="3" Span="6" />
|
||||
<KhNumberBox Label="@T["Items.Fields.GrossWeight"]" Name="GrossWeight" Value="I.GrossWeight" ValueChanged="v => Change(() => I.GrossWeight = v)" Min="0" Decimals="3" Span="6" />
|
||||
</KhFieldGroup>
|
||||
<KhFieldGroup Title="@T["Items.Groups.Prices"]" Icon="euro">
|
||||
<KhNumberBox Label="@T["Items.Fields.ItemPrice"]" Name="Price" Value="I.Price" ValueChanged="v => Change(() => I.Price = v)" Min="0" Span="6"
|
||||
Hint="@T["Items.Hints.ItemPrice"]" />
|
||||
@if (_costs)
|
||||
{
|
||||
<KhNumberBox Label="@T["Items.Fields.StandardCost"]" Name="StandardCost" Value="I.StandardCost" ValueChanged="v => Change(() => I.StandardCost = v)" Min="0" Span="6" />
|
||||
<KhNumberBox Label="@T["Items.Fields.LastCost"]" Name="LastCost" Value="I.LastCost" ReadOnly="true" Span="4" />
|
||||
<KhNumberBox Label="@T["Items.Fields.AverageCost"]" Name="AverageCost" Value="I.AverageCost" ReadOnly="true" Span="4" />
|
||||
<KhTextBox Label="@T["Items.Fields.Margin"]" Name="Margin" Value="@ItemScreens.MarginText(BasePrice, Cost, T.Culture)" ReadOnly="true" Span="4" />
|
||||
<p class="muted sm c12">@T["Items.Hints.Costs"]</p>
|
||||
}
|
||||
else
|
||||
{
|
||||
<p class="muted sm c6">@T["Items.Hints.CostsHidden"]</p>
|
||||
}
|
||||
</KhFieldGroup>
|
||||
<KhFieldGroup Title="@T["Items.Groups.Stock"]" Icon="layers">
|
||||
<KhCheck Label="@T["Items.Fields.Stocked"]" Name="Stocked" Value="I.Stocked" ValueChanged="v => Change(() => I.Stocked = v)" Span="6"
|
||||
Disabled="@(I.Kind != ItemKind.Goods)" />
|
||||
<KhSelect TValue="string" Label="@T["Items.Fields.WarehouseId"]" Name="WarehouseId" Options="_lookups.Warehouses" Empty="" Span="6"
|
||||
Value="@PartyScreens.Text(I.WarehouseId)" ValueChanged="v => Change(() => I.WarehouseId = PartyScreens.Id(v))" Disabled="@(!I.Stocked)" />
|
||||
<KhNumberBox Label="@T["Items.Fields.MinimumStock"]" Name="MinimumStock" Value="I.MinimumStock" ValueChanged="v => Change(() => I.MinimumStock = v)" Min="0" Decimals="3" Span="4" />
|
||||
<KhNumberBox Label="@T["Items.Fields.ReorderPoint"]" Name="ReorderPoint" Value="I.ReorderPoint" ValueChanged="v => Change(() => I.ReorderPoint = v)" Min="0" Decimals="3" Span="4" />
|
||||
<KhNumberBox Label="@T["Items.Fields.ReorderLot"]" Name="ReorderLot" Value="I.ReorderLot" ValueChanged="v => Change(() => I.ReorderLot = v)" Min="0" Decimals="3" Span="4" />
|
||||
<p class="muted sm c12">@T[I.Kind == ItemKind.Goods ? "Items.Hints.Stock" : "Items.Hints.NotStocked"]</p>
|
||||
</KhFieldGroup>
|
||||
<KhFieldGroup Title="@T["Items.Groups.Accounts"]" Icon="book" Wide="true">
|
||||
<KhTextBox Label="@T["Items.Fields.RevenueAccountCode"]" Name="RevenueAccountCode" Value="@I.RevenueAccountCode" ValueChanged="v => Change(() => I.RevenueAccountCode = v)"
|
||||
Mono="true" Span="3" MaxLength="20" />
|
||||
<KhTextBox Label="@T["Items.Fields.CostAccountCode"]" Name="CostAccountCode" Value="@I.CostAccountCode" ValueChanged="v => Change(() => I.CostAccountCode = v)"
|
||||
Mono="true" Span="3" MaxLength="20" />
|
||||
</KhFieldGroup>
|
||||
break;
|
||||
|
||||
case ItemScreens.Tabs.Units:
|
||||
<p class="muted kh-pad sm"><KhIcon Name="info" /> @T["Items.Hints.Units"]</p>
|
||||
@for (var i = 0; i < Record.Units.Count; i++)
|
||||
{
|
||||
var index = i;
|
||||
var u = Record.Units[i];
|
||||
<KhFieldGroup Title="@(PartyScreens.Describe(_lookups.Units, u.UnitOfMeasureId, full: true) ?? T["Items.Actions.AddUnit"])" Icon="layers" Wide="true">
|
||||
<KhSelect TValue="string" Label="@T["Items.Fields.UnitOfMeasureId"]" Name="@Key("Units", index, "UnitOfMeasureId")" Options="_lookups.Units" Empty="" Span="4" Required="true"
|
||||
Value="@PartyScreens.Text(u.UnitOfMeasureId is 0 ? null : u.UnitOfMeasureId)" ValueChanged="v => Change(() => u.UnitOfMeasureId = PartyScreens.Id(v) ?? 0)" />
|
||||
<KhNumberBox Label="@T["Items.Fields.Factor"]" Name="@Key("Units", index, "Factor")" Value="u.Factor" ValueChanged="v => Change(() => u.Factor = v ?? 0)" Min="0" Decimals="4" Span="3" />
|
||||
<KhTextBox Label="@T["Items.Fields.Barcode"]" Name="@Key("Units", index, "Barcode")" Value="@u.Barcode" ValueChanged="v => Change(() => u.Barcode = v)" Mono="true" Span="3" MaxLength="20" />
|
||||
@if (!IsReadOnly)
|
||||
{
|
||||
<div class="c2 kh-endrow">
|
||||
<button type="button" class="btn danger" @onclick="() => Remove(Record.Units, index)"><KhIcon Name="trash" /> @T["Items.Actions.Remove"]</button>
|
||||
</div>
|
||||
}
|
||||
</KhFieldGroup>
|
||||
}
|
||||
<DetailFooter Empty="@(Record.Units.Count == 0 ? T["Items.Empty.Units"] : null)" CanAdd="!IsReadOnly" AddText="@T["Items.Actions.AddUnit"]"
|
||||
OnAdd="() => Add(Record.Units, new ItemUnit())" />
|
||||
break;
|
||||
|
||||
case ItemScreens.Tabs.Barcodes:
|
||||
<p class="muted kh-pad sm"><KhIcon Name="info" /> @T["Items.Hints.Barcodes"]</p>
|
||||
@for (var i = 0; i < Record.Barcodes.Count; i++)
|
||||
{
|
||||
var index = i;
|
||||
var b = Record.Barcodes[i];
|
||||
<KhFieldGroup Title="@(b.Code.Length > 0 ? b.Code : T["Items.Actions.AddBarcode"])" Icon="key" Wide="true">
|
||||
<KhTextBox Label="@T["Items.Fields.Code"]" Name="@Key("Barcodes", index, "Code")" Value="@b.Code" ValueChanged="v => Change(() => b.Code = v ?? string.Empty)"
|
||||
Mono="true" Span="4" Required="true" MaxLength="40" />
|
||||
<KhTextBox Label="@T["Items.Fields.Description"]" Name="@Key("Barcodes", index, "Description")" Value="@b.Description" ValueChanged="v => Change(() => b.Description = v)"
|
||||
Span="6" MaxLength="100" />
|
||||
@if (!IsReadOnly)
|
||||
{
|
||||
<div class="c2 kh-endrow">
|
||||
<button type="button" class="btn danger" @onclick="() => Remove(Record.Barcodes, index)"><KhIcon Name="trash" /> @T["Items.Actions.Remove"]</button>
|
||||
</div>
|
||||
}
|
||||
</KhFieldGroup>
|
||||
}
|
||||
<DetailFooter Empty="@(Record.Barcodes.Count == 0 ? T["Items.Empty.Barcodes"] : null)" CanAdd="!IsReadOnly" AddText="@T["Items.Actions.AddBarcode"]"
|
||||
OnAdd="() => Add(Record.Barcodes, new ItemBarcode())" />
|
||||
break;
|
||||
|
||||
case ItemScreens.Tabs.Prices:
|
||||
@if (_today is { } today && !IsNew)
|
||||
{
|
||||
<KhFieldGroup Title="@T["Items.Groups.Today"]" Icon="tag" Wide="true">
|
||||
<table class="kh-table c12">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>@T["Items.Fields.PriceListId"]</th>
|
||||
<th class="num">@T["Items.Fields.Price"]</th>
|
||||
<th>@T["Items.Fields.ValidFrom"]</th>
|
||||
<th>@T["Items.Fields.Source"]</th>
|
||||
@if (_costs)
|
||||
{
|
||||
<th class="num">@T["Items.Fields.Margin"]</th>
|
||||
}
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
@foreach (var list in _columns)
|
||||
{
|
||||
var cell = today.Prices.GetValueOrDefault(list.Id) ?? PriceCell.Empty;
|
||||
<tr>
|
||||
<td><span class="code">@list.Code</span> @list.Description</td>
|
||||
<td class="num">@(cell.Price is { } p ? T.Money(p) : "-")</td>
|
||||
<td>@(cell.ValidFrom is { } from ? T.Date(from) : null)</td>
|
||||
<td class="muted sm">@(cell.Derived ? T["Items.Hints.Derived"] : null)</td>
|
||||
@if (_costs)
|
||||
{
|
||||
<td class="num">@ItemScreens.MarginText(cell.Price, Cost, T.Culture)</td>
|
||||
}
|
||||
</tr>
|
||||
}
|
||||
</tbody>
|
||||
</table>
|
||||
</KhFieldGroup>
|
||||
}
|
||||
<p class="muted kh-pad sm"><KhIcon Name="info" /> @T["Items.Hints.Prices"]</p>
|
||||
<KhFieldGroup Title="@T["Items.Groups.ListPrices"]" Icon="tag" Wide="true">
|
||||
@foreach (var index in PriceRows(net: false))
|
||||
{
|
||||
var p = Record.Prices[index];
|
||||
<KhSelect TValue="string" Label="@T["Items.Fields.PriceListId"]" Name="@Key("Prices", index, "PriceListId")" Options="_lookups.PriceLists" Empty="" Span="5" Required="true"
|
||||
Value="@PartyScreens.Text(p.PriceListId is 0 ? null : p.PriceListId)" ValueChanged="v => Change(() => p.PriceListId = PartyScreens.Id(v) ?? 0)" />
|
||||
<KhNumberBox Label="@T["Items.Fields.Price"]" Name="@Key("Prices", index, "Price")" Value="p.Price" ValueChanged="v => Change(() => p.Price = v ?? 0)" Min="0" Span="3" />
|
||||
<KhDateBox Label="@T["Items.Fields.ValidFrom"]" Name="@Key("Prices", index, "ValidFrom")" Value="p.ValidFrom" ValueChanged="v => Change(() => p.ValidFrom = v)" Span="2" />
|
||||
@if (!IsReadOnly)
|
||||
{
|
||||
<div class="c2 kh-endrow">
|
||||
<button type="button" class="btn danger" @onclick="() => Remove(Record.Prices, index)"><KhIcon Name="trash" /> @T["Items.Actions.Remove"]</button>
|
||||
</div>
|
||||
}
|
||||
}
|
||||
@if (!Record.Prices.Any(p => p.PartyId is null))
|
||||
{
|
||||
<p class="muted sm c12">@T["Items.Empty.ListPrices"]</p>
|
||||
}
|
||||
@if (!IsReadOnly)
|
||||
{
|
||||
<div class="c12">
|
||||
<button type="button" class="btn" @onclick="AddListPrice"><KhIcon Name="plus" /> @T["Items.Actions.AddPrice"]</button>
|
||||
</div>
|
||||
}
|
||||
</KhFieldGroup>
|
||||
<KhFieldGroup Title="@T["Items.Groups.NetPrices"]" Icon="users" Wide="true">
|
||||
@foreach (var index in PriceRows(net: true))
|
||||
{
|
||||
var p = Record.Prices[index];
|
||||
<KhHotlink TItem="PartyRow" Label="@T["Items.Fields.PartyId"]" Name="@Key("Prices", index, "PartyId")" Span="5" Required="true"
|
||||
Value="PartyOf(p.PartyId)" ValueChanged="v => SetParty(v, id => p.PartyId = id ?? 0)"
|
||||
Search="SearchCustomersAsync" CodeOf="r => r.Code" DescriptionOf="r => r.Name" OnOpen="OpenCustomer" />
|
||||
<KhNumberBox Label="@T["Items.Fields.Price"]" Name="@Key("Prices", index, "Price")" Value="p.Price" ValueChanged="v => Change(() => p.Price = v ?? 0)" Min="0" Span="3" />
|
||||
<KhDateBox Label="@T["Items.Fields.ValidFrom"]" Name="@Key("Prices", index, "ValidFrom")" Value="p.ValidFrom" ValueChanged="v => Change(() => p.ValidFrom = v)" Span="2" />
|
||||
@if (!IsReadOnly)
|
||||
{
|
||||
<div class="c2 kh-endrow">
|
||||
<button type="button" class="btn danger" @onclick="() => Remove(Record.Prices, index)"><KhIcon Name="trash" /> @T["Items.Actions.Remove"]</button>
|
||||
</div>
|
||||
}
|
||||
}
|
||||
@if (!Record.Prices.Any(p => p.PartyId is not null))
|
||||
{
|
||||
<p class="muted sm c12">@T["Items.Empty.NetPrices"]</p>
|
||||
}
|
||||
@if (!IsReadOnly)
|
||||
{
|
||||
<div class="c12">
|
||||
<button type="button" class="btn" @onclick="AddNetPrice"><KhIcon Name="plus" /> @T["Items.Actions.AddNetPrice"]</button>
|
||||
</div>
|
||||
}
|
||||
</KhFieldGroup>
|
||||
break;
|
||||
|
||||
case ItemScreens.Tabs.Suppliers:
|
||||
@for (var i = 0; i < Record.Suppliers.Count; i++)
|
||||
{
|
||||
var index = i;
|
||||
var s = Record.Suppliers[i];
|
||||
<KhFieldGroup Title="@(PartyOf(s.PartyId)?.Name ?? T["Items.Actions.AddSupplier"])" Icon="truck" Wide="true">
|
||||
<KhHotlink TItem="PartyRow" Label="@T["Items.Fields.Supplier"]" Name="@Key("Suppliers", index, "PartyId")" Span="5" Required="true"
|
||||
Value="PartyOf(s.PartyId)" ValueChanged="v => SetParty(v, id => s.PartyId = id ?? 0)"
|
||||
Search="SearchSuppliersAsync" CodeOf="r => r.Code" DescriptionOf="r => r.Name" OnOpen="OpenSupplier" />
|
||||
<KhTextBox Label="@T["Items.Fields.SupplierCode"]" Name="@Key("Suppliers", index, "SupplierCode")" Value="@s.SupplierCode" ValueChanged="v => Change(() => s.SupplierCode = v)"
|
||||
Mono="true" Span="4" MaxLength="40" />
|
||||
<KhCheck Label="@T["Items.Fields.IsDefault"]" Name="@Key("Suppliers", index, "IsDefault")" Value="s.IsDefault" ValueChanged="v => Change(() => s.IsDefault = v)" Span="3" />
|
||||
<KhNumberBox Label="@T["Items.Fields.Price"]" Name="@Key("Suppliers", index, "Price")" Value="s.Price" ValueChanged="v => Change(() => s.Price = v)" Min="0" Span="3" />
|
||||
<KhNumberBox Label="@T["Items.Fields.LeadTimeDays"]" Name="@Key("Suppliers", index, "LeadTimeDays")" Value="s.LeadTimeDays" ValueChanged="v => Change(() => s.LeadTimeDays = (int?)v)"
|
||||
Min="0" Decimals="0" Span="3" />
|
||||
<KhNumberBox Label="@T["Items.Fields.MinimumQuantity"]" Name="@Key("Suppliers", index, "MinimumQuantity")" Value="s.MinimumQuantity" ValueChanged="v => Change(() => s.MinimumQuantity = v)"
|
||||
Min="0" Decimals="3" Span="3" />
|
||||
@if (!IsReadOnly)
|
||||
{
|
||||
<div class="c3 kh-endrow">
|
||||
<button type="button" class="btn danger" @onclick="() => Remove(Record.Suppliers, index)"><KhIcon Name="trash" /> @T["Items.Actions.Remove"]</button>
|
||||
</div>
|
||||
}
|
||||
</KhFieldGroup>
|
||||
}
|
||||
<DetailFooter Empty="@(Record.Suppliers.Count == 0 ? T["Items.Empty.Suppliers"] : null)" CanAdd="!IsReadOnly" AddText="@T["Items.Actions.AddSupplier"]"
|
||||
OnAdd="() => Add(Record.Suppliers, new ItemSupplier { IsDefault = Record.Suppliers.Count == 0 })" />
|
||||
break;
|
||||
|
||||
case ItemScreens.Tabs.Substitutes:
|
||||
@for (var i = 0; i < Record.Substitutes.Count; i++)
|
||||
{
|
||||
var index = i;
|
||||
var s = Record.Substitutes[i];
|
||||
<KhFieldGroup Title="@(ItemOf(s.SubstituteId)?.Description ?? T["Items.Actions.AddSubstitute"])" Icon="refresh" Wide="true">
|
||||
<KhHotlink TItem="ItemRow" Label="@T["Items.Fields.SubstituteId"]" Name="@Key("Substitutes", index, "SubstituteId")" Span="5" Required="true"
|
||||
Value="ItemOf(s.SubstituteId)" ValueChanged="v => SetItem(v, id => s.SubstituteId = id ?? 0)"
|
||||
Search="SearchItemsAsync" CodeOf="r => r.Code" DescriptionOf="r => r.Description" OnOpen="OpenItem" />
|
||||
<KhTextBox Label="@T["Items.Fields.Notes"]" Name="@Key("Substitutes", index, "Notes")" Value="@s.Notes" ValueChanged="v => Change(() => s.Notes = v)" Span="5" MaxLength="200" />
|
||||
@if (!IsReadOnly)
|
||||
{
|
||||
<div class="c2 kh-endrow">
|
||||
<button type="button" class="btn danger" @onclick="() => Remove(Record.Substitutes, index)"><KhIcon Name="trash" /> @T["Items.Actions.Remove"]</button>
|
||||
</div>
|
||||
}
|
||||
</KhFieldGroup>
|
||||
}
|
||||
<DetailFooter Empty="@(Record.Substitutes.Count == 0 ? T["Items.Empty.Substitutes"] : null)" CanAdd="!IsReadOnly" AddText="@T["Items.Actions.AddSubstitute"]"
|
||||
OnAdd="() => Add(Record.Substitutes, new ItemSubstitute())" />
|
||||
break;
|
||||
|
||||
case ItemScreens.Tabs.Notes:
|
||||
<KhFieldGroup Title="@T["Items.Groups.Notes"]" Icon="edit" Wide="true">
|
||||
<KhTextArea Label="@T["Items.Fields.Notes"]" Name="Notes" Value="@I.Notes" ValueChanged="v => Change(() => I.Notes = v)" Span="12" Rows="6" />
|
||||
</KhFieldGroup>
|
||||
break;
|
||||
}
|
||||
</KhForm>
|
||||
@if (ActiveTab == ItemScreens.Tabs.Notes && !IsNew && Session.Permissions.Allows(AttachmentService.ReadPermission))
|
||||
{
|
||||
<div class="kh-tab-body"><KhAttachmentList Entity="@ItemService.Entity" EntityId="I.Id" OnCountChanged="c => _attachments = c" /></div>
|
||||
}
|
||||
@if (ActiveTab == ItemScreens.Tabs.History)
|
||||
{
|
||||
<div class="kh-tab-body"><KhAuditList Items="_history" FieldName="FieldLabel" /></div>
|
||||
}
|
||||
</ChildContent>
|
||||
</KhRecordLayout>
|
||||
}
|
||||
|
||||
@code {
|
||||
private ItemLookups _lookups = ItemLookups.Empty;
|
||||
private IReadOnlyList<AuditItem> _history = [];
|
||||
private IReadOnlyList<PriceListColumn> _columns = [];
|
||||
private readonly Dictionary<long, PartyRow> _parties = [];
|
||||
private readonly Dictionary<long, ItemRow> _items = [];
|
||||
private PriceGridRow? _today;
|
||||
private int _attachments;
|
||||
private bool _costs;
|
||||
private bool _loaded;
|
||||
private bool _busy;
|
||||
|
||||
/// <summary>The item, absent for a new one.</summary>
|
||||
[Parameter]
|
||||
public long? Id { get; set; }
|
||||
|
||||
private Item I => Record!.Item;
|
||||
|
||||
private bool CanWrite => Session.Permissions.Allows(ItemService.WritePermission);
|
||||
|
||||
private string PageTitle => Record is null ? T["Items.Title"] : IsNew ? T["Items.NewTitle"] : (Record.Item.Code + " · " + Record.Item.Description);
|
||||
|
||||
private PriceListColumn? BaseList => _columns.FirstOrDefault(c => c.IsBase);
|
||||
|
||||
private decimal? BasePrice => BaseList is { } list && _today?.Prices.GetValueOrDefault(list.Id) is { Price: { } price } ? price : I.Price;
|
||||
|
||||
private string BaseLabel => BaseList is { } list ? T["Items.Radar.BasePrice"] + " · " + list.Code : T["Items.Fields.ItemPrice"];
|
||||
|
||||
private decimal? Cost => I.AverageCost ?? I.StandardCost;
|
||||
|
||||
private IReadOnlyList<KhStat>? HeadStats => !_costs || IsNew ? null :
|
||||
[
|
||||
new(T["Items.Fields.AverageCost"], Cost is { } cost ? T.Money(cost) : "-"),
|
||||
new(T["Items.Fields.Margin"], ItemScreens.MarginText(BasePrice, Cost, T.Culture) ?? "-"),
|
||||
];
|
||||
|
||||
private IReadOnlyList<string> HeadLines
|
||||
{
|
||||
get
|
||||
{
|
||||
var lines = new List<string>();
|
||||
if (string.Join(" · ", new[] { I.Brand, I.Manufacturer }.Where(s => !string.IsNullOrWhiteSpace(s)).Distinct()) is { Length: > 0 } brand)
|
||||
{
|
||||
lines.Add(brand);
|
||||
}
|
||||
|
||||
if (I.Barcode is { } barcode)
|
||||
{
|
||||
lines.Add(T["Items.Fields.Barcode"] + " " + barcode);
|
||||
}
|
||||
|
||||
return lines;
|
||||
}
|
||||
}
|
||||
|
||||
private IReadOnlyList<KhOption<string>> KindChoices => ItemScreens.Choices<ItemKind>(T, "Kinds");
|
||||
|
||||
/// <inheritdoc />
|
||||
public override bool IsReadOnly => !CanWrite;
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override bool IsNew => Record is { Item.Id: 0 };
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override bool CanDelete => base.CanDelete && Session.Permissions.Allows(ItemService.DeletePermission);
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override string? NewUrl => CanWrite ? ItemScreens.NewUrl : null;
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override int? AttachmentCount => IsNew || Record is null ? null : _attachments;
|
||||
|
||||
/// <inheritdoc />
|
||||
public override IReadOnlyList<KhTabItem> Tabs => Record is null ? [] :
|
||||
[
|
||||
TabOf(ItemScreens.Tabs.Main, "box", "Main"),
|
||||
TabOf(ItemScreens.Tabs.Units, "layers", "Units", Record.Units.Count),
|
||||
TabOf(ItemScreens.Tabs.Barcodes, "key", "Barcodes", Record.Barcodes.Count),
|
||||
TabOf(ItemScreens.Tabs.Prices, "tag", "Prices", Record.Prices.Count),
|
||||
TabOf(ItemScreens.Tabs.Suppliers, "truck", "Suppliers", Record.Suppliers.Count),
|
||||
TabOf(ItemScreens.Tabs.Substitutes, "refresh", "Substitutes", Record.Substitutes.Count),
|
||||
TabOf(ItemScreens.Tabs.Notes, "paperclip", "Notes", IsNew ? null : _attachments),
|
||||
TabOf(ItemScreens.Tabs.History, "history", "History"),
|
||||
];
|
||||
|
||||
private KhTabItem TabOf(string id, string icon, string text, int? count = null)
|
||||
{
|
||||
// A tab with errors shows how many; otherwise how many details it holds.
|
||||
var errors = Validation.Messages.Count(m => ItemScreens.TabOf(m.Field) == id);
|
||||
return new(id, icon, T["Items.Tabs." + text], errors > 0 ? errors : count is > 0 ? count : null);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override async Task OnParametersSetAsync()
|
||||
{
|
||||
await Session.EnsureLoadedAsync();
|
||||
if (Session.Actor is { } actor && Session.Company?.Code is { } company && Session.Permissions.Allows(ItemService.ReadPermission))
|
||||
{
|
||||
if (!_loaded)
|
||||
{
|
||||
_lookups = await ItemLookups.ForRecordAsync(Tables, actor, company);
|
||||
_costs = await Items.CanSeeCostsAsync(actor, company);
|
||||
}
|
||||
|
||||
if (Record is null || Record.Item.Id != (Id ?? 0))
|
||||
{
|
||||
await ReloadAsync();
|
||||
MarkSaved();
|
||||
}
|
||||
}
|
||||
|
||||
_loaded = true;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override async Task ReloadAsync()
|
||||
{
|
||||
if (Session.Actor is not { } actor || Session.Company?.Code is not { } company)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
Validation.Clear();
|
||||
if (Id is { } id)
|
||||
{
|
||||
Record = await Items.GetAsync(actor, company, id);
|
||||
await LoadSideAsync(actor, company);
|
||||
}
|
||||
else
|
||||
{
|
||||
Record = await Items.NewAsync(actor, company);
|
||||
_history = [];
|
||||
_attachments = 0;
|
||||
_today = null;
|
||||
_columns = await PriceLists.ListsAsync(actor, company);
|
||||
}
|
||||
}
|
||||
|
||||
private async Task LoadSideAsync(Actor actor, string company)
|
||||
{
|
||||
if (Record is not { Item.Id: > 0 } record)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_history = [.. (await Items.HistoryAsync(actor, company, record.Item.Id)).Select(AuditTrailService.Item)];
|
||||
_attachments = Session.Permissions.Allows(AttachmentService.ReadPermission)
|
||||
? await Attachments.CountAsync(actor, company, ItemService.Entity, record.Item.Id)
|
||||
: 0;
|
||||
var grid = await PriceLists.GridAsync(actor, company,
|
||||
new ListQuery { Filters = [ListFilter.Of("code", ListFilterOperator.Equals, record.Item.Code)], Limit = 1 }, Today, null);
|
||||
_columns = grid.Lists;
|
||||
_today = grid.Page.Items.FirstOrDefault(r => r.ItemId == record.Item.Id);
|
||||
|
||||
// The names shown by the links: customers of the net prices, suppliers, substitutes.
|
||||
long[] parties = [.. record.Prices.Where(p => p.PartyId is not null).Select(p => p.PartyId!.Value).Concat(record.Suppliers.Select(s => s.PartyId)).Where(p => !_parties.ContainsKey(p))];
|
||||
if (parties.Length > 0 && Session.Permissions.Allows(PartyService.ReadPermission))
|
||||
{
|
||||
foreach (var row in await Parties.RowsAsync(actor, company, parties))
|
||||
{
|
||||
_parties[row.Id] = row;
|
||||
}
|
||||
}
|
||||
|
||||
long[] items = [.. record.Substitutes.Select(s => s.SubstituteId).Where(i => !_items.ContainsKey(i))];
|
||||
if (items.Length > 0)
|
||||
{
|
||||
foreach (var row in await Items.RowsAsync(actor, company, items))
|
||||
{
|
||||
_items[row.Id] = row;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static DateOnly Today => DateOnly.FromDateTime(DateTime.Today);
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override async Task<bool> SaveCoreAsync()
|
||||
{
|
||||
if (Record is null || Session.Actor is not { } actor || Session.Company?.Code is not { } company || _busy)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
_busy = true;
|
||||
Validation.Clear();
|
||||
try
|
||||
{
|
||||
var wasNew = IsNew;
|
||||
var problems = await Items.ValidateAsync(actor, company, Record);
|
||||
if (problems.Any(p => !p.IsWarning))
|
||||
{
|
||||
Refuse(problems.Where(p => !p.IsWarning).Select(p => ((string?)p.Field, p.Code)));
|
||||
return false;
|
||||
}
|
||||
|
||||
Record = await Items.SaveAsync(actor, company, Record);
|
||||
await LoadSideAsync(actor, company);
|
||||
if (problems.Count > 0)
|
||||
{
|
||||
Toasts.Show(ToastKind.Warning, T.Format("Items.Actions.Warnings", string.Join(" ", problems.Select(p => Message(p.Code)))));
|
||||
}
|
||||
|
||||
if (wasNew)
|
||||
{
|
||||
MarkSaved();
|
||||
Navigation.NavigateTo(ItemScreens.RecordUrl(Record.Item.Id), new NavigationOptions { ReplaceHistoryEntry = true });
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
catch (ValidationFailedException ex)
|
||||
{
|
||||
Refuse(ex.Errors.Select(TableValues.SplitError));
|
||||
return false;
|
||||
}
|
||||
catch (ConcurrencyException)
|
||||
{
|
||||
Toasts.Show(ToastKind.Error, T["CompanyTables.NotSaved"], T["CompanyTables.Concurrency"]);
|
||||
return false;
|
||||
}
|
||||
finally
|
||||
{
|
||||
_busy = false;
|
||||
}
|
||||
}
|
||||
|
||||
private void Refuse(IEnumerable<(string? Field, string Code)> errors)
|
||||
{
|
||||
foreach (var (field, code) in errors)
|
||||
{
|
||||
Validation.Add(field, Message(code));
|
||||
}
|
||||
|
||||
// Show the tab of the first error when the open one has none.
|
||||
if (!Validation.Messages.Any(m => ItemScreens.TabOf(m.Field) == ActiveTab) && Validation.Messages.FirstOrDefault() is { } first)
|
||||
{
|
||||
_ = ShowTabAsync(ItemScreens.TabOf(first.Field));
|
||||
}
|
||||
}
|
||||
|
||||
private string Message(string code) => T.Contains(code) ? T[code] : T["CompanyTables.UnknownError"];
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override async Task DeleteCoreAsync()
|
||||
{
|
||||
if (Record is not { Item.Id: > 0 } record || Session.Actor is not { } actor || Session.Company?.Code is not { } company)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (await Items.DeleteAsync(actor, company, record.Item.Id) == ItemDeleteOutcome.Disabled)
|
||||
{
|
||||
Toasts.Show(ToastKind.Info, T["Items.Actions.DeletedInstead"]);
|
||||
}
|
||||
|
||||
Navigation.NavigateTo(ItemScreens.RadarUrl);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override Task RadarAsync()
|
||||
{
|
||||
Navigation.NavigateTo(ItemScreens.RadarUrl);
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override Task AttachmentsAsync() => ShowTabAsync(ItemScreens.Tabs.Notes);
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override IEnumerable<ToolbarItem> ContextActions()
|
||||
{
|
||||
if (Record is null || IsNew)
|
||||
{
|
||||
yield break;
|
||||
}
|
||||
|
||||
yield return new ToolbarItem("pricelists", "tag", T["Items.Actions.PriceLists"])
|
||||
{
|
||||
Kind = ToolbarKind.Action, OnClick = () =>
|
||||
{
|
||||
Navigation.NavigateTo(ItemScreens.PriceListsUrl);
|
||||
return Task.CompletedTask;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override IEnumerable<ToolbarItem> MenuCommands()
|
||||
{
|
||||
if (Record is null || IsNew || !CanWrite)
|
||||
{
|
||||
yield break;
|
||||
}
|
||||
|
||||
yield return new ToolbarItem("disable", I.Disabled ? "check-circle" : "x-circle", T[I.Disabled ? "Items.Actions.Enable" : "Items.Actions.Disable"])
|
||||
{
|
||||
Kind = ToolbarKind.Menu, Disabled = IsModified || _busy, OnClick = ToggleDisabledAsync,
|
||||
};
|
||||
}
|
||||
|
||||
private async Task ToggleDisabledAsync()
|
||||
{
|
||||
if (Record is null || Session.Actor is not { } actor || Session.Company?.Code is not { } company)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var disabled = !I.Disabled;
|
||||
await Items.SetDisabledAsync(actor, company, [I.Id], disabled);
|
||||
Toasts.Show(ToastKind.Success, T.Format(disabled ? "Items.Actions.Disabled" : "Items.Actions.Enabled", 1));
|
||||
Record = await Items.GetAsync(actor, company, I.Id) ?? Record;
|
||||
await LoadSideAsync(actor, company);
|
||||
StateHasChanged();
|
||||
}
|
||||
|
||||
private void Change(Action change)
|
||||
{
|
||||
change();
|
||||
MarkModified();
|
||||
}
|
||||
|
||||
private static string Key(string list, int index, string field) => list + "." + index.ToString(System.Globalization.CultureInfo.InvariantCulture) + "." + field;
|
||||
|
||||
private void Add<TDetail>(List<TDetail> list, TDetail detail)
|
||||
{
|
||||
list.Add(detail);
|
||||
MarkModified();
|
||||
}
|
||||
|
||||
private void Remove<TDetail>(List<TDetail> list, int index)
|
||||
{
|
||||
if (index < list.Count)
|
||||
{
|
||||
list.RemoveAt(index);
|
||||
Validation.Clear();
|
||||
MarkModified();
|
||||
}
|
||||
}
|
||||
|
||||
// The positions of the list prices or of the net prices: the errors name a row by its position in Prices.
|
||||
private List<int> PriceRows(bool net) => [.. Enumerable.Range(0, Record!.Prices.Count).Where(i => Record.Prices[i].PartyId is not null == net)];
|
||||
|
||||
private void AddListPrice() => Add(Record!.Prices, new ItemPrice { PriceListId = BaseList?.Id ?? 0, ValidFrom = Today });
|
||||
|
||||
private void AddNetPrice() => Add(Record!.Prices, new ItemPrice { PartyId = 0, ValidFrom = Today });
|
||||
|
||||
private void SetKind(string? value) => Change(() =>
|
||||
{
|
||||
I.Kind = Enum.Parse<ItemKind>(value!);
|
||||
// Only goods go in stock.
|
||||
if (I.Kind != ItemKind.Goods)
|
||||
{
|
||||
I.Stocked = false;
|
||||
}
|
||||
});
|
||||
|
||||
private PartyRow? PartyOf(long? id) => id is { } key && _parties.TryGetValue(key, out var row) ? row : null;
|
||||
|
||||
private ItemRow? ItemOf(long id) => _items.TryGetValue(id, out var row) ? row : null;
|
||||
|
||||
private void SetParty(PartyRow? row, Action<long?> set) => Change(() =>
|
||||
{
|
||||
if (row is not null)
|
||||
{
|
||||
_parties[row.Id] = row;
|
||||
}
|
||||
|
||||
set(row?.Id);
|
||||
});
|
||||
|
||||
private void SetItem(ItemRow? row, Action<long?> set) => Change(() =>
|
||||
{
|
||||
if (row is not null)
|
||||
{
|
||||
_items[row.Id] = row;
|
||||
}
|
||||
|
||||
set(row?.Id);
|
||||
});
|
||||
|
||||
private async Task<IReadOnlyList<PartyRow>> SearchCustomersAsync(string text, CancellationToken cancellationToken) =>
|
||||
Session.Actor is { } actor && Session.Company?.Code is { } company && Session.Permissions.Allows(PartyService.ReadPermission)
|
||||
? await Parties.SearchAsync(actor, company, PartyArchive.Customers, text, cancellationToken)
|
||||
: [];
|
||||
|
||||
private async Task<IReadOnlyList<PartyRow>> SearchSuppliersAsync(string text, CancellationToken cancellationToken) =>
|
||||
Session.Actor is { } actor && Session.Company?.Code is { } company && Session.Permissions.Allows(PartyService.ReadPermission)
|
||||
? await Parties.SearchAsync(actor, company, PartyArchive.Suppliers, text, cancellationToken)
|
||||
: [];
|
||||
|
||||
private async Task<IReadOnlyList<ItemRow>> SearchItemsAsync(string text, CancellationToken cancellationToken) =>
|
||||
Session.Actor is { } actor && Session.Company?.Code is { } company
|
||||
? [.. (await Items.SearchAsync(actor, company, text, null, cancellationToken)).Where(r => r.Id != I.Id)]
|
||||
: [];
|
||||
|
||||
private void OpenCustomer(PartyRow row) => Navigation.NavigateTo(PartyScreens.RecordUrl(PartyArchive.Customers, row.Id));
|
||||
|
||||
private void OpenSupplier(PartyRow row) => Navigation.NavigateTo(PartyScreens.RecordUrl(PartyArchive.Suppliers, row.Id));
|
||||
|
||||
private void OpenItem(ItemRow row) => Navigation.NavigateTo(ItemScreens.RecordUrl(row.Id));
|
||||
|
||||
private string? FieldLabel(string field)
|
||||
{
|
||||
var key = "Items.Fields." + field.Split('.')[^1];
|
||||
return T.Contains(key) ? T[key] : null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,151 @@
|
||||
@page "/anagrafiche/articoli"
|
||||
@attribute [Authorize]
|
||||
@using Khaemhat.Application.Items
|
||||
@using Khaemhat.Application.Tables
|
||||
@using Khaemhat.Core.Items
|
||||
@using Khaemhat.Web.Items
|
||||
@using Khaemhat.Web.Parties
|
||||
@inject ShellSession Session
|
||||
@inject ItemService Items
|
||||
@inject TableService Tables
|
||||
@inject ToastService Toasts
|
||||
@inject NavigationManager Navigation
|
||||
|
||||
@* The radar of the items (SPEC §11.2): search on code, description, bar code, brand and producer; filters for kind,
|
||||
category, stock and state; the price of the base list today and, for who may see it, the average cost. Selection to
|
||||
disable or enable; Enter or double click opens the record. Stock arrives with the warehouse (M6). *@
|
||||
<KhPageTitle Text="@T["Items.Title"]" Icon="box" />
|
||||
|
||||
@if (!_loaded)
|
||||
{
|
||||
<p class="muted kh-pad">@T["Common.Loading"]</p>
|
||||
}
|
||||
else if (Session.Company is null)
|
||||
{
|
||||
<div class="kh-message"><KhIcon Name="building" Class="lg" /><h1>@T["Items.NoCompany"]</h1></div>
|
||||
}
|
||||
else if (!Session.Permissions.Allows(ItemService.ReadPermission))
|
||||
{
|
||||
<div class="kh-message">
|
||||
<KhIcon Name="lock" Class="lg" />
|
||||
<h1>@T["Pages.AccessDenied.Title"]</h1>
|
||||
<p class="lead">@T["Pages.AccessDenied.Lead"]</p>
|
||||
</div>
|
||||
}
|
||||
else
|
||||
{
|
||||
<KhRadar TItem="ItemRow" @ref="_radar" Id="items" Columns="Columns" Source="ListAsync" KeyOf="r => r.Id" Selectable="CanWrite" SelectionChanged="SetSelection"
|
||||
OnOpen="Open" QuickFilters="QuickFilters" InitialFilters="InitialFilters" RowClass="RowClassOf" SearchPlaceholder="@T["Items.Radar.Search"]"
|
||||
ExportName="articoli" Label="@T["Items.Title"]">
|
||||
<Toolbar>
|
||||
@if (CanWrite)
|
||||
{
|
||||
<button type="button" class="btn primary" @onclick="New"><KhIcon Name="plus" /> @T["Items.New"]</button>
|
||||
<button type="button" class="btn" disabled="@(_selected.Count == 0 || _busy)" @onclick="() => SetDisabledAsync(true)">
|
||||
<KhIcon Name="x-circle" /> @T["Items.Actions.Disable"]
|
||||
</button>
|
||||
<button type="button" class="btn" disabled="@(_selected.Count == 0 || _busy)" @onclick="() => SetDisabledAsync(false)">
|
||||
<KhIcon Name="check-circle" /> @T["Items.Actions.Enable"]
|
||||
</button>
|
||||
}
|
||||
<a class="btn" href="@ItemScreens.PriceListsUrl"><KhIcon Name="tag" /> @T["Items.Actions.PriceLists"]</a>
|
||||
</Toolbar>
|
||||
</KhRadar>
|
||||
}
|
||||
|
||||
@code {
|
||||
private ItemLookups _lookups = ItemLookups.Empty;
|
||||
private KhRadar<ItemRow>? _radar;
|
||||
private List<long> _selected = [];
|
||||
private bool _costs;
|
||||
private bool _loaded;
|
||||
private bool _busy;
|
||||
|
||||
private bool CanWrite => Session.Permissions.Allows(ItemService.WritePermission);
|
||||
|
||||
private static IReadOnlyList<ListFilter> InitialFilters => [ListFilter.Of("disabled", ListFilterOperator.Equals, "false")];
|
||||
|
||||
private IReadOnlyList<KhColumn<ItemRow>> Columns =>
|
||||
[
|
||||
new("code", T["Items.Fields.Code"], r => r.Code) { Kind = KhColumnKind.Code, Width = "130px" },
|
||||
new("description", T["Items.Fields.Description"], r => r.Description),
|
||||
new("category", T["Items.Radar.Category"], r => PartyScreens.Describe(_lookups.Categories, r.CategoryId)) { Width = "110px" },
|
||||
new("unit", T["Items.Radar.Unit"], r => PartyScreens.Describe(_lookups.Units, r.UnitOfMeasureId)) { Width = "60px" },
|
||||
new("barcode", T["Items.Fields.Barcode"], r => r.Barcode) { Width = "140px", Visible = false },
|
||||
new("brand", T["Items.Fields.Brand"], r => r.Brand) { Width = "130px" },
|
||||
new("kind", T["Items.Radar.Kind"], r => T["Items.Kinds." + r.Kind]) { Width = "100px" },
|
||||
new("averageCost", T["Items.Radar.AverageCost"], r => r.AverageCost) { Kind = KhColumnKind.Money, Width = "110px", Sortable = false, Visible = _costs, Export = _costs },
|
||||
new("basePrice", T["Items.Radar.BasePrice"], r => r.BasePrice) { Kind = KhColumnKind.Money, Width = "110px", Sortable = false },
|
||||
new("state", T["Items.Radar.State"], r => StateOf(r).Text)
|
||||
{
|
||||
Sortable = false, Width = "130px",
|
||||
Template = r => @<KhBadge Tone="StateOf(r).Tone">@StateOf(r).Text</KhBadge>,
|
||||
},
|
||||
];
|
||||
|
||||
private IReadOnlyList<KhQuickFilter> QuickFilters =>
|
||||
[
|
||||
new("kind", T["Items.Radar.Kind"], [new(string.Empty, T["Items.Radar.All"]), .. ItemScreens.Choices<ItemKind>(T, "Kinds")]),
|
||||
new("category", T["Items.Radar.Category"], [new(string.Empty, T["Items.Radar.All"]), .. _lookups.Categories]),
|
||||
new("stocked", T["Items.Radar.Stocked"],
|
||||
[new(string.Empty, T["Items.Radar.All"]), new("true", T["Items.Fields.Stocked"]), new("false", T["Items.States.NotStocked"])]),
|
||||
new("disabled", T["Items.Radar.State"],
|
||||
[new(string.Empty, T["Items.Radar.All"]), new("false", T["Items.Radar.Active"]), new("true", T["Items.Radar.Disabled"])]),
|
||||
];
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override async Task OnParametersSetAsync()
|
||||
{
|
||||
await Session.EnsureLoadedAsync();
|
||||
if (!_loaded && Session.Actor is { } actor && Session.Company?.Code is { } company && Session.Permissions.Allows(ItemService.ReadPermission))
|
||||
{
|
||||
_lookups = await ItemLookups.ForRadarAsync(Tables, actor, company);
|
||||
_costs = await Items.CanSeeCostsAsync(actor, company);
|
||||
}
|
||||
|
||||
_loaded = true;
|
||||
}
|
||||
|
||||
private (string Text, KhTone Tone) StateOf(ItemRow row) => row switch
|
||||
{
|
||||
{ Disabled: true } => (T["Items.States.Disabled"], KhTone.Neutral),
|
||||
{ Stocked: false } => (T["Items.States.NotStocked"], KhTone.Info),
|
||||
_ => (T["Items.States.Active"], KhTone.Ok),
|
||||
};
|
||||
|
||||
private Task<ListPage<ItemRow>> ListAsync(ListQuery query, CancellationToken cancellationToken) =>
|
||||
Session.Actor is { } actor && Session.Company?.Code is { } company
|
||||
? Items.ListAsync(actor, company, query, cancellationToken)
|
||||
: Task.FromResult(new ListPage<ItemRow>([], 0, new Dictionary<string, decimal>()));
|
||||
|
||||
private void SetSelection(IReadOnlyCollection<object> keys) => _selected = [.. keys.OfType<long>()];
|
||||
|
||||
private static string? RowClassOf(ItemRow row) => row.Disabled ? "muted" : null;
|
||||
|
||||
private void Open(ItemRow row) => Navigation.NavigateTo(ItemScreens.RecordUrl(row.Id));
|
||||
|
||||
private void New() => Navigation.NavigateTo(ItemScreens.NewUrl);
|
||||
|
||||
private async Task SetDisabledAsync(bool disabled)
|
||||
{
|
||||
if (Session.Actor is not { } actor || Session.Company?.Code is not { } company || _selected.Count == 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_busy = true;
|
||||
try
|
||||
{
|
||||
var count = await Items.SetDisabledAsync(actor, company, _selected, disabled);
|
||||
Toasts.Show(ToastKind.Success, T.Format(disabled ? "Items.Actions.Disabled" : "Items.Actions.Enabled", count));
|
||||
if (_radar is not null)
|
||||
{
|
||||
await _radar.ReloadAsync();
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
_busy = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,431 @@
|
||||
@page "/anagrafiche/listini"
|
||||
@attribute [Authorize]
|
||||
@using Khaemhat.Application.Items
|
||||
@using Khaemhat.Application.Parties
|
||||
@using Khaemhat.Application.Security
|
||||
@using Khaemhat.Application.Tables
|
||||
@using Khaemhat.Core.Items
|
||||
@using Khaemhat.Web.Items
|
||||
@using Khaemhat.Web.Parties
|
||||
@using Khaemhat.Web.Tables
|
||||
@inject ShellSession Session
|
||||
@inject PriceListService PriceLists
|
||||
@inject ItemService Items
|
||||
@inject PartyService Parties
|
||||
@inject TableService Tables
|
||||
@inject ToastService Toasts
|
||||
@inject DialogService Dialogs
|
||||
@inject NavigationManager Navigation
|
||||
|
||||
@* The price grid (SPEC §11.2, mockup 018): one row per item, one column per active price list with the price in effect
|
||||
at the validity date, the net prices of a customer and the margin. A price is changed in its cell (double click or
|
||||
F2) and a mass update computes many at once: the changed cells stay highlighted until saved, and every saved price
|
||||
starts at the validity date, so older documents keep the price of their day (ADR 0030). *@
|
||||
<KhPageTitle Text="@T["Items.PriceLists.Title"]" Icon="tag" />
|
||||
|
||||
@if (!_loaded)
|
||||
{
|
||||
<p class="muted kh-pad">@T["Common.Loading"]</p>
|
||||
}
|
||||
else if (Session.Company is null)
|
||||
{
|
||||
<div class="kh-message"><KhIcon Name="building" Class="lg" /><h1>@T["Items.NoCompany"]</h1></div>
|
||||
}
|
||||
else if (!Session.Permissions.Allows(ItemService.ReadPermission))
|
||||
{
|
||||
<div class="kh-message">
|
||||
<KhIcon Name="lock" Class="lg" />
|
||||
<h1>@T["Pages.AccessDenied.Title"]</h1>
|
||||
<p class="lead">@T["Pages.AccessDenied.Lead"]</p>
|
||||
</div>
|
||||
}
|
||||
else if (_lists.Count == 0)
|
||||
{
|
||||
<div class="kh-message">
|
||||
<KhIcon Name="tag" Class="lg" />
|
||||
<h1>@T["Items.PriceLists.NoLists"]</h1>
|
||||
<a class="btn" href="tabelle/listini">@T["Items.PriceLists.NewList"]</a>
|
||||
</div>
|
||||
}
|
||||
else
|
||||
{
|
||||
<div class="kh-pricebar">
|
||||
<div class="f">
|
||||
<label for="kh-pl-list">@T["Items.PriceLists.List"]</label>
|
||||
<select id="kh-pl-list" class="in" @onchange="e => _onlyList = PartyScreens.Id(e.Value as string)">
|
||||
<option value="" selected="@(_onlyList is null)">@T["Items.PriceLists.All"]</option>
|
||||
@foreach (var list in _lists)
|
||||
{
|
||||
<option value="@list.Id" selected="@(_onlyList == list.Id)">@list.Code · @list.Description</option>
|
||||
}
|
||||
</select>
|
||||
</div>
|
||||
<div class="kh-pricebar-date">
|
||||
<KhDateBox Label="@T["Items.PriceLists.Validity"]" Name="validity" Value="_date" ValueChanged="SetDateAsync" Span="12" />
|
||||
</div>
|
||||
@if (Session.Permissions.Allows(PartyService.ReadPermission))
|
||||
{
|
||||
<div class="kh-pricebar-party">
|
||||
<KhHotlink TItem="PartyRow" Label="@T["Items.PriceLists.Net"]" Name="party" Span="12" Value="_party" ValueChanged="SetPartyAsync"
|
||||
Search="SearchCustomersAsync" CodeOf="r => r.Code" DescriptionOf="r => r.Name" />
|
||||
</div>
|
||||
}
|
||||
@if (_costs)
|
||||
{
|
||||
<label class="kh-pricebar-check"><input type="checkbox" checked="@_showMargin" @onchange="e => _showMargin = e.Value is true" /> @T["Items.PriceLists.ShowMargin"]</label>
|
||||
}
|
||||
<span class="grow"></span>
|
||||
<KhBadge Tone="KhTone.Info">@(_party is null ? T.Format("Items.PriceLists.Count", _lists.Count) : T.Format("Items.PriceLists.CountNet", _lists.Count))</KhBadge>
|
||||
</div>
|
||||
|
||||
<KhRadar TItem="PriceGridRow" @ref="_radar" Id="pricelists" Columns="Columns" Source="ListAsync" KeyOf="r => r.ItemId" Selectable="CanWrite"
|
||||
SelectionChanged="SetSelection" OnOpen="Open" QuickFilters="QuickFilters" InitialFilters="InitialFilters" RowClass="RowClassOf"
|
||||
SearchPlaceholder="@T["Items.PriceLists.Search"]" ExportName="listini" Label="@T["Items.PriceLists.Title"]" Class="kh-pricegrid">
|
||||
<Toolbar>
|
||||
@if (CanWrite)
|
||||
{
|
||||
<button type="button" class="btn primary" disabled="@(_pending.Count == 0 || _busy)" @onclick="SaveAsync"><KhIcon Name="save" /> @T["Items.PriceLists.Save"]</button>
|
||||
<button type="button" class="btn" disabled="@(_pending.Count == 0 || _busy)" @onclick="UndoAsync"><KhIcon Name="undo" /> @T["Items.PriceLists.Undo"]</button>
|
||||
<button type="button" class="btn" disabled="@_busy" @onclick="OpenBulk"><KhIcon Name="zap" /> @T["Items.PriceLists.Bulk"]</button>
|
||||
}
|
||||
@if (Session.Permissions.Allows(TableService.WritePermission))
|
||||
{
|
||||
<a class="btn" href="tabelle/listini"><KhIcon Name="plus" /> @T["Items.PriceLists.NewList"]</a>
|
||||
}
|
||||
</Toolbar>
|
||||
<Summary>
|
||||
<span class="kh-pricefoot">@T.Format("Items.PriceLists.Footer", _pending.Count, T.Date(_date))</span>
|
||||
</Summary>
|
||||
</KhRadar>
|
||||
|
||||
<div class="callout info kh-pricehint"><KhIcon Name="info" /> <span>@T["Items.PriceLists.Hint"]</span></div>
|
||||
|
||||
<KhDialog Open="_bulkOpen" Title="@T["Items.Bulk.Title"]" Icon="zap" Size="md" OnClose="() => _bulkOpen = false">
|
||||
<ChildContent>
|
||||
<KhForm Validation="_bulkValidation" Layout="KhFormLayout.Grid">
|
||||
<KhSelect TValue="string" Label="@T["Items.Bulk.List"]" Name="PriceListId" Options="ListChoices" Value="@PartyScreens.Text(_bulk.PriceListId)" Span="6" Required="true"
|
||||
ValueChanged="v => _bulk = _bulk with { PriceListId = PartyScreens.Id(v) ?? 0 }" />
|
||||
<KhSelect TValue="string" Label="@T["Items.Bulk.Source"]" Name="SourcePriceListId" Options="ListChoices" Empty="@T["Items.Bulk.SourceSame"]" Span="6"
|
||||
Value="@PartyScreens.Text(_bulk.SourcePriceListId)" ValueChanged="v => _bulk = _bulk with { SourcePriceListId = PartyScreens.Id(v) }" />
|
||||
<KhNumberBox Label="@T["Items.Bulk.Percent"]" Name="Percent" Value="_bulk.Percent" ValueChanged="v => _bulk = _bulk with { Percent = v ?? 0 }" Min="-99" Max="1000" Span="4" />
|
||||
<KhSelect TValue="string" Label="@T["Items.Bulk.Step"]" Name="RoundingStep" Options="StepChoices" Value="@StepText(_bulk.RoundingStep)" Span="4"
|
||||
ValueChanged="SetStep" />
|
||||
<KhSelect TValue="string" Label="@T["Items.Bulk.Direction"]" Name="Direction" Options="DirectionChoices" Value="@_bulk.Direction.ToString()" Span="4"
|
||||
ValueChanged="SetDirection" />
|
||||
<KhSelect TValue="string" Label="@T["Items.Fields.CategoryId"]" Name="CategoryId" Options="_lookups.Categories" Empty="@T["Items.Bulk.ScopeAll"]" Span="6"
|
||||
Value="@PartyScreens.Text(_bulk.CategoryId)" ValueChanged="v => _bulk = _bulk with { CategoryId = PartyScreens.Id(v) }" />
|
||||
<KhDateBox Label="@T["Items.Bulk.Date"]" Name="Date" Value="_bulk.Date" ValueChanged="v => _bulk = _bulk with { Date = v ?? _date }" Span="6" Required="true" />
|
||||
@if (_selected.Count > 0)
|
||||
{
|
||||
<KhCheck Label="@T.Format("Items.Bulk.ScopeSelected", _selected.Count)" Name="Selected" Value="_bulkSelected" ValueChanged="v => _bulkSelected = v" Span="12" />
|
||||
}
|
||||
</KhForm>
|
||||
</ChildContent>
|
||||
<Footer>
|
||||
<button type="button" class="btn" @onclick="() => _bulkOpen = false">@T["Common.Cancel"]</button>
|
||||
<button type="button" class="btn primary" disabled="@_busy" @onclick="ApplyBulkAsync"><KhIcon Name="zap" /> @T["Items.Bulk.Apply"]</button>
|
||||
</Footer>
|
||||
</KhDialog>
|
||||
}
|
||||
|
||||
@code {
|
||||
private readonly Dictionary<Target, Pending> _pending = [];
|
||||
private readonly KhValidation _bulkValidation = new();
|
||||
private IReadOnlyList<PriceListColumn> _lists = [];
|
||||
private ItemLookups _lookups = ItemLookups.Empty;
|
||||
private KhRadar<PriceGridRow>? _radar;
|
||||
private List<long> _selected = [];
|
||||
private PartyRow? _party;
|
||||
private long? _onlyList;
|
||||
private DateOnly _date = DateOnly.FromDateTime(DateTime.Today);
|
||||
private BulkUpdate _bulk = new();
|
||||
private bool _bulkOpen;
|
||||
private bool _bulkSelected;
|
||||
private bool _showMargin = true;
|
||||
private bool _costs;
|
||||
private bool _loaded;
|
||||
private bool _busy;
|
||||
|
||||
/// <summary>A cell of the grid: a list price, or the net price of a customer.</summary>
|
||||
private readonly record struct Target(long ItemId, long? PriceListId, long? PartyId);
|
||||
|
||||
/// <summary>A price changed and not saved: none removes the price of that day.</summary>
|
||||
private readonly record struct Pending(decimal? Price, DateOnly ValidFrom);
|
||||
|
||||
private bool CanWrite => Session.Permissions.Allows(ItemService.WritePermission);
|
||||
|
||||
private static IReadOnlyList<ListFilter> InitialFilters => [ListFilter.Of("disabled", ListFilterOperator.Equals, "false")];
|
||||
|
||||
private PriceListColumn? MarginList => _lists.FirstOrDefault(l => l.Id == _onlyList) ?? _lists.FirstOrDefault(l => l.IsBase) ?? _lists.FirstOrDefault();
|
||||
|
||||
private IReadOnlyList<KhOption<string>> ListChoices => [.. _lists.Select(l => new KhOption<string>(PartyScreens.Text(l.Id)!, l.Code + " · " + l.Description))];
|
||||
|
||||
private IReadOnlyList<KhOption<string>> DirectionChoices => ItemScreens.Choices<RoundingDirection>(T, "Directions");
|
||||
|
||||
private IReadOnlyList<KhOption<string>> StepChoices =>
|
||||
[.. new[] { 0.01m, 0.10m, 0.50m, 1.00m }.Select(s => new KhOption<string>(StepText(s), s.ToString("0.00", T.Culture)))];
|
||||
|
||||
private void SetStep(string? value) =>
|
||||
_bulk = _bulk with { RoundingStep = decimal.TryParse(value, System.Globalization.NumberStyles.Number, System.Globalization.CultureInfo.InvariantCulture, out var step) ? step : 0.01m };
|
||||
|
||||
private void SetDirection(string? value) => _bulk = _bulk with { Direction = Enum.TryParse<RoundingDirection>(value, out var direction) ? direction : RoundingDirection.Nearest };
|
||||
|
||||
private static string StepText(decimal step) => step.ToString("0.00", System.Globalization.CultureInfo.InvariantCulture);
|
||||
|
||||
private IReadOnlyList<KhColumn<PriceGridRow>> Columns
|
||||
{
|
||||
get
|
||||
{
|
||||
var columns = new List<KhColumn<PriceGridRow>>
|
||||
{
|
||||
new("code", T["Items.Fields.Code"], r => r.Code) { Kind = KhColumnKind.Code, Width = "120px" },
|
||||
new("description", T["Items.Fields.Description"], r => r.Description),
|
||||
new("unit", T["Items.Radar.Unit"], r => PartyScreens.Describe(_lookups.Units, r.UnitOfMeasureId)) { Width = "60px" },
|
||||
};
|
||||
if (_costs)
|
||||
{
|
||||
columns.Add(new("averageCost", T["Items.Radar.AverageCost"], r => r.AverageCost) { Kind = KhColumnKind.Money, Width = "110px", Sortable = false });
|
||||
}
|
||||
|
||||
foreach (var list in _lists.Where(l => _onlyList is null || l.Id == _onlyList))
|
||||
{
|
||||
var id = list.Id;
|
||||
columns.Add(new("list-" + PartyScreens.Text(id), list.Code + " " + list.Description, r => PriceOf(r, id))
|
||||
{
|
||||
Kind = KhColumnKind.Money, Width = "120px", Sortable = false,
|
||||
CellClass = r => CellClassOf(r, new Target(r.ItemId, id, null)),
|
||||
Edit = CanWrite ? (r, text) => EditAsync(new Target(r.ItemId, id, null), CurrentOf(r, id), text) : null,
|
||||
});
|
||||
}
|
||||
|
||||
if (_party is { } party)
|
||||
{
|
||||
var partyId = party.Id;
|
||||
columns.Add(new("net", T.Format("Items.PriceLists.NetColumn", party.Name), r => NetOf(r, partyId))
|
||||
{
|
||||
Kind = KhColumnKind.Money, Width = "140px", Sortable = false,
|
||||
CellClass = r => CellClassOf(r, new Target(r.ItemId, null, partyId)),
|
||||
Edit = CanWrite ? (r, text) => EditAsync(new Target(r.ItemId, null, partyId), r.Net?.Price, text) : null,
|
||||
});
|
||||
}
|
||||
|
||||
if (_costs && _showMargin && MarginList is { } marginList)
|
||||
{
|
||||
var id = marginList.Id;
|
||||
columns.Add(new("margin", T.Format("Items.PriceLists.Margin", marginList.Code), r => ItemScreens.MarginText(PriceOf(r, id), r.AverageCost, T.Culture))
|
||||
{
|
||||
Width = "100px", Sortable = false, CellClass = _ => "num",
|
||||
});
|
||||
}
|
||||
|
||||
return columns;
|
||||
}
|
||||
}
|
||||
|
||||
private IReadOnlyList<KhQuickFilter> QuickFilters =>
|
||||
[
|
||||
new("category", T["Items.Radar.Category"], [new(string.Empty, T["Items.Radar.All"]), .. _lookups.Categories]),
|
||||
new("disabled", T["Items.Radar.State"],
|
||||
[new(string.Empty, T["Items.Radar.All"]), new("false", T["Items.Radar.Active"]), new("true", T["Items.Radar.Disabled"])]),
|
||||
];
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override async Task OnParametersSetAsync()
|
||||
{
|
||||
await Session.EnsureLoadedAsync();
|
||||
if (!_loaded && Session.Actor is { } actor && Session.Company?.Code is { } company && Session.Permissions.Allows(ItemService.ReadPermission))
|
||||
{
|
||||
_lookups = await ItemLookups.ForRadarAsync(Tables, actor, company);
|
||||
_lists = await PriceLists.ListsAsync(actor, company);
|
||||
_costs = await Items.CanSeeCostsAsync(actor, company);
|
||||
}
|
||||
|
||||
_loaded = true;
|
||||
}
|
||||
|
||||
private async Task<ListPage<PriceGridRow>> ListAsync(ListQuery query, CancellationToken cancellationToken)
|
||||
{
|
||||
if (Session.Actor is not { } actor || Session.Company?.Code is not { } company)
|
||||
{
|
||||
return new ListPage<PriceGridRow>([], 0, new Dictionary<string, decimal>());
|
||||
}
|
||||
|
||||
var grid = await PriceLists.GridAsync(actor, company, query, _date, _party?.Id, cancellationToken);
|
||||
return grid.Page;
|
||||
}
|
||||
|
||||
private decimal? CurrentOf(PriceGridRow row, long listId) => row.Prices.GetValueOrDefault(listId)?.Price;
|
||||
|
||||
private decimal? PriceOf(PriceGridRow row, long listId) =>
|
||||
_pending.TryGetValue(new Target(row.ItemId, listId, null), out var pending) ? pending.Price : CurrentOf(row, listId);
|
||||
|
||||
private decimal? NetOf(PriceGridRow row, long partyId) =>
|
||||
_pending.TryGetValue(new Target(row.ItemId, null, partyId), out var pending) ? pending.Price : row.Net?.Price;
|
||||
|
||||
private string? CellClassOf(PriceGridRow row, Target target)
|
||||
{
|
||||
if (_pending.ContainsKey(target))
|
||||
{
|
||||
return "kh-changed";
|
||||
}
|
||||
|
||||
return target.PriceListId is { } list && row.Prices.GetValueOrDefault(list) is { Derived: true } ? "kh-derived" : null;
|
||||
}
|
||||
|
||||
private Task<string?> EditAsync(Target target, decimal? current, string text)
|
||||
{
|
||||
if (!ItemScreens.TryParsePrice(text, T.Culture, out var price))
|
||||
{
|
||||
return Task.FromResult<string?>(T["Items.PriceLists.Invalid"]);
|
||||
}
|
||||
|
||||
// Back to the price in effect: nothing to save for this cell.
|
||||
if (price == current)
|
||||
{
|
||||
_pending.Remove(target);
|
||||
}
|
||||
else
|
||||
{
|
||||
_pending[target] = new Pending(price, _date);
|
||||
}
|
||||
|
||||
// The grid calls this as a plain delegate: the page renders again for Save and Undo to follow the count.
|
||||
StateHasChanged();
|
||||
return Task.FromResult<string?>(null);
|
||||
}
|
||||
|
||||
private static string? RowClassOf(PriceGridRow row) => null;
|
||||
|
||||
private void SetSelection(IReadOnlyCollection<object> keys) => _selected = [.. keys.OfType<long>()];
|
||||
|
||||
private void Open(PriceGridRow row) => Navigation.NavigateTo(ItemScreens.RecordUrl(row.ItemId));
|
||||
|
||||
private async Task SetDateAsync(DateOnly? value)
|
||||
{
|
||||
if (_pending.Count > 0)
|
||||
{
|
||||
Toasts.Show(ToastKind.Warning, T["Items.PriceLists.Leave"]);
|
||||
return;
|
||||
}
|
||||
|
||||
_date = value ?? DateOnly.FromDateTime(DateTime.Today);
|
||||
await ReloadAsync();
|
||||
}
|
||||
|
||||
private async Task SetPartyAsync(PartyRow? value)
|
||||
{
|
||||
if (_pending.Keys.Any(k => k.PartyId is not null))
|
||||
{
|
||||
Toasts.Show(ToastKind.Warning, T["Items.PriceLists.Leave"]);
|
||||
return;
|
||||
}
|
||||
|
||||
_party = value;
|
||||
await ReloadAsync();
|
||||
}
|
||||
|
||||
private async Task<IReadOnlyList<PartyRow>> SearchCustomersAsync(string text, CancellationToken cancellationToken) =>
|
||||
Session.Actor is { } actor && Session.Company?.Code is { } company
|
||||
? await Parties.SearchAsync(actor, company, PartyArchive.Customers, text, cancellationToken)
|
||||
: [];
|
||||
|
||||
private async Task ReloadAsync()
|
||||
{
|
||||
StateHasChanged();
|
||||
if (_radar is not null)
|
||||
{
|
||||
await _radar.ReloadAsync();
|
||||
}
|
||||
}
|
||||
|
||||
private async Task SaveAsync()
|
||||
{
|
||||
if (Session.Actor is not { } actor || Session.Company?.Code is not { } company)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (_pending.Count == 0)
|
||||
{
|
||||
Toasts.Show(ToastKind.Info, T["Items.PriceLists.NoChanges"]);
|
||||
return;
|
||||
}
|
||||
|
||||
_busy = true;
|
||||
try
|
||||
{
|
||||
IReadOnlyList<PriceEdit> edits = [.. _pending.Select(p => new PriceEdit(p.Key.ItemId, p.Key.PriceListId, p.Key.PartyId, p.Value.Price, p.Value.ValidFrom))];
|
||||
var written = await PriceLists.SaveAsync(actor, company, edits);
|
||||
_pending.Clear();
|
||||
Toasts.Show(ToastKind.Success, T.Format("Items.PriceLists.Saved", written));
|
||||
await ReloadAsync();
|
||||
}
|
||||
catch (ValidationFailedException ex)
|
||||
{
|
||||
Toasts.Show(ToastKind.Error, T["CompanyTables.NotSaved"],
|
||||
string.Join(" ", ex.Errors.Select(TableValues.SplitError).Select(e => e.Code).Distinct().Select(c => T.Contains(c) ? T[c] : T["CompanyTables.UnknownError"])));
|
||||
}
|
||||
finally
|
||||
{
|
||||
_busy = false;
|
||||
}
|
||||
}
|
||||
|
||||
private async Task UndoAsync()
|
||||
{
|
||||
if (_pending.Count == 0
|
||||
|| !await Dialogs.ConfirmAsync(new(T["Items.PriceLists.UndoTitle"], T["Items.PriceLists.UndoText"], T["Items.PriceLists.Undo"], T["Common.Cancel"], Danger: true)))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_pending.Clear();
|
||||
await ReloadAsync();
|
||||
}
|
||||
|
||||
private void OpenBulk()
|
||||
{
|
||||
_bulkValidation.Clear();
|
||||
_bulk = new BulkUpdate
|
||||
{
|
||||
PriceListId = _onlyList ?? _lists.FirstOrDefault(l => l.IsBase)?.Id ?? _lists[0].Id, RoundingStep = 0.10m, Direction = RoundingDirection.Nearest, Date = _date,
|
||||
};
|
||||
_bulkSelected = _selected.Count > 0;
|
||||
_bulkOpen = true;
|
||||
}
|
||||
|
||||
private async Task ApplyBulkAsync()
|
||||
{
|
||||
if (Session.Actor is not { } actor || Session.Company?.Code is not { } company)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_busy = true;
|
||||
try
|
||||
{
|
||||
var update = _bulk with { ItemIds = _bulkSelected && _selected.Count > 0 ? [.. _selected] : null };
|
||||
var edits = await PriceLists.PreviewAsync(actor, company, update);
|
||||
foreach (var edit in edits)
|
||||
{
|
||||
_pending[new Target(edit.ItemId, edit.PriceListId, edit.PartyId)] = new Pending(edit.Price, edit.ValidFrom ?? update.Date);
|
||||
}
|
||||
|
||||
_bulkOpen = false;
|
||||
Toasts.Show(edits.Count == 0 ? ToastKind.Info : ToastKind.Success, edits.Count == 0 ? T["Items.Bulk.None"] : T.Format("Items.Bulk.Result", edits.Count));
|
||||
await ReloadAsync();
|
||||
}
|
||||
catch (ValidationFailedException ex)
|
||||
{
|
||||
_bulkValidation.Clear();
|
||||
foreach (var (field, code) in ex.Errors.Select(TableValues.SplitError))
|
||||
{
|
||||
_bulkValidation.Add(field, T.Contains(code) ? T[code] : T["CompanyTables.UnknownError"]);
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
_busy = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
@* The foot of a list of details of a party (addresses, contacts, bank accounts): what to say when it is empty and the
|
||||
button that adds one. *@
|
||||
<div class="kh-detailfoot">
|
||||
@if (Empty is not null)
|
||||
{
|
||||
<span class="muted">@Empty</span>
|
||||
}
|
||||
@if (CanAdd)
|
||||
{
|
||||
<button type="button" class="btn" @onclick="OnAdd"><KhIcon Name="plus" /> @AddText</button>
|
||||
}
|
||||
</div>
|
||||
|
||||
@code {
|
||||
/// <summary>The text of an empty list, or <see langword="null"/>.</summary>
|
||||
[Parameter]
|
||||
public string? Empty { get; set; }
|
||||
|
||||
/// <summary>Whether a detail can be added.</summary>
|
||||
[Parameter]
|
||||
public bool CanAdd { get; set; }
|
||||
|
||||
/// <summary>The text of the button.</summary>
|
||||
[Parameter]
|
||||
public string AddText { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>Adds a detail.</summary>
|
||||
[Parameter]
|
||||
public EventCallback OnAdd { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,165 @@
|
||||
@page "/anagrafiche/clienti"
|
||||
@page "/anagrafiche/fornitori"
|
||||
@page "/anagrafiche/contatti"
|
||||
@attribute [Authorize]
|
||||
@using Khaemhat.Application.Parties
|
||||
@using Khaemhat.Application.Tables
|
||||
@using Khaemhat.Core.Parties
|
||||
@using Khaemhat.Web.Parties
|
||||
@inject ShellSession Session
|
||||
@inject PartyService Parties
|
||||
@inject TableService Tables
|
||||
@inject ToastService Toasts
|
||||
@inject NavigationManager Navigation
|
||||
|
||||
@* The radar of the parties (SPEC §11.2, mockups 012 and 013): customers, suppliers, or prospects and leads. Search on
|
||||
code, name, VAT number, tax code and city; filters for kind, subject and state; selection to disable or enable; Enter
|
||||
or double click opens the record. Turnover and overdue arrive with sales (M5) and the schedule (M9). *@
|
||||
<KhPageTitle Text="@Title" Icon="users" />
|
||||
|
||||
@if (!_loaded)
|
||||
{
|
||||
<p class="muted kh-pad">@T["Common.Loading"]</p>
|
||||
}
|
||||
else if (Session.Company is null)
|
||||
{
|
||||
<div class="kh-message"><KhIcon Name="building" Class="lg" /><h1>@T["Parties.NoCompany"]</h1></div>
|
||||
}
|
||||
else if (!Session.Permissions.Allows(PartyService.ReadPermission))
|
||||
{
|
||||
<div class="kh-message">
|
||||
<KhIcon Name="lock" Class="lg" />
|
||||
<h1>@T["Pages.AccessDenied.Title"]</h1>
|
||||
<p class="lead">@T["Pages.AccessDenied.Lead"]</p>
|
||||
</div>
|
||||
}
|
||||
else
|
||||
{
|
||||
<KhRadar TItem="PartyRow" @key="_archive" @ref="_radar" Id="@("parties." + PartyScreens.SegmentOf(_archive))" Columns="Columns" Source="ListAsync"
|
||||
KeyOf="r => r.Id" Selectable="CanWrite" SelectionChanged="SetSelection" OnOpen="Open" QuickFilters="QuickFilters"
|
||||
InitialFilters="InitialFilters" RowClass="RowClassOf" SearchPlaceholder="@T["Parties.Radar.Search"]"
|
||||
ExportName="@PartyScreens.SegmentOf(_archive)" Label="@Title">
|
||||
<Toolbar>
|
||||
@if (CanWrite)
|
||||
{
|
||||
<button type="button" class="btn primary" @onclick="() => New(null)"><KhIcon Name="plus" /> @T["Parties.New." + PartyScreens.NewKindOf(_archive)]</button>
|
||||
@if (_archive == PartyArchive.Contacts)
|
||||
{
|
||||
<button type="button" class="btn" @onclick="() => New(PartyKind.Lead)"><KhIcon Name="plus" /> @T["Parties.New.Lead"]</button>
|
||||
}
|
||||
<button type="button" class="btn" disabled="@(_selected.Count == 0 || _busy)" @onclick="() => SetDisabledAsync(true)">
|
||||
<KhIcon Name="x-circle" /> @T["Parties.Actions.Disable"]
|
||||
</button>
|
||||
<button type="button" class="btn" disabled="@(_selected.Count == 0 || _busy)" @onclick="() => SetDisabledAsync(false)">
|
||||
<KhIcon Name="check-circle" /> @T["Parties.Actions.Enable"]
|
||||
</button>
|
||||
}
|
||||
</Toolbar>
|
||||
</KhRadar>
|
||||
}
|
||||
|
||||
@code {
|
||||
private PartyArchive _archive;
|
||||
private PartyLookups _lookups = PartyLookups.Empty;
|
||||
private KhRadar<PartyRow>? _radar;
|
||||
private List<long> _selected = [];
|
||||
private bool _loaded;
|
||||
private bool _busy;
|
||||
|
||||
private string Title => T["Parties.Archives." + _archive];
|
||||
|
||||
private bool CanWrite => Session.Permissions.Allows(PartyService.WritePermission);
|
||||
|
||||
private static IReadOnlyList<ListFilter> InitialFilters => [ListFilter.Of("disabled", ListFilterOperator.Equals, "false")];
|
||||
|
||||
private IReadOnlyList<KhColumn<PartyRow>> Columns =>
|
||||
[
|
||||
new("code", T["Parties.Fields.Code"], r => r.Code) { Kind = KhColumnKind.Code, Width = "110px" },
|
||||
new("name", T["Parties.Fields.Name"], r => r.Name),
|
||||
new("vatNumber", T["Parties.Radar.Identifier"], r => r.Identifier) { Width = "170px" },
|
||||
new("city", T["Parties.Radar.City"], r => r.Province is { } p ? r.City + " (" + p + ")" : r.City) { Width = "170px" },
|
||||
new("payment", T["Parties.Radar.Payment"], r => PartyScreens.Describe(_lookups.PaymentTerms, r.Terms?.PaymentTermId, full: true)) { Sortable = false, Visible = _archive != PartyArchive.Contacts },
|
||||
new("priceList", T["Parties.Radar.PriceList"], r => PartyScreens.Describe(_lookups.PriceLists, r.Terms?.PriceListId)) { Sortable = false, Width = "90px", Visible = _archive == PartyArchive.Customers },
|
||||
new("salesperson", T["Parties.Radar.Salesperson"], r => PartyScreens.Describe(_lookups.Salespeople, r.SalespersonId, full: true)) { Width = "120px" },
|
||||
new("kind", T["Parties.Radar.Kind"], r => T["Parties.Kinds." + r.Kind]) { Width = "100px", Visible = _archive == PartyArchive.Contacts },
|
||||
new("state", T["Parties.Radar.State"], r => StateOf(r).Text)
|
||||
{
|
||||
Sortable = false, Width = "130px",
|
||||
Template = r => @<KhBadge Tone="StateOf(r).Tone">@StateOf(r).Text</KhBadge>,
|
||||
},
|
||||
];
|
||||
|
||||
private IReadOnlyList<KhQuickFilter> QuickFilters =>
|
||||
[
|
||||
.. _archive == PartyArchive.Contacts
|
||||
? [new KhQuickFilter("kind", T["Parties.Radar.Kind"],
|
||||
[new(string.Empty, T["Parties.Radar.All"]), new(nameof(PartyKind.Prospect), T["Parties.Kinds.Prospect"]), new(nameof(PartyKind.Lead), T["Parties.Kinds.Lead"])])]
|
||||
: Array.Empty<KhQuickFilter>(),
|
||||
new("subjectType", T["Parties.Radar.Subject"],
|
||||
[new(string.Empty, T["Parties.Radar.All"]), .. PartyScreens.Choices<SubjectType>(T, "SubjectTypes")]),
|
||||
new("salesperson", T["Parties.Radar.Salesperson"], [new(string.Empty, T["Parties.Radar.All"]), .. _lookups.Salespeople]),
|
||||
new("disabled", T["Parties.Radar.State"],
|
||||
[new(string.Empty, T["Parties.Radar.All"]), new("false", T["Parties.Radar.Active"]), new("true", T["Parties.Radar.Disabled"])]),
|
||||
];
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override async Task OnParametersSetAsync()
|
||||
{
|
||||
_archive = PartyScreens.ArchiveOf(Navigation.ToBaseRelativePath(Navigation.Uri));
|
||||
_selected = [];
|
||||
await Session.EnsureLoadedAsync();
|
||||
if (!_loaded && Session.Actor is { } actor && Session.Company?.Code is { } company && Session.Permissions.Allows(PartyService.ReadPermission))
|
||||
{
|
||||
_lookups = await PartyLookups.ForRadarAsync(Tables, actor, company);
|
||||
}
|
||||
|
||||
_loaded = true;
|
||||
}
|
||||
|
||||
private (string Text, KhTone Tone) StateOf(PartyRow row) => row switch
|
||||
{
|
||||
{ Disabled: true } => (T["Parties.States.Disabled"], KhTone.Neutral),
|
||||
{ Terms.Blocked: true } => (T["Parties.States.Blocked"], KhTone.Error),
|
||||
{ Terms.SplitPayment: true } => (T["Parties.States.Split"], KhTone.Info),
|
||||
{ SubjectType: SubjectType.EuCompany or SubjectType.NonEuCompany or SubjectType.Person } => (T["Parties.SubjectTypes." + row.SubjectType], KhTone.Info),
|
||||
{ Kind: PartyKind.Customer, IsAlsoSupplier: true } when _archive == PartyArchive.Suppliers => (T["Parties.States.AlsoCustomer"], KhTone.Accent),
|
||||
{ IsAlsoSupplier: true } => (T["Parties.States.AlsoSupplier"], KhTone.Accent),
|
||||
_ => (T["Parties.States.Active"], KhTone.Ok),
|
||||
};
|
||||
|
||||
private Task<ListPage<PartyRow>> ListAsync(ListQuery query, CancellationToken cancellationToken) =>
|
||||
Session.Actor is { } actor && Session.Company?.Code is { } company
|
||||
? Parties.ListAsync(actor, company, _archive, query, cancellationToken)
|
||||
: Task.FromResult(new ListPage<PartyRow>([], 0, new Dictionary<string, decimal>()));
|
||||
|
||||
private void SetSelection(IReadOnlyCollection<object> keys) => _selected = [.. keys.OfType<long>()];
|
||||
|
||||
private static string? RowClassOf(PartyRow row) => row.Disabled ? "muted" : null;
|
||||
|
||||
private void Open(PartyRow row) => Navigation.NavigateTo(PartyScreens.RecordUrl(_archive, row.Id));
|
||||
|
||||
private void New(PartyKind? kind) => Navigation.NavigateTo(PartyScreens.NewUrl(_archive, kind));
|
||||
|
||||
private async Task SetDisabledAsync(bool disabled)
|
||||
{
|
||||
if (Session.Actor is not { } actor || Session.Company?.Code is not { } company || _selected.Count == 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_busy = true;
|
||||
try
|
||||
{
|
||||
var count = await Parties.SetDisabledAsync(actor, company, _selected, disabled);
|
||||
Toasts.Show(ToastKind.Success, T.Format(disabled ? "Parties.Actions.Disabled" : "Parties.Actions.Enabled", count));
|
||||
if (_radar is not null)
|
||||
{
|
||||
await _radar.ReloadAsync();
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
_busy = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -99,7 +99,7 @@
|
||||
<div class="kh-seg" role="radiogroup" aria-label="@T["Pages.Profile.Density"]">
|
||||
@foreach (var density in Enum.GetValues<Density>())
|
||||
{
|
||||
<button type="button" role="radio" class="@(Draft.Density == density ? "on" : null)" aria-checked="@(Draft.Density == density)"
|
||||
<button type="button" role="radio" class="@(Draft.Density == density ? "on" : null)" aria-checked="@(Draft.Density == density ? "true" : "false")"
|
||||
@onclick="() => ChangeAsync(Draft with { Density = density })">@T["Pages.Profile.Density." + density]</button>
|
||||
}
|
||||
</div>
|
||||
@@ -110,7 +110,7 @@
|
||||
<div class="kh-seg" role="radiogroup" aria-label="@T["Pages.Profile.TextSize"]">
|
||||
@foreach (var size in UserPreferences.TextSizes)
|
||||
{
|
||||
<button type="button" role="radio" class="@(Draft.TextSize == size ? "on" : null)" aria-checked="@(Draft.TextSize == size)"
|
||||
<button type="button" role="radio" class="@(Draft.TextSize == size ? "on" : null)" aria-checked="@(Draft.TextSize == size ? "true" : "false")"
|
||||
@onclick="() => ChangeAsync(Draft with { TextSize = size })">@T.Format("Pages.Profile.TextSize.Value", size)</button>
|
||||
}
|
||||
</div>
|
||||
@@ -121,7 +121,7 @@
|
||||
<div class="kh-seg" role="radiogroup" aria-label="@T["Pages.Profile.Menu"]">
|
||||
@foreach (var (value, key) in MenuChoices)
|
||||
{
|
||||
<button type="button" role="radio" class="@(Draft.MenuCollapsed == value ? "on" : null)" aria-checked="@(Draft.MenuCollapsed == value)"
|
||||
<button type="button" role="radio" class="@(Draft.MenuCollapsed == value ? "on" : null)" aria-checked="@(Draft.MenuCollapsed == value ? "true" : "false")"
|
||||
@onclick="() => ChangeAsync(Draft with { MenuCollapsed = value })">@T[key]</button>
|
||||
}
|
||||
</div>
|
||||
|
||||
@@ -0,0 +1,249 @@
|
||||
@page "/tabelle/preferenze"
|
||||
@attribute [Authorize]
|
||||
@using Khaemhat.Application.Licensing
|
||||
@using Khaemhat.Application.Security
|
||||
@using Khaemhat.Application.Tables
|
||||
@using Khaemhat.Core.Tables
|
||||
@using Khaemhat.Web.Tables
|
||||
@inject ShellSession Session
|
||||
@inject CodeRuleService Codes
|
||||
@inject AutoFillService AutoFill
|
||||
@inject TableService Tables
|
||||
@inject ILicenseGate License
|
||||
@inject ToastService Toasts
|
||||
@inject TimeProvider Clock
|
||||
|
||||
@* Company preferences (SPEC §11.12, mockup 074): the masks of the automatic codes with the preview of the next code,
|
||||
and the automatic filling options. The other tabs of the mockup arrive with the documents and the e-mails. *@
|
||||
<KhPageTitle Text="@T["CompanyPreferences.Title"]" Icon="settings" />
|
||||
|
||||
<TablesGuard>
|
||||
<div class="phead">
|
||||
<div>
|
||||
<div class="crumbs"><a href="@TableScreens.BasePath">@T["Shell.Menu.CompanyTables"]</a> / @T["CompanyPreferences.Title"]</div>
|
||||
<h1>@T["CompanyPreferences.Heading"]</h1>
|
||||
<div class="sub">@T["CompanyPreferences.Hint"]</div>
|
||||
</div>
|
||||
<div class="grow"></div>
|
||||
@if (_modified)
|
||||
{
|
||||
<KhBadge Tone="KhTone.Warning">@T["CompanyTables.Modified"]</KhBadge>
|
||||
}
|
||||
<div class="toolbar">
|
||||
<button type="button" class="btn" disabled="@(!_modified)" @onclick="UndoAsync"><KhIcon Name="undo" /> @T["CompanyTables.Undo"]</button>
|
||||
<button type="button" class="btn primary" disabled="@(!_modified || !CanWrite || _busy)" @onclick="SaveAsync"><KhIcon Name="save" /> @T["Common.Save"]</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@if (_loaded)
|
||||
{
|
||||
<section class="panel kh-tables-profile">
|
||||
<KhTabs Items="TabItems" Active="@_tab" ActiveChanged="t => _tab = t" Label="@T["CompanyPreferences.Title"]" />
|
||||
@if (_tab == "codes")
|
||||
{
|
||||
<KhForm Validation="_validation" ReadOnly="!CanWrite" Layout="KhFormLayout.Groups">
|
||||
@foreach (var group in CodeRuleService.Definitions.GroupBy(d => d.Group))
|
||||
{
|
||||
<KhFieldGroup Title="@T["CompanyPreferences.Groups." + group.Key]" Icon="@GroupIcon(group.Key)">
|
||||
@foreach (var definition in group)
|
||||
{
|
||||
var rule = _rules[definition.Key];
|
||||
<KhTextBox Label="@T["CompanyPreferences.Rules." + definition.Key]" Name="@(definition.Key + "." + CodeRuleService.MaskField)" Mono="true"
|
||||
Value="@rule.Mask" MaxLength="40" ReadOnly="!CanWrite" Hint="@HintOf(definition)"
|
||||
ValueChanged="v => ChangeMaskAsync(definition.Key, v)" Span="6" />
|
||||
}
|
||||
<KhCheck Label="@T["CompanyPreferences.AllowManual"]" Name="@(group.Key + ".manual")" Value="group.All(d => _rules[d.Key].AllowManual)"
|
||||
ValueChanged="v => SetManual(group.Key, v)" ReadOnly="!CanWrite" Span="12" />
|
||||
@if (group.Key == "items")
|
||||
{
|
||||
<KhCheck Label="@T["CompanyPreferences.UniqueBarcode"]" Name="items.unique-barcode" Value="UniqueBarcode"
|
||||
ValueChanged="SetUniqueBarcode" ReadOnly="!CanWrite" Span="12" />
|
||||
}
|
||||
</KhFieldGroup>
|
||||
}
|
||||
<KhFieldGroup Title="@T["CompanyPreferences.Groups.documents"]" Icon="file">
|
||||
<p class="muted c12">@T["CompanyPreferences.Numerators"] <a href="/tabelle/numeratori">@T["CompanyPreferences.NumeratorsLink"]</a></p>
|
||||
</KhFieldGroup>
|
||||
</KhForm>
|
||||
<p class="muted kh-pad"><KhIcon Name="info" /> @T["CompanyPreferences.Placeholders"]</p>
|
||||
}
|
||||
else
|
||||
{
|
||||
<div class="kh-pad kh-autofill">
|
||||
@foreach (var option in AutoFillService.Options)
|
||||
{
|
||||
<KhSwitchRow Label="@T["CompanyPreferences.Options." + option.Key]" Hint="@T["CompanyPreferences.Options." + option.Key + ".Hint"]"
|
||||
Value="_options.GetValueOrDefault(option.Key)" ValueChanged="v => SetOption(option.Key, v)" />
|
||||
}
|
||||
<p class="muted"><KhIcon Name="info" /> @T["CompanyPreferences.AutoFillHint"]</p>
|
||||
</div>
|
||||
}
|
||||
</section>
|
||||
}
|
||||
</TablesGuard>
|
||||
|
||||
@code {
|
||||
private readonly KhValidation _validation = new();
|
||||
private Dictionary<string, CodeRule> _rules = new(StringComparer.Ordinal);
|
||||
private Dictionary<string, CodeRule> _savedRules = new(StringComparer.Ordinal);
|
||||
private Dictionary<string, bool> _options = new(StringComparer.Ordinal);
|
||||
private Dictionary<string, bool> _savedOptions = new(StringComparer.Ordinal);
|
||||
private readonly Dictionary<string, string?> _previews = new(StringComparer.Ordinal);
|
||||
private string? _category;
|
||||
private string _tab = "codes";
|
||||
private bool _loaded;
|
||||
private bool _modified;
|
||||
private bool _busy;
|
||||
|
||||
private bool CanWrite => Session.Permissions.Allows(TableService.WritePermission);
|
||||
|
||||
private bool UniqueBarcode => _rules.TryGetValue("items", out var items) && items.UniqueBarcode;
|
||||
|
||||
private IReadOnlyList<KhTabItem> TabItems =>
|
||||
[
|
||||
new("codes", "key", T["CompanyPreferences.Tabs.codes"], _validation.Messages.Count is > 0 and var n ? n : null),
|
||||
new("autofill", "zap", T["CompanyPreferences.Tabs.autofill"], null),
|
||||
];
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override async Task OnInitializedAsync()
|
||||
{
|
||||
await Session.EnsureLoadedAsync();
|
||||
if (Session.Actor is { } actor && Session.Company?.Code is { } company && Session.Permissions.Allows(TableService.ReadPermission))
|
||||
{
|
||||
_category = (await Tables.ActiveAsync<ItemCategory>(actor, company)).OrderBy(c => c.Code, StringComparer.Ordinal).FirstOrDefault()?.Code ?? "GEN";
|
||||
Show(await Codes.RulesAsync(actor, company), await AutoFill.OptionsAsync(actor, company));
|
||||
await PreviewAllAsync();
|
||||
_loaded = true;
|
||||
}
|
||||
}
|
||||
|
||||
private void Show(IReadOnlyList<CodeRule> rules, IReadOnlyDictionary<string, bool> options)
|
||||
{
|
||||
_rules = rules.ToDictionary(r => r.Key, StringComparer.Ordinal);
|
||||
_savedRules = new(_rules, StringComparer.Ordinal);
|
||||
_options = options.ToDictionary(o => o.Key, o => o.Value, StringComparer.Ordinal);
|
||||
_savedOptions = new(_options, StringComparer.Ordinal);
|
||||
_modified = false;
|
||||
_validation.Clear();
|
||||
}
|
||||
|
||||
private string HintOf(CodeRuleDefinition definition)
|
||||
{
|
||||
if (!License.IsModuleActive(definition.Module))
|
||||
{
|
||||
return T.Format("CompanyPreferences.ModuleOff", definition.Module);
|
||||
}
|
||||
|
||||
return _previews.GetValueOrDefault(definition.Key) is { } next ? T.Format("CompanyPreferences.Next", next) : T["CompanyPreferences.NextInvalid"];
|
||||
}
|
||||
|
||||
private static string GroupIcon(string group) => group switch
|
||||
{
|
||||
"parties" => "users",
|
||||
"items" => "box",
|
||||
_ => "target",
|
||||
};
|
||||
|
||||
private async Task ChangeMaskAsync(string key, string? mask)
|
||||
{
|
||||
_rules[key] = _rules[key] with { Mask = (mask ?? string.Empty).Trim() };
|
||||
_modified = true;
|
||||
await PreviewAsync(key);
|
||||
}
|
||||
|
||||
private void SetManual(string group, bool allow)
|
||||
{
|
||||
foreach (var definition in CodeRuleService.Definitions.Where(d => d.Group == group))
|
||||
{
|
||||
_rules[definition.Key] = _rules[definition.Key] with { AllowManual = allow };
|
||||
}
|
||||
|
||||
_modified = true;
|
||||
}
|
||||
|
||||
private void SetUniqueBarcode(bool unique)
|
||||
{
|
||||
_rules["items"] = _rules["items"] with { UniqueBarcode = unique };
|
||||
_modified = true;
|
||||
}
|
||||
|
||||
private void SetOption(string key, bool on)
|
||||
{
|
||||
if (!CanWrite)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_options[key] = on;
|
||||
_modified = true;
|
||||
}
|
||||
|
||||
private async Task PreviewAllAsync()
|
||||
{
|
||||
foreach (var key in _rules.Keys.ToList())
|
||||
{
|
||||
await PreviewAsync(key);
|
||||
}
|
||||
}
|
||||
|
||||
private async Task PreviewAsync(string key)
|
||||
{
|
||||
if (Session.Actor is { } actor && Session.Company?.Code is { } company)
|
||||
{
|
||||
var today = DateOnly.FromDateTime(Clock.GetLocalNow().DateTime);
|
||||
_previews[key] = await Codes.PreviewAsync(actor, company, _rules[key], today, _category);
|
||||
}
|
||||
}
|
||||
|
||||
private async Task UndoAsync()
|
||||
{
|
||||
Show([.. _savedRules.Values], _savedOptions);
|
||||
await PreviewAllAsync();
|
||||
}
|
||||
|
||||
private async Task SaveAsync()
|
||||
{
|
||||
if (Session.Actor is not { } actor || Session.Company?.Code is not { } company)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_busy = true;
|
||||
_validation.Clear();
|
||||
try
|
||||
{
|
||||
var problems = CodeRuleService.Validate(_rules.Values);
|
||||
if (problems.Count > 0)
|
||||
{
|
||||
Refuse(problems.Select(p => ((string?)p.Field, p.Code)));
|
||||
return;
|
||||
}
|
||||
|
||||
var rules = await Codes.SaveAsync(actor, company, [.. _rules.Values]);
|
||||
var options = await AutoFill.SaveOptionsAsync(actor, company, _options);
|
||||
Show(rules, options);
|
||||
await PreviewAllAsync();
|
||||
Toasts.Show(ToastKind.Success, T["CompanyPreferences.Saved"], null);
|
||||
}
|
||||
catch (ValidationFailedException ex)
|
||||
{
|
||||
Refuse(ex.Errors.Select(TableValues.SplitError));
|
||||
}
|
||||
finally
|
||||
{
|
||||
_busy = false;
|
||||
}
|
||||
}
|
||||
|
||||
private void Refuse(IEnumerable<(string? Field, string Code)> errors)
|
||||
{
|
||||
foreach (var (field, code) in errors)
|
||||
{
|
||||
_validation.Add(field, T.Contains(code) ? T[code] : T["CompanyTables.UnknownError"]);
|
||||
}
|
||||
|
||||
_tab = "codes";
|
||||
Toasts.Show(ToastKind.Error, T["CompanyTables.NotSaved"], T["CompanyTables.FixFields"]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,173 @@
|
||||
@page "/tabelle/profilo-azienda"
|
||||
@attribute [Authorize]
|
||||
@using Khaemhat.Application.Security
|
||||
@using Khaemhat.Application.Tables
|
||||
@using Khaemhat.Core.Common
|
||||
@using Khaemhat.Core.Tables
|
||||
@using Khaemhat.Web.Tables
|
||||
@using Khaemhat.Web.Components.Tables
|
||||
@inject ShellSession Session
|
||||
@inject CompanyProfileService Profiles
|
||||
@inject TableService Tables
|
||||
@inject CompanyFiscalContext Fiscal
|
||||
@inject ToastService Toasts
|
||||
|
||||
@* The company profile (SPEC §11.1, mockup 075): company data, tax and e-invoice, default bank, print, fiscal year and
|
||||
VAT, transmitter and intermediary. The country of the profile picks the fiscal pack of the company. *@
|
||||
<KhPageTitle Text="@T["CompanyTables.Profile.Title"]" Icon="building" />
|
||||
|
||||
<TablesGuard>
|
||||
<div class="phead">
|
||||
<div>
|
||||
<div class="crumbs"><a href="@TableScreens.BasePath">@T["Shell.Menu.CompanyTables"]</a> / @T["CompanyTables.Profile.Title"]</div>
|
||||
<h1>@(_profile?.LegalName is { Length: > 0 } name ? name : T["CompanyTables.Profile.Title"])</h1>
|
||||
<div class="sub">@T["CompanyTables.Profile.Hint"]</div>
|
||||
</div>
|
||||
<div class="grow"></div>
|
||||
@if (_modified)
|
||||
{
|
||||
<KhBadge Tone="KhTone.Warning">@T["CompanyTables.Modified"]</KhBadge>
|
||||
}
|
||||
<div class="toolbar">
|
||||
<button type="button" class="btn" disabled="@(!_modified)" @onclick="UndoAsync"><KhIcon Name="undo" /> @T["CompanyTables.Undo"]</button>
|
||||
<button type="button" class="btn primary" disabled="@(!_modified || !CanWrite || _busy)" @onclick="SaveAsync"><KhIcon Name="save" /> @T["Common.Save"]</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@if (_profile is not null)
|
||||
{
|
||||
<section class="panel kh-tables-profile">
|
||||
<KhTabs Items="TabItems" Active="@_tab" ActiveChanged="t => _tab = t" Label="@T["CompanyTables.Profile.Title"]" />
|
||||
<KhForm Validation="_validation" ReadOnly="!CanWrite" Layout="KhFormLayout.Groups">
|
||||
@foreach (var group in ProfileLayout.Tabs.First(t => t.Id == _tab).Groups)
|
||||
{
|
||||
<KhFieldGroup Title="@T["CompanyTables.Profile.Groups." + group.Key]" Icon="@group.Icon">
|
||||
@foreach (var field in group.Fields)
|
||||
{
|
||||
<KhRowField Row="_profile" Field="field" Options="_options" ReadOnly="!CanWrite" OnChanged="() => _modified = true" />
|
||||
}
|
||||
</KhFieldGroup>
|
||||
}
|
||||
</KhForm>
|
||||
@if (_tab == "esercizi")
|
||||
{
|
||||
<p class="muted kh-pad"><KhIcon Name="info" /> @T["CompanyTables.Profile.YearsHint"] <a href="/tabelle/esercizi">@T["CompanyTables.FiscalYears.Title"]</a></p>
|
||||
}
|
||||
@if (_tab == "stampa")
|
||||
{
|
||||
<p class="muted kh-pad"><KhIcon Name="info" /> @T["CompanyTables.Profile.LogoHint"]</p>
|
||||
}
|
||||
</section>
|
||||
}
|
||||
</TablesGuard>
|
||||
|
||||
@code {
|
||||
private readonly KhValidation _validation = new();
|
||||
private readonly TableOptions _options = new();
|
||||
private CompanyProfile? _profile;
|
||||
private CompanyProfile? _saved;
|
||||
private string _tab = ProfileLayout.Tabs[0].Id;
|
||||
private bool _modified;
|
||||
private bool _busy;
|
||||
|
||||
private bool CanWrite => Session.Permissions.Allows(TableService.WritePermission);
|
||||
|
||||
private IReadOnlyList<KhTabItem> TabItems =>
|
||||
[
|
||||
.. ProfileLayout.Tabs.Select(t => new KhTabItem(t.Id, t.Icon, T["CompanyTables.Profile.Tabs." + t.Id],
|
||||
_validation.Messages.Count(m => ProfileLayout.TabOf(m.Field) == t) is > 0 and var n ? n : null)),
|
||||
];
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override async Task OnInitializedAsync()
|
||||
{
|
||||
await Session.EnsureLoadedAsync();
|
||||
if (Session.Actor is { } actor && Session.Company?.Code is { } company && Session.Permissions.Allows(TableService.ReadPermission))
|
||||
{
|
||||
await _options.LoadAsync(Tables, Fiscal, ProfileLayout.Fields, actor, company);
|
||||
Show(await Profiles.GetAsync(actor, company));
|
||||
}
|
||||
}
|
||||
|
||||
private void Show(CompanyProfile profile)
|
||||
{
|
||||
_profile = profile;
|
||||
_saved = Copy(profile);
|
||||
_modified = false;
|
||||
_validation.Clear();
|
||||
}
|
||||
|
||||
private Task UndoAsync()
|
||||
{
|
||||
if (_saved is { } saved)
|
||||
{
|
||||
Show(Copy(saved));
|
||||
}
|
||||
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
private async Task SaveAsync()
|
||||
{
|
||||
if (_profile is null || Session.Actor is not { } actor || Session.Company?.Code is not { } company)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_busy = true;
|
||||
_validation.Clear();
|
||||
try
|
||||
{
|
||||
var problems = Profiles.Validate(_profile);
|
||||
if (problems.Count > 0)
|
||||
{
|
||||
Refuse(problems.Select(p => ((string?)p.Field, p.Code)));
|
||||
return;
|
||||
}
|
||||
|
||||
Show(await Profiles.SaveAsync(actor, company, _profile));
|
||||
await _options.LoadAsync(Tables, Fiscal, ProfileLayout.Fields, actor, company);
|
||||
Toasts.Show(ToastKind.Success, T["CompanyTables.Saved"], _profile.LegalName);
|
||||
}
|
||||
catch (ValidationFailedException ex)
|
||||
{
|
||||
Refuse(ex.Errors.Select(TableValues.SplitError));
|
||||
}
|
||||
catch (ConcurrencyException)
|
||||
{
|
||||
Toasts.Show(ToastKind.Error, T["CompanyTables.NotSaved"], T["CompanyTables.Concurrency"]);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_busy = false;
|
||||
}
|
||||
}
|
||||
|
||||
private void Refuse(IEnumerable<(string? Field, string Code)> errors)
|
||||
{
|
||||
foreach (var (field, code) in errors)
|
||||
{
|
||||
_validation.Add(field, T.Contains(code) ? T[code] : T["CompanyTables.UnknownError"]);
|
||||
}
|
||||
|
||||
// Show the tab of the first error, which may not be the one open.
|
||||
if (_validation.Messages.Select(m => ProfileLayout.TabOf(m.Field)).FirstOrDefault(t => t is not null) is { } tab
|
||||
&& !_validation.Messages.Any(m => ProfileLayout.TabOf(m.Field)?.Id == _tab))
|
||||
{
|
||||
_tab = tab.Id;
|
||||
}
|
||||
|
||||
Toasts.Show(ToastKind.Error, T["CompanyTables.NotSaved"], T["CompanyTables.FixFields"]);
|
||||
}
|
||||
|
||||
private static CompanyProfile Copy(CompanyProfile profile)
|
||||
{
|
||||
var copy = new CompanyProfile();
|
||||
foreach (var property in typeof(CompanyProfile).GetProperties().Where(p => p.CanRead && p.CanWrite))
|
||||
{
|
||||
property.SetValue(copy, property.GetValue(profile));
|
||||
}
|
||||
|
||||
return copy;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
@page "/tabelle/cambi"
|
||||
@attribute [Authorize]
|
||||
@using Khaemhat.Application.Security
|
||||
@using Khaemhat.Application.Tables
|
||||
@using Khaemhat.Core.Tables
|
||||
@using Khaemhat.Web.Tables
|
||||
@inject ShellSession Session
|
||||
@inject ExchangeRateService Rates
|
||||
@inject TableService Tables
|
||||
@inject ToastService Toasts
|
||||
@inject TimeProvider Clock
|
||||
|
||||
@* Exchange rates (SPEC §11.1): the reference rates of the European Central Bank, read every working day by the system
|
||||
task "Cambi di riferimento BCE", and the rates typed by hand, which the task never overwrites. *@
|
||||
<KhPageTitle Text="@T["CompanyTables.Rates.Title"]" Icon="euro" />
|
||||
|
||||
<TablesGuard>
|
||||
<div class="phead">
|
||||
<div>
|
||||
<div class="crumbs"><a href="@TableScreens.BasePath">@T["Shell.Menu.CompanyTables"]</a> / @T["CompanyTables.Rates.Title"]</div>
|
||||
<h1>@T["CompanyTables.Rates.Title"]</h1>
|
||||
<div class="sub">@T["CompanyTables.Rates.Hint"]</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="kh-tables">
|
||||
<KhRadar TItem="ExchangeRate" @ref="_radar" Id="tables.exchange-rates" Columns="Columns" Source="ListAsync" KeyOf="r => r.Id" Selectable="false"
|
||||
QuickFilters="QuickFilters" ShowHints="false" Compact="true" Height="360px" ExportName="cambi" Label="@T["CompanyTables.Rates.Title"]" />
|
||||
|
||||
@if (CanWrite)
|
||||
{
|
||||
<KhPanel Title="@T["CompanyTables.Rates.Manual"]" Icon="edit">
|
||||
<KhForm Validation="_validation" Layout="KhFormLayout.Grid">
|
||||
<KhSelect TValue="string" Label="@T["CompanyTables.Fields.CurrencyCode"]" Name="CurrencyCode" Options="_currencies" @bind-Value="_currency" Required="true" Span="4" />
|
||||
<KhDateBox Label="@T["CompanyTables.Fields.RateDate"]" Name="RateDate" @bind-Value="_date" Required="true" Span="4" />
|
||||
<KhNumberBox Label="@T["CompanyTables.Fields.Rate"]" Name="Rate" @bind-Value="_rate" Decimals="6" Min="0" Required="true" Span="4" />
|
||||
</KhForm>
|
||||
<div class="kh-pad">
|
||||
<button type="button" class="btn primary" disabled="@_busy" @onclick="SaveAsync"><KhIcon Name="save" /> @T["CompanyTables.Rates.Save"]</button>
|
||||
<span class="muted sm">@T["CompanyTables.Rates.ManualHint"]</span>
|
||||
</div>
|
||||
</KhPanel>
|
||||
}
|
||||
</div>
|
||||
</TablesGuard>
|
||||
|
||||
@code {
|
||||
private readonly KhValidation _validation = new();
|
||||
private KhRadar<ExchangeRate>? _radar;
|
||||
private IReadOnlyList<KhOption<string>> _currencies = [];
|
||||
private string? _currency;
|
||||
private DateOnly? _date;
|
||||
private decimal? _rate;
|
||||
private bool _busy;
|
||||
|
||||
private bool CanWrite => Session.Permissions.Allows(TableService.WritePermission);
|
||||
|
||||
private IReadOnlyList<KhColumn<ExchangeRate>> Columns =>
|
||||
[
|
||||
new("currency", T["CompanyTables.Fields.CurrencyCode"], r => r.CurrencyCode) { Kind = KhColumnKind.Code, Width = "90px" },
|
||||
new("date", T["CompanyTables.Fields.RateDate"], r => r.RateDate) { Kind = KhColumnKind.Date, Width = "120px" },
|
||||
new("rate", T["CompanyTables.Fields.Rate"], r => r.Rate) { Kind = KhColumnKind.Number, Decimals = 6, Width = "140px" },
|
||||
new("source", T["CompanyTables.Fields.Source"], r => T["CompanyTables.Values.Source." + r.Source]) { Sortable = false },
|
||||
];
|
||||
|
||||
private IReadOnlyList<KhQuickFilter> QuickFilters =>
|
||||
[
|
||||
new("source", T["CompanyTables.Fields.Source"],
|
||||
[
|
||||
new(string.Empty, T["CompanyTables.Filter.All"]), new(ExchangeRateService.EcbSource, T["CompanyTables.Values.Source.ECB"]),
|
||||
new(ExchangeRateService.ManualSource, T["CompanyTables.Values.Source.MANUAL"]),
|
||||
]),
|
||||
];
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override async Task OnInitializedAsync()
|
||||
{
|
||||
await Session.EnsureLoadedAsync();
|
||||
_date = DateOnly.FromDateTime(Clock.GetLocalNow().DateTime);
|
||||
if (Session.Actor is { } actor && Session.Company?.Code is { } company && Session.Permissions.Allows(TableService.ReadPermission))
|
||||
{
|
||||
var currencies = await Tables.ActiveAsync<Currency>(actor, company);
|
||||
_currencies = [.. currencies.Where(c => c.Code != "EUR").Select(c => new KhOption<string>(c.Code, c.Code + " · " + c.Description))];
|
||||
}
|
||||
}
|
||||
|
||||
private Task<ListPage<ExchangeRate>> ListAsync(ListQuery query, CancellationToken cancellationToken) =>
|
||||
Session.Actor is { } actor && Session.Company?.Code is { } company
|
||||
? Rates.ListAsync(actor, company, query, cancellationToken)
|
||||
: Task.FromResult(new ListPage<ExchangeRate>([], 0, new Dictionary<string, decimal>()));
|
||||
|
||||
private async Task SaveAsync()
|
||||
{
|
||||
if (Session.Actor is not { } actor || Session.Company?.Code is not { } company)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_validation.Clear();
|
||||
if (_currency is null || _date is null || _rate is not > 0)
|
||||
{
|
||||
_validation.Add(_currency is null ? "CurrencyCode" : _date is null ? "RateDate" : "Rate", T[ExchangeRateService.RateInvalid]);
|
||||
return;
|
||||
}
|
||||
|
||||
_busy = true;
|
||||
try
|
||||
{
|
||||
await Rates.SetManualAsync(actor, company, _currency, _date.Value, _rate.Value);
|
||||
Toasts.Show(ToastKind.Success, T["CompanyTables.Saved"], _currency);
|
||||
_rate = null;
|
||||
if (_radar is not null)
|
||||
{
|
||||
await _radar.ReloadAsync();
|
||||
}
|
||||
}
|
||||
catch (ValidationFailedException ex)
|
||||
{
|
||||
foreach (var (field, code) in ex.Errors.Select(TableValues.SplitError))
|
||||
{
|
||||
_validation.Add(field ?? "Rate", T.Contains(code) ? T[code] : T["CompanyTables.UnknownError"]);
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
_busy = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,217 @@
|
||||
@page "/tabelle/esercizi"
|
||||
@attribute [Authorize]
|
||||
@using Khaemhat.Application.Security
|
||||
@using Khaemhat.Application.Tables
|
||||
@using Khaemhat.Core.Tables
|
||||
@using Khaemhat.Web.Tables
|
||||
@inject ShellSession Session
|
||||
@inject FiscalYearService Years
|
||||
@inject ToastService Toasts
|
||||
@inject DialogService Dialogs
|
||||
@inject TimeProvider Clock
|
||||
|
||||
@* Fiscal years and periods (SPEC §11.1, mockup 052): the years with their state, the months of the chosen year with
|
||||
the lock that stops new entries and documents on those dates. The VAT settlement (M7) marks a month as settled. *@
|
||||
<KhPageTitle Text="@T["CompanyTables.FiscalYears.Title"]" Icon="calendar" />
|
||||
|
||||
<TablesGuard>
|
||||
<div class="phead">
|
||||
<div>
|
||||
<div class="crumbs"><a href="@TableScreens.BasePath">@T["Shell.Menu.CompanyTables"]</a> / @T["CompanyTables.FiscalYears.Title"]</div>
|
||||
<h1>@T["CompanyTables.FiscalYears.Heading"]</h1>
|
||||
<div class="sub">@T["CompanyTables.FiscalYears.Hint"]</div>
|
||||
</div>
|
||||
<div class="grow"></div>
|
||||
<div class="toolbar">
|
||||
<button type="button" class="btn primary" disabled="@(!CanWrite || _busy)" @onclick="CreateAsync"><KhIcon Name="plus" /> @T["CompanyTables.FiscalYears.New"]</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="kh-tables">
|
||||
<KhPanel Title="@T["CompanyTables.FiscalYears.Years"]" Icon="calendar" Tight="true">
|
||||
@if (_years.Count == 0)
|
||||
{
|
||||
<p class="muted kh-pad">@T["CompanyTables.FiscalYears.None"]</p>
|
||||
}
|
||||
else
|
||||
{
|
||||
<table class="grid" aria-label="@T["CompanyTables.FiscalYears.Years"]">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>@T["CompanyTables.FiscalYears.Year"]</th>
|
||||
<th>@T["CompanyTables.FiscalYears.Start"]</th>
|
||||
<th>@T["CompanyTables.FiscalYears.End"]</th>
|
||||
<th>@T["CompanyTables.FiscalYears.State"]</th>
|
||||
<th>@T["CompanyTables.FiscalYears.LockedMonths"]</th>
|
||||
<th>@T["CompanyTables.FiscalYears.LastSettled"]</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
@foreach (var view in _years)
|
||||
{
|
||||
var year = view.Year;
|
||||
<tr class="@(year.Id == _selected?.Year.Id ? "sel" : null)" @onclick="() => _selected = view" style="cursor:pointer">
|
||||
<td><b class="mono">@year.Code</b></td>
|
||||
<td>@T.Date(year.StartDate)</td>
|
||||
<td>@T.Date(year.EndDate)</td>
|
||||
<td><KhBadge Tone="ToneOf(year.Status)">@T[TableScreens.EnumKey(year.Status)]</KhBadge></td>
|
||||
<td>@view.Periods.Count(p => p.Status != FiscalPeriodStatus.Open) / @view.Periods.Count</td>
|
||||
<td>@(view.Periods.LastOrDefault(p => p.Status == FiscalPeriodStatus.Settled) is { } last ? MonthName(last) : "-")</td>
|
||||
</tr>
|
||||
}
|
||||
</tbody>
|
||||
</table>
|
||||
}
|
||||
</KhPanel>
|
||||
|
||||
@if (_selected is { } selected)
|
||||
{
|
||||
<KhPanel Title="@T.Format("CompanyTables.FiscalYears.Periods", selected.Year.Code, T[TableScreens.EnumKey(_periodicity)])" Icon="lock" Tight="true">
|
||||
<table class="grid" aria-label="@T["CompanyTables.FiscalYears.PeriodsLabel"]">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>@T["CompanyTables.FiscalYears.Period"]</th>
|
||||
<th>@T["CompanyTables.FiscalYears.From"]</th>
|
||||
<th>@T["CompanyTables.FiscalYears.To"]</th>
|
||||
<th>@T["CompanyTables.FiscalYears.State"]</th>
|
||||
<th>@T["CompanyTables.FiscalYears.Lock"]</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
@foreach (var period in selected.Periods)
|
||||
{
|
||||
<tr>
|
||||
<td>@MonthName(period)</td>
|
||||
<td>@T.Date(period.StartDate)</td>
|
||||
<td>@T.Date(period.EndDate)</td>
|
||||
<td><KhBadge Tone="ToneOf(period.Status)">@T[TableScreens.EnumKey(period.Status)]</KhBadge></td>
|
||||
<td>
|
||||
@if (period.Status == FiscalPeriodStatus.Settled)
|
||||
{
|
||||
<span class="muted">@T["CompanyTables.FiscalYears.SettledLock"]</span>
|
||||
}
|
||||
else
|
||||
{
|
||||
var locked = period.Status == FiscalPeriodStatus.Locked;
|
||||
<button type="button" class="btn sm" disabled="@(!CanWrite || _busy || selected.Year.Status != FiscalYearStatus.Open)"
|
||||
@onclick="() => LockAsync(period, !locked)">
|
||||
<KhIcon Name="@(locked ? "key" : "lock")" /> @T[locked ? "CompanyTables.FiscalYears.Unlock" : "CompanyTables.FiscalYears.LockMonth"]
|
||||
</button>
|
||||
}
|
||||
</td>
|
||||
</tr>
|
||||
}
|
||||
</tbody>
|
||||
</table>
|
||||
</KhPanel>
|
||||
}
|
||||
</div>
|
||||
</TablesGuard>
|
||||
|
||||
@code {
|
||||
private IReadOnlyList<FiscalYearView> _years = [];
|
||||
private FiscalYearView? _selected;
|
||||
private Khaemhat.Core.Tax.VatPeriodicity _periodicity;
|
||||
private bool _busy;
|
||||
|
||||
/// <summary>The service of the company profile, for the VAT periodicity shown on the months.</summary>
|
||||
[Inject]
|
||||
private CompanyProfileService Profiles { get; set; } = default!;
|
||||
|
||||
private bool CanWrite => Session.Permissions.Allows(TableService.WritePermission);
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override async Task OnInitializedAsync()
|
||||
{
|
||||
await Session.EnsureLoadedAsync();
|
||||
if (Session.Actor is { } actor && Session.Company?.Code is { } company && Session.Permissions.Allows(TableService.ReadPermission))
|
||||
{
|
||||
_periodicity = (await Profiles.GetAsync(actor, company)).VatPeriodicity;
|
||||
await LoadAsync(actor, company);
|
||||
}
|
||||
}
|
||||
|
||||
private async Task LoadAsync(Actor actor, string company)
|
||||
{
|
||||
var selected = _selected?.Year.Id;
|
||||
_years = await Years.ListAsync(actor, company);
|
||||
var today = DateOnly.FromDateTime(Clock.GetLocalNow().DateTime);
|
||||
_selected = _years.FirstOrDefault(y => y.Year.Id == selected)
|
||||
?? _years.FirstOrDefault(y => y.Year.StartDate <= today && today <= y.Year.EndDate)
|
||||
?? _years.FirstOrDefault();
|
||||
}
|
||||
|
||||
private async Task CreateAsync()
|
||||
{
|
||||
if (Session.Actor is not { } actor || Session.Company?.Code is not { } company)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_busy = true;
|
||||
try
|
||||
{
|
||||
var created = await Years.CreateNextAsync(actor, company, DateOnly.FromDateTime(Clock.GetLocalNow().DateTime));
|
||||
_selected = created;
|
||||
await LoadAsync(actor, company);
|
||||
Toasts.Show(ToastKind.Success, T["CompanyTables.FiscalYears.Created"], created.Year.Code);
|
||||
}
|
||||
catch (ValidationFailedException ex)
|
||||
{
|
||||
Toasts.Show(ToastKind.Error, T["CompanyTables.NotSaved"], string.Join(" ", ex.Errors.Select(e => T[TableValues.SplitError(e).Code])));
|
||||
}
|
||||
finally
|
||||
{
|
||||
_busy = false;
|
||||
}
|
||||
}
|
||||
|
||||
private async Task LockAsync(FiscalPeriod period, bool locked)
|
||||
{
|
||||
if (Session.Actor is not { } actor || Session.Company?.Code is not { } company)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (!locked && !await Dialogs.ConfirmAsync(new ConfirmRequest(T["CompanyTables.FiscalYears.Unlock"], T.Format("CompanyTables.FiscalYears.UnlockText", MonthName(period)),
|
||||
T["CompanyTables.FiscalYears.Unlock"], T["Common.Cancel"])))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_busy = true;
|
||||
try
|
||||
{
|
||||
await Years.SetLockedAsync(actor, company, period.Id, locked);
|
||||
await LoadAsync(actor, company);
|
||||
}
|
||||
catch (ValidationFailedException ex)
|
||||
{
|
||||
Toasts.Show(ToastKind.Error, T["CompanyTables.NotSaved"], string.Join(" ", ex.Errors.Select(e => T[TableValues.SplitError(e).Code])));
|
||||
}
|
||||
finally
|
||||
{
|
||||
_busy = false;
|
||||
}
|
||||
}
|
||||
|
||||
private string MonthName(FiscalPeriod period)
|
||||
{
|
||||
var text = period.StartDate.ToString("MMMM yyyy", T.Culture);
|
||||
return char.ToUpper(text[0], T.Culture) + text[1..];
|
||||
}
|
||||
|
||||
private static KhTone ToneOf(FiscalYearStatus status) => status switch
|
||||
{
|
||||
FiscalYearStatus.Open => KhTone.Ok,
|
||||
FiscalYearStatus.Closing => KhTone.Warning,
|
||||
_ => KhTone.Neutral,
|
||||
};
|
||||
|
||||
private static KhTone ToneOf(FiscalPeriodStatus status) => status switch
|
||||
{
|
||||
FiscalPeriodStatus.Open => KhTone.Ok,
|
||||
FiscalPeriodStatus.Settled => KhTone.Info,
|
||||
_ => KhTone.Warning,
|
||||
};
|
||||
}
|
||||
Loaded 100 of 156 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user