CI / Build and test (SQLite) (pull_request) Successful in 45s
CI / PostgreSQL 16 integration (pull_request) Skipped
CI / PostgreSQL 17 integration (pull_request) Skipped
CI / YAML check (pull_request) Successful in 3s
CI / Docker image (pull_request) Successful in 51s
Every later milestone stores its data through this layer, so it has to behave the same on both engines and be safe by construction: - Khaemhat.Data: explicit entity maps, typed queries over a safe expression subset, SqlFragment where every interpolated value becomes a parameter, unit of work with transactions, repositories with audit columns and optimistic concurrency on row_version, retries on transient errors. - SQLite provider (STRICT tables, WAL, exact decimals as integers scaled by 10^6, Unicode case-insensitive LIKE, serialised writes) and PostgreSQL 16+ provider (numeric(19,6), timestamptz, jsonb, advisory locks, database creation and server info). Databases are configured from postgres:// and sqlite:// URLs whose password never appears in messages. - C# migrations with system and company catalogues, schema_version with checksums, one transaction per migration under a lock, refusal of unknown applied versions; first system tables sys_companies and sys_settings. - CompanyRegistry stores each company's database URL encrypted with the instance key (AES-256-GCM, HKDF-derived key, purpose as associated data), so a copied row cannot be read for another company. - tools/Khaemhat.DataModelTool, scripts/gen-datamodel.sh and scripts/new-migration.sh: the current schema section of docs/DATA-MODEL.md is generated from the migrations and a test fails when it is stale. - C# 14 binds array.Contains to MemoryExtensions over spans; the query translator unwraps the span conversion. - Tests run every data scenario on SQLite and PostgreSQL (PostgreSQL in CI); ADR 0018 records where the contracts differ from SPEC 5.1. Docs, wiki, changelog and status updated. Closes #7, #8, #9, #10, #11, #12, #13, #14 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
523 lines
40 KiB
Markdown
523 lines
40 KiB
Markdown
# Architettura di Khaemhat
|
|
|
|
> Stato: bozza · Revisione 2026-11-11 · Fonte: SPEC §1, §2, §3, §4, §5, §7, §9, §13, §15, §19, §21; ADR 0009-0018
|
|
|
|
Questo documento descrive l'architettura **prevista** del gestionale: livelli, progetti, regole di dipendenza,
|
|
composizione dei moduli, gestione multi-database, ciclo di una richiesta e servizi trasversali. Il codice non esiste
|
|
ancora: ogni sezione indica la milestone (SPEC §20) in cui la parte viene realizzata. Quando il codice cambia questo
|
|
file va aggiornato nello stesso commit (SPEC §17).
|
|
|
|
Documenti collegati: [DATA-MODEL.md](DATA-MODEL.md) (tabelle), [MODULES.md](MODULES.md) (moduli e licenze),
|
|
[API.md](API.md) (REST), [MCP.md](MCP.md) (agenti AI), [SPEC.md](SPEC.md) (specifica normativa),
|
|
[adr/](adr/) (decisioni).
|
|
|
|
---
|
|
|
|
## 1. Principi
|
|
|
|
| Principio | Conseguenza pratica | Fonte |
|
|
|---|---|---|
|
|
| Un solo runtime: C# 14 su .NET 10 | nessun altro linguaggio lato server; JavaScript solo come interop minimo in `wwwroot/js` | SPEC §1.1 |
|
|
| Nessuna libreria esterna | ammessi solo framework condivisi Microsoft, `Npgsql`, `Microsoft.Data.Sqlite` e, nei soli test, `Microsoft.NET.Test.Sdk` + `MSTest`; allowlist in `Directory.Packages.props` verificata da `scripts/check-packages.sh` | SPEC §1.2 |
|
|
| Codice indifferente al motore | sopra `Khaemhat.Data` nessuno sa se il database è SQLite o PostgreSQL | SPEC §1.3 |
|
|
| Un database di sistema + uno per azienda | le tabelle operative non hanno `company_id` | SPEC §1.4, §5.4 |
|
|
| Configurazione iniziale solo da variabili `KHAEMHAT_*` | nessun file di impostazioni con segreti, scritture solo in `KHAEMHAT_DATA_DIR` | SPEC §1.5, §6 |
|
|
| Fiscalità isolata | tutto ciò che è italiano vive in `Khaemhat.Fiscal.Italy` dietro `Khaemhat.Fiscal.Abstractions` | SPEC §1.10 |
|
|
| Moduli dietro licenza | un modulo non licenziato non registra menu, API, tool MCP né procedure | SPEC §1.8, §8 |
|
|
| Distribuzione solo Docker | unico artefatto: `gitea.encke-hake.ts.net/balbosoft/khaemhat:<versione>` | ADR 0010 |
|
|
|
|
## 2. Livelli e progetti
|
|
|
|
```
|
|
┌───────────────────────────────────────────────────────────────────────────┐
|
|
│ Khaemhat.Web UI Blazor (Interactive Server) · REST /api/v1 · │
|
|
│ MCP /mcp · autenticazione · host · aiuto /help │
|
|
├───────────────────────────────────────────────────────────────────────────┤
|
|
│ Khaemhat.Application casi d'uso per modulo · DTO · permessi · │
|
|
│ motore documenti · motore contabile · procedure ·│
|
|
│ automazioni · seeder · report · orchestrazione │
|
|
│ backup · registro moduli │
|
|
├──────────────────────────────────────┬────────────────────────────────────┤
|
|
│ Khaemhat.Fiscal.Abstractions │ Khaemhat.Fiscal.Italy │
|
|
│ interfacce paese (IVA, e-invoice, │ FatturaPA · TD · nature · F24 · │
|
|
│ calendario, ritenute, cespiti, CEE) │ LIPE · Intrastat · ritenute · │
|
|
│ │ cespiti · bilancio CEE · SDI │
|
|
├──────────────────────────────────────┴────────────────────────────────────┤
|
|
│ Khaemhat.Core entità · value object · enum · regole di dominio │
|
|
│ · calcoli · validatori · partita doppia │
|
|
├───────────────────────────────────────────────────────────────────────────┤
|
|
│ Khaemhat.Infrastructure cache/Redis (RESP) · crypto · licenze · SMTP/IMAP│
|
|
│ · PDF · XLSX/CSV/ZIP · job · file · backup │
|
|
│ (pg_dump, S3, WebDAV) · protocollo MCP · HTTP │
|
|
│ (VIES, BCE, registro pacchetti Gitea, interm.) │
|
|
├───────────────────────────────────────────────────────────────────────────┤
|
|
│ Khaemhat.Data astrazioni DB · query builder · mappe · │
|
|
│ migrazioni · unit of work · registro database │
|
|
│ ├─ Khaemhat.Data.Sqlite └─ Khaemhat.Data.PostgreSql │
|
|
└───────────────────────────────────────────────────────────────────────────┘
|
|
```
|
|
|
|
Nota: nella figura di SPEC §3 il livello Infrastructure cita "GitHub packages"; per l'emendamento E1 (ADR 0009) il
|
|
client degli aggiornamenti è `GiteaPackagesClient`.
|
|
|
|
### 2.1 Progetti della soluzione
|
|
|
|
| Progetto | Ruolo | Milestone |
|
|
|---|---|---|
|
|
| `Khaemhat.Core` | dominio puro: entità, value object (`Money`, `Quantity`, `Percentage`), regole e calcoli, validatori | M1 → M10 |
|
|
| `Khaemhat.Fiscal.Abstractions` | contratti del pacchetto paese (`IFiscalPack`, `ITaxEngine`, `IEInvoiceFormat`, `ISdiTransport`, …) | M4 |
|
|
| `Khaemhat.Fiscal.Italy` | implementazione italiana (`ItalyFiscalPack`, `FatturaPaWriter`, `F24Exporter`, `LipeWriter`, …) | M4 → M10 |
|
|
| `Khaemhat.Data` | micro-ORM interno: `IDbProvider`, `ISqlDialect`, `EntityMap<T>`, `QueryBuilder<T>`, migrazioni | M1 |
|
|
| `Khaemhat.Data.Sqlite` | provider SQLite (`SqliteProvider`, `SqliteDialect`, `SqliteWriteLock`, `SqliteDecimalConverter`) | M1 |
|
|
| `Khaemhat.Data.PostgreSql` | provider PostgreSQL ≥ 16 (`PostgresProvider`, `PostgresDatabaseCreator`, `PostgresAdvisoryLocks`, `PostgresPartitioning`) | M1 |
|
|
| `Khaemhat.Infrastructure` | servizi tecnici scritti in casa (cache, crypto, PDF, mail, job, backup, MCP, log) | M1 → M12 |
|
|
| `Khaemhat.Application` | casi d'uso, moduli (`IModule`), motore documenti e contabile, seeding, report | M2 → M12 |
|
|
| `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 |
|
|
| `tests/*` | `Core`, `Data`, `Infrastructure`, `Fiscal.Italy`, `Application`, `Web` (MSTest) | ogni milestone |
|
|
|
|
## 3. Regole di dipendenza
|
|
|
|
Le regole sono **verificate da test di architettura** in `Khaemhat.Core.Tests` (SPEC §3, §18): un riferimento non
|
|
ammesso fa fallire la build di test.
|
|
|
|
| Progetto | Può dipendere da | Non può dipendere da |
|
|
|---|---|---|
|
|
| `Core` | nulla (solo BCL) | qualunque altro progetto |
|
|
| `Fiscal.Abstractions` | `Core` | tutto il resto |
|
|
| `Fiscal.Italy` | `Core`, `Fiscal.Abstractions`, `Infrastructure` (solo XML/PDF/crypto/HTTP) | `Application`, `Web`, `Data.*` |
|
|
| `Data` | `Core`, `System.Data.Common` | provider concreti, `Infrastructure`, `Application` |
|
|
| `Data.Sqlite` | `Data`, `Microsoft.Data.Sqlite` | tutto il resto |
|
|
| `Data.PostgreSql` | `Data`, `Npgsql` | tutto il resto |
|
|
| `Infrastructure` | `Core`, `Data` | `Application`, `Web`, `Fiscal.*`, provider concreti |
|
|
| `Application` | `Core`, `Data`, `Infrastructure`, `Fiscal.Abstractions` | **`Fiscal.Italy`**, provider concreti, `Web` |
|
|
| `Web` | `Application` (e transitivamente il resto); registra in `Program.cs` i provider concreti e i pacchetti paese | — |
|
|
|
|
Altri controlli di architettura (SPEC §18):
|
|
|
|
- nessun `PackageReference` fuori dall'allowlist di `Directory.Packages.props`;
|
|
- nessun testo dell'interfaccia scritto direttamente nei componenti (tutto passa da `ITexts`);
|
|
- nessun accesso al pacchetto fiscale se non tramite le interfacce di `Fiscal.Abstractions`;
|
|
- nessun `Process.Start` fuori da `Infrastructure/Backup` (unico uso: `pg_dump` / `pg_restore`).
|
|
|
|
```
|
|
Web ──────────────► Application ──────► Fiscal.Abstractions ──► Core
|
|
│ │ │ ▲
|
|
│ (solo Program.cs) │ └──► Infrastructure ───┼──► Data ──► Core
|
|
▼ ▼ ▲ │
|
|
Data.Sqlite / Data.PostgreSql │ │
|
|
Fiscal.Italy ────────────────────────────┴─────────────┘
|
|
```
|
|
|
|
## 4. Moduli: `IModule` e `ModuleRegistry`
|
|
|
|
Ogni area funzionale è un modulo dentro `Khaemhat.Application/Modules/<Nome>/` con struttura fissa (SPEC §4):
|
|
|
|
```
|
|
Modules/Sales/
|
|
├── Services/ casi d'uso (SaleDocumentService, …)
|
|
├── Dtos/ record di input/output
|
|
├── Validators/ Validator<T> applicativi
|
|
├── Migrations/ migrazioni del catalogo azienda (o sistema)
|
|
├── Seed/Base/ seeder dati di base
|
|
├── Seed/Demo/ seeder dati dimostrativi
|
|
├── Reports/ ReportDefinition del modulo
|
|
├── Api/ endpoint REST del modulo
|
|
├── Mcp/ tool MCP del modulo
|
|
├── Procedures/ IProcedure del modulo
|
|
├── Permissions.cs PermissionDefinition del modulo
|
|
├── Menu.cs MenuItem del modulo
|
|
└── SalesModule.cs implementazione di IModule
|
|
```
|
|
|
|
`IModule` (in `Application.Modules`) dichiara, per ogni modulo:
|
|
|
|
| Membro (indicativo) | Contenuto |
|
|
|---|---|
|
|
| codice licenza (`ModuleCode`) | uno dei 13 codici di SPEC §8.1 (`CORE`, `ACCT`, …) |
|
|
| nome, ordine | nome localizzato e posizione nel menu |
|
|
| voci di menu (`MenuItem`) | percorso, icona, contatori, permesso richiesto |
|
|
| permessi (`PermissionDefinition`) | codici `modulo.entità.azione` |
|
|
| migrazioni | classi `IMigration` del catalogo **sistema** o **azienda** |
|
|
| seeder | `ISeeder` *base* e *demo* |
|
|
| endpoint API | mappatura Minimal API sotto `/api/v1` |
|
|
| tool MCP | `McpTool` registrati in `McpToolRegistry` |
|
|
| procedure | `IProcedure` per `ProcedureCatalog` |
|
|
| eventi per le automazioni | trigger esposti a `TriggerCatalog` |
|
|
| sezione di log | valore di `LogSection` |
|
|
| pagine wiki | `HelpLink` verso `docs/wiki/<Pagina>.md` (F1) |
|
|
|
|
`ModuleRegistry` enumera i moduli **staticamente** (nessuna scoperta per riflessione o plugin: SPEC §1.7) e li filtra
|
|
con `LicenseGate` in base alle licenze attive. Effetti di un modulo non licenziato (SPEC §8.1): voci di menu
|
|
nascoste, endpoint API e tool MCP **non registrati**, procedure non eseguibili, dati conservati; ogni accesso
|
|
residuo equivale a permesso negato con codice `module_not_licensed` (`ModuleNotLicensedException`).
|
|
|
|
Elenco dei moduli, codici licenza e milestone: [MODULES.md](MODULES.md).
|
|
|
|
## 5. Multi-database
|
|
|
|
### 5.1 Database di sistema e database aziendali
|
|
|
|
| Database | Nome | Contenuto |
|
|
|---|---|---|
|
|
| Sistema | `khaemhat_system` (da `KHAEMHAT_SYSTEM_DB`) | registro aziende, account di istanza (super utente e amministratori), modelli di ruolo, impostazioni, licenze, attività programmate, esecuzioni, politiche e set di backup, log, audit di sicurezza, chiavi DataProtection, chiavi API di istanza, notifiche e sessioni di istanza (tabelle `sys_*`) |
|
|
| Azienda | `khaemhat_<codice>` (es. `khaemhat_demo`) | tutte le tabelle operative + utenti, ruoli, permessi, sessioni, preferenze, chiavi API, notifiche, allegati, audit, `company_profile` |
|
|
|
|
Con SQLite ogni database è un file sotto `KHAEMHAT_DATA_DIR`; con PostgreSQL i database aziendali vengono creati
|
|
(`CREATE DATABASE`) sul server indicato da `KHAEMHAT_DB_SERVER` con un ruolo dotato di `CREATEDB`. Il dettaglio delle
|
|
tabelle è in [DATA-MODEL.md](DATA-MODEL.md).
|
|
|
|
### 5.2 Contratti principali
|
|
|
|
| Tipo | Progetto | Responsabilità |
|
|
|---|---|---|
|
|
| `IDbProvider` | Data | motore (`DbEngine`), dialetto, generatore DDL (`Ddl`), connection string da `DatabaseUrl`, creazione connessioni, `EnsureDatabaseExistsAsync`, `DatabaseExistsAsync`, `DropDatabaseAsync`, `GetServerInfoAsync`, `IsTransient`, `EnterWriteScopeAsync` (ADR 0018) |
|
|
| `ISqlDialect` | Data | quoting, parametri, paginazione, `InsertReturningId`, `Upsert`, `CaseInsensitiveLike` e `AdvisoryLock` come `SqlFragment`, conversioni `ColumnType` |
|
|
| `IUnitOfWorkFactory` | Data | `CreateAsync(DatabaseScope scope)` dove lo scope è `System` oppure `Company(code)` |
|
|
| `IUnitOfWork` / `IRepository<T,TKey>` | Data | transazione, repository tipizzati, `ExecuteAsync`/`QueryAsync`/`StreamAsync` su `SqlFragment` |
|
|
| `ICompanyRegistry` (`CompanyRegistry`) | Data | registra le aziende e risolve `companyCode → DatabaseTarget` (provider + connection string) decifrando l'URL salvato in `sys_companies` |
|
|
| `ICompanyContext` | Core (interfaccia), Web (`CompanyContextAccessor`) | azienda corrente: **per circuito Blazor** e **per richiesta API** (header `X-Company`) |
|
|
| `SecretProtector` | Infrastructure | AES-256-GCM con chiave derivata da `KHAEMHAT_SECRET_KEY` per connection string e credenziali |
|
|
|
|
### 5.3 Risoluzione dell'azienda
|
|
|
|
1. Un **utente aziendale** è vincolato alla propria azienda (scelta nella pagina di accesso, mockup 001).
|
|
2. Un **account di istanza** (super utente o amministratore) sceglie l'azienda dalla barra superiore
|
|
(`CompanySwitcher`) ed entra con permessi completi su di essa.
|
|
3. Un client API indica l'azienda con l'header `X-Company: <codice>`; una chiave aziendale è già legata a
|
|
un'azienda (vedi [API.md](API.md)).
|
|
4. `ICompanyContext` espone il codice; `IUnitOfWorkFactory` lo usa per aprire il database giusto tramite
|
|
`ICompanyRegistry`. Le chiavi di cache sono prefissate con l'azienda (`kh:{azienda}:{area}:{key}`).
|
|
5. Lo stato dell'azienda in `sys_companies` (*attiva / manutenzione / sola lettura / disattivata*) è applicato da
|
|
`MaintenanceMiddleware`: in manutenzione gli utenti vengono disconnessi e le API rispondono `503`.
|
|
|
|
### 5.4 Bootstrap al primo avvio
|
|
|
|
`docker/entrypoint.sh` attende il database e avvia l'app; `StartupOrchestrator` esegue (SPEC §5.4):
|
|
|
|
1. validazione delle variabili con `KhaemhatOptions.Validate()` (termina con messaggio esplicito se manca qualcosa,
|
|
in particolare `KHAEMHAT_SECRET_KEY`);
|
|
2. migrazione del database di sistema;
|
|
3. creazione del super utente da `KHAEMHAT_SUPERUSER*` (solo se `sys_users` è vuota; cambio password obbligatorio);
|
|
4. creazione della prima azienda da `KHAEMHAT_COMPANY_CODE` / `KHAEMHAT_COMPANY_NAME` (`CREATE DATABASE` o file
|
|
SQLite), migrazione, tabelle di base (`KHAEMHAT_SEED_BASE`), dati demo se `KHAEMHAT_SEED_DEMO=true`;
|
|
5. le variabili di bootstrap vengono rilette solo se la tabella corrispondente è vuota.
|
|
|
|
## 6. Flusso di una richiesta
|
|
|
|
### 6.1 Interfaccia Blazor (circuito interattivo)
|
|
|
|
```
|
|
Browser ──HTTP──► Kestrel ──► SecurityHeadersMiddleware ──► TraceIdMiddleware
|
|
──► CookieSessionAuthenticationHandler (cookie HttpOnly, riga in user_sessions/sys_sessions)
|
|
──► MaintenanceMiddleware ──► pagina Razor prerender ──► circuito SignalR
|
|
Circuito: CurrentUserAccessor + CompanyContextAccessor (azienda del circuito)
|
|
──► componente pagina (es. SaleDocumentPage) ── code-behind ──► servizio applicativo
|
|
──► PermissionAuthorizationHandler / [RequirePermission] / LicenseGate
|
|
──► IUnitOfWorkFactory.CreateAsync(Company(code)) ──► transazione ──► commit
|
|
──► audit_log · log di sezione · notifiche · invalidazione cache
|
|
```
|
|
|
|
- Il circuito verifica la sessione a ogni riconnessione (SPEC §7.3).
|
|
- Nessuna logica nei `.razor`: code-behind + servizi (SPEC §19). L'interfaccia nasconde ciò che non è permesso, il
|
|
server verifica sempre.
|
|
- Ogni servizio applicativo è transazionale per operazione; motore documenti e contabile garantiscono atomicità di
|
|
documento + magazzino + partite + registrazione + numerazione + allegati.
|
|
|
|
### 6.2 REST API
|
|
|
|
```
|
|
Client ──► /api/v1/... ──► TraceIdMiddleware ──► rate limiter per chiave
|
|
──► ApiKeyAuthenticationHandler (Bearer kh_…, hash SHA-256, IP consentiti, scadenza)
|
|
oppure CookieSessionAuthenticationHandler
|
|
──► risoluzione X-Company ──► MaintenanceMiddleware (503 se in manutenzione)
|
|
──► [RequireModule] + [RequirePermission] ──► <Modulo>Endpoints ──► servizio applicativo
|
|
──► risposta JSON camelCase · ETag · errori RFC 9457 (ProblemDetailsMiddleware) con trace id
|
|
```
|
|
|
|
Il dettaglio dei contratti HTTP è in [API.md](API.md); MCP segue lo stesso percorso di autenticazione su `/mcp`
|
|
([MCP.md](MCP.md)).
|
|
|
|
## 7. Servizi trasversali
|
|
|
|
### 7.1 Cache (SPEC §9, M2)
|
|
|
|
- `ICacheProvider`: `GetAsync`, `SetAsync` (TTL), `RemoveAsync`, `RemoveByPrefixAsync`, `GetOrCreateAsync`,
|
|
`PublishInvalidationAsync`.
|
|
- Implementazioni: `MemoryCacheProvider` (predefinita) e `RedisCacheProvider` (se `KHAEMHAT_REDIS` è valorizzata),
|
|
con client RESP2 scritto in casa (`RespClient`, `RespReader`, `RespWriter`, `RedisConnectionPool`,
|
|
`RedisSubscriber`) su `TcpClient`/`SslStream`.
|
|
- Contenuto: tabelle di base, permessi, menu, piano dei conti, listini, licenze, ricerche recenti. Chiavi
|
|
`kh:{azienda}:{area}:{key}`.
|
|
- Se Redis cade l'app prosegue in memoria e lo segnala (barra di stato, *Stato sistema*, log).
|
|
|
|
### 7.2 Scheduler (SPEC §9, §12.5; base in M2, attività da UI in M12)
|
|
|
|
- `JobRunner` in-process con `CronExpression` (sottoinsieme di cron) e `JobLock` nel database di sistema: ogni
|
|
attività gira una sola volta anche tra riavvii.
|
|
- Job di sistema: pulizia, verifica licenza, cambi BCE, inbox e canali SDI, coda e-mail, verifica giacenze, backup.
|
|
- **Attività programmate** degli amministratori (`sys_scheduled_tasks`): tipi *backup*, *procedura*, *report via
|
|
e-mail*, *notifica*, *import/export*, *verifica*, *script di manutenzione* dal catalogo interno (mai shell
|
|
libera); timeout, retry, notifica esito, storico in `sys_job_runs`.
|
|
|
|
### 7.3 Log (SPEC §9.5, M2)
|
|
|
|
- Un solo pipeline `ILogger` → `JsonConsoleFormatter` (una riga JSON su stdout) + `DbLogSink` in `sys_log`.
|
|
- Ogni modulo scrive nella propria **sezione** (`LogSection`, `LogSectionScope`): Sistema, Autenticazione, Database,
|
|
Migrazioni, Documenti, Contabilità, Magazzino, SDI/e-invoicing, CRM, Automazioni, Attività programmate, Backup,
|
|
API/MCP, E-mail/PEC, Integrazioni, UI/circuiti, Prestazioni (`SlowQueryLogger`: query > 500 ms).
|
|
- Correlazione con `trace_id` (generato da `TraceIdMiddleware`): compare negli errori mostrati all'utente
|
|
("Codice errore") e nelle risposte API.
|
|
- Retention per livello (errori 365 gg, avvisi 180, info 90, debug 7) e regole di avviso (`LogAlertRules`).
|
|
- Azioni di sicurezza e di istanza → `sys_security_audit` (immutabile); modifiche ai dati aziendali → `audit_log`.
|
|
|
|
### 7.4 Pacchetto fiscale (SPEC §1.10, M4 → M10)
|
|
|
|
- `Application` conosce solo `Fiscal.Abstractions`: `IFiscalPack`, `ITaxEngine`, `ITaxCodeCatalog`,
|
|
`IEInvoiceFormat`, `IEInvoiceNotificationReader`, `ISdiTransport`, `IFiscalReports`, `IFiscalCalendar`,
|
|
`IWithholdingRules`, `IFixedAssetRules`, `IFinancialStatementsSchema`, `IChartOfAccountsTemplate`,
|
|
`IIntrastatExporter`, `ITaxPaymentFormExporter`.
|
|
- `Program.cs` registra `ItalyFiscalPack`; il pacchetto attivo per un'azienda è scelto da
|
|
`company_profile.country` (`IT` → `ItalyFiscalPack`). Un altro paese sarà un nuovo progetto
|
|
`Khaemhat.Fiscal.<Paese>`.
|
|
- Canali SDI: `ISdiTransport` con quattro implementazioni (`PecSdiTransport`, `SdiCoopTransport`,
|
|
`IntermediaryATransport`, `IntermediaryBTransport`) e `SdiRouter` per le regole di instradamento.
|
|
|
|
### 7.5 Allegati e file generati (SPEC §9.4, M3)
|
|
|
|
- Tabella `attachments` per azienda; un allegato appartiene **a un solo documento** (`entity`, `entity_id`).
|
|
- File su volume: `/data/files/<azienda>/<yyyy>/<guid>` tramite `IFileStore` (`VolumeFileStore`) con quota per
|
|
azienda; upload in streaming, limite configurabile (25 MB), hook antivirus predisposto.
|
|
- `FileGenerationService` + `GeneratedFileFactory`: ogni generazione (PDF, XML FatturaPA, XLSX/CSV, ZIP di cortesia,
|
|
etichette, estratti conto, rapportini) crea un allegato **versionato** (`v1`, `v2`, …); "Rigenera" crea una
|
|
nuova versione. Gli XML inviati sono `locked`.
|
|
- Formati scritti in casa: `PdfWriter` (con `PdfA3Embedder`), `XlsxWriter`/`XlsxReader`, `CsvWriter`/`CsvReader`,
|
|
`ZipStreamWriter`. Le stampe massive producono ZIP in streaming, mai file temporanei fuori da `/data`.
|
|
|
|
### 7.6 Backup e ripristino (SPEC §13, M12)
|
|
|
|
| Motore | Backup | Verifica | Ripristino |
|
|
|---|---|---|---|
|
|
| PostgreSQL | `PgDumpRunner`: `pg_dump -Fc --no-owner --no-privileges` in streaming verso `/data/backups/<db>/bk-<db>-<timestamp>.dump` | `pg_restore --list` (`BackupVerifier`) | `PgRestoreRunner` in `khaemhat_restore_<ts>` + scambio atomico |
|
|
| SQLite | `SqliteBackup`: `VACUUM INTO` | apertura e `integrity_check` | sostituzione del file in manutenzione |
|
|
| Entrambi | backup logico JSON Lines + manifest (`LogicalBackupWriter`) | manifest + hash | `LogicalBackupReader` su database vuoto (anche SQLite → PostgreSQL) |
|
|
|
|
- Ogni set ha `sha256`, cifratura AES-256-GCM (`BackupEncryptor`), copie remote su S3 compatibile (`S3Client`,
|
|
`SigV4Signer`) e WebDAV (`WebDavClient`); retention GFS (`RetentionPolicy`); gli allegati dell'azienda sono inclusi.
|
|
- Ripristino: manutenzione → backup di sicurezza → ripristino su database temporaneo → controllo schema e migrazioni
|
|
→ integrità → scambio → fine manutenzione; avviato da un amministratore e **confermato dal super utente**
|
|
(notifica + TOTP). Il database di sistema si ripristina solo da CLI (`scripts/restore-system.sh`) a istanza ferma.
|
|
|
|
### 7.7 Sicurezza (SPEC §7, M2)
|
|
|
|
- Cookie `HttpOnly; Secure; SameSite=Lax`, sessioni in tabella (revoca, dispositivi, IP), DataProtection con chiavi
|
|
in `sys_data_protection_keys` (`DataProtectionDbXmlRepository`).
|
|
- Password PBKDF2-SHA256 600.000 iterazioni (`PasswordHasher`), policy, storico, lockout, TOTP RFC 6238
|
|
(`TotpGenerator`) obbligatorio per account di istanza.
|
|
- Chiavi API `kh_…` con hash SHA-256 (`ApiKeyHasher`), prefisso visibile, utente tecnico, permessi propri.
|
|
- Header di sicurezza (`SecurityHeadersMiddleware`): CSP con nonce, `X-Frame-Options: DENY`, `Referrer-Policy`;
|
|
HSTS dal reverse proxy.
|
|
|
|
## 8. Strato dati in breve
|
|
|
|
- Micro-ORM interno: mappe esplicite `XxxMap : EntityMap<Xxx>`, `QueryBuilder<T>` con un sottoinsieme sicuro di
|
|
espressioni, il resto come `SqlFragment` parametrizzato; mai concatenazione di input utente.
|
|
- Optimistic locking su `row_version` (`ConcurrencyException`).
|
|
- SQLite: WAL, `foreign_keys=ON`, `busy_timeout=5000`, scritture serializzate da `SqliteWriteLock`, decimali come
|
|
interi scalati x10⁶.
|
|
- PostgreSQL: pool per database, `statement_timeout` per sessione, `pg_advisory_xact_lock` per numeratori,
|
|
chiusure e scheduler; partizionamento annuale predisposto per le tabelle grandi.
|
|
- Migrazioni in C# con due cataloghi (sistema, azienda) e `schema_version` per database.
|
|
|
|
Convenzioni, tipi e tabelle: [DATA-MODEL.md](DATA-MODEL.md).
|
|
|
|
## 9. Struttura del repository
|
|
|
|
Adattata da SPEC §4 con gli emendamenti E1 (Gitea) ed E2 (solo Docker).
|
|
|
|
```
|
|
Khaemhat/
|
|
├── CLAUDE.md memoria di progetto ed emendamenti
|
|
├── README.md LICENSE CHANGELOG.md
|
|
├── Khaemhat.sln global.json Directory.Build.props Directory.Packages.props
|
|
├── .editorconfig .gitignore .dockerignore .gitattributes
|
|
├── assets/ icon.svg, icon-v1.0.svg, icon-mono.svg, PNG 16-512, favicon.ico
|
|
├── deploy/
|
|
│ ├── docker-compose.yml app + postgres + redis (profilo)
|
|
│ ├── docker-compose.sqlite.yml demo autonoma SQLite
|
|
│ ├── docker-compose.unraid.yml etichette net.unraid.docker.*
|
|
│ ├── .env.example
|
|
│ └── unraid/khaemhat.xml template Community Applications
|
|
├── docker/
|
|
│ ├── Dockerfile multi-stage, non root, HEALTHCHECK, postgresql-client-17
|
|
│ ├── entrypoint.sh attesa DB, migrazioni di sistema, bootstrap, avvio
|
|
│ └── postgres/init.sql
|
|
├── .gitea/workflows/
|
|
│ ├── ci.yml build + test: PR verso main, push su main che toccano codice, tag v*, manuale
|
|
│ ├── release.yml tag v* e manuale: immagine → registro pacchetti Gitea, release con note
|
|
│ └── wiki.yml push su main che tocca docs/wiki/**: sincronizza Khaemhat.wiki.git
|
|
├── scripts/
|
|
│ ├── build.sh test.sh run-dev.sh check-packages.sh new-migration.sh
|
|
│ ├── publish-image.sh build locale + push nel registro Gitea (alternativa a release.yml)
|
|
│ ├── publish-wiki.sh push di docs/wiki nel wiki Gitea
|
|
│ ├── gen-datamodel.sh genera docs/DATA-MODEL.md dalle mappe
|
|
│ ├── restore-system.sh ripristino del database di sistema a istanza ferma
|
|
│ └── seed.sh CLI: --base / --demo [--scale N] [--company CODE]
|
|
├── src/
|
|
│ ├── Khaemhat.Core/ Common/ Entities/ Enums/ Rules/ Validation/ Abstractions/
|
|
│ ├── Khaemhat.Fiscal.Abstractions/
|
|
│ ├── Khaemhat.Fiscal.Italy/ Vat/ FatturaPa/ Sdi/ Withholding/ F24/ Intrastat/ StampDuty/
|
|
│ │ FixedAssets/ FinancialStatements/ ChartOfAccounts/ Resources/
|
|
│ ├── Khaemhat.Data/ Khaemhat.Data.Sqlite/ Khaemhat.Data.PostgreSql/
|
|
│ ├── Khaemhat.Infrastructure/ Caching/ Security/ Licensing/ Mail/ Pdf/ Export/ Jobs/ Files/
|
|
│ │ Backup/ Http/ Mcp/ Logging/ Notifications/
|
|
│ ├── Khaemhat.Application/ Modules/ Documents/ Ledger/ Automation/ Seeding/ Search/ Audit/
|
|
│ │ │ Backup/ Licensing/
|
|
│ │ └── Modules/ Company/ Parties/ Items/ Sales/ Purchases/ Inventory/ Ledger/ Vat/
|
|
│ │ Assets/ Finance/ EInvoicing/ Crm/ Services/ Channels/ Reports/
|
|
│ │ Admin/ UserSettings/
|
|
│ └── 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/
|
|
└── docs/
|
|
├── SPEC.md ARCHITECTURE.md DATA-MODEL.md MODULES.md API.md MCP.md
|
|
├── DEPLOY.md DEVELOPMENT.md SECURITY.md STATUS.md
|
|
├── adr/
|
|
├── mockups/ mockup.css, png/ (22 + galleria), thumbs/ (88 miniature), README.md
|
|
└── wiki/ sorgente della wiki Gitea
|
|
```
|
|
|
|
Differenze rispetto a SPEC §4: `.gitea/workflows/` al posto di `.github/workflows/`; registro pacchetti Gitea al
|
|
posto di GHCR; nessun repository `khaemhat-assets` (icona servita come file raw del repository pubblico);
|
|
`docs/SPEC.md` contiene la specifica e `CLAUDE.md` è breve (ADR 0011); `docs/mockups/thumbs/` aggiunta;
|
|
`scripts/restore-system.sh` è citato in SPEC §13 e qui riportato nell'albero; è copiato nell'immagine in
|
|
`/app/scripts/` (ADR 0017). Nessun installer né binario distribuito (ADR 0010). In più `.vscode/` (debug e attività
|
|
di Visual Studio Code) e `.gitea/scripts/check-yaml.rb` (controllo YAML della CI).
|
|
|
|
Le regole di dipendenza della §3 e l'allowlist dei pacchetti sono verificate da test: `Khaemhat.Core.Tests`,
|
|
cartella `Architecture/`, legge i file di progetto e fallisce su ogni riferimento non ammesso.
|
|
|
|
## 10. Classi principali per progetto
|
|
|
|
Riassunto per area dell'elenco normativo di SPEC §21 (che resta il riferimento completo). Le entità sono
|
|
elencate in [DATA-MODEL.md](DATA-MODEL.md) accanto alle tabelle.
|
|
|
|
### 10.1 `Khaemhat.Core`
|
|
|
|
| Area | Classi |
|
|
|---|---|
|
|
| Fondamenta | `Entity<TKey>`, `IEntity<TKey>`, `IAuditable`, `IDemoMarkable`, `Result`/`Result<T>`, `Error`, `DomainException`, `ConcurrencyException`, `ModuleNotLicensedException`, `Guard` |
|
|
| Value object | `Money`, `Quantity`, `Percentage`, `DiscountFormula` |
|
|
| Contesto | `IClock`/`SystemClock`, `ICurrentUser`, `ICompanyContext`, `IEventBus`, `DomainEvent` |
|
|
| Entità | tabelle azienda, anagrafiche, documenti, contabilità, finanza, e-invoicing, CRM/servizi/canali, utenti aziendali, sistema (vedi DATA-MODEL) |
|
|
| Enum | `DbEngine`, `DatabaseScope`, `UserLevel`, `ModuleCode`, `DocumentKind`, `DocumentStatus`, `EInvoiceStatus`, `SdiChannelKind`, `TaxNature`, `LogSection`, `BackupTarget`, … |
|
|
| Regole documenti | `DocumentTotalsCalculator`, `TaxSummaryBuilder`, `InstallmentGenerator`, `StampDutyRule`, `WithholdingCalculator`, `SocialSecurityCalculator`, `PriceResolver`, `DiscountResolver`, `StockEffectMatrix`, `UomConverter` |
|
|
| Regole contabili | `JournalPostingRules`, `VatSettlementCalculator`, `ProRataCalculator`, `DepreciationCalculator`, `AccrualDeferralCalculator`, `ExchangeDifferenceCalculator` |
|
|
| Regole finanza/CRM | `AgingCalculator`, `DunningRules`, `BankMatcher`, `LeadScoring` |
|
|
| Formati e codici | `NumberFormatter`, `DocumentNumberFormat`, `CodeMaskFormatter` |
|
|
| Dashboard | `TodoAggregator`, `DoneAggregator`, `DeadlineAggregator` |
|
|
| Validatori | `ItalianVatNumberValidator`, `FiscalCodeValidator`/`FiscalCodeCalculator`, `IbanValidator`, `EanValidator`, `SdiRecipientCodeValidator`, `EmailValidator`, `JournalEntryValidator`, `ChartOfAccountsImportValidator`, `Validator<T>`, `ValidationResult` |
|
|
|
|
Nota: alcuni validatori di Core hanno nome "italiano" (`ItalianVatNumberValidator`, `FiscalCodeValidator`) pur
|
|
stando fuori dal pacchetto fiscale: è la collocazione indicata da SPEC §21.
|
|
|
|
### 10.2 `Khaemhat.Fiscal.Abstractions` / `Khaemhat.Fiscal.Italy`
|
|
|
|
| Area | Classi |
|
|
|---|---|
|
|
| Contratti | `IFiscalPack`, `ITaxEngine`, `ITaxCodeCatalog`, `IEInvoiceFormat`, `IEInvoiceNotificationReader`, `ISdiTransport`, `IFiscalReports`, `IFiscalCalendar`, `IWithholdingRules`, `IFixedAssetRules`, `IFinancialStatementsSchema`, `IChartOfAccountsTemplate`, `IIntrastatExporter`, `ITaxPaymentFormExporter` |
|
|
| IVA | `ItalyFiscalPack`, `ItalianTaxEngine`, `ItalianTaxCodeCatalog`, `VatNatures`, `ReverseChargeRules`, `SplitPaymentRules`, `CashVatRules`, `VatSettlementRules`, `VatAdvanceCalculator`, `LipeWriter` |
|
|
| FatturaPA | `FatturaPaWriter`, `FatturaPaReader`, `FatturaPaValidator`, `FatturaPaDocument`, `FatturaPaCodeLists` (con `SpecVersion`), `SdiFileNaming`, `SdiNotificationParser`, `P7mExtractor`, `CadesVerifier` |
|
|
| Canali SDI | `PecSdiTransport`, `SdiCoopTransport`, `IntermediaryATransport`, `IntermediaryBTransport`, `SdiRouter` |
|
|
| Ritenute e F24 | `WithholdingRulesIt`, `EnasarcoRules`, `CuExporter`, `F24Model`, `F24Codes`, `F24Exporter` |
|
|
| Intrastat | `IntrastatModel`, `IntrastatExporterIt`, `CombinedNomenclature` |
|
|
| Bollo, cespiti | `StampDutyRulesIt`, `FixedAssetRulesIt`, `MinisterialCoefficients` |
|
|
| Bilancio | `CeeSchema2424`, `CeeSchema2425`, `FinancialRatios` |
|
|
| Piano dei conti e dataset | `ItalianChartOfAccountsTemplate`, `ChartOfAccountsCsvFormat`, `ChartOfAccountsJsonFormat`, `MunicipalitiesDataset`, `AbiCabDataset` |
|
|
|
|
### 10.3 `Khaemhat.Data` e provider
|
|
|
|
| Area | Classi |
|
|
|---|---|
|
|
| Contratti | `IDbProvider`, `ISqlDialect`, `ISchemaBuilder`, `IUnitOfWork`, `IUnitOfWorkFactory`, `IRepository<,>`, `Repository<,>`, `DatabaseUrl`, `DatabaseTarget`, `DbProviderCatalog` |
|
|
| Registro database | `ICompanyRegistry`, `CompanyRegistry`, `IDatabaseLocator`, `DatabaseLocator`, `DatabaseScope`, `CompanyCodes` |
|
|
| Mappe e query | `EntityMap<T>`, `ColumnMap`, `ColumnType`, `MapRegistry`, `QueryBuilder<T>`, `Query<T>`, `PagedResult<T>`, `SqlFragment`, `ExpressionTranslator` |
|
|
| Esecuzione | `UnitOfWork`, `UnitOfWorkFactory`, `DataAccessContext` (orologio, utente, tentativi), `DbExecutor`, `ReaderMapper`, `CommandCache`, `TransientRetryPolicy` |
|
|
| Migrazioni | `IMigration`, `MigrationAttribute`, `MigrationRunner`, `MigrationReport`, `MigrationCatalog` (`ForSystem`/`ForCompany`), `SchemaVersionStore`, `SchemaModel`, `DataModelDocument`, `TableDefinition`, `ColumnDefinition`, `IndexDefinition`, `ForeignKeyDefinition`, `DdlGenerator` |
|
|
| SQLite | `SqliteProvider`, `SqliteDialect`, `SqliteSchemaBuilder`, `SqliteWriteLock`, `SqliteDecimalConverter` |
|
|
| PostgreSQL | `PostgresProvider`, `PostgresDialect`, `PostgresSchemaBuilder`, `PostgresDatabaseCreator`, `PostgresAdvisoryLocks`, `PostgresPartitioning`, `PostgresServerInfo` |
|
|
|
|
### 10.4 `Khaemhat.Infrastructure`
|
|
|
|
| Area | Classi |
|
|
|---|---|
|
|
| Cache | `ICacheProvider`, `MemoryCacheProvider`, `RedisCacheProvider`, `RespClient`, `RespReader`, `RespWriter`, `RedisConnectionPool`, `RedisSubscriber` |
|
|
| Sicurezza | `PasswordHasher`, `PasswordPolicy`, `TotpGenerator`, `SecureTokenGenerator`, `ApiKeyHasher`, `DataProtectionDbXmlRepository`, `SecretProtector`, `SecretRotation` |
|
|
| Licenze | `LicenseKey`, `LicenseDocument`, `LicenseVerifier`, `ModuleActivationCode`, `TestLicenseCatalog`, `ILicenseActivationService`, `OfflineActivationService`, `LicenseMonitor` |
|
|
| Mail | `IMailSender`, `SmtpMailSender`, `MailQueue`, `MailTemplateRenderer`, `ImapClient`, `MimeParser` |
|
|
| PDF ed export | `PdfWriter`, `PdfDocument`, `PdfPage`, `PdfFont`, `PdfTextLayout`, `PdfImage`, `PdfA3Embedder`, `CsvWriter`, `CsvReader`, `XlsxWriter`, `XlsxReader`, `ZipStreamWriter` |
|
|
| Job | `IJobScheduler`, `JobRunner`, `JobDefinition`, `JobContext`, `CronExpression`, `JobLock` |
|
|
| File | `IFileStore`, `VolumeFileStore`, `StoredFile`, `AttachmentStore`, `GeneratedFileFactory` |
|
|
| Backup | `PgDumpRunner`, `PgRestoreRunner`, `SqliteBackup`, `LogicalBackupWriter`, `LogicalBackupReader`, `BackupEncryptor`, `S3Client`, `SigV4Signer`, `WebDavClient`, `RetentionPolicy`, `BackupVerifier` |
|
|
| HTTP | `ViesClient`, `EcbRatesClient`, `GiteaPackagesClient` (al posto di `GhcrPackagesClient`, ADR 0009), `OutboundWebhookClient` |
|
|
| MCP | `McpServer`, `JsonRpc*`, `McpTool`, `McpToolRegistry`, `McpSchemaGenerator` |
|
|
| Log e notifiche | `DbLogSink`, `DbLoggerProvider`, `JsonConsoleFormatter`, `LogSectionScope`, `SlowQueryLogger`, `LogAlertRules`, `NotificationDispatcher` |
|
|
|
|
### 10.5 `Khaemhat.Application`
|
|
|
|
| Area | Classi |
|
|
|---|---|
|
|
| Moduli | `IModule`, `ModuleRegistry`, `ModuleInfo`, `MenuItem`, `PermissionDefinition`, `HelpLink`, `LicenseGate` |
|
|
| Motore documenti | `DocumentDefinition(s)`, `DocumentService<,>`, `DocumentFlowService`, `DocumentFlowWizard`, `FulfillmentCalculator`, `DocumentNumberingService`, `DocumentStateMachine`, `DocumentCopyService`, `DeferredInvoicingService`, `SelfInvoiceService` |
|
|
| Contabilizzazione | `DocumentPostingService`, `InventoryPoster`, `InstallmentPoster`, `LedgerPoster`, `PostingEngine` |
|
|
| Stampa, mail, file | `DocumentPrintService`, `IDocumentPrinter`, `HtmlDocumentPrinter`, `PdfDocumentPrinter`, `DocumentMailService`, `AttachmentService`, `FileGenerationService` |
|
|
| Contabilità | `JournalService`, `PeriodLockService`, `LedgerQueries`, `PartitarioService`, `TrialBalanceService`, `FinancialStatementsService`, `RecurringEntriesService`, `ExchangeDifferenceService`, `ChartOfAccountsImportService`, `ClosingProcedure`/`ClosingStep`, `AccrualDeferralService` |
|
|
| IVA e adempimenti | `VatRegisterService`, `VatSettlementService`, `StampDutyService`, `WithholdingService`, `IntrastatService`, `IntentDeclarationService` |
|
|
| Cespiti | `FixedAssetService`, `DepreciationService` |
|
|
| Tesoreria | `OpenItemService`, `PaymentService`, `RemittanceService`, `SddMandateService`, `BankStatementImportService`, `BankReconciliationService`, `DunningService`, `CashFlowForecastService`, `AgingReportService` |
|
|
| E-invoicing | `EInvoiceService`, `EInvoiceExportService`, `SdiChannelService`, `SdiInboxService`, `SdiNotificationImportService`, `PurchaseInvoiceImportService`, `ConservationExportService` |
|
|
| CRM | `LeadService`, `OpportunityService`, `PipelineService`, `ActivityService`, `CampaignService`, `TicketService`, `Party360Service`, `CrmDashboardService`, `SalesForecastService` |
|
|
| Servizi e canali | `ContractService`, `InterventionService`, `InterventionSchedulingService`, `ServiceBillingService`, `IChannelConnector`, `GenericChannelConnector`, `ChannelOrderImportService`, `ChannelSyncService` |
|
|
| Report e dashboard | `ReportDefinition`, `ReportRunner`, `ReportCatalog`, `ScheduledReportService`, `DashboardService`, `WidgetCatalog` |
|
|
| Amministrazione | `SystemUserService`, `UserService`, `RoleService`, `PermissionService`, `SessionService`, `LicenseService`, `ModuleActivationService`, `CompanyService`, `MaintenanceModeService`, `DatabaseMaintenanceService`, `IntegrityCheckService`, `RebuildService`, `ScheduledTaskService`, `BackupService`, `RestoreService`, `SystemSettingsService`, `SecretRotationService`, `LogQueryService`, `LogAlertService`, `SystemStatusService`, `UpdateCheckService`, `ApiKeyService`, `WebhookService` |
|
|
| Import | `ImportWizardService`, `CsvImportMapper`, `OpeningBalancesImportService` |
|
|
| Automazioni | `CodeRuleService`, `CodeSequenceService`, `AutoFillService`, `RuleEngine`, `TriggerCatalog`, `ConditionEvaluator`, `ActionExecutor`, `ProcedureCatalog`, `IProcedure`, `ProcedureRunner` |
|
|
| Preferenze | `UserSettingsService`, `CompanySettingsService` |
|
|
| Seeding | `ISeeder`, `SeedRunner`, `SeedContext`, `BaseDataSeeder`/`DemoDataSeeder` per area, `DemoDataRemover` |
|
|
| Trasversali | `GlobalSearchService`, `AuditTrailService` |
|
|
|
|
### 10.6 `Khaemhat.Web`
|
|
|
|
| Area | Classi |
|
|
|---|---|
|
|
| Host | `Program`, `KhaemhatOptions`, `EnvironmentConfigurationReader`, `StartupOrchestrator`, `HealthEndpoints`, `MetricsEndpoint` |
|
|
| Middleware | `MaintenanceMiddleware`, `TraceIdMiddleware`, `SecurityHeadersMiddleware`, `ProblemDetailsMiddleware` |
|
|
| Autenticazione e autorizzazione | `CookieSessionAuthenticationHandler`, `ApiKeyAuthenticationHandler`, `SessionStore`, `CurrentUserAccessor`, `CompanyContextAccessor`, `PermissionAuthorizationHandler`, `RequirePermissionAttribute`, `RequireLevelAttribute`, `RequireModuleAttribute`, `LoginRateLimiter` |
|
|
| API e MCP | `<Modulo>Endpoints`, `AttachmentEndpoints`, `OpenApiWriter`, `ApiDocsPage`, `McpEndpoint`, `WebhookEndpoints` |
|
|
| Shell | `App`, `Routes`, `MainLayout`, `TopBar`, `CompanySwitcher`, `GlobalSearch`, `NotificationBell`, `UserMenu`, `KhSideMenu`, `KhTabHost`, `KhStatusBar` |
|
|
| Dashboard | `Dashboard`, `DashboardCustomizer`, `KpiWidget`, `TodoWidget`, `DoneTodayWidget`, `DeadlinesWidget`, `FulfillmentWidget`, `RevenueChartWidget`, `CrmActivitiesWidget`, `PersonalNotesWidget`, `ShortcutsWidget`, … |
|
|
| Componenti `Kh*` | libreria di SPEC §10.7 (`KhIconToolbar`, `KhDocHead`, `KhGrid`, `KhHotlink`, `KhKanban`, `KhLogViewer`, …) |
|
|
| Pagine generiche | `DocumentPage<,>`, `MasterDataPage<T>` |
|
|
| Pagine per modulo | `PartyPage`, `ItemPage`, `SaleDocumentPage`, `PurchaseInvoiceImportPage`, `JournalEntryPage`, `VatSettlementPage`, `EInvoiceDashboard`, `PipelineBoard`, `Admin*Page`, … (elenco completo in SPEC §21) |
|
|
| Servizi UI | `ITexts`, `JsonTextProvider`, `KeyboardShortcutService`, `ToastService`, `DialogService`, `DrawerService`, `TabService`, `PrintService`, `ThemeService`, `MenuStateService`, `HelpService` |
|
|
|
|
## 11. Regole di codice rilevanti per l'architettura (SPEC §19)
|
|
|
|
- `record` per DTO e value object, `sealed` di default, `decimal` per importi e quantità (mai `double`).
|
|
- Date: `DateOnly` / `DateTime` UTC; conversione a `Europe/Rome` solo in presentazione.
|
|
- Async ovunque con `CancellationToken`; `Result<T>` per esiti attesi, eccezioni di dominio localizzabili.
|
|
- Validazione in `Core`/`Application`: l'interfaccia mostra, non decide.
|
|
- Ogni file appartiene a un modulo; nessuna cartella `Utils`. Commenti solo per i *perché*; XML doc sui tipi
|
|
pubblici di `Core`, `Data`, `Fiscal.Abstractions`.
|
|
- Codice, commenti e commit in inglese; testi dell'interfaccia in italiano tramite `Resources/it-IT/*.json`.
|
|
|
|
## 12. Punti aperti
|
|
|
|
| Punto | Nota |
|
|
|---|---|
|
|
| Modulo *Automation* | SPEC §4 colloca il motore in `Application/Automation/` e non elenca `Modules/Automation/`; serve comunque un `IModule` con codice `AUTO` per filtrare menu e procedure. Da fissare con un ADR in M12. |
|
|
| Sezioni di log per anagrafiche, servizi e report | SPEC §9.5 non prevede sezioni dedicate; vedi le proposte in [MODULES.md](MODULES.md). |
|
|
| Client aggiornamenti | `GhcrPackagesClient` di SPEC §21 è sostituito da `GiteaPackagesClient` (ADR 0009). |
|