Compare commits

..
Author SHA1 Message Date
Alby96andClaude Opus 5.5 f7c9cf6da8 docs: record M3 as closed (v0.3.0) and M4 as the current milestone
CI / Build and test (SQLite) (pull_request) Successful in 1m29s
CI / PostgreSQL 16 integration (pull_request) Skipped
CI / PostgreSQL 17 integration (pull_request) Skipped
CI / YAML check (pull_request) Successful in 5s
CI / Docker image (pull_request) Successful in 1m44s
STATUS is the resume point of every session; after the M3 merge and tag
it must point at M4 instead of the pending merge.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 21:02:42 +01:00
Alby96 4ecf15b609 Merge M3 · Framework UI (#119)
Wiki / Publish the wiki (push) Successful in 7s
Release / Image and release (push) Successful in 3m27s
CI / PostgreSQL 16 integration (push) Successful in 1m17s
CI / Build and test (SQLite) (push) Successful in 1m31s
CI / Docker image (push) Skipped
CI / YAML check (push) Successful in 5s
CI / PostgreSQL 17 integration (push) Successful in 1m17s
2026-11-11 21:00:44 +01:00
Alby96andClaude Opus 5.5 b4a2802bed docs: close M3 with real screenshots, ADR 0024 and the 0.3.0 changelog (#36)
CI / Build and test (SQLite) (pull_request) Successful in 1m36s
CI / PostgreSQL 16 integration (pull_request) Skipped
CI / PostgreSQL 17 integration (pull_request) Skipped
CI / YAML check (pull_request) Successful in 5s
CI / Docker image (pull_request) Successful in 1m13s
The milestone's Definition of Done asks for real screenshots, complete
wiki pages and a changelog for everything delivered. Fifteen screenshots
taken on a fresh instance now sit next to the mockups in the wiki;
Interfaccia, Dashboard, Preferenze, Design UI and Allegati are marked
complete, with the date-field shortcuts and the profile tabs that are not
built yet described as they really are. ADR 0024 records the Kh component
library, record pages and the shared list query, which shipped without
one, and the changelog gains its entries and a 0.3.0 section.

The visual check against the mockups found three layout bugs, fixed here:
the document total label took the timeline's .tl style and was cut, the
radar's .kh-choices class stacked the profile's theme cards in a column
(renamed .kh-radio-set), and on phones the top bar wrapped; it now keeps
icons only and the status bar shows only the live values.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 20:26:36 +01:00
Alby96andClaude Opus 5.5 8198e0a754 feat: attachments panel, file previews, print preview and history (#34)
Documents need to show, upload and generate their files from the interface,
and users need to see who changed a record. This adds the attachment list
(upload, preview, download, lock, trash and restore, older versions, ZIP,
generate/regenerate), in-app previews for PDF, images, XML, text, CSV and
XLSX, an A4 print preview with "save as attachment", and an audit history
list read through a permission-checked AuditTrailService.

Files are served by /files endpoints that require a signed-in user and the
company permissions; only PDF and images open inline, with their own CSP
that allows framing by this site only.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 19:59:37 +01:00
Alby96andClaude Opus 5.5 f415dc37a8 feat: in-app help, notifications panel and global search (#32)
F1 and "?" now open the wiki page of the screen inside the application
(/aiuto, mockup 011) from a copy of the wiki shipped next to the program,
so help works offline and always matches the installed version. Markdown
is converted in-house and fully encoded; images of the repository are
served from the copy. KHAEMHAT_HELP_URL sets the online wiki behind
"Apri nel wiki"; "Segnala un problema" opens a new issue of that repo.
A test checks that every page and menu entry has an existing wiki page.

The bell opens a notifications panel (mockup 010) with all/unread
filters and mark read. Broadcast notifications are now read per user
through sys_notification_reads / notification_reads instead of one
shared read_at.

The global search asks ISearchProvider implementations through
GlobalSearchService after a short pause; the first provider finds help
pages and sections, # and @ say which modules will fill them.

Escape also closes a side panel when the focus fell out of it.
Decisions in ADR 0023.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 19:39:17 +01:00
Alby96andClaude Opus 5.5 acb7e598d1 feat: widget dashboard and company settings (#30, #31)
The home page becomes the widget dashboard of mockups 004-006. Each user
switches widgets on and off, orders them (drag and drop or buttons that
also work from the keyboard), sizes them on the 12-column grid and picks
the start page; every change is saved at once. Whoever may change the
company settings sets a default layout per role, used by people who
never customized; Reset goes back to it.

Todo, Done and Deadlines collect lines from sources each module
registers, so later milestones fill them without touching the widgets;
a failing source is logged and skipped. M3 provides licence, unread
warnings and scheduled task runs. Notes, Shortcuts and System status
work now; widgets of modules still to come say which milestone brings
their data instead of showing fake numbers.

Role defaults live in the new company_settings table, written through
CompanySettingsService with company.settings.write (ADR 0022).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 19:15:06 +01:00
Alby96andClaude Opus 5.5 75d60ee4c4 feat: grids, radar and document lines (#28)
Lists need one component for the whole app (SPEC §10.6-§10.7): a list
query model that turns search, filters, sort and paging into SQL or runs
over rows in memory, a KhGrid that pages 100,000 rows while scrolling
(or in pages) with sort, selection, keyboard, inline edit, totals, row
menu, saved column layout and CSV/XLSX export, the KhRadar around it
with search, quick filters, a filter builder and saved filters, a radar
window for F4 lookups, and KhLinesGrid for document lines typed from the
keyboard.

Checked in the browser on the component catalog and the sample document.
Fixed on the way: the grid height lost to the flex basis, a new search
kept the old scroll position, Save of a filter needed a second click,
page shortcuts (Ctrl+Canc) reached the record behind a modal window,
Escape did nothing once focus left a dialog, totals did not follow an
inline edit, and amounts exported as 0 instead of 0,00.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 18:47:38 +01:00
Alby96 d0f9d0e651 Merge attachments and file writers (#34) into the M3 branch
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

# Conflicts:
#	src/Khaemhat.Web/Hosting/KhaemhatServices.cs
2026-11-11 18:12:34 +01:00
Alby96andClaude Opus 5.5 d958e7372d feat: Kh component library, record pages and profile security (M3, part 2)
Adds the building blocks every later screen uses, so modules are built from
one set of components instead of ad hoc markup:

- Form components (KhForm, KhTextBox, KhNumberBox, KhDateBox, KhSelect,
  KhCheck, KhSwitch, KhHotlink) with Italian number and date input, inline
  calculation (=10*3), field messages plus a summary that focuses the field,
  and service errors added by field name.
- Display and window components (panels, tiles, badges, chips, money, tabs
  with Alt+1..9, steps, dialog, side drawer and DrawerService).
- KhIconToolbar that keeps one line and moves less used commands into the
  "..." menu, KhDocHead, and the RecordPage/DocumentPage/MasterDataPage bases
  with standard commands, shortcuts and save/cancel/delete flow (#27, #29).
- Development-only component catalog and sample document page.
- Profile: personal data, password change that ends other sessions, TOTP
  enable/disable and recovery codes through ProfileService (#31).

Refs #27 #29 #31

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 18:11:16 +01:00
Alby96andClaude Opus 5.5 b341ade9e9 feat: attachments, file store and in-house PDF/CSV/XLSX/ZIP writers (#34)
Documents need attachments and generated files (SPEC 9.4) before the UI of
M3 can show them, and the spec forbids external libraries for PDF and
spreadsheets.

- VolumeFileStore keeps files under <data>/files/<COMPANY>/<yyyy>/<guid>,
  writing a .part file in the same folder with size limit and SHA-256, then
  quota and scanner checks (IFileScanner hook, no-op by default).
- attachments table (migration 007) with kind, version series, lock, trash
  and the uploading user; AttachmentService uploads, adds generated files as
  the next version, lists, opens, zips, locks, trashes, restores and purges
  after 30 days (new system job system.attachments-trash).
- FileGenerationService runs IFileGenerator implementations into the store;
  three generators for the fictitious test document (PDF, CSV, XLSX).
- CsvWriter (Italian Excel defaults, formula-injection guard), XlsxWriter,
  ZipStreamWriter and PdfWriter (standard Type1 fonts, WinAnsi, AFM widths,
  JPEG, Flate, xref) only write asynchronously, so they can stream to an
  HTTP response.
- ADR 0021 records versioning, storage layout, PDF scope and CSV defaults.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 18:06:48 +01:00
Alby96andClaude Opus 5.5 cf6f849cc1 feat: application shell, localized texts and user preferences (M3, part 1)
The pages built so far now live inside the shell of the mockups instead of the
M0 placeholder, every interface text comes from Resources/it-IT, and each user
keeps their own look and start page.

- Shell: top bar, collapsible side menu with fly-out sub-menus, status bar and
  tabs that keep each page alive (page type and route values per tab, so a tab
  never shows another page); at most 12 tabs, least-used clean tab evicted.
- One shortcut table with Alt variants for the combinations browsers keep
  (Ctrl+W, Ctrl+Tab, Ctrl+N); command palette for pages and commands.
- ITexts over embedded JSON; tests forbid literal texts in .razor components
  and check that every key used exists.
- User settings in sys_user_settings / user_settings; theme written on the
  server; profile page with live preview, start page, sessions and shortcuts.
- Home, coming-soon pages for later milestones, localized sign-in and error
  pages; ADR 0020; wiki, CHANGELOG, STATUS and data model updated.

Refs #25 #26 #31 #33

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 16:44:59 +01:00
Alby96 1c30054e3d Merge M2 · Sistema e sicurezza (#118)
Wiki / Publish the wiki (push) Successful in 8s
Release / Image and release (push) Successful in 2m25s
CI / PostgreSQL 16 integration (push) Successful in 1m23s
CI / Build and test (SQLite) (push) Successful in 1m0s
CI / Docker image (push) Skipped
CI / YAML check (push) Successful in 4s
CI / PostgreSQL 17 integration (push) Failing after 2m38s
2026-11-11 15:56:07 +01:00
Alby96andClaude Opus 5.5 4502526f4d ci: start the smoke-test containers with the variables M2 requires
CI / Build and test (SQLite) (pull_request) Successful in 59s
CI / PostgreSQL 16 integration (pull_request) Skipped
CI / PostgreSQL 17 integration (pull_request) Skipped
CI / YAML check (pull_request) Successful in 4s
CI / Docker image (pull_request) Successful in 1m20s
Since M2 the instance refuses to start without a secret key, a super user and a
first company, and the home page redirects to the login. The CI and release smoke
tests now pass a throwaway key and test values, wait for /health/ready and check
the login page and its security headers.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 15:35:06 +01:00
Alby96andClaude Opus 5.5 032c602b49 feat: system and security - start-up, accounts, sign-in, licences, log, jobs, companies (M2)
CI / Build and test (SQLite) (pull_request) Successful in 55s
CI / PostgreSQL 16 integration (pull_request) Skipped
CI / PostgreSQL 17 integration (pull_request) Skipped
CI / YAML check (pull_request) Successful in 5s
CI / Docker image (pull_request) Failing after 2m4s
The instance now starts on its own from KHAEMHAT_* variables: it migrates the system
and company databases, creates the super user and the first company, and only then
reports ready. Users sign in with password and TOTP through revocable database
sessions, and licences decide which modules and how many companies are available.

- Configuration: every wrong variable reported at once (exit code 2), _FILE variants
- Accounts, password policy and lockout, TOTP with recovery codes, session states
  with token rotation, security audit with a hash chain
- Sign-in pages (mockups 001-003), authorization attributes, security headers and a
  CSP without inline scripts, login rate limit
- Signed licences, activation codes, test mode, licence tool
- DataProtection keys in the system database, encrypted with the instance key
- Memory or Redis cache (in-house RESP client) that falls back to memory
- Database log by section with trace id; cron scheduler with locks and system jobs;
  record history (audit_log)
- Company creation, states, company context and X-Company, 503 in maintenance
- In-memory SQLite databases stay alive for the process (tests, demo)
- Tests for all of the above, ADR 0019, wiki, SECURITY, CHANGELOG, STATUS, DATA-MODEL

Refs #15 #16 #17 #18 #19 #20 #21 #22 #23 #24

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 15:29:24 +01:00
Alby96 4582837b70 Merge docs: chiusura M1 (#117)
Wiki / Publish the wiki (push) Successful in 13s
2026-11-11 13:27:42 +01:00
Alby96andClaude Opus 5.5 edce4702da docs: close M1 in STATUS and describe the data layer in the Architettura wiki page
CI / Build and test (SQLite) (pull_request) Successful in 54s
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 1m21s
M1 is tagged v0.1.0. STATUS now points at M2 and lists what M1 handed over to it (migration log section, startup
refusal without a valid KHAEMHAT_SECRET_KEY, PostgreSQL performance numbers); the wiki explains the encrypted
company registry and the two engines in plain words.

Refs #14

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 13:19:12 +01:00
Alby96 6eef15c487 Merge M1 · Strato dati (#116)
Wiki / Publish the wiki (push) Successful in 6s
Release / Image and release (push) Successful in 2m16s
CI / PostgreSQL 16 integration (push) Successful in 1m10s
CI / Build and test (SQLite) (push) Successful in 47s
CI / Docker image (push) Skipped
CI / YAML check (push) Successful in 4s
CI / PostgreSQL 17 integration (push) Successful in 1m7s
2026-11-11 13:18:03 +01:00
Alby96andClaude Opus 5.5 738c43ba0a feat: data layer with SQLite and PostgreSQL providers, migrations and encrypted company registry (M1)
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>
2026-11-11 13:11:34 +01:00
Alby96 28e7a6e18a Merge M0 · Bootstrap (#115)
Wiki / Publish the wiki (push) Successful in 13s
Release / Image and release (push) Successful in 2m18s
CI / PostgreSQL 16 integration (push) Successful in 1m21s
CI / Build and test (SQLite) (push) Successful in 38s
CI / Docker image (push) Skipped
CI / YAML check (push) Successful in 19s
CI / PostgreSQL 17 integration (push) Successful in 1m28s
Closes #1, #2, #3, #4, #5, #114
2026-11-11 11:57:24 +01:00
394 changed files with 47194 additions and 361 deletions

No files matched your search

+4
View File
@@ -10,6 +10,10 @@
.data/
out/
docs/
# ...except the copy of the wiki and the images it shows, shipped as the in-app help (ADR 0023).
!docs/wiki/
!docs/mockups/thumbs/
!docs/mockups/png/
deploy/
*.md
!README.md
+8
View File
@@ -70,4 +70,12 @@ dotnet_diagnostic.IDE0005.severity = warning
[tests/**.cs]
# CA1707 (underscores in names): test names read as Method_Condition_Result.
dotnet_diagnostic.CA1707.severity = none
# CA1861/CA1847/CA1862: tests pass literal arrays and write the string predicates the query translator must handle.
dotnet_diagnostic.CA1861.severity = none
dotnet_diagnostic.CA1847.severity = none
dotnet_diagnostic.CA1862.severity = none
# MSTEST0037 and friends stay at their defaults.
# Migration classes are named after their version, M<yyyymmdd>_<nnn>_<Name> (SPEC 5.3).
[**/Migrations/*.cs]
dotnet_diagnostic.CA1707.severity = none
+11 -5
View File
@@ -135,19 +135,25 @@ jobs:
docker build -f docker/Dockerfile --build-arg VERSION=0.0.0-ci --build-arg GIT_SHA="$(git rev-parse --short HEAD)" \
--label khaemhat-ci.job="$(hostname)" -t "$NAME:image" .
- name: Smoke test (/health/live, non-root user, PUID/PGID)
- name: Smoke test (start-up, login page, non-root user, PUID/PGID)
run: |
docker network create --label khaemhat-ci.job="$(hostname)" "$NAME"
docker network connect "$NAME" "$(hostname)"
# Since M2 the instance needs a key, a super user and a first company; the key is thrown away with the run.
docker run -d --name "$NAME-app" --network "$NAME" --label khaemhat-ci.job="$(hostname)" \
-e KHAEMHAT_SYSTEM_DB=sqlite:///data/system.db -e KHAEMHAT_LICENSE_MODE=test -e PUID=99 -e PGID=100 "$NAME:image"
for i in $(seq 1 30); do
if curl -fsS --max-time 5 "http://$NAME-app:8080/health/live"; then echo; break; fi
-e KHAEMHAT_SYSTEM_DB=sqlite:///data/system.db -e KHAEMHAT_LICENSE_MODE=test \
-e KHAEMHAT_SECRET_KEY="$(head -c 32 /dev/urandom | base64)" \
-e KHAEMHAT_SUPERUSER=root -e KHAEMHAT_SUPERUSER_PASSWORD=Ci-Smoke-Test-2026 -e KHAEMHAT_COMPANY_CODE=CI \
-e PUID=99 -e PGID=100 "$NAME:image"
for i in $(seq 1 60); do
if curl -fsS --max-time 5 "http://$NAME-app:8080/health/ready"; then echo; break; fi
sleep 2
done
curl -fsS --max-time 5 "http://$NAME-app:8080/health"
echo
curl -fsS --max-time 5 "http://$NAME-app:8080/" | grep -q "in costruzione"
test "$(curl -s -o /dev/null -w '%{http_code}' --max-time 5 "http://$NAME-app:8080/")" = "302"
curl -fsS --max-time 5 "http://$NAME-app:8080/login" | grep -q "Accedi"
curl -fsS -D - -o /dev/null --max-time 5 "http://$NAME-app:8080/login" | grep -qi "content-security-policy"
test "$(docker exec "$NAME-app" sh -c 'stat -c %u:%g /proc/1')" = "99:100"
test "$(docker exec "$NAME-app" stat -c %u:%g /data)" = "99:100"
docker exec "$NAME-app" pg_dump --version
+7 -4
View File
@@ -113,15 +113,18 @@ jobs:
--label khaemhat-ci.job="$(hostname)" \
-t "$IMAGE:$VERSION" .
- name: Smoke test (/health/live)
- name: Smoke test (/health/ready)
if: env.PUBLISHED != 'true'
run: |
docker network create --label khaemhat-ci.job="$(hostname)" "$NAME"
docker network connect "$NAME" "$(hostname)"
docker run -d --name "$NAME-app" --network "$NAME" --label khaemhat-ci.job="$(hostname)" \
-e KHAEMHAT_SYSTEM_DB=sqlite:///data/system.db -e KHAEMHAT_LICENSE_MODE=test "$IMAGE:$VERSION"
for i in $(seq 1 30); do
if curl -fsS --max-time 5 "http://$NAME-app:8080/health/live"; then echo; break; fi
-e KHAEMHAT_SYSTEM_DB=sqlite:///data/system.db -e KHAEMHAT_LICENSE_MODE=test \
-e KHAEMHAT_SECRET_KEY="$(head -c 32 /dev/urandom | base64)" \
-e KHAEMHAT_SUPERUSER=root -e KHAEMHAT_SUPERUSER_PASSWORD=Ci-Smoke-Test-2026 -e KHAEMHAT_COMPANY_CODE=CI \
"$IMAGE:$VERSION"
for i in $(seq 1 60); do
if curl -fsS --max-time 5 "http://$NAME-app:8080/health/ready"; then echo; break; fi
sleep 2
done
report="$(curl -fsS --max-time 5 "http://$NAME-app:8080/health")"
+1
View File
@@ -424,3 +424,4 @@ deploy/.env
out/
# License signing keys (tools/Khaemhat.LicenseTool): the private key never enters the repository (ADR 0008).
*.khkey
*.pem
+142
View File
@@ -7,6 +7,148 @@ un'immagine `gitea.encke-hake.ts.net/balbosoft/khaemhat:X.Y.Z`.
## [Unreleased]
## [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
dashboard a widget, le preferenze dell'utente, ricerca, aiuto e notifiche, allegati e anteprima di stampa, tutto
provato su un documento di sviluppo in attesa delle maschere vere (da M4).
### Added
- Libreria di componenti `Kh*` (ADR 0024): campi con numeri e date all'italiana (`T`, `F`, `I`, `+n`, cifre senza
separatori) e calcolo `=10*3`, messaggi accanto al campo e riepilogo che porta al campo, pannelli, tessere, badge,
chip, importi, schede con `Alt+1`…`Alt+9`, passi, finestre di dialogo, pannelli laterali e messaggi a comparsa.
- `KhIconToolbar` su una riga con il menu `…`, `KhDocHead` a tre blocchi e le basi `RecordPage`, `DocumentPage`,
`MasterDataPage` con comandi standard, conferme e scorciatoie `Ctrl+S`, `Ctrl+N`, `Ctrl+P`, `Ctrl+Canc`, `F9`.
- Liste con un solo modello di richiesta (`ListQuery`, `ListFields`): la stessa descrizione dei campi diventa SQL o
filtra righe in memoria. `KhGrid` virtualizzata (100.000 righe) con ordinamento, selezione, tastiera, modifica in
riga, totali, menu di riga, colonne salvate ed esportazione CSV/XLSX; `KhRadar` con ricerca, filtri rapidi,
costruttore di filtri e filtri salvati; finestra radar per la ricerca `F4`; `KhLinesGrid` per le righe dei
documenti.
- *Il mio profilo*: dati personali, cambio password che chiude le altre sessioni, attivazione e disattivazione della
verifica in due passaggi con codici di recupero.
- Catalogo dei componenti e documento di prova per gli sviluppatori (`/sviluppo/componenti`, `/sviluppo/documento`,
solo in sviluppo).
- Primi screenshot reali nella wiki (`docs/wiki/img/`): finestra, menu compresso, ricerca, notifiche, aiuto,
dashboard, profilo, tema scuro, documento, allegati, storico, anteprima di stampa, telefono.
- Shell (mockup 004, 007, 013): barra superiore con marchio e versione, cambio azienda per gli account di istanza,
ricerca, recenti, notifiche, tema rapido, aiuto e menu utente; menu laterale per sezioni con voci filtrate da
licenza e permessi, compresso a sole icone con sottomenu a comparsa (`Ctrl+B`, stato ricordato per utente,
compresso sotto i 1100 px); barra di stato con azienda, esercizio, utente, latenza, cache e versione.
- Schede tenute in vita: ogni pagina aperta resta com'era passando da una scheda all'altra, pallino delle modifiche,
conferma alla chiusura, massimo 12 schede (si chiude la meno usata senza modifiche) (ADR 0020).
- Scorciatoie da tastiera in un'unica tabella, con le varianti `Alt+W`, `Alt+PagGiù`/`Alt+PagSu`, `Alt+N` per le
combinazioni che i browser tengono per sé; ricerca rapida `Ctrl+K` di pagine e comandi; `F1` apre la pagina wiki
della maschera.
- Testi dell'interfaccia in `Resources/it-IT/*.json` letti da `ITexts`, formati italiani per importi e date; test che
vietano i testi letterali nei componenti e controllano che ogni chiave esista.
- *Il mio profilo*: aspetto (tema automatico, chiaro, scuro, alto contrasto; otto accenti; densità; dimensione del
testo; menu; numeri tabellari, animazioni ridotte, suggerimenti, evidenza della riga) con anteprima dal vivo,
pagina iniziale, sessioni attive con chiusura, elenco delle scorciatoie.
- Preferenze salvate per utente in `sys_user_settings` (account di istanza) e `user_settings` (utenti aziendali); il
tema è già nella pagina inviata dal server.
- Aiuto in app (mockup 011): `F1` e `?` aprono in una scheda la pagina wiki della maschera dalla copia della wiki
contenuta nell'immagine (`/aiuto`, funziona senza Internet), con indice, *Apri nel wiki* e *Segnala un problema*;
Markdown convertito in casa; nuova variabile facoltativa `KHAEMHAT_HELP_URL` per la wiki online (ADR 0023).
- Pannello notifiche (mockup 010): filtri *Tutte* e *Non lette*, segna come letta, *Segna tutte come lette*,
conteggio aggiornato ogni minuto; le notifiche per tutti si segnano lette per ciascun utente (tabelle
`sys_notification_reads` e `notification_reads`).
- Ricerca globale a fornitori (`GlobalSearchService`, `ISearchProvider`): oltre a pagine e comandi trova le pagine e
le sezioni dell'aiuto; prefissi `#` documenti e `@` persone pronti per i moduli successivi.
- Allegati nell'interfaccia (mockup 024): `KhAttachmentList` con caricamento, anteprima, download, blocco, cestino
con ripristino, versioni precedenti, *Scarica tutto (ZIP)* e *Genera file* / *Rigenera*; anteprima di PDF e
immagini nel browser, di XML e testo come testo, di CSV e XLSX come griglia (lettore XLSX scritto in casa).
- Anteprima di stampa (mockup 025): `KhPrintPreview` con foglio A4 in HTML e CSS, *Stampa* del solo foglio, PDF da
aprire o scaricare e *Salva come allegato*; prova sul documento di sviluppo con `Ctrl+P`.
- Storico di un record: `AuditTrailService` legge il registro delle modifiche e `KhAuditList` mostra chi ha cambiato
cosa, con i valori prima e dopo.
- Indirizzi `/files/{id}`, `/files/zip` e `/files/generate` per scaricare gli allegati, tutti gli allegati di un
record e un file generato al volo; solo PDF e immagini si aprono nel browser, con una politica di sicurezza propria
che permette l'anteprima dentro Khaemhat.
- Con la dashboard spenta, Home con licenza, moduli, azienda e aree disponibili; le aree delle prossime versioni
aprono una pagina che dice con quale milestone arrivano.
- Dashboard a widget (mockup 004-006, ADR 0022): Da fare oggi, Fatto oggi, Scadenze 30 giorni, Promemoria personali,
Scorciatoie e Stato del sistema con dati veri; i widget dei moduli futuri si possono già accendere e dicono da quale
versione arrivano i dati. Pannello *Personalizza* con pagina iniziale, interruttore della dashboard, widget da
accendere, ordinare e dimensionare, trascinamento sulla griglia e pulsanti equivalenti da tastiera, *Ripristina* e
layout predefinito per ruolo. Le liste raccolgono le righe da sorgenti che ogni modulo registra.
- Impostazioni dell'azienda nella tabella `company_settings`, scritte con il permesso `company.settings.write`.
- Token, temi e classi dei mockup in `css/tokens.css` e `css/components.css`, sprite di icone proprie, stampa sempre
in chiaro.
### Changed
- `Esc` chiude anche un pannello laterale aperto quando il focus non è in un campo.
- Su telefono la barra superiore mostra solo le icone e la barra di stato solo connessione, cache e versione.
### Fixed
- L'etichetta *Totale documento* dell'intestazione era tagliata: prendeva lo stile della timeline (`.tl`).
- Le schede dei temi e dei colori nel profilo andavano in colonna: la classe `.kh-choices` del radar le
ridefiniva; il gruppo di scelte del radar ora si chiama `.kh-radio-set`.
- Pagine di accesso, errori e riconnessione con i testi localizzati e i colori del tema.
## [0.2.0] - 2026-11-11
M2 — Sistema e sicurezza. L'istanza si avvia da sola, crea super utente e prima azienda, e si entra con password e
verifica in due passaggi.
### Added
- Avvio guidato dalle variabili `KHAEMHAT_*` (anche `_FILE`): tutte le variabili sbagliate elencate insieme e uscita
con codice 2; migrazioni del sistema e delle aziende all'avvio, super utente e prima azienda al primo avvio,
pagina "Avvio in corso" e `/health/ready` a 503 finché non è pronto (ADR 0019).
- Account di istanza (super utente, amministratori) e utenti aziendali, password PBKDF2-SHA256 con storico, blocco
dopo 5 errori, limite di 10 accessi al minuto per indirizzo IP.
- Pagine di accesso (mockup 001-003): scelta dell'azienda, cambio password obbligatorio, attivazione e verifica in
due passaggi (TOTP, RFC 6238) con 10 codici di recupero; uscita con `POST /logout`.
- Sessioni nel database con token salvato come hash, rigenerato a ogni passo, revocabili, riverificate dal circuito
Blazor ogni minuto; audit di sicurezza in `sys_security_audit` con catena di hash.
- Ruoli predefiniti, permessi `modulo.area.azione` con override per utente, attributi `[RequirePermission]`,
`[RequireLevel]`, `[RequireModule]`.
- Licenze: trial di 60 giorni, file `.khl` firmati ECDSA P-256, codici di attivazione dei moduli, modalità test con
i codici fittizi, limite di aziende e di utenti contemporanei; strumento `tools/Khaemhat.LicenseTool`.
- Chiavi DataProtection nel database di sistema, cifrate con la chiave di istanza.
- Cache in memoria o su Redis (client RESP scritto in casa, `KHAEMHAT_REDIS`), con ritorno alla memoria se Redis non
risponde.
- Log su database (`sys_log`) per sezioni, con identificativo di traccia (`X-Trace-Id`), utente e azienda; query
lente nella sezione *Prestazioni*; esito delle migrazioni nella sezione *Migrazioni*.
- Attività programmate: cron a 5 campi con fuso orario, lock, timeout, tentativi, storico; job di sistema per pulizia
sessioni, controllo licenza e retention del log.
- Storico dei record (`audit_log` aziendale) con i soli campi cambiati.
- Aziende: creazione e collegamento, stati attiva / manutenzione / sola lettura / disattivata, contesto azienda per
pagine e API (`X-Company`), risposta 503 per le aziende in manutenzione.
- Header di sicurezza su tutte le risposte (CSP senza script inline, `X-Frame-Options`, `nosniff`,
`Referrer-Policy`, `Permissions-Policy`).
- Tabelle di sistema e aziendali di M2, documentate in `docs/DATA-MODEL.md` (rigenerato).
### Changed
- La home richiede l'accesso: senza sessione porta a `/login`.
- I database SQLite in memoria restano disponibili per tutta la vita del processo.
## [0.1.0] - 2026-11-11
M1 — Strato dati. Nessuna funzione visibile nell'interfaccia: è il motore su cui si appoggiano tutte le milestone
successive.
### Added
- Micro-ORM interno in `Khaemhat.Data` (ADR 0004, ADR 0018): mappe esplicite `EntityMap<T>`, query tipizzate
`Query.For<T>().Where(...)` con un sottoinsieme sicuro di espressioni, `SqlFragment` con valori sempre
parametrizzati, `IUnitOfWork` con transazioni, `IRepository<T,TKey>` con colonne di audit e concorrenza
ottimistica su `row_version` (`ConcurrencyException`), tentativi automatici sugli errori transitori.
- Provider SQLite (tabelle `STRICT`, WAL, decimali esatti come interi scalati x10^6, LIKE senza distinzione di
maiuscole anche per le lettere accentate, scritture serializzate) e PostgreSQL 16+ (`numeric(19,6)`, `timestamptz`,
`jsonb`, `ILIKE`, lock di transazione, creazione ed eliminazione dei database aziendali, informazioni sul server).
- Configurazione dei database da URL `postgres://` e `sqlite://` (`DatabaseUrl`), con la password mai mostrata nei
messaggi.
- Migrazioni in C#: cataloghi di sistema e aziendale, `schema_version` con checksum in ogni database, una
migrazione per transazione sotto lock, rifiuto delle versioni sconosciute; prime tabelle di sistema
`sys_companies` e `sys_settings`.
- Registro delle aziende (`CompanyRegistry`) con la posizione del database cifrata e risoluzione
`DatabaseScope.System` / `DatabaseScope.Company(codice)` in `IUnitOfWorkFactory`.
- Cifratura dei segreti a riposo con AES-256-GCM e chiave derivata da `KHAEMHAT_SECRET_KEY` (`SecretProtector`,
formato `khs1`), con il mattone della rotazione delle chiavi.
- `scripts/new-migration.sh` e `scripts/gen-datamodel.sh` (con `tools/Khaemhat.DataModelTool`): la sezione
*Schema attuale* di `docs/DATA-MODEL.md` è generata dalle migrazioni e un test ne verifica l'aggiornamento.
- Test su SQLite e PostgreSQL (tipi, decimali, paginazione, upsert, LIKE, ordinamento temporale, CRUD, concorrenza,
transazioni, input ostile, migrazioni, registro, cifratura) e misure di riferimento delle prestazioni.
## [0.0.1] - 2026-11-11
Prima versione: M0 — Bootstrap. Nessuna funzione gestionale ancora; c'è lo scheletro su cui costruirle.
+15
View File
@@ -41,6 +41,8 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "tools", "tools", "{07C2787E
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Khaemhat.LicenseTool", "tools\Khaemhat.LicenseTool\Khaemhat.LicenseTool.csproj", "{4317FFD0-9473-43FD-8543-F80EF9BA812A}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Khaemhat.DataModelTool", "tools\Khaemhat.DataModelTool\Khaemhat.DataModelTool.csproj", "{7CA26565-5E1A-46AA-A2F7-C38FBADF0E3F}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
@@ -243,6 +245,18 @@ Global
{4317FFD0-9473-43FD-8543-F80EF9BA812A}.Release|x64.Build.0 = Release|Any CPU
{4317FFD0-9473-43FD-8543-F80EF9BA812A}.Release|x86.ActiveCfg = Release|Any CPU
{4317FFD0-9473-43FD-8543-F80EF9BA812A}.Release|x86.Build.0 = Release|Any CPU
{7CA26565-5E1A-46AA-A2F7-C38FBADF0E3F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{7CA26565-5E1A-46AA-A2F7-C38FBADF0E3F}.Debug|Any CPU.Build.0 = Debug|Any CPU
{7CA26565-5E1A-46AA-A2F7-C38FBADF0E3F}.Debug|x64.ActiveCfg = Debug|Any CPU
{7CA26565-5E1A-46AA-A2F7-C38FBADF0E3F}.Debug|x64.Build.0 = Debug|Any CPU
{7CA26565-5E1A-46AA-A2F7-C38FBADF0E3F}.Debug|x86.ActiveCfg = Debug|Any CPU
{7CA26565-5E1A-46AA-A2F7-C38FBADF0E3F}.Debug|x86.Build.0 = Debug|Any CPU
{7CA26565-5E1A-46AA-A2F7-C38FBADF0E3F}.Release|Any CPU.ActiveCfg = Release|Any CPU
{7CA26565-5E1A-46AA-A2F7-C38FBADF0E3F}.Release|Any CPU.Build.0 = Release|Any CPU
{7CA26565-5E1A-46AA-A2F7-C38FBADF0E3F}.Release|x64.ActiveCfg = Release|Any CPU
{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
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
@@ -264,5 +278,6 @@ Global
{C5C8124F-3B12-43A9-BD0F-5AA5F7261699} = {0AB3BF05-4346-4AA6-1389-037BE0695223}
{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}
EndGlobalSection
EndGlobal
+1
View File
@@ -32,6 +32,7 @@
<Config Name="KHAEMHAT_LICENSE_MODE" Target="KHAEMHAT_LICENSE_MODE" Default="production" Mode="" Description="production oppure test (abilita i codici di licenza fittizi)" Type="Variable" Display="advanced" Required="false" Mask="false">production</Config>
<Config Name="KHAEMHAT_LICENSE" Target="KHAEMHAT_LICENSE" Default="" Mode="" Description="Licenza firmata (.khl, testo). Vuoto = Trial" Type="Variable" Display="advanced" Required="false" Mask="true"></Config>
<Config Name="KHAEMHAT_SEED_DEMO" Target="KHAEMHAT_SEED_DEMO" Default="false" Mode="" Description="true = dati dimostrativi al primo avvio (solo database vuoto)" Type="Variable" Display="advanced" Required="false" Mask="false">false</Config>
<Config Name="KHAEMHAT_HELP_URL" Target="KHAEMHAT_HELP_URL" Default="" Mode="" Description="Opzionale: wiki online aperta da Apri nel wiki (predefinita https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/wiki/)" Type="Variable" Display="advanced" Required="false" Mask="false"></Config>
<Config Name="KHAEMHAT_UPDATE_FEED" Target="KHAEMHAT_UPDATE_FEED" Default="" Mode="" Description="Opzionale: URL API pacchetti Gitea per il controllo aggiornamenti (https://gitea.encke-hake.ts.net/api/v1/packages/BalboSoft?type=container&amp;q=khaemhat)" Type="Variable" Display="advanced" Required="false" Mask="false"></Config>
<Config Name="TZ" Target="TZ" Default="Europe/Rome" Mode="" Description="Fuso orario" Type="Variable" Display="advanced" Required="false" Mask="false">Europe/Rome</Config>
<Config Name="PUID" Target="PUID" Default="99" Mode="" Description="UID per i file in /data" Type="Variable" Display="advanced" Required="false" Mask="false">99</Config>
+9 -8
View File
@@ -1,6 +1,6 @@
# Architettura di Khaemhat
> Stato: bozza · Revisione 2026-11-11 · Fonte: SPEC §1, §2, §3, §4, §5, §7, §9, §13, §15, §19, §21; ADR 0009-0017
> 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
@@ -74,6 +74,7 @@ client degli aggiornamenti è `GiteaPackagesClient`.
| `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
@@ -171,11 +172,11 @@ tabelle è in [DATA-MODEL.md](DATA-MODEL.md).
| Tipo | Progetto | Responsabilità |
|---|---|---|
| `IDbProvider` | Data | motore (`DbEngine`), dialetto, `SchemaBuilder`, creazione connessioni, `EnsureDatabaseExistsAsync`, `DropDatabaseAsync`, `GetServerInfoAsync` |
| `ISqlDialect` | Data | quoting, parametri, paginazione, `InsertReturningId`, `Upsert`, `CaseInsensitiveLike`, `AdvisoryLock`, conversioni `ColumnType` |
| `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 | risolve `companyCode → (IDbProvider, connection string decifrata)` leggendo `sys_companies` |
| `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 |
@@ -440,11 +441,11 @@ stando fuori dal pacchetto fiscale: è la collocazione indicata da SPEC §21.
| Area | Classi |
|---|---|
| Contratti | `IDbProvider`, `ISqlDialect`, `ISchemaBuilder`, `IUnitOfWork`, `IUnitOfWorkFactory`, `IRepository<,>`, `Repository<,>` |
| Registro database | `ICompanyRegistry`, `CompanyRegistry`, `DatabaseScope` |
| 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 | `DbExecutor`, `ReaderMapper<T>`, `CommandCache`, `TransientRetryPolicy` |
| Migrazioni | `IMigration`, `MigrationAttribute`, `MigrationRunner`, `MigrationCatalog` (System/Company), `SchemaVersionStore`, `TableDefinition`, `ColumnDefinition`, `IndexDefinition`, `ForeignKeyDefinition`, `DdlGenerator` |
| 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` |
+663 -21
View File
@@ -1,12 +1,13 @@
# Modello dati
> Stato: bozza · Revisione 2026-11-10 · Fonte: SPEC §5, §7, §8, §9, §11, §12, §13, §14, §21
> Stato: in corso · Revisione 2026-11-11 (M1) · Fonte: SPEC §5, §7, §8, §9, §11, §12, §13, §14, §21
> **Versione pianificata.** A partire dalla milestone 1 questo file sarà **generato** da `scripts/gen-datamodel.sh`
> leggendo le mappe `XxxMap : EntityMap<Xxx>` e le migrazioni: non andrà più modificato a mano. Finché il codice non
> esiste, questa è la versione pianificata ricavata dalla specifica: nomi e colonne sono indicativi e verranno
> confermati (o corretti) dalla prima generazione. I nomi di tabella contrassegnati con **†** non compaiono
> letteralmente in SPEC: sono derivati dal nome dell'entità di SPEC §21 secondo la convenzione snake_case plurale.
> **Due parti.** La sezione [8. Schema attuale](#8-schema-attuale-generato) è **generata** da
> `scripts/gen-datamodel.sh` leggendo le migrazioni: non si modifica a mano e un test fallisce se non è aggiornata.
> Le sezioni 3-4 sono la **pianificazione** ricavata dalla specifica: nomi e colonne sono indicativi e vengono
> confermati (o corretti) dalla migrazione che crea ciascuna tabella, milestone dopo milestone. I nomi di tabella
> contrassegnati con **†** non compaiono letteralmente in SPEC: sono derivati dal nome dell'entità di SPEC §21
> secondo la convenzione snake_case plurale.
Documenti collegati: [ARCHITECTURE.md](ARCHITECTURE.md) · [MODULES.md](MODULES.md) · [API.md](API.md).
@@ -31,24 +32,29 @@ Documenti collegati: [ARCHITECTURE.md](ARCHITECTURE.md) · [MODULES.md](MODULES.
| `ColumnType` | PostgreSQL | SQLite | Note |
|---|---|---|---|
| `String(n)` | `varchar(n)` | `TEXT` | lunghezza verificata dall'applicazione su SQLite |
| `String(n)` | `varchar(n)` | `TEXT` + `CHECK (length(col) <= n)` | la lunghezza è imposta dal database su entrambi i motori |
| `Text` | `text` | `TEXT` | |
| `Int32` | `int` | `INTEGER` | |
| `Int32` | `integer` | `INTEGER` | |
| `Int64` | `bigint` | `INTEGER` | chiavi primarie ed esterne |
| `Decimal(19,6)` | `numeric(19,6)` | `INTEGER` scalato x10⁶ | vedi §1.3 |
| `Bool` | `boolean` | `INTEGER` 0/1 | |
| `Bool` | `boolean` | `INTEGER` + `CHECK (col IN (0, 1))` | |
| `Date` | `date` | `TEXT` `yyyy-MM-dd` | `DateOnly` in C# |
| `DateTimeUtc` | `timestamptz` | `TEXT` ISO 8601 UTC | `DateTime` UTC; conversione a `Europe/Rome` solo in presentazione |
| `DateTimeUtc` | `timestamptz` | `TEXT` `yyyy-MM-ddTHH:mm:ss.ffffffZ` | `DateTime` UTC al microsecondo su entrambi i motori; conversione a `Europe/Rome` solo in presentazione |
| `Guid` | `uuid` | `TEXT` | |
| `Bytes` | `bytea` | `BLOB` | |
| `Json` | `jsonb` | `TEXT` | diff di audit, payload dei canali, dati di log |
Le tabelle SQLite sono `STRICT`: un valore del tipo sbagliato è rifiutato invece di essere convertito. Le enumerazioni
sono memorizzate **per nome** (`String(40)`), così un riordino dei valori in C# non altera i dati.
### 1.3 Decimali scalati su SQLite
SQLite non ha un tipo decimale esatto: i valori `Decimal(19,6)` sono memorizzati come **interi moltiplicati per
10⁶** (`SqliteDecimalConverter`). Conseguenze per chi scrive query:
- `ISqlDialect.ToDbValue` / `FromDbValue` convertono in scrittura e in lettura; i parametri passano già scalati;
- l'arrotondamento al sesto decimale è *half away from zero* (`1,2345675` diventa `1,234568`), come `numeric(19,6)`
su PostgreSQL; un valore oltre l'intervallo solleva `OverflowException` invece di essere troncato;
- le **somme in SQL** (`SUM`, `GROUP BY`) operano sugli interi scalati e vengono **riscalate in lettura**: niente
aritmetica in virgola mobile;
- prodotti e divisioni fra due colonne decimali non vanno fatti in SQL su SQLite (il fattore di scala si
@@ -59,8 +65,14 @@ SQLite non ha un tipo decimale esatto: i valori `Decimal(19,6)` sono memorizzati
- Ogni entità ha una mappa `XxxMap : EntityMap<Xxx>` (tabella, colonne, chiave, indici, FK, conversioni); nessuna
riflessione a runtime oltre la costruzione iniziale (`MapRegistry`).
- `QueryBuilder<T>`: uguaglianza, confronto, `Contains`/`StartsWith`, `In`, `And`/`Or`/`Not`, `IsNull`; il resto come
`SqlFragment` parametrizzato. Mai concatenare input utente in SQL.
- `Query.For<T>().Where(x => ...)`: uguaglianza, confronto, `== null`, `Contains`/`StartsWith`/`EndsWith` (LIKE
senza distinzione di maiuscole e accenti compresi, con `%` e `_` dell'utente protetti), `lista.Contains(x.Col)`
(`IN`), `&&`/`||`/`!`, `string.IsNullOrEmpty`; il resto come `SqlFragment` parametrizzato. Un'espressione fuori da
questo insieme solleva `NotSupportedException`, non viene valutata in memoria. Mai concatenare input utente in SQL:
in `SqlFragment.Of($"... {valore}")` ogni valore interpolato diventa un parametro.
- `IRepository<T, TKey>` compila le colonne di audit, imposta `row_version = 1` all'inserimento e la incrementa a ogni
modifica; `IUnitOfWork.AcquireLockAsync(chiave)` prende un lock di transazione (`pg_advisory_xact_lock` o il lock di
scrittura di SQLite) per numeratori e chiusure.
- SQLite: `journal_mode=WAL; foreign_keys=ON; busy_timeout=5000`; scritture serializzate da `SqliteWriteLock`.
- PostgreSQL: pool separato per database (`MaxPoolSize` da impostazioni), `statement_timeout` per sessione,
`pg_advisory_xact_lock` per numeratori, chiusure e scheduler.
@@ -68,22 +80,24 @@ SQLite non ha un tipo decimale esatto: i valori `Decimal(19,6)` sono memorizzati
## 2. Migrazioni (SPEC §5.3)
```csharp
[Migration(20261013_001, "create_parties")]
public sealed class M20261013_001 : IMigration
[Migration(20261013_001, "create_parties")] // Target = MigrationTarget.Company se omesso
public sealed class M20261013_001_CreateParties : IMigration
{
public void Up(ISchemaBuilder sb) { /* tabelle, colonne, indici, FK in forma neutra */ }
public string? UpSql(ISqlDialect d) => null; // SQL specifico del dialetto, se serve
public void Up(ISchemaBuilder schema) { /* tabelle, colonne, indici, FK in forma neutra */ }
public string? UpSql(ISqlDialect dialect) => null; // SQL specifico del dialetto, se serve
}
```
| Regola | Dettaglio |
|---|---|
| Due cataloghi | `MigrationCatalog.System` (database di sistema) e `MigrationCatalog.Company` (ogni azienda) |
| Versioni | `schema_version(module, version, name, applied_at, checksum)` in **ogni** database |
| Esecuzione | `MigrationRunner` applica in transazione, è idempotente, registra l'esito nella sezione di log *Migrazioni* |
| Downgrade | non supportato: se trova versioni applicate non note rifiuta di partire |
| Due cataloghi | `MigrationCatalog.ForSystem()` (database di sistema) e `MigrationCatalog.ForCompany(assembly dei moduli)` |
| Versioni | `yyyymmdd_nnn` (11 cifre, data valida, `nnn` da 001), uniche per modulo; `schema_version(module, version, name, applied_at, checksum)` in **ogni** database, `checksum` = SHA-256 delle istruzioni generate |
| Esecuzione | `MigrationRunner` applica **una migrazione per transazione** sotto lock (più istanze che partono insieme non si pestano i piedi), è idempotente e restituisce un `MigrationReport`; la registrazione nella sezione di log *Migrazioni* arriva con il log (M2) |
| Checksum diverso | una migrazione già applicata e poi modificata produce un avviso, non un errore: le migrazioni applicate non si cambiano, se ne scrive una nuova |
| Downgrade | non supportato: se trova versioni applicate non note rifiuta di partire (`MigrationException`) |
| Avvio | il sistema è migrato all'avvio; le aziende all'avvio (impostazione) o dal pannello (SPEC §12.1) in modalità manutenzione |
| Nuova migrazione | `scripts/new-migration.sh` |
| Nuova migrazione | `scripts/new-migration.sh <system\|company> <nome_snake_case> [cartella] [modulo]` |
| Documentazione | `scripts/gen-datamodel.sh` rigenera la [sezione 8](#8-schema-attuale-generato); `--check` verifica soltanto |
| Test obbligatorio | tutte le migrazioni da zero su SQLite e PostgreSQL, `schema_version` coerente, riapplicazione senza effetti |
## 3. Database di sistema (`khaemhat_system`)
@@ -325,9 +339,637 @@ qualunque modifica ──► audit_log
- Obiettivi di prestazione di riferimento (SPEC §18): bilancio di verifica su 2 M righe < 10 s, pagina log con 1 M
righe < 1 s per filtro.
### 6.1 Misure di riferimento dello strato dati (M1)
`PerformanceBaselineTests` inserisce righe con tutti i tipi di colonna tramite `IRepository` in una sola transazione,
poi le legge tutte e legge una pagina filtrata con il conteggio totale. Con `KHAEMHAT_PERF=1` usa 100.000 righe,
altrimenti 2.000 (prova di fumo, sempre eseguita anche in CI).
```bash
KHAEMHAT_PERF=1 scripts/test.sh --filter TestCategory=Performance --logger "console;verbosity=detailed"
```
| Data | Motore | Macchina | Inserimenti | Lettura di tutte le righe | Pagina filtrata + conteggio |
|---|---|---|---|---|---|
| 2026-11-11 | SQLite (file in memoria) | Ryzen 5 2600X, Windows 11, .NET 10.0.403 | 100.000 in 5,6 s (circa 17.800/s) | 0,9 s | 17 ms |
Le misure servono a riconoscere un peggioramento, non come soglia: il test non fallisce sui tempi. Le misure su
PostgreSQL si aggiungono dal job `postgres` della CI alla chiusura della milestone.
## 7. Segreti nel database
Cifrati con AES-256-GCM e chiave derivata da `KHAEMHAT_SECRET_KEY` (`SecretProtector`): connection string delle
aziende (`sys_companies`), password SMTP/PEC/S3/WebDAV (`sys_settings`), token degli intermediari e credenziali dei
canali SDI (`sdi_channels`), credenziali dei canali e-commerce (`sales_channels`), segreti dei webhook. La rotazione
avviene con `KHAEMHAT_SECRET_KEY_NEW` (SPEC §12.9). Gli hash (password, chiavi API) non sono cifrati ma irreversibili.
## 8. Schema attuale (generato)
Questa sezione è scritta da `scripts/gen-datamodel.sh` a partire dalle migrazioni presenti nel codice; il test
`DataModelDocumentTests` fallisce se non è aggiornata. Comprende `schema_version`, presente in ogni database.
<!-- BEGIN GENERATED: scripts/gen-datamodel.sh, do not edit by hand -->
### Database di sistema
Migrazioni applicate in ordine:
- `core` 20261111001 `create_sys_companies` (M20261111_001_CreateSysCompanies)
- `core` 20261111002 `create_sys_settings` (M20261111_002_CreateSysSettings)
- `core` 20261111003 `create_sys_users` (M20261111_003_CreateSysUsers)
- `core` 20261111004 `create_sys_sessions` (M20261111_004_CreateSysSessions)
- `core` 20261111005 `create_sys_roles_templates` (M20261111_005_CreateSysRolesTemplates)
- `core` 20261111006 `create_sys_licenses` (M20261111_006_CreateSysLicenses)
- `core` 20261111007 `create_sys_data_protection_keys` (M20261111_007_CreateSysDataProtectionKeys)
- `core` 20261111008 `create_sys_log` (M20261111_008_CreateSysLog)
- `core` 20261111009 `create_sys_security_audit` (M20261111_009_CreateSysSecurityAudit)
- `core` 20261111010 `create_sys_scheduler` (M20261111_010_CreateSysScheduler)
- `core` 20261111011 `create_sys_notifications` (M20261111_011_CreateSysNotifications)
- `core` 20261111012 `create_sys_user_settings` (M20261111_012_CreateSysUserSettings)
- `core` 20261111013 `create_sys_notification_reads` (M20261111_013_CreateSysNotificationReads)
#### `schema_version`
| Colonna | Tipo | Null | Default | Note |
|---|---|---|---|---|
| `module` | String(50) | no | | chiave primaria |
| `version` | Int64 | no | | chiave primaria |
| `name` | String(200) | no | | |
| `applied_at` | DateTimeUtc | no | | |
| `checksum` | String(64) | no | | |
Chiave primaria: `module`, `version`.
#### `sys_companies`
| Colonna | Tipo | Null | Default | Note |
|---|---|---|---|---|
| `id` | Int64 | no | | chiave primaria, identity |
| `code` | String(20) | no | | |
| `name` | String(200) | no | | |
| `engine` | String(20) | no | | |
| `connection_string` | Text | no | | |
| `status` | String(40) | no | `'Active'` | |
| `is_default` | Bool | no | `false` | |
| `notes` | Text | sì | | |
| `created_at` | DateTimeUtc | no | | |
| `created_by` | String(100) | sì | | |
| `updated_at` | DateTimeUtc | sì | | |
| `updated_by` | String(100) | sì | | |
| `row_version` | Int64 | no | `1` | |
- indice unico `ux_sys_companies_code` su `code`
#### `sys_data_protection_keys`
| Colonna | Tipo | Null | Default | Note |
|---|---|---|---|---|
| `id` | Int64 | no | | chiave primaria, identity |
| `friendly_name` | String(200) | no | | |
| `xml` | Text | no | | |
| `created_at` | DateTimeUtc | no | | |
| `created_by` | String(100) | sì | | |
| `updated_at` | DateTimeUtc | sì | | |
| `updated_by` | String(100) | sì | | |
| `row_version` | Int64 | no | `1` | |
- indice unico `ux_sys_data_protection_keys_friendly_name` su `friendly_name`
#### `sys_job_locks`
| Colonna | Tipo | Null | Default | Note |
|---|---|---|---|---|
| `id` | String(100) | no | | chiave primaria |
| `owner` | String(100) | no | | |
| `acquired_at` | DateTimeUtc | no | | |
| `expires_at` | DateTimeUtc | no | | |
#### `sys_job_runs`
| Colonna | Tipo | Null | Default | Note |
|---|---|---|---|---|
| `id` | Int64 | no | | chiave primaria, identity |
| `task_code` | String(100) | no | | |
| `started_at` | DateTimeUtc | no | | |
| `finished_at` | DateTimeUtc | sì | | |
| `outcome` | String(40) | no | | |
| `attempt` | Int32 | no | `1` | |
| `message` | Text | sì | | |
| `trace_id` | String(64) | sì | | |
- indice `ix_sys_job_runs_task_code_started_at` su `task_code`, `started_at`
#### `sys_license_activations`
| Colonna | Tipo | Null | Default | Note |
|---|---|---|---|---|
| `id` | Int64 | no | | chiave primaria, identity |
| `action` | String(40) | no | | |
| `source` | String(40) | no | | |
| `modules` | String(400) | sì | | |
| `outcome` | String(60) | no | | |
| `message` | Text | sì | | |
| `created_at` | DateTimeUtc | no | | |
| `created_by` | String(100) | sì | | |
| `updated_at` | DateTimeUtc | sì | | |
| `updated_by` | String(100) | sì | | |
| `row_version` | Int64 | no | `1` | |
#### `sys_licenses`
| Colonna | Tipo | Null | Default | Note |
|---|---|---|---|---|
| `id` | Int64 | no | | chiave primaria, identity |
| `source` | String(40) | no | | |
| `payload` | Text | no | | |
| `licensee` | String(200) | sì | | |
| `modules` | String(400) | no | | |
| `max_concurrent_users` | Int32 | no | `0` | |
| `max_companies` | Int32 | no | `0` | |
| `issued_at` | DateTimeUtc | sì | | |
| `expires_at` | DateTimeUtc | sì | | |
| `grace_period_days` | Int32 | no | `0` | |
| `is_active` | Bool | no | `true` | |
| `created_at` | DateTimeUtc | no | | |
| `created_by` | String(100) | sì | | |
| `updated_at` | DateTimeUtc | sì | | |
| `updated_by` | String(100) | sì | | |
| `row_version` | Int64 | no | `1` | |
#### `sys_log`
| Colonna | Tipo | Null | Default | Note |
|---|---|---|---|---|
| `id` | Int64 | no | | chiave primaria, identity |
| `at` | DateTimeUtc | no | | |
| `level` | String(20) | no | | |
| `section` | String(40) | no | | |
| `source` | String(200) | no | | |
| `message` | Text | no | | |
| `exception` | Text | sì | | |
| `user_name` | String(100) | sì | | |
| `company_code` | String(20) | sì | | |
| `trace_id` | String(64) | sì | | |
| `request` | String(400) | sì | | |
| `entity` | String(100) | sì | | |
| `entity_id` | String(100) | sì | | |
| `data` | Json | sì | | |
- indice `ix_sys_log_at` su `at`
- indice `ix_sys_log_section_at` su `section`, `at`
- indice `ix_sys_log_trace_id` su `trace_id`
#### `sys_notification_reads`
| Colonna | Tipo | Null | Default | Note |
|---|---|---|---|---|
| `id` | Int64 | no | | chiave primaria, identity |
| `notification_id` | Int64 | no | | |
| `user_id` | Int64 | no | | |
| `created_at` | DateTimeUtc | no | | |
| `created_by` | String(100) | sì | | |
| `updated_at` | DateTimeUtc | sì | | |
| `updated_by` | String(100) | sì | | |
| `row_version` | Int64 | no | `1` | |
- indice `ix_sys_notification_reads_user_id` su `user_id`
- indice unico `ux_sys_notification_reads_notification_user` su `notification_id`, `user_id`
#### `sys_notifications`
| Colonna | Tipo | Null | Default | Note |
|---|---|---|---|---|
| `id` | Int64 | no | | chiave primaria, identity |
| `recipient_user_id` | Int64 | sì | | |
| `category` | String(40) | no | | |
| `severity` | String(40) | no | | |
| `title` | String(200) | no | | |
| `body` | Text | sì | | |
| `link` | String(400) | sì | | |
| `read_at` | DateTimeUtc | sì | | |
| `created_at` | DateTimeUtc | no | | |
| `created_by` | String(100) | sì | | |
| `updated_at` | DateTimeUtc | sì | | |
| `updated_by` | String(100) | sì | | |
| `row_version` | Int64 | no | `1` | |
- indice `ix_sys_notifications_recipient_user_id` su `recipient_user_id`
#### `sys_roles_templates`
| Colonna | Tipo | Null | Default | Note |
|---|---|---|---|---|
| `id` | Int64 | no | | chiave primaria, identity |
| `code` | String(50) | no | | |
| `name` | String(100) | no | | |
| `description` | Text | sì | | |
| `permissions` | Json | no | | |
| `sort_order` | Int32 | no | `0` | |
| `created_at` | DateTimeUtc | no | | |
| `created_by` | String(100) | sì | | |
| `updated_at` | DateTimeUtc | sì | | |
| `updated_by` | String(100) | sì | | |
| `row_version` | Int64 | no | `1` | |
- indice unico `ux_sys_roles_templates_code` su `code`
#### `sys_scheduled_tasks`
| Colonna | Tipo | Null | Default | Note |
|---|---|---|---|---|
| `id` | Int64 | no | | chiave primaria, identity |
| `code` | String(100) | no | | |
| `name` | String(200) | no | | |
| `job_type` | String(100) | no | | |
| `company_code` | String(20) | sì | | |
| `cron` | String(100) | no | | |
| `time_zone` | String(64) | no | | |
| `timeout_seconds` | Int32 | no | `600` | |
| `max_retries` | Int32 | no | `0` | |
| `is_enabled` | Bool | no | `true` | |
| `is_system` | Bool | no | `false` | |
| `parameters` | Json | sì | | |
| `last_run_at` | DateTimeUtc | sì | | |
| `next_run_at` | DateTimeUtc | sì | | |
| `last_outcome` | String(40) | sì | | |
| `created_at` | DateTimeUtc | no | | |
| `created_by` | String(100) | sì | | |
| `updated_at` | DateTimeUtc | sì | | |
| `updated_by` | String(100) | sì | | |
| `row_version` | Int64 | no | `1` | |
- indice unico `ux_sys_scheduled_tasks_code` su `code`
#### `sys_security_audit`
| Colonna | Tipo | Null | Default | Note |
|---|---|---|---|---|
| `id` | Int64 | no | | chiave primaria, identity |
| `at` | DateTimeUtc | no | | |
| `action` | String(100) | no | | |
| `user_name` | String(100) | sì | | |
| `company_code` | String(20) | sì | | |
| `ip_address` | String(64) | sì | | |
| `target` | String(200) | sì | | |
| `details` | Json | sì | | |
| `previous_hash` | String(64) | no | | |
| `hash` | String(64) | no | | |
- indice `ix_sys_security_audit_at` su `at`
#### `sys_sessions`
| Colonna | Tipo | Null | Default | Note |
|---|---|---|---|---|
| `id` | Int64 | no | | chiave primaria, identity |
| `token_hash` | String(64) | no | | |
| `user_id` | Int64 | no | | -> `sys_users` (Cascade) |
| `state` | String(40) | no | | |
| `company_code` | String(20) | sì | | |
| `ip_address` | String(64) | sì | | |
| `user_agent` | String(400) | sì | | |
| `persistent` | Bool | no | `false` | |
| `last_seen_at` | DateTimeUtc | no | | |
| `expires_at` | DateTimeUtc | no | | |
| `revoked_at` | DateTimeUtc | sì | | |
| `revoked_reason` | String(100) | sì | | |
| `created_at` | DateTimeUtc | no | | |
| `created_by` | String(100) | sì | | |
| `updated_at` | DateTimeUtc | sì | | |
| `updated_by` | String(100) | sì | | |
| `row_version` | Int64 | no | `1` | |
- indice `ix_sys_sessions_user_id` su `user_id`
- indice unico `ux_sys_sessions_token_hash` su `token_hash`
#### `sys_settings`
| Colonna | Tipo | Null | Default | Note |
|---|---|---|---|---|
| `id` | Int64 | no | | chiave primaria, identity |
| `key` | String(200) | no | | |
| `value` | Text | sì | | |
| `is_secret` | Bool | no | `false` | |
| `created_at` | DateTimeUtc | no | | |
| `created_by` | String(100) | sì | | |
| `updated_at` | DateTimeUtc | sì | | |
| `updated_by` | String(100) | sì | | |
| `row_version` | Int64 | no | `1` | |
- indice unico `ux_sys_settings_key` su `key`
#### `sys_user_settings`
| Colonna | Tipo | Null | Default | Note |
|---|---|---|---|---|
| `id` | Int64 | no | | chiave primaria, identity |
| `user_id` | Int64 | no | | |
| `key` | String(200) | no | | |
| `value` | Text | sì | | |
| `created_at` | DateTimeUtc | no | | |
| `created_by` | String(100) | sì | | |
| `updated_at` | DateTimeUtc | sì | | |
| `updated_by` | String(100) | sì | | |
| `row_version` | Int64 | no | `1` | |
- indice unico `ux_sys_user_settings_user_id_key` su `user_id`, `key`
#### `sys_users`
| Colonna | Tipo | Null | Default | Note |
|---|---|---|---|---|
| `id` | Int64 | no | | chiave primaria, identity |
| `user_name` | String(100) | no | | |
| `display_name` | String(200) | no | | |
| `email` | String(254) | sì | | |
| `level` | String(40) | no | | |
| `password_hash` | String(200) | sì | | |
| `password_history` | Json | sì | | |
| `password_changed_at` | DateTimeUtc | sì | | |
| `must_change_password` | Bool | no | `false` | |
| `temporary_password_expires_at` | DateTimeUtc | sì | | |
| `failed_login_count` | Int32 | no | `0` | |
| `locked_until` | DateTimeUtc | sì | | |
| `totp_secret` | Text | sì | | |
| `totp_enabled` | Bool | no | `false` | |
| `totp_last_step` | Int64 | sì | | |
| `totp_recovery_codes` | Json | sì | | |
| `recovery_token_hash` | String(64) | sì | | |
| `recovery_token_expires_at` | DateTimeUtc | sì | | |
| `is_active` | Bool | no | `true` | |
| `last_login_at` | DateTimeUtc | sì | | |
| `linked_company_code` | String(20) | sì | | |
| `linked_user_id` | Int64 | sì | | |
| `created_at` | DateTimeUtc | no | | |
| `created_by` | String(100) | sì | | |
| `updated_at` | DateTimeUtc | sì | | |
| `updated_by` | String(100) | sì | | |
| `row_version` | Int64 | no | `1` | |
- indice unico `ux_sys_users_user_name` su `user_name`
### Database aziendale
Migrazioni applicate in ordine:
- `core` 20261111001 `create_users` (M20261111_001_CreateUsers)
- `core` 20261111002 `create_user_sessions` (M20261111_002_CreateUserSessions)
- `core` 20261111003 `create_roles` (M20261111_003_CreateRoles)
- `core` 20261111004 `create_audit_log` (M20261111_004_CreateAuditLog)
- `core` 20261111005 `create_notifications` (M20261111_005_CreateNotifications)
- `core` 20261111006 `create_user_settings` (M20261111_006_CreateUserSettings)
- `core` 20261111007 `create_attachments` (M20261111_007_CreateAttachments)
- `core` 20261111008 `create_company_settings` (M20261111_008_CreateCompanySettings)
- `core` 20261111009 `create_notification_reads` (M20261111_009_CreateNotificationReads)
#### `attachments`
| Colonna | Tipo | Null | Default | Note |
|---|---|---|---|---|
| `id` | Int64 | no | | chiave primaria, identity |
| `entity` | String(100) | no | | |
| `entity_id` | Int64 | no | | |
| `kind` | String(40) | no | | |
| `name` | String(255) | no | | |
| `mime` | String(150) | no | | |
| `size` | Int64 | no | | |
| `sha256` | String(64) | no | | |
| `version` | Int32 | no | | |
| `version_key` | String(300) | no | | |
| `generated_by` | String(100) | sì | | |
| `storage_key` | String(60) | no | | |
| `user_name` | String(100) | sì | | |
| `locked` | Bool | no | `false` | |
| `deleted_at` | DateTimeUtc | sì | | |
| `created_at` | DateTimeUtc | no | | |
| `created_by` | String(100) | sì | | |
| `updated_at` | DateTimeUtc | sì | | |
| `updated_by` | String(100) | sì | | |
| `row_version` | Int64 | no | `1` | |
- indice `ix_attachments_deleted_at` su `deleted_at`
- indice `ix_attachments_entity_entity_id` su `entity`, `entity_id`
- indice unico `ux_attachments_entity_entity_id_version_key_version` su `entity`, `entity_id`, `version_key`, `version`
#### `audit_log`
| Colonna | Tipo | Null | Default | Note |
|---|---|---|---|---|
| `id` | Int64 | no | | chiave primaria, identity |
| `at` | DateTimeUtc | no | | |
| `entity` | String(100) | no | | |
| `entity_id` | String(100) | no | | |
| `action` | String(20) | no | | |
| `user_name` | String(100) | sì | | |
| `diff` | Json | sì | | |
| `trace_id` | String(64) | sì | | |
- indice `ix_audit_log_at` su `at`
- indice `ix_audit_log_entity_entity_id` su `entity`, `entity_id`
#### `company_settings`
| Colonna | Tipo | Null | Default | Note |
|---|---|---|---|---|
| `id` | Int64 | no | | chiave primaria, identity |
| `key` | String(200) | no | | |
| `value` | Text | sì | | |
| `created_at` | DateTimeUtc | no | | |
| `created_by` | String(100) | sì | | |
| `updated_at` | DateTimeUtc | sì | | |
| `updated_by` | String(100) | sì | | |
| `row_version` | Int64 | no | `1` | |
- indice unico `ux_company_settings_key` su `key`
#### `notification_reads`
| Colonna | Tipo | Null | Default | Note |
|---|---|---|---|---|
| `id` | Int64 | no | | chiave primaria, identity |
| `notification_id` | Int64 | no | | |
| `user_id` | Int64 | no | | |
| `created_at` | DateTimeUtc | no | | |
| `created_by` | String(100) | sì | | |
| `updated_at` | DateTimeUtc | sì | | |
| `updated_by` | String(100) | sì | | |
| `row_version` | Int64 | no | `1` | |
- indice `ix_notification_reads_user_id` su `user_id`
- indice unico `ux_notification_reads_notification_user` su `notification_id`, `user_id`
#### `notifications`
| Colonna | Tipo | Null | Default | Note |
|---|---|---|---|---|
| `id` | Int64 | no | | chiave primaria, identity |
| `recipient_user_id` | Int64 | sì | | |
| `category` | String(40) | no | | |
| `severity` | String(40) | no | | |
| `title` | String(200) | no | | |
| `body` | Text | sì | | |
| `link` | String(400) | sì | | |
| `read_at` | DateTimeUtc | sì | | |
| `created_at` | DateTimeUtc | no | | |
| `created_by` | String(100) | sì | | |
| `updated_at` | DateTimeUtc | sì | | |
| `updated_by` | String(100) | sì | | |
| `row_version` | Int64 | no | `1` | |
- indice `ix_notifications_recipient_user_id` su `recipient_user_id`
#### `role_permissions`
| Colonna | Tipo | Null | Default | Note |
|---|---|---|---|---|
| `id` | Int64 | no | | chiave primaria, identity |
| `role_id` | Int64 | no | | -> `roles` (Cascade) |
| `permission` | String(100) | no | | |
| `created_at` | DateTimeUtc | no | | |
| `created_by` | String(100) | sì | | |
| `updated_at` | DateTimeUtc | sì | | |
| `updated_by` | String(100) | sì | | |
| `row_version` | Int64 | no | `1` | |
- indice unico `ux_role_permissions_role_id_permission` su `role_id`, `permission`
#### `roles`
| Colonna | Tipo | Null | Default | Note |
|---|---|---|---|---|
| `id` | Int64 | no | | chiave primaria, identity |
| `code` | String(50) | no | | |
| `name` | String(100) | no | | |
| `description` | Text | sì | | |
| `is_predefined` | Bool | no | `false` | |
| `template_code` | String(50) | sì | | |
| `created_at` | DateTimeUtc | no | | |
| `created_by` | String(100) | sì | | |
| `updated_at` | DateTimeUtc | sì | | |
| `updated_by` | String(100) | sì | | |
| `row_version` | Int64 | no | `1` | |
- indice unico `ux_roles_code` su `code`
#### `schema_version`
| Colonna | Tipo | Null | Default | Note |
|---|---|---|---|---|
| `module` | String(50) | no | | chiave primaria |
| `version` | Int64 | no | | chiave primaria |
| `name` | String(200) | no | | |
| `applied_at` | DateTimeUtc | no | | |
| `checksum` | String(64) | no | | |
Chiave primaria: `module`, `version`.
#### `user_permission_overrides`
| Colonna | Tipo | Null | Default | Note |
|---|---|---|---|---|
| `id` | Int64 | no | | chiave primaria, identity |
| `user_id` | Int64 | no | | -> `users` (Cascade) |
| `permission` | String(100) | no | | |
| `allowed` | Bool | no | | |
| `created_at` | DateTimeUtc | no | | |
| `created_by` | String(100) | sì | | |
| `updated_at` | DateTimeUtc | sì | | |
| `updated_by` | String(100) | sì | | |
| `row_version` | Int64 | no | `1` | |
- indice unico `ux_user_permission_overrides_user_id_permission` su `user_id`, `permission`
#### `user_roles`
| Colonna | Tipo | Null | Default | Note |
|---|---|---|---|---|
| `id` | Int64 | no | | chiave primaria, identity |
| `user_id` | Int64 | no | | -> `users` (Cascade) |
| `role_id` | Int64 | no | | -> `roles` (Cascade) |
| `created_at` | DateTimeUtc | no | | |
| `created_by` | String(100) | sì | | |
| `updated_at` | DateTimeUtc | sì | | |
| `updated_by` | String(100) | sì | | |
| `row_version` | Int64 | no | `1` | |
- indice unico `ux_user_roles_user_id_role_id` su `user_id`, `role_id`
#### `user_sessions`
| Colonna | Tipo | Null | Default | Note |
|---|---|---|---|---|
| `id` | Int64 | no | | chiave primaria, identity |
| `token_hash` | String(64) | no | | |
| `user_id` | Int64 | no | | -> `users` (Cascade) |
| `state` | String(40) | no | | |
| `company_code` | String(20) | sì | | |
| `ip_address` | String(64) | sì | | |
| `user_agent` | String(400) | sì | | |
| `persistent` | Bool | no | `false` | |
| `last_seen_at` | DateTimeUtc | no | | |
| `expires_at` | DateTimeUtc | no | | |
| `revoked_at` | DateTimeUtc | sì | | |
| `revoked_reason` | String(100) | sì | | |
| `created_at` | DateTimeUtc | no | | |
| `created_by` | String(100) | sì | | |
| `updated_at` | DateTimeUtc | sì | | |
| `updated_by` | String(100) | sì | | |
| `row_version` | Int64 | no | `1` | |
- indice `ix_user_sessions_user_id` su `user_id`
- indice unico `ux_user_sessions_token_hash` su `token_hash`
#### `user_settings`
| Colonna | Tipo | Null | Default | Note |
|---|---|---|---|---|
| `id` | Int64 | no | | chiave primaria, identity |
| `user_id` | Int64 | no | | |
| `key` | String(200) | no | | |
| `value` | Text | sì | | |
| `created_at` | DateTimeUtc | no | | |
| `created_by` | String(100) | sì | | |
| `updated_at` | DateTimeUtc | sì | | |
| `updated_by` | String(100) | sì | | |
| `row_version` | Int64 | no | `1` | |
- indice unico `ux_user_settings_user_id_key` su `user_id`, `key`
#### `users`
| Colonna | Tipo | Null | Default | Note |
|---|---|---|---|---|
| `id` | Int64 | no | | chiave primaria, identity |
| `user_name` | String(100) | no | | |
| `display_name` | String(200) | no | | |
| `email` | String(254) | sì | | |
| `kind` | String(40) | no | | |
| `password_hash` | String(200) | sì | | |
| `password_history` | Json | sì | | |
| `password_changed_at` | DateTimeUtc | sì | | |
| `must_change_password` | Bool | no | `false` | |
| `temporary_password_expires_at` | DateTimeUtc | sì | | |
| `failed_login_count` | Int32 | no | `0` | |
| `locked_until` | DateTimeUtc | sì | | |
| `totp_secret` | Text | sì | | |
| `totp_enabled` | Bool | no | `false` | |
| `totp_required` | Bool | no | `false` | |
| `totp_last_step` | Int64 | sì | | |
| `totp_recovery_codes` | Json | sì | | |
| `recovery_token_hash` | String(64) | sì | | |
| `recovery_token_expires_at` | DateTimeUtc | sì | | |
| `is_active` | Bool | no | `true` | |
| `last_login_at` | DateTimeUtc | sì | | |
| `own_customers_only` | Bool | no | `false` | |
| `can_see_costs` | Bool | no | `false` | |
| `can_export` | Bool | no | `false` | |
| `can_use_api` | Bool | no | `false` | |
| `created_at` | DateTimeUtc | no | | |
| `created_by` | String(100) | sì | | |
| `updated_at` | DateTimeUtc | sì | | |
| `updated_by` | String(100) | sì | | |
| `row_version` | Int64 | no | `1` | |
- indice unico `ux_users_user_name` su `user_name`
<!-- END GENERATED -->
+13 -2
View File
@@ -30,9 +30,20 @@ Se manca l'SDK 10 ci si ferma e lo si chiede al titolare (SPEC §23). Su Windows
| `docker compose -f deploy/docker-compose.sqlite.yml up` | demo autonoma (con `KHAEMHAT_VERSION` per scegliere l'immagine) |
| `scripts/publish-image.sh vX.Y.Z [--arm64]` | pubblicazione dalla macchina di sviluppo se il runner non c'è (ADR 0015) |
| `scripts/publish-wiki.sh` | pubblica `docs/wiki/` nel wiki Gitea senza passare dal runner |
| `scripts/new-migration.sh <system\|company> <nome_snake_case> [cartella] [modulo]` | crea `M<yyyymmdd>_<nnn>_<Nome>.cs` con il primo numero libero del giorno (SPEC §5.3) |
| `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 `new-migration.sh` (M1), `gen-datamodel.sh` (M1), `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.
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.
#### Test sui due motori
I test dello strato dati girano con `[DataRow("Sqlite")]` e `[DataRow("PostgreSql")]`. SQLite usa un database in
memoria condiviso, sempre disponibile. PostgreSQL usa `KHAEMHAT_TEST_PG` (URL
`postgres://utente:password@host:5432/postgres` di un ruolo con `CREATEDB`): ogni test crea un database
`khaemhat_t_<casuale>` e lo elimina alla fine; senza la variabile i test PostgreSQL risultano *saltati*. In CI il
job `postgres` li esegue su PostgreSQL 16 e 17 sui tag e all'avvio manuale del workflow.
### 1.2 Visual Studio Code
+35 -18
View File
@@ -136,8 +136,8 @@ programmata passa da un controllo esplicito.
| Aspetto | Regola |
|---|---|
| Autenticazione | cookie ASP.NET Core con `CookieSessionAuthenticationHandler`; nessun ASP.NET Identity/EF |
| Attributi del cookie | `HttpOnly; Secure; SameSite=Lax` |
| Autenticazione | schema `KhaemhatSession` scritto in casa (`SessionAuthenticationHandler`, ADR 0019); nessun ASP.NET Identity/EF |
| Attributi del cookie | `khaemhat_session`, `HttpOnly; SameSite=Lax`; `Secure` quando la richiesta è HTTPS o `KHAEMHAT_PUBLIC_URL` è `https` |
| Identificatore | 256 bit casuali da `SecureTokenGenerator` (`RandomNumberGenerator`) |
| Stato | riga di sessione in `sys_sessions` (account di istanza) o `user_sessions` (utenti aziendali): dispositivo, IP, creazione, ultimo uso, revoca |
| Scadenza | scorrevole, con timeout di inattività da impostazioni (mockup 086: 480 minuti) |
@@ -148,9 +148,12 @@ programmata passa da un controllo esplicito.
| Antiforgery | sui form statici (login, cambio password, recupero) |
| Cookie ammessi | sessione e tema prima del login (SPEC §1.5); nessun cookie di profilazione |
Proposta: nella riga di sessione salvare l'**hash SHA-256** dell'identificatore, non il valore, così una lettura del
database non consente di impersonare le sessioni attive. Rigenerare l'identificatore dopo il login e dopo il
passaggio TOTP (prevenzione della session fixation).
**Implementato in M2.** La riga di sessione contiene solo l'**hash SHA-256** dell'identificatore: una lettura del
database non consente di impersonare le sessioni attive. L'identificatore viene **rigenerato a ogni passaggio di
stato** (password verificata, TOTP verificato, password cambiata), contro la session fixation. Una sessione che non è
ancora *attiva* (manca il TOTP o il cambio password) apre solo le pagine del suo passo. Il circuito Blazor ricontrolla
la sessione ogni minuto e si chiude se è stata revocata; mettere un'azienda in manutenzione o disattivarla revoca le
sessioni dei suoi utenti.
---
@@ -240,15 +243,21 @@ passaggio TOTP (prevenzione della session fixation).
- `SecretProtector` cifra con **AES-256-GCM** (`System.Security.Cryptography.AesGcm`) i segreti salvati: connection
string delle aziende (`sys_companies`), password SMTP/PEC/S3/WebDAV, token degli intermediari SDI, credenziali dei
canali e-commerce.
- La chiave AES è **derivata** da `KHAEMHAT_SECRET_KEY`. Proposta: HKDF-SHA256 (in-box, `HKDF`) con etichette di
contesto distinte per uso (`secrets`, `backup`, `totp`), così una chiave non viene riusata fra domini.
- Proposta di formato del testo cifrato: `v1` (versione/identificativo chiave) ‖ nonce 12 byte casuale ‖
ciphertext ‖ tag 16 byte, in base64. Il nonce non si riusa mai con la stessa chiave. Come dato associato (AAD)
usare tabella+colonna+id, così un segreto copiato in un'altra riga non si decifra.
- La chiave AES è **derivata** da `KHAEMHAT_SECRET_KEY` con HKDF-SHA256 (in-box, `HKDF`) ed etichetta di contesto
`khaemhat/secrets/aes-256-gcm/v1`; altri usi (backup, TOTP) avranno etichette proprie, così una chiave non viene
riusata fra domini. L'identificativo della chiave è una seconda derivazione HKDF di 4 byte (8 cifre esadecimali):
identifica la chiave senza rivelarla.
- **Formato del testo cifrato (M1):** `khs1.<id-chiave>.<base64url(nonce 12 byte | tag 16 byte | ciphertext)>`.
Il nonce è casuale e non si riusa mai con la stessa chiave. Il dato associato (AAD) è lo **scopo** del segreto
(per esempio `company:ACME:database` per la connessione di un'azienda): un valore copiato in un'altra riga o
usato per un altro scopo non si decifra. Un valore cifrato con un'altra chiave è rifiutato con un messaggio che
indica i due identificativi (`SecretProtectionException`), senza mai ripetere il segreto.
- Implementazione: `Khaemhat.Infrastructure.Security.SecretProtector` (con `SecretKey` e `SecretRotation`),
interfaccia `ISecretProtector` in `Khaemhat.Core`.
- La chiave e i segreti in chiaro **non vanno mai** in log, messaggi d'errore, diagnostica, risposte API o file su
disco (SPEC §1.5: nessun `appsettings.<Env>.json` con segreti, nessun file temporaneo).
- Le varianti `_FILE` delle variabili (Docker secrets) sono previste per `KHAEMHAT_SYSTEM_DB` e le credenziali del
super utente; proposta: estenderle a `KHAEMHAT_SECRET_KEY` e alle altre variabili sensibili.
- Le varianti `_FILE` (Docker secrets) valgono per tutte le variabili sensibili, `KHAEMHAT_SECRET_KEY` compresa
(ADR 0014); impostare sia la variabile sia la sua `_FILE` è un errore di avvio.
### 7.2 Rotazione (`SecretRotationService`, `SecretRotation`)
@@ -258,6 +267,9 @@ passaggio TOTP (prevenzione della session fixation).
3. L'operatore sostituisce `KHAEMHAT_SECRET_KEY` con la nuova e rimuove `KHAEMHAT_SECRET_KEY_NEW`.
4. Evento in `sys_security_audit`.
In M1 esiste il mattone `SecretRotation` (`NeedsRotation` legge l'identificativo della chiave, `Rotate` decifra e
ri-cifra); la procedura che percorre tutte le colonne cifrate arriva in M12.
Da decidere con ADR: trattamento dei **backup già cifrati** con la vecchia chiave (ri-cifratura o conservazione
della vecchia chiave come chiave di sola decifratura identificata dalla versione nel formato).
@@ -266,8 +278,9 @@ della vecchia chiave come chiave di sola decifratura identificata dalla versione
- Le chiavi DataProtection di ASP.NET Core (cookie, antiforgery) sono nel **database di sistema**
(`sys_data_protection_keys`) tramite `DataProtectionDbXmlRepository`: nessun file su disco, cookie validi dopo un
riavvio o un nuovo container.
- Proposta: cifrare l'XML delle chiavi a riposo con un `IXmlEncryptor` basato su `SecretProtector`, così la sola
lettura del database di sistema non consente di falsificare cookie.
- **Implementato in M2** (`DataProtectionKeyStore`, `SecretKeyXmlEncryptor`): l'XML delle chiavi è cifrato a riposo
con `SecretProtector` (scopo `dataprotection:keys`), così la sola lettura del database di sistema non consente di
falsificare cookie o token antiforgery. Il database di sistema è migrato prima che DataProtection legga le chiavi.
---
@@ -277,14 +290,18 @@ della vecchia chiave come chiave di sola decifratura identificata dalla versione
| Header | Valore |
|---|---|
| `Content-Security-Policy` | `default-src 'self'`; script solo `'self'` + **nonce** per gli script di Blazor; `connect-src 'self'` (WebSocket del circuito sullo stesso host); `frame-ancestors 'none'`; `object-src 'none'`; `base-uri 'self'` (dettaglio proposto) |
| `Content-Security-Policy` | `default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self'; connect-src 'self'; frame-ancestors 'none'; form-action 'self'; base-uri 'self'; object-src 'none'` |
| `X-Frame-Options` | `DENY` |
| `Referrer-Policy` | proposta: `strict-origin-when-cross-origin` (o `no-referrer`) |
| `X-Content-Type-Options` | proposta: `nosniff` |
| `Referrer-Policy` | `same-origin` |
| `X-Content-Type-Options` | `nosniff` |
| `Permissions-Policy` | `camera=(), microphone=(), geolocation=(), payment=()` |
| `Cross-Origin-Opener-Policy` | `same-origin` |
| `Strict-Transport-Security` | impostato dal **reverse proxy**, che termina TLS |
- Nessuna risorsa da CDN, nessun font scaricato, nessuno script di terze parti (SPEC §1.2): la CSP può restare
rigorosa. JavaScript solo in `wwwroot/js`, senza `eval` né gestori inline.
rigorosa. In M2 non serve nemmeno il nonce: nessuna pagina ha script inline (la `<ImportMap />` di Blazor, che
ne scriverebbe uno, non è usata). `style-src 'unsafe-inline'` resta perché Blazor applica stili agli elementi
durante la riconnessione. JavaScript solo in `wwwroot/js`, senza `eval` né gestori inline.
- L'impostazione *CSP rigorosa (nonce)* (mockup 086) esiste per la diagnosi; disattivarla è un evento di audit.
- Blazor esegue l'escaping dell'output: vietato `MarkupString` su contenuti provenienti da utenti o da file
(eccezione: l'anteprima XML formattata, che va resa come testo).
+34 -6
View File
@@ -3,25 +3,53 @@
> Punto di ripresa per ogni sessione. Aggiornare a fine sessione.
**Ultimo aggiornamento:** 2026-11-11
**Milestone corrente:** M0 — Bootstrap (via allo sviluppo dato dal titolare il 2026-11-11)
**Prossimo passo:** chiudere M0 (PR `feat/m0-bootstrap` → `main`, CI verde, tag `v0.0.1`, immagine e release), poi
M1 — Fondamenta dati, partendo dall'issue #7 (colonna *Da fare* del progetto *Khaemhat 1.0 — Sviluppo*).
**Milestone corrente:** M4 — Tabelle, anagrafiche, articoli (issue #37-#46, nel progetto in *Da fare*). M3 chiusa:
PR #119 in `main`, tag `v0.3.0`, immagine e release.
**Prossimo passo:** M4, a partire dal pacchetto fiscale (#37) e dal profilo azienda (#38). #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.
## Fatto
- Specifica normativa in `docs/SPEC.md`; `CLAUDE.md` con emendamenti E1-E6.
- ADR 0001-0011.
- ADR 0001-0024.
- 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`,
`MCP.md`, `DEPLOY.md`, `SECURITY.md`, `DEVELOPMENT.md`.
- Wiki completa in bozza in `docs/wiki/`, pubblicata nel wiki Gitea.
- **M0 (in chiusura):** soluzione `Khaemhat.sln` con i 10 progetti di SPEC §3 e 6 progetti di test; regole di build
- **M0 (chiusa, `v0.0.1`):** soluzione `Khaemhat.sln` con i 10 progetti di SPEC §3 e 6 progetti di test; regole di build
(`Directory.Build.props/targets`, Central Package Management con l'allowlist, `.editorconfig`, warning come errori);
test architetturali delle dipendenze e dei pacchetti; `Khaemhat.Web` con pagina "in costruzione", icone,
`/health/live`, `/health/ready`, `/health` (ADR 0012); `docker/Dockerfile`, `entrypoint.sh` con `PUID`/`PGID`
(ADR 0013), `postgres/init.sql`; `deploy/docker-compose.yml` e `docker-compose.sqlite.yml`; Gitea Actions `ci.yml`,
`release.yml`, `wiki.yml` con controllo YAML; script di build, test, avvio, pubblicazione e stub; ADR 0012-0017.
- **M1 (chiusa, `v0.1.0`, PR #116):** micro-ORM in `Khaemhat.Data` (mappe, query tipizzate, `SqlFragment`, unit of work,
repository con audit e `row_version`), provider SQLite e PostgreSQL, `DatabaseUrl`, migrazioni con
`schema_version`, tabelle `sys_companies` e `sys_settings`, `CompanyRegistry` con URL cifrato, `SecretProtector`
(AES-256-GCM, formato `khs1`), `tools/Khaemhat.DataModelTool` e gli script `new-migration.sh` e
`gen-datamodel.sh`; ADR 0018. Test: 106 test dello strato dati verdi su SQLite in locale e su PostgreSQL 16 e 17 in CI
(in locale Docker non è disponibile).
- **M2 (chiusa, `v0.2.0`, PR #118):** avvio da variabili con elenco degli errori, migrazioni all'avvio, super utente e
prima azienda; account di istanza e aziendali, password con storico e blocco, sessioni nel database, TOTP con codici
di recupero, pagine di accesso (mockup 001-003); ruoli, permessi e attributi di autorizzazione; licenze firmate,
codici di attivazione, modalità test, `tools/Khaemhat.LicenseTool`; DataProtection nel database cifrata; cache
memoria/Redis (client RESP in casa); log su database per sezioni con traccia; attività programmate con cron, lock e
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 (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
`RecordPage`/`DocumentPage`/`MasterDataPage`; liste con `ListQuery`/`ListFields`, `KhGrid` virtualizzata, `KhRadar`
e `KhLinesGrid`; dashboard a widget con layout per utente e per ruolo e `company_settings`; ricerca globale a
fornitori, aiuto in app dalla copia della wiki, pannello notifiche; allegati con anteprime, *Genera file*, ZIP,
cestino e storico; anteprima di stampa A4; catalogo dei componenti e documento di prova per gli sviluppatori;
primi screenshot reali in `docs/wiki/img/`; ADR 0020-0024. Test: 368 verdi in locale, 21 di PostgreSQL saltati;
immagine costruita in locale e avviata da zero con SQLite.
- Su Gitea: etichette, milestone M0-M14, 114 issue con checklist, progetti *Khaemhat 1.0 — Sviluppo* (M0-M13)
e *Khaemhat 1.1+ — Fase 2* (M14). Numerazione: M0 #1-#6 e #114, M1 #7-#14, M2 #15-#24, M3 #25-#36,
M4 #37-#46, M5 #47-#54, M6 #55-#61, M7 #62-#68, M8 #69-#73, M9 #74-#81, M10 #82-#87, M11 #88-#91,
@@ -62,7 +90,7 @@ Emersi durante la stesura della documentazione. Si decidono con un ADR quando si
6. Tag e doppia build: `publish-image.sh` (Appendice D) crea il tag git, ma con `release.yml` sui tag `v*` l'immagine verrebbe costruita due volte. Proposta: lo script non crea tag, oppure `release.yml` salta le versioni già nel registro. **Deciso in M0: ADR 0015.**
7. Formato tag: tag git `vX.Y.Z`, tag immagine `X.Y.Z` (senza `v`). **Deciso in M0: ADR 0015.**
8. Icona versionata: `build.sh` deve produrre PNG, serve un rasterizzatore; proposta: generarla sulla macchina di sviluppo e committarla prima del rilascio. **Deciso in M0: ADR 0016.**
9. Rotazione della password PostgreSQL: le connection string delle aziende sono cifrate per intero in `sys_companies`; serve una procedura di aggiornamento.
9. Rotazione della password PostgreSQL: l'URL del database di ogni azienda è cifrato per intero in `sys_companies` (ADR 0018); serve una procedura di aggiornamento (M12).
10. Il mockup 085 mostra ancora `ghcr.io`: l'app mostrerà il registro Gitea (ADR 0009).
11. Non definiti: schermata di attivazione TOTP, nome dell'impostazione "migra aziende all'avvio", recupero password del super utente senza SMTP, chi modifica le impostazioni di backup cloud (scritto: super utente), flusso di ripristino da backup logico.
@@ -0,0 +1,44 @@
# ADR 0018 - Contratti dello strato dati: scostamenti da SPEC §5.1
- **Stato:** accettata
- **Data:** 2026-11-11
- **Modifica:** SPEC §5.1-§5.4, §3 (con ADR 0004); milestone M1, issue #7-#14
## Contesto
SPEC §5.1 elenca firme indicative di `IDbProvider`, `ISqlDialect`, `ICompanyRegistry` e del motore di migrazione.
Implementandole su due motori sono emersi punti in cui la firma letterale costringeva a soluzioni peggiori
(stringhe SQL da ricomporre, chiamate non annullabili, segreti in chiaro in memoria più del necessario). Questo ADR
fissa le firme effettive.
## Decisione
1. **`CancellationToken` ovunque.** Tutti i metodi asincroni di `IDbProvider`, `IUnitOfWork`, `IRepository<T,TKey>`,
`ICompanyRegistry` e `MigrationRunner` accettano un `CancellationToken` (default `default`).
2. **DDL fuori dal builder.** `IDbProvider` espone `DdlGenerator Ddl` invece di `ISchemaBuilder SchemaBuilder`:
le migrazioni scrivono su un `ISchemaBuilder` neutro che **registra** operazioni (`SchemaOperation`), e il
generatore del provider le traduce in istruzioni. Così la stessa registrazione serve per eseguire, calcolare il
checksum e generare `docs/DATA-MODEL.md`. Le classi dei provider mantengono i nomi di SPEC
(`SqliteSchemaBuilder`, `PostgresSchemaBuilder`) ma sono generatori DDL.
3. **Frammenti, non stringhe.** `ISqlDialect.CaseInsensitiveLike` e `AdvisoryLock` restituiscono `SqlFragment`
(testo + parametri), non `string`, perché il pattern e la chiave del lock sono valori e devono restare parametri.
4. **Membri aggiunti a `IDbProvider`:** `BuildConnectionString(DatabaseUrl)` (configurazione da URL `postgres://` o
`sqlite://`, mai stringhe ADO.NET nelle variabili), `DatabaseExistsAsync`, `IsTransient(Exception)` per i
tentativi automatici, `EnterWriteScopeAsync` (il `SqliteWriteLock` su SQLite, nulla su PostgreSQL).
5. **Registro aziende cifrato per intero.** `sys_companies.connection_string` contiene l'URL del database cifrato
con `SecretProtector` e scopo `company:<CODICE>:database`: una riga copiata su un'altra azienda non si decifra.
La rotazione della password PostgreSQL resta un punto aperto (`docs/STATUS.md`, punto 9).
6. **Esito delle migrazioni al chiamante.** `MigrationRunner.RunAsync` restituisce un `MigrationReport` (applicate con
durata, già presenti, avvisi); la scrittura nella sezione di log *Migrazioni* arriva con il log in M2. Ogni
migrazione gira in una propria transazione sotto lock, con un nuovo controllo di `schema_version` dopo il lock.
7. **Enumerazioni per nome.** Le proprietà enum sono salvate come testo (`String(40)`), non come intero.
8. **Strumento di sviluppo.** `tools/Khaemhat.DataModelTool` (dipende solo da `Khaemhat.Data`, non distribuito)
rigenera la sezione generata di `docs/DATA-MODEL.md`; la regola di dipendenza è nel test architetturale.
## Conseguenze
- Il codice sopra lo strato dati usa `DatabaseScope`, `IUnitOfWorkFactory` e `SqlFragment`; nessun riferimento a
Npgsql o Microsoft.Data.Sqlite fuori dai provider (verificato da un test).
- Chi scrive una migrazione usa `scripts/new-migration.sh` e poi `scripts/gen-datamodel.sh`; un test fallisce se il
documento non è aggiornato.
- Le firme di SPEC §5.1 restano il riferimento per i nomi; dove divergono vale questo ADR.
+54
View File
@@ -0,0 +1,54 @@
# ADR 0019 - Sistema e sicurezza: scelte di M2
- **Stato:** accettata
- **Data:** 2026-11-11
- **Modifica:** SPEC §5.4, §6, §7, §8, §9.3, §9.5, §9.6; milestone M2, issue #15-#24
## Contesto
M2 costruisce avvio, account, accesso, licenze, cache, log, attività programmate e contesto azienda. La specifica
indica il risultato ma lascia aperti alcuni dettagli, o li descrive con componenti che non si possono usare senza
librerie esterne (SPEC §1.2). Questo ADR fissa le scelte fatte.
## Decisione
1. **Autenticazione con uno schema proprio.** Lo schema `KhaemhatSession` (`SessionAuthenticationHandler`) legge il
cookie `khaemhat_session` = `<database>.<token>`: `_` per gli account di istanza (`sys_sessions`), il codice
azienda per gli utenti aziendali (`user_sessions`). Nel database c'è solo l'hash SHA-256 del token. Non si usa il
cookie di autenticazione di ASP.NET Core: la sessione deve essere revocabile e contata per la licenza, e il suo
stato vive nel database, non nel cookie.
2. **Accesso in passi.** Una sessione nasce in uno stato (`PendingPasswordChange`, `PendingTotpSetup`,
`PendingTotp`, `Active`) e solo `Active` autentica le pagine. Ogni passaggio di stato rigenera il token. Le pagine
di accesso sono SSR statiche con `EditForm` (antiforgery incluso), escluse dal routing interattivo.
3. **Attivazione TOTP senza QR.** La pagina mostra la chiave in base32 a gruppi di quattro e il collegamento
`otpauth://`; un codice QR richiederebbe una libreria o un generatore scritto in casa che non vale il costo. Dopo
la conferma si mostrano 10 codici di recupero monouso (salvati come hash).
4. **Avvio in due tempi.** `BootstrapService.StartAsync` migra il database di sistema **prima** che parta il server
(DataProtection legge le chiavi da lì); il resto (licenza, super utente, prima azienda, migrazioni delle aziende)
gira in background mentre `/health/ready` risponde 503 e le pagine mostrano "Avvio in corso". Un errore di
configurazione ferma il processo con codice 2 ed elenca tutte le variabili sbagliate; un errore di avvio con
codice 1. Un'azienda che non si migra va in manutenzione senza fermare le altre.
5. **Chiavi DataProtection** in `sys_data_protection_keys`, cifrate con `SecretProtector`.
6. **Log su database** con un `ILoggerProvider` scritto in casa: coda limitata (20 000 eventi, si scartano i più
vecchi), scrittura a blocchi di 200 ogni secondo, sezione ricavata dalla categoria o dallo scope `Section`,
`TraceId`, utente e azienda dallo scope della richiesta. Gli eventi di `Microsoft.*` e `System.*` sotto
`Warning` non vanno nel database. Retention per livello con un job notturno.
7. **Redis** con un client RESP2 scritto in casa (una connessione, un comando alla volta, `AUTH`, `SELECT`, TLS
con `rediss://`). Se Redis non risponde la cache passa alla memoria e lo scrive nel log una volta al minuto:
la cache non fa mai fallire una richiesta.
8. **Attività programmate**: cron a 5 campi con fuso orario (le ore che non esistono al cambio dell'ora legale si
saltano), lock per attività in `sys_job_locks` con scadenza pari al timeout (un lock scaduto si riprende), una
riga di `sys_job_runs` per tentativo, notifica agli account di istanza quando l'ultimo tentativo fallisce.
9. **Contesto azienda**: gli utenti aziendali lavorano solo nella propria azienda; gli account di istanza la
scelgono (sessione, o header `X-Company` per le API). Un'azienda in manutenzione è chiusa agli utenti aziendali,
una disattivata a tutti: pagine con avviso 503, API con 503 e `Retry-After`; un `X-Company` di un'altra azienda
dà 403.
10. **Database SQLite in memoria** (test e demo): il provider tiene aperta una connessione per ogni database in
memoria creato con `EnsureDatabaseExistsAsync`, che altrimenti sparirebbe con l'ultima connessione.
## Conseguenze
- Nessuna dipendenza nuova; tutto è coperto da test (vettori RFC 6238, RESP, cron con ora legale, flusso di accesso
sull'host reale, isolamento di due aziende).
- Le schermate di amministrazione (utenti, ruoli, licenze, log, attività) arrivano in M12 sopra questi servizi.
- La pagina di cambio password è più semplice del mockup 003 (niente indicatore di robustezza) fino a M3.
+53
View File
@@ -0,0 +1,53 @@
# ADR 0020 - Shell dell'interfaccia: schede, testi, preferenze, scorciatoie
- **Stato:** accettata
- **Data:** 2026-11-11
- **Modifica:** SPEC §1.9, §10.2, §10.5, §10.6, §10.8, §11.12; milestone M3, issue #25, #26, #31, #33
## Contesto
M3 costruisce la shell (barra superiore, menu comprimibile, schede, barra di stato), i testi localizzati e le
preferenze utente. La specifica fissa il risultato visivo (mockup 004, 007, 008, 013) ma lascia aperti alcuni punti
tecnici; altri si scontrano con il browser o con Blazor. Questo ADR fissa le scelte.
## Decisione
1. **Schede tenute in vita.** Ogni indirizzo aperto diventa una scheda (`TabService`, massimo 12). La scheda conserva
il **tipo di pagina e una copia dei parametri di rotta** (`RouteData` passato in cascata da `Routes.razor`), non il
`Body` del layout: `Body` disegna sempre la pagina corrente, quindi tutte le schede avrebbero mostrato l'ultima.
Il layout disegna un pannello per scheda e nasconde quelli inattivi (`hidden`), così passando da una scheda
all'altra lo stato della pagina resta. La stessa pagina con un'altra query (`/profilo?scheda=sessioni`) riusa la
scheda. Alla tredicesima si chiude la scheda meno usata **senza modifiche**; se tutte hanno modifiche l'apertura
è rifiutata con un avviso. Il titolo del browser lo scrive il layout dalla scheda attiva; `KhPageTitle` imposta
solo il titolo della scheda.
2. **Scorciatoie riservate dal browser.** `Ctrl+W`, `Ctrl+Tab` e `Ctrl+N` restano dei browser, che non le passano alla
pagina. Si tengono come da specifica e si aggiungono `Alt+W`, `Alt+PagGiù` / `Alt+PagSu` e `Alt+N`, che arrivano
sempre. Le scorciatoie sono un'unica tabella (`KeyboardShortcuts.All`) usata dal gestore JavaScript, dalla
ricerca e dalla scheda *Scorciatoie* del profilo; un test controlla che ogni combinazione sia unica.
3. **Testi in JSON incorporati.** I testi stanno in `src/Khaemhat.Web/Resources/<cultura>/*.json`, risorse incorporate
lette da `JsonTextProvider` (`ITexts`). Gli oggetti annidati danno chiavi puntate (`Shell.Menu.Parties`), la
proprietà `_` dà il testo all'oggetto che ha anche figli, una chiave definita due volte è un errore all'avvio, una
chiave mancante si vede come `[chiave]`. Niente `.resx`: il JSON si legge e si confronta meglio nelle revisioni e
non richiede generatori. Due test lo fanno rispettare: nessun testo letterale nei componenti `.razor` (testo fra i
tag e attributi `title`, `placeholder`, `alt`, `aria-label`, `label`) e ogni chiave usata nel codice esiste.
4. **Preferenze per utente nel database del proprietario.** `UserSettingsService` salva coppie chiave/valore in
`sys_user_settings` per gli account di istanza e in `user_settings` per gli utenti aziendali (valore massimo 64 KB,
chiave massimo 200 caratteri). `UserPreferences` legge e scrive l'insieme tipizzato (tema, accento, densità,
dimensione testo, numeri tabellari, animazioni, suggerimenti, evidenza riga, menu, pagina iniziale) e scarta i
valori non validi; la pagina iniziale accetta solo percorsi locali.
5. **Tema scritto dal server.** Le preferenze diventano attributi `data-*` sull'elemento `<html>` già nella risposta
del server (`App.razor`), così la prima pagina ha i colori giusti; il cambio dal profilo o dalla barra superiore li
aggiorna dal vivo con `khaemhat.applyRoot`. Prima dell'accesso vale `data-theme="auto"`, che segue il sistema. Il
profilo mostra ogni scelta subito (anteprima) e la conserva solo con **Salva**; chiudendo la scheda senza salvare
torna l'aspetto salvato.
6. **Aree non ancora costruite.** Il menu mostra le aree concesse da licenza e permessi anche se arrivano con
milestone successive; aprono una pagina che dice con quale milestone arrivano (`MenuItem.Milestone`). Quando una
pagina vera esiste, la sua rotta prende il posto di quella generica e la milestone si toglie dal catalogo.
## Conseguenze
- Le pagine aperte restano in memoria nel circuito finché la scheda è aperta: il limite di 12 schede tiene il
consumo sotto controllo.
- Una pagina che usa parametri da query li riceve anche quando è nascosta e cambia la query di un'altra scheda con
lo stesso nome di parametro: i nomi dei parametri da query vanno scelti specifici della pagina.
- Aggiungere un testo vuol dire aggiungere una chiave al JSON; i test falliscono se manca.
+73
View File
@@ -0,0 +1,73 @@
# ADR 0021 - File e allegati: archivio su volume, versioni, cestino, scrittori in casa
- **Stato:** accettata
- **Data:** 2026-11-11
- **Modifica:** SPEC §2 (riga *PDF e file*), §9.4; milestone M3, issue #34
## Contesto
La specifica chiede allegati per azienda con versioni, cestino di 30 giorni, archivio su volume con limite, quota e
aggancio per l'antivirus, e scrittori PDF, CSV, XLSX e ZIP scritti in casa (nessuna libreria esterna, ADR 0002). Lascia
aperti la regola di numerazione delle versioni, la forma dell'archivio, il perimetro della prima versione del PDF e le
impostazioni predefinite del CSV. Questo ADR fissa le scelte.
## Decisione
1. **Archivio.** `IFileStore` sta in `Khaemhat.Core.Files` (l'implementazione è in Infrastructure, che non vede
Application); `VolumeFileStore` scrive in `<KHAEMHAT_DATA_DIR>/files/<AZIENDA>/<aaaa>/<guid>`. Ogni file è scritto
prima come `<guid>.part` **nella stessa cartella**, contando i byte (limite) e calcolando lo SHA-256 durante la
copia; poi passa quota e scanner e viene rinominato. Mai file temporanei fuori dal volume dei dati. La chiave
salvata nel database è `aaaa/guid` (relativa alla cartella dell'azienda) e viene validata: non può uscire dalla
cartella. I `.part` rimasti da caricamenti interrotti si cancellano dopo un giorno.
2. **Limiti.** 25 MB per file e nessuna quota per impostazione predefinita; gli amministratori li cambiano con le
impostazioni di istanza `files.max-upload-mb` e `files.company-quota-mb`. Il limite di dimensione vale per i file
caricati; i file generati hanno solo la quota. La quota si calcola sommando i file della cartella dell'azienda.
3. **Antivirus.** `IFileScanner` riceve il file completo prima che diventi visibile; quello registrato
(`NoOpFileScanner`) accetta tutto.
4. **Versioni.** Ogni allegato ha una *serie* (`version_key`): per i file generati il codice del generatore
(`gen:<codice>`), per gli altri il nome in minuscolo (`name:<nome>`). La versione è il massimo della serie nel
record più uno, contando anche gli allegati nel cestino; un indice unico su record + serie + versione impedisce due
versioni uguali (in caso di conflitto si riprova). *Rigenera* è una nuova generazione: non sovrascrive mai.
Caricare un file con lo stesso nome ne crea la versione successiva e lascia consultabile la precedente. L'elenco
mostra di norma solo l'ultima versione di ogni serie; il nome di download porta il suffisso `_vN` dalla v2.
5. **Cestino.** Cancellare un allegato o il documento lo sposta nel cestino (`deleted_at`); il job di sistema
`system.attachments-trash` (ogni notte alle 3:45) elimina righe e file dopo 30 giorni. Un allegato **bloccato**
(`locked`, ad esempio l'XML inviato allo SDI) non si cancella, e un documento con allegati bloccati non può mandarli
nel cestino. Il blocco è definitivo.
6. **Permessi.** `attachments.read` per vedere e scaricare, `attachments.write` per caricare, generare e bloccare,
`attachments.delete` per cancellare e ripristinare. Il permesso sul documento lo verifica chi chiama, che lo
conosce. Ogni modifica scrive lo storico (`audit_log`); l'utente che ha caricato o generato il file è salvato anche
in `attachments.user_name`, perché le colonne di audit conoscono l'utente solo dentro una richiesta HTTP.
7. **Tipi di file.** Il tipo MIME si ricava dall'estensione quando è nota; quello dichiarato dal browser si usa solo
per estensioni sconosciute. I nomi file sono ripuliti (niente cartelle né caratteri vietati, massimo 255).
8. **CSV.** Predefiniti per Excel in italiano: separatore `;`, BOM UTF-8, virgola decimale, date `gg/mm/aaaa`,
righe CRLF, virgolette RFC 4180. Le celle di testo che iniziano con `=`, `+`, `-`, `@`, tabulazione o ritorno a capo
ricevono un apostrofo davanti (iniezione di formule); i numeri non vengono toccati. Disponibile anche il profilo
invariante (`,`, punto decimale, date ISO, senza BOM).
9. **Scrittura in streaming.** CSV, XLSX, ZIP e PDF scrivono sull'uscita solo con chiamate asincrone, quindi possono
scrivere direttamente nella risposta HTTP (dove le scritture sincrone sono vietate). `ZipArchive` scrive ancora in
modo sincrono le chiusure delle voci e la directory centrale: quei pochi byte passano da un piccolo buffer in
memoria (`AsyncOutputBuffer`) e vengono inviati con la chiamata asincrona successiva.
10. **PDF, prima versione.** PDF 1.7 con i 12 font Type1 standard latini (Symbol e ZapfDingbats esclusi) in
`WinAnsiEncoding` (lettere accentate, `€`, virgolette tipografiche), testo, linee, rettangoli, colori RGB,
immagini JPEG incorporate così come sono (`DCTDecode`), più pagine, dizionario *Info*, flussi compressi
`FlateDecode`, tabella xref. Coordinate in punti dall'angolo **in basso a sinistra**, testo posizionato sulla linea
di base. Le larghezze per misurare e andare a capo sono quelle AFM di Helvetica, Helvetica-Bold e Times-Roman;
corsivi e grassetti di Times usano quelle del tondo, Courier è a passo fisso. Una pagina viene scritta sull'uscita
quando inizia la successiva. **PDF/A-3** (font incorporati, XMP, output intent, allegati XML per la copia di
cortesia FatturaPA) è rimandato: annotato come TODO in `PdfWriter`.
11. **Generatori.** Un'uscita di *Genera file* è un `IFileGenerator` (codice, chiave del testo, tipo, estensione,
entità supportate, nome file, `GenerateAsync`); `FileGenerationService` scrive il risultato direttamente
nell'archivio e lo registra come allegato generato con la versione successiva, oppure lo scrive su un flusso senza
salvarlo (anteprima di stampa). Per il *documento di prova* dell'issue #34 ci sono tre generatori dell'entità
fittizia `demo.document`: PDF, CSV e XLSX con righe e importi inventati.
## Conseguenze
- Gli allegati nel cestino occupano spazio e quota per 30 giorni.
- Il calcolo della quota legge la cartella dell'azienda a ogni caricamento quando una quota è impostata: va bene per
le dimensioni attese; se diventasse lento si terrà un contatore.
- Un file rimasto senza riga (crash fra scrittura del file e inserimento) è solo spazio perso; il contrario non può
accadere, perché la riga si scrive dopo il file e il file si cancella se l'inserimento fallisce.
- I moduli che producono file (stampe, FatturaPA, report) registrano i loro `IFileGenerator`; quelli che ricevono
file dall'esterno (SDI, e-mail) usano `AttachmentService.AddAsync` con il tipo giusto e, se serve, `Locked`.
+47
View File
@@ -0,0 +1,47 @@
# ADR 0022 - Dashboard a widget: layout per utente e per ruolo, liste fornite dai moduli
- **Stato:** accettata
- **Data:** 2026-11-11
- **Modifica:** SPEC §10.3, §11.12; milestone M3, issue #30 e #31
## Contesto
La specifica descrive la dashboard (mockup 004-006) con widget attivabili, ordinabili e ridimensionabili, una pagina
iniziale scelta dall'utente e un layout predefinito per ruolo, ma non dice dove si salvano i layout dei ruoli, quale
layout vede chi non ha mai personalizzato, né come i moduli che arrivano dopo M3 (vendite, magazzino, CRM) riempiono
i widget. Lascia anche aperto il comando per tornare alla disposizione iniziale.
## Decisione
1. **Catalogo fisso.** I widget sono un catalogo nel codice (`WidgetCatalog`): id, titolo, icona, larghezza
predefinita, modulo di licenza, permesso di lettura, solo amministratori, milestone che porta i dati. Un widget è
*disponibile* se il modulo è attivo, l'utente ha il permesso e, per *Stato del sistema*, è un account di istanza.
2. **Layout in JSON.** `{"v":1,"widgets":[{"id":"todo","w":4}]}`: l'ordine è quello dell'elenco, le larghezze sono 3,
4, 6, 8 o 12 colonne (una larghezza diversa va alla più vicina, la più larga a parità). Leggendolo si scartano id
sconosciuti e ripetuti; un layout illeggibile vale come assente. Al massimo 30 widget.
3. **Dove si salva.** Il layout dell'utente è un'impostazione utente (`dashboard.layout`, ADR 0020: sistema per gli
account di istanza, azienda per gli utenti aziendali). Il layout di un ruolo è un'impostazione **dell'azienda**
(`dashboard.layout.role.<CODICE>`) nella nuova tabella `company_settings`, scritta da `CompanySettingsService`
con il permesso `company.settings.write`. Promemoria (`dashboard.notes`) e scorciatoie (`dashboard.shortcuts`)
sono impostazioni utente.
4. **Quale layout si vede.** Quello dell'utente; altrimenti quello del primo ruolo dell'utente (per id) che ne ha uno;
altrimenti il layout di Khaemhat. In ogni caso si tolgono i widget non disponibili. **Ripristina** cancella il
layout dell'utente e riporta quello del ruolo o di Khaemhat.
5. **Layout di Khaemhat.** Solo widget che hanno già dati: Da fare oggi, Fatto oggi, Scadenze, Scorciatoie,
Promemoria, Stato del sistema. I widget dei moduli futuri (KPI, Da evadere, Fatturato, Sottoscorta, CRM, Ultimi
documenti) si possono già accendere e mostrano da quale milestone arrivano i dati, senza numeri finti.
6. **Liste dai moduli.** *Da fare oggi*, *Fatto oggi* e *Scadenze 30 giorni* raccolgono le righe da sorgenti
registrate nel contenitore (`ITodoSource`, `IDoneSource`, `IDeadlineSource`): ogni modulo aggiunge le sue. Le
sorgenti si chiamano una dopo l'altra; una che fallisce si scrive nel log e si salta, il widget mostra le altre.
In M3 ci sono licenza, avvisi non letti e attività programmate.
7. **Personalizza.** Pannello laterale non modale (la pagina resta visibile) con pagina iniziale, interruttore della
dashboard, elenco dei widget con interruttore, larghezza e frecce, e il predefinito per ruolo per chi gestisce
l'azienda. Sulla griglia i widget si trascinano (HTML drag and drop) e hanno anche pulsanti per spostare,
allargare, restringere e nascondere, così tutto funziona da tastiera. Ogni modifica si salva subito.
## Conseguenze
- I moduli di M5, M6 e M11 riempiono i widget registrando sorgenti e sostituendo il componente del widget; il layout
salvato dagli utenti resta valido.
- `company_settings` è il posto per le altre impostazioni di azienda delle prossime milestone.
- Un utente con più ruoli prende il predefinito del primo; se servirà una priorità esplicita fra ruoli si aggiungerà.
+55
View File
@@ -0,0 +1,55 @@
# ADR 0023 - Aiuto in app dalla copia della wiki, notifiche lette per utente, ricerca a fornitori
- **Stato:** accettata
- **Data:** 2026-11-11
- **Modifica:** SPEC §10.2, §17; milestone M3, issue #32 (mockup 009, 010, 011)
## Contesto
La specifica chiede che `F1` apra la pagina wiki della maschera dentro l'applicazione (mockup 011), con indice,
*Apri nel wiki* e *Segnala un problema*, e che l'aiuto funzioni anche nelle installazioni senza Internet servendo
una copia della wiki "all'indirizzo `/help`". Non dice come la copia arriva nell'immagine, come si converte il
Markdown senza librerie esterne (SPEC §1.2), né come una notifica "per tutti" diventa letta per un utente e non per
gli altri. Per la ricerca globale (mockup 009) dice cosa trovare, ma i dati (clienti, articoli, documenti) arrivano
con le milestone successive.
## Decisione
1. **La wiki viaggia con il programma.** La compilazione copia `docs/wiki/*.md` in `help/wiki/` accanto al
programma, e in `help/media/` le immagini che le pagine mostrano (miniature e PNG dei mockup, icone, `img/` della
wiki), con lo stesso percorso che hanno nel repository. `.dockerignore` lascia entrare solo quelle cartelle di
`docs/`. Nessun download all'avvio, nessuna scrittura: la copia è di sola lettura e corrisponde alla versione.
2. **Markdown in casa.** `WikiMarkdown` converte il sottoinsieme che la wiki usa: titoli con ancora, paragrafi,
elenchi annidati, tabelle, citazioni, blocchi di codice, linee, immagini, collegamenti, grassetto, corsivo,
codice. Tutto il testo è codificato (niente HTML grezzo); diventano collegamenti solo indirizzi `http(s)`,
ancore `#` e nomi di pagina. La citazione `> **Stato:** …` in testa a ogni pagina è lo stato della pagina e si
mostra come tale, riga per riga; le altre citazioni sono riquadri informativi.
3. **Indirizzi.** L'aiuto è la pagina Blazor `/aiuto/{Pagina}` (nelle schede come ogni altra maschera); le immagini
sono servite da `/aiuto/media/{percorso}` solo se il percorso è fra quelli copiati e ha un'estensione d'immagine.
L'indirizzo `/help` della specifica resta come rinvio a `/aiuto`. Le immagini che puntano ai file del repository
(`…/raw/branch/main/<percorso>`) si servono dalla copia locale; le altre restano sul web.
4. **Una pagina per ogni maschera.** `HelpLinks` associa a ogni prefisso di percorso una pagina wiki; un test
controlla che ogni pagina dell'applicazione e ogni voce di menu porti a una pagina che esiste, e che tutti i
collegamenti fra pagine della wiki trovino la loro pagina.
5. **Wiki online configurabile.** `KHAEMHAT_HELP_URL` (facoltativa, indirizzo assoluto `http(s)`) è la wiki aperta da
*Apri nel wiki*; predefinita la wiki del progetto. *Segnala un problema* apre `…/issues/new` del repository della
wiki quando l'indirizzo finisce con `/wiki/` (Gitea e GitHub), altrimenti non compare.
6. **Notifiche lette per utente.** Una notifica personale (con destinatario) usa la sua colonna `read_at`. Una
notifica per tutti resta una riga sola; chi la legge aggiunge una riga in `sys_notification_reads` (notifiche di
sistema) o `notification_reads` (notifiche dell'azienda), con vincolo unico su notifica e utente. Il pannello
mostra le ultime 100 notifiche dell'utente, filtri *Tutte* e *Non lette*, *Segna tutte come lette*; la campanella
aggiorna il conteggio ogni minuto.
7. **Ricerca a fornitori.** Pagine del menu e comandi si cercano subito nel browser. I record arrivano da
`ISearchProvider` registrati nel contenitore e interrogati in parallelo da `GlobalSearchService` dopo una pausa di
200 ms e almeno 2 caratteri: ognuno dichiara gli ambiti (tutto, `#` documenti, `@` persone), dà al massimo 8
risultati, e uno lento (oltre 3 secondi) o in errore si scrive nel log e si salta. In M3 c'è il fornitore delle
pagine dell'aiuto (titoli e sezioni); `#` e `@` dicono con quali moduli arriveranno i risultati.
## Conseguenze
- L'aiuto funziona senza Internet ed è sempre quello della versione installata; l'immagine cresce delle sole pagine
e immagini citate (qualche MB).
- Il convertitore copre solo la sintassi usata dalla wiki: una pagina nuova con sintassi diversa si vede come testo,
e il test di conversione di tutte le pagine la segnala.
- I moduli successivi aggiungono i propri fornitori di ricerca e le proprie sorgenti di notifiche senza toccare la
shell.
@@ -0,0 +1,53 @@
# ADR 0024 - Componenti `Kh*`, pagine record e liste con un solo modello di richiesta
- **Stato:** accettata
- **Data:** 2026-11-11
- **Modifica:** SPEC §10.5, §10.6, §10.7, §19; milestone M3, issue #27, #28, #29
## Contesto
SPEC §10.7 elenca i componenti `Kh*` e §10.5 la struttura comune di documenti e anagrafiche (toolbar a icone,
intestazione, schede, scorciatoie), ma non dice come si condividono il comportamento delle pagine che modificano un
record, come una griglia legge 100.000 righe senza librerie esterne, né dove finiscono filtri e colonne salvati. Le
maschere vere arrivano da M4 in poi: se ogni modulo scrivesse il proprio markup e le proprie query, toolbar,
scorciatoie e filtri divergerebbero subito.
## Decisione
1. **Una libreria, nomi dei mockup.** I componenti vivono in `Components/Ui` con prefisso `Kh` e riproducono le
classi di `mockup.css` con gli stessi nomi semantici (`toolbar.icons`, `dochead`, `fgroup`, `grid`…). Le varianti
che i mockup non hanno prendono un nome nuovo `kh-…`: una classe ha un solo significato (in 0.3.0 `.tl` e
`.kh-choices` usati in due sensi hanno rotto il totale documento e le schede dei temi).
2. **Campi all'italiana.** `KhTextBox`, `KhNumberBox`, `KhDateBox`, `KhSelect`, `KhCheck`, `KhSwitch`, `KhHotlink`
dentro `KhForm`. Numeri con virgola e punto delle migliaia e calcolo `=…` (quattro operazioni e parentesi, parser
in casa); date con `T`, `F`, `I`, `+n`, `-n` e cifre senza separatori (`ItalianDate`). Gli errori del servizio
tornano per nome di campo, il riepilogo porta il focus sul campo.
3. **Pagine record come classi base.** `RecordPage<T>` gestisce comandi standard, stato modificato sulla scheda della
shell, conferme prima di scartare o eliminare e le scorciatoie di §10.5.7, attive solo quando la pagina è la
scheda visibile. `DocumentPage<TDoc, TLine>` apre sulla scheda **Righe**; `MasterDataPage<T>` sui dati principali.
I comandi sono `Func<Task>`: chi li ridefinisce chiama `StateHasChanged` se cambia lo stato della pagina.
4. **`KhIconToolbar` su una riga.** I comandi meno usati scendono nel menu `…` invece di andare a capo.
5. **Un modello di richiesta per tutte le liste.** `ListQuery` (testo cercato, filtri, ordinamento, pagina) e
`ListPage<T>` (righe, totale, totali di colonna su tutte le righe selezionate). `ListFields<T>` descrive una volta i
campi e li applica sia a una query del micro-ORM (SQL, `LIKE` senza distinzione di maiuscole) sia a righe in
memoria (`InMemoryListSource`). I valori dei filtri sono testi invarianti, così un filtro si salva e si rilegge
uguale.
6. **`KhGrid` virtualizzata.** `Virtualize` di Blazor con righe alte 30 px e 20 righe di margine legge le pagine
mentre si scorre (oppure a pagine con il pager); ordinamento, selezione, tastiera, modifica in riga, totali, menu
di riga, esportazione CSV/XLSX con gli scrittori in casa (ADR 0021). Una ricerca nuova annulla quella in corso.
7. **Salvati per utente.** Disposizione delle colonne di una griglia e filtri del radar (stella) sono impostazioni
utente (ADR 0020) con chiave della lista; si eliminano dalla griglia e dal radar. La scheda *Layout salvati* del
profilo arriva con le prime maschere che li usano (M4).
8. **`KhRadar` intorno alla griglia**: ricerca, filtri rapidi, costruttore di filtri, filtri salvati; la stessa
finestra serve la ricerca `F4` degli hotlink. `KhLinesGrid` è la griglia delle righe dei documenti, pensata per la
tastiera (`Invio` cella successiva, `Ctrl+↓` nuova riga, `Ctrl+Canc` togli la riga).
9. **Catalogo per gli sviluppatori.** `/sviluppo/componenti` e `/sviluppo/documento` (solo in ambiente di sviluppo)
mostrano ogni componente con dati finti; gli screenshot della wiki si fanno da lì finché mancano le maschere vere.
## Conseguenze
- Le maschere di M4 e seguenti sono composizione di componenti e di una `ListFields<T>`; un comportamento comune si
corregge in un punto.
- La griglia non usa librerie esterne e regge 100.000 righe in memoria; con PostgreSQL la paginazione è nella query.
- I nomi di classe nuovi vanno controllati contro `mockup.css` e i fogli esistenti prima di introdurli.
- Rinomina e scelta del filtro predefinito, e la scheda *Layout salvati* del profilo, restano da fare (M4).
+51 -17
View File
@@ -1,7 +1,7 @@
# Allegati e file
> **Stato:** bozza · **Ultima revisione:** 2026-11-10 · **Versione software:** non ancora rilasciata (milestone M3, completata in M5)
> **Modulo di licenza:** CORE · **Permessi principali:** `attachments.delete`, permessi di lettura del documento · **Specifica:** SPEC §9.4
> **Stato:** completa per M3 (invio e-mail e scanner con M5) · **Ultima revisione:** 2026-11-11 · **Versione software:** 0.3.0 (milestone M3)
> **Modulo di licenza:** CORE · **Permessi principali:** `attachments.read`, `attachments.write`, `attachments.delete` · **Specifica:** SPEC §9.4
Ogni documento e ogni anagrafica può avere **allegati**: file caricati dall'utente (l'ordine del cliente in PDF, una
foto, un foglio di calcolo) e file **generati** da Khaemhat (PDF di stampa, XML FatturaPA, esportazioni, pacchetti
@@ -12,9 +12,17 @@ ZIP). Gli allegati sono archiviati sul volume dei dati dell'istanza, con version
Da qualunque documento: icona **Allegati** nella toolbar (con il numero degli allegati) oppure scheda **Allegati (n)**.
Si apre il pannello laterale **Allegati e file generati**.
> **In questa versione** i documenti veri arrivano con le vendite (M5): pannello, anteprime e anteprima di stampa si
> provano sul **documento di prova** degli sviluppatori (dal catalogo dei componenti `/sviluppo/componenti`,
> solo in ambiente di sviluppo), che ha
> tre file generabili (PDF, righe in CSV, righe in Excel). Mancano ancora **Invia** per e-mail e **Da scanner / foto**.
![024 · Allegati del documento e generazione file](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/mockups/thumbs/024-allegati-e-file-generati.png)
*Mockup 024 — pannello laterale sopra la fattura: elenco degli allegati con azioni, Carica file, Da scanner / foto, Scarica tutto (ZIP) e sezione Genera file (anteprima ridotta).*
![Khaemhat 0.3.0 · allegati](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/allegati-pannello.png)
*Khaemhat 0.3.0 — la scheda Allegati del documento di prova: tre file generati con le loro versioni, Carica file, Scarica tutto (ZIP) e Genera file.*
## Regole di base
- Un allegato appartiene **a un solo documento** (o a una sola anagrafica). Non esistono allegati "sciolti": se lo
@@ -42,10 +50,12 @@ caricato o generato e quando, dimensione, versione, eventuale modello usato.
|---|---|
| occhio | **Anteprima** in app |
| freccia in giù | **Scarica** |
| busta | **Invia** per e-mail |
| frecce circolari | **Rigenera**: crea una nuova versione del file generato |
| cestino | **Elimina** (solo file non bloccati e con permesso) |
| lucchetto | il file è bloccato |
| busta | **Invia** per e-mail (con le vendite) |
| frecce circolari | **Rigenera** (nella sezione *Genera file*): crea una nuova versione del file generato |
| lucchetto | **Blocca**: da quel momento il file non si può più eliminare; accanto al nome indica un file bloccato |
| cestino | **Sposta nel cestino** (solo file non bloccati e con permesso), dopo una conferma |
La casella **Versioni precedenti** mostra anche le versioni superate dei file generati (`v1` quando c'è già `v2`).
In fondo all'elenco:
@@ -79,19 +89,41 @@ Il pannello apre in app l'anteprima di:
| Formato | Come si vede |
|---|---|
| PDF | visualizzatore integrato |
| Immagini | a dimensione piena con zoom |
| XML | testo formattato e indentato |
| CSV, XLSX | griglia |
| PDF | visualizzatore PDF del browser, dentro la finestra di anteprima |
| Immagini (JPEG, PNG, GIF, WebP) | adattate alla finestra |
| XML, testo | testo così com'è |
| CSV, XLSX | griglia (il primo foglio per gli XLSX) |
Gli altri formati si scaricano. Per i documenti c'è anche l'**anteprima di stampa** (`Ctrl+P`, mockup 025), descritta
in [Vendite](Vendite).
![Khaemhat 0.3.0 · anteprima di un XLSX](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/allegati-anteprima.png)
*Khaemhat 0.3.0 — l'anteprima di un file Excel generato: il primo foglio come griglia.*
Dei file lunghi l'anteprima mostra l'inizio (200 righe, 200.000 caratteri) e lo dice. Gli altri formati si scaricano;
PDF e immagini si aprono anche in una nuova finestra del browser.
### Anteprima di stampa
![025 · Anteprima di stampa](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/mockups/thumbs/025-anteprima-stampa-pdf.png)
*Mockup 025 — anteprima di stampa di una fattura in formato A4 (anteprima ridotta).*
`Ctrl+P` o l'icona **Stampa** del documento aprono in una scheda l'**anteprima di stampa**: il documento come foglio
A4, con ingrandimento al 75, 100 o 125%. In alto:
- **Stampa** — la stampa del browser, che stampa solo il foglio (non menu e barre);
- **Apri PDF** e **Scarica PDF** — il PDF prodotto da Khaemhat, senza salvarlo fra gli allegati;
- **Salva come allegato** — salva il PDF fra gli allegati del documento come nuova versione.
Modello di stampa, copie e lingua arrivano con i documenti di vendita ([Vendite](Vendite)).
![Khaemhat 0.3.0 · anteprima di stampa](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/stampa-anteprima.png)
*Khaemhat 0.3.0 — l'anteprima di stampa del documento di prova, con Stampa, Apri PDF, Scarica PDF, Salva come allegato e l'ingrandimento.*
## Cestino
Quando un documento viene cancellato, i suoi allegati non spariscono subito: restano nel **cestino dell'azienda per
30 giorni** e possono essere recuperati in quel periodo; poi vengono eliminati definitivamente. La maschera di
consultazione del cestino sarà definita in sviluppo.
Quando un allegato viene spostato nel cestino, o quando viene cancellato il suo documento, il file non sparisce
subito: resta nel **cestino dell'azienda per 30 giorni** e poi viene eliminato definitivamente da un'attività
programmata. In fondo al pannello degli allegati, la sezione **Nel cestino** elenca i file del documento
che sono nel cestino, con la data in cui saranno eliminati e il pulsante **Ripristina** (serve
`attachments.delete`).
## Limiti e archiviazione
@@ -119,8 +151,10 @@ consultazione del cestino sarà definita in sviluppo.
## Permessi e licenza
Gli allegati sono nel modulo **CORE**. Chi può leggere un documento ne vede gli allegati; caricare richiede il
permesso di modifica del documento; cancellare richiede `attachments.delete`. Gli allegati sono raggiungibili anche
Gli allegati sono nel modulo **CORE**. Vedere e scaricare richiede `attachments.read`; caricare, generare e bloccare
richiede `attachments.write`; spostare nel cestino e ripristinare richiede `attachments.delete`. Un utente aziendale
vede solo gli allegati della propria azienda. I file si scaricano solo dopo l'accesso: un indirizzo copiato non
funziona per chi non è collegato. Gli allegati sono raggiungibili anche
dalle API (download e caricamento su un documento, modulo API; vedi [API e MCP](API-e-MCP)).
## Domande frequenti
+9 -2
View File
@@ -1,7 +1,7 @@
# Architettura
> **Stato:** bozza · **Ultima revisione:** 2026-11-10 · **Versione software:** non ancora rilasciata (milestone M0-M13)
> **Specifica:** SPEC §1-§5, §9, §13, §21 · ADR 0009-0011
> **Stato:** bozza · **Ultima revisione:** 2026-11-11 · **Versione software:** 0.1.0 (accesso ai dati); il resto arriva con le milestone M2-M13
> **Specifica:** SPEC §1-§5, §9, §13, §21 · ADR 0004, 0009-0018
Come è fatto Khaemhat "dentro", spiegato senza entrare nel codice. Chi sviluppa trova il documento tecnico completo
(regole di dipendenza, contratti, elenco delle classi) in
@@ -63,6 +63,13 @@ I dati di un'azienda non si mescolano mai con quelli di un'altra: stanno fisicam
lavora solo nella sua azienda; gli amministratori scelgono l'azienda dalla barra superiore. Gestione in
[Istanza-e-database](Istanza-e-database).
Il database di sistema tiene l'elenco delle aziende e, per ciascuna, **dove si trova il suo database**: questa
informazione contiene la password del database ed è salvata **cifrata** con la chiave dell'istanza
(`KHAEMHAT_SECRET_KEY`), in modo che non si possa leggere nemmeno copiandola da un'azienda all'altra. Quando il
programma lavora per un'azienda apre il database giusto da solo; la struttura di ogni database viene aggiornata dalle
**migrazioni** ([Modello-dati](Modello-dati)). Tutto il programma funziona allo stesso modo su PostgreSQL (16 o
successivo) e su SQLite: i test girano su entrambi a ogni versione.
![078 · Istanza e database](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/mockups/thumbs/078-admin-istanza-database.png)
*Mockup 078 — elenco dei database dell'istanza (sistema e aziende) con motore, dimensione, stato dello schema, ultimo backup e stato; sotto, le informazioni sul server PostgreSQL (anteprima ridotta).*
+14 -1
View File
@@ -1,8 +1,13 @@
# Attività programmate
> **Stato:** bozza · **Ultima revisione:** 2026-11-10 · **Versione software:** non ancora rilasciata (milestone M2 e M12)
> **Stato:** parziale · **Ultima revisione:** 2026-11-11 · **Versione software:** 0.2.0 (milestone M2 e M12)
> **Modulo di licenza:** CORE (procedure oltre quelle di sistema: AUTO; report pianificati: REPORT) · **Livello richiesto:** amministratore · **Specifica:** SPEC §9, §11.12, §11.13, §12.5
> **Nella versione 0.2.0** c'è il motore: espressioni cron a 5 campi con fuso orario, lock per attività (una sola
> esecuzione anche con più istanze), timeout, tentativi, storico delle esecuzioni e notifica agli amministratori
> quando un'attività fallisce. Girano i tre job di sistema (pulizia sessioni, controllo licenza, retention del log).
> La schermata e le attività create dagli utenti arrivano in M12.
## A cosa serve
Le **attività programmate** fanno lavorare Khaemhat da solo a orari stabiliti: backup notturni, fatturazione
@@ -132,6 +137,14 @@ il dettaglio dell'ultima. Le esecuzioni sono registrate nel database di sistema.
## Job di sistema
Nella versione 0.2.0 i job di sistema sono questi (orari nel fuso `Europe/Rome`):
| Codice | Cosa fa | Quando |
|---|---|---|
| `system.sessions-cleanup` | elimina le sessioni scadute o revocate da più di 30 giorni, nel database di sistema e in ogni azienda non disattivata | al minuto 15 di ogni ora |
| `system.license-check` | ricalcola la licenza; avvisa gli amministratori a 30, 14, 7, 3 e 1 giorno dalla scadenza e quando è scaduta | ogni ora |
| `system.log-retention` | elimina gli eventi di log più vecchi della retention del loro livello | ogni notte alle 03:30 |
Oltre alle attività degli amministratori, Khaemhat esegue sempre alcuni **job di sistema**: pulizia (log e sessioni
secondo la retention), controllo della licenza, aggiornamento dei cambi BCE, lettura dell'inbox e dei canali SDI,
coda delle e-mail, verifica delle giacenze, backup. Le attività di sistema predefinite sono create con le tabelle di
+5 -2
View File
@@ -1,6 +1,6 @@
# Changelog
> **Stato:** completa per 0.0.1 · **Ultima revisione:** 2026-11-11
> **Stato:** completa per 0.3.0 · **Ultima revisione:** 2026-11-11
Le novità di ogni versione sono nel file
[`CHANGELOG.md`](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/src/branch/main/CHANGELOG.md) del repository
@@ -11,11 +11,14 @@ Le novità di ogni versione sono nel file
| Versione | Data | Contenuto |
|---|---|---|
| 0.3.0 | 2026-11-11 | M3 — Framework UI: la finestra di Khaemhat con menu, schede e barra di stato, la dashboard a widget, *Il mio profilo* con temi e colori, ricerca globale, aiuto in app, notifiche, componenti per maschere e liste, allegati e anteprima di stampa (provati su un documento di prova, le maschere gestionali arrivano da 0.4.0). |
| 0.2.0 | 2026-11-11 | M2 — Sistema e sicurezza: avvio da variabili d'ambiente, super utente e prima azienda, accesso con password e verifica in due passaggi, utenti, ruoli e permessi, licenze e moduli con codici di prova, log per sezioni, attività programmate. |
| 0.1.0 | 2026-11-11 | M1 — Strato dati: accesso ai database SQLite e PostgreSQL, migrazioni dello schema, registro delle aziende, cifratura dei dati riservati. Nessuna funzione visibile nell'interfaccia. |
| 0.0.1 | 2026-11-11 | M0 — Bootstrap: struttura del codice, immagine Docker con pagina "in costruzione" ed endpoint di salute, compose, CI e rilascio su Gitea Actions. Nessuna funzione gestionale ancora. |
| *preparazione* | 2026-11-10 | Documentazione, specifica, mockup, wiki e pianificazione su Gitea. Nessun software. |
Ogni immagine Docker pubblicata ha lo stesso numero di versione del tag git (senza la `v` iniziale), ad esempio
`gitea.encke-hake.ts.net/balbosoft/khaemhat:0.1.0`. Prima di aggiornare leggi [Aggiornamento](Aggiornamento).
`gitea.encke-hake.ts.net/balbosoft/khaemhat:0.3.0`. Prima di aggiornare leggi [Aggiornamento](Aggiornamento).
## Pagine correlate
+63 -21
View File
@@ -1,6 +1,6 @@
# Dashboard
> **Stato:** bozza · **Ultima revisione:** 2026-11-10 · **Versione software:** non ancora rilasciata (milestone M3)
> **Stato:** completa · **Ultima revisione:** 2026-11-11 · **Versione software:** 0.3.0 (milestone M3)
> **Modulo di licenza:** CORE (alcuni widget richiedono il modulo dell'area, ad esempio CRM) · **Specifica:** SPEC §10.3, §11.12
La **dashboard** è la pagina *Home*: una griglia di **widget** che riassume che cosa c'è da fare oggi, che cosa è
@@ -17,17 +17,33 @@ diversamente in *Pagina iniziale*.
![004 · Dashboard](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/mockups/thumbs/004-dashboard.png)
*Mockup 004 — dashboard con saluto e data, KPI, Da fare oggi, Fatto oggi, Scadenze prossimi 30 giorni, Da evadere, Fatturato 12 mesi (anteprima ridotta).*
![Khaemhat 0.3.0 · dashboard](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/interfaccia-home.png)
*Khaemhat 0.3.0 — la dashboard predefinita di un super utente. Indicatori, Da evadere e Fatturato 12 mesi si accendono quando arrivano i dati (vendite, M5).*
![005 · Dashboard in tema scuro](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/mockups/thumbs/005-dashboard-tema-scuro.png)
*Mockup 005 — la stessa dashboard in tema scuro (anteprima ridotta).*
![Khaemhat 0.3.0 · tema scuro](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/design-tema-scuro.png)
*Khaemhat 0.3.0 — la stessa dashboard in tema scuro.*
![006 · Dashboard · personalizzazione](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/mockups/thumbs/006-dashboard-personalizza.png)
*Mockup 006 — modalità Personalizza: widget con bordo tratteggiato e pannello laterale con pagina iniziale ed elenco dei widget attivabili (anteprima ridotta).*
In testa alla pagina: il saluto (*Buongiorno Alberto*) con la data, a destra **Personalizza** e **Nuovo documento**.
![Khaemhat 0.3.0 · Personalizza](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/dashboard-personalizza.png)
*Khaemhat 0.3.0 — Personalizza: widget con bordo tratteggiato e comandi di spostamento e larghezza, pannello con pagina iniziale ed elenco dei widget.*
In testa alla pagina: il saluto (*Buongiorno Alberto*, *Buon pomeriggio*, *Buonasera*) con la data, a destra
**Personalizza**. Il pulsante **Nuovo documento** arriva con le vendite (M5).
## Widget disponibili
La griglia ha 12 colonne; ogni widget può occupare 3, 4, 6, 8 o 12 colonne.
La griglia ha 12 colonne; ogni widget può occupare 3, 4, 6, 8 o 12 colonne (sotto i 1000 px di larghezza ogni
widget prende tutta la riga).
Nella versione 0.3.0 hanno già dati **Da fare oggi**, **Fatto oggi**, **Scadenze 30 giorni**, **Promemoria
personali**, **Scorciatoie** e **Stato del sistema**. Gli altri si possono già accendere, mettere in ordine e
dimensionare: finché il loro modulo non c'è dicono con quale versione arrivano i dati (*Vendite* M5, *Acquisti e
magazzino* M6, *CRM* M11), senza numeri finti.
| Widget | Cosa mostra | Note |
|---|---|---|
@@ -43,38 +59,63 @@ La griglia ha 12 colonne; ogni widget può occupare 3, 4, 6, 8 o 12 colonne.
| **Sottoscorta** | articoli sotto la scorta minima | |
| **Pipeline CRM** | valore delle opportunità per fase | richiede il modulo CRM |
| **Ultimi documenti** | ultimi documenti aperti o creati | |
| **Stato sistema** | stato dell'istanza (database, backup, scheduler) | solo amministratori |
| **Stato del sistema** | versione, database, cache, licenza, aziende aperte, attività programmate di oggi, ognuno con un pallino verde, giallo o rosso | solo account di istanza |
Ogni widget ha in alto a destra un menu **⋯** con le azioni proprie (ad esempio aggiornare o aprire l'elenco
completo). I dati rispettano i permessi: un utente che non vede costi e margini non li trova nemmeno nei widget.
Ogni widget ha in alto a destra le sue azioni: il numero di righe nelle liste, la matita delle **Scorciatoie** (scegli
fino a 12 pagine fra quelle che puoi aprire), il cestino dei **Promemoria** che toglie quelli spuntati. Un clic su una
riga di *Da fare oggi*, *Fatto oggi* o *Scadenze* apre la pagina giusta. I dati rispettano i permessi: un utente che
non vede costi e margini non li trova nemmeno nei widget.
Nella versione 0.3.0 le righe vengono da:
| Widget | Righe |
|---|---|
| Da fare oggi | licenza scaduta, in tolleranza o in scadenza entro 7 giorni (account di istanza); avvisi non letti di livello *attenzione* o *errore*; attività programmate la cui ultima esecuzione di oggi non è riuscita (account di istanza) |
| Fatto oggi | attività programmate riuscite oggi, una riga per attività con il numero di esecuzioni e l'ora dell'ultima |
| Scadenze 30 giorni | fine della prova o scadenza della licenza (account di istanza) |
I moduli delle prossime versioni aggiungono le loro righe (scarti SDI, liquidazioni, incassi, ordini da evadere…).
Se una fonte non risponde, il widget mostra le altre e l'errore finisce nel [log](Log).
I **promemoria** si scrivono nel campo in fondo al widget e si aggiungono con Invio (al massimo 20, di 300 caratteri
ciascuno); la casella li segna come fatti, la **×** li toglie.
## Come si personalizza
1. Premi **Personalizza** in alto a destra. I widget si contornano con un bordo tratteggiato e si apre il pannello
laterale **Personalizza dashboard**.
2. Nel pannello, sezione **Widget (trascina per ordinare)**, attiva o disattiva ciascun widget con l'interruttore e
trascinalo per cambiarne l'ordine.
3. Sulla griglia trascina i widget per spostarli e ridimensionali (3, 4, 6, 8 o 12 colonne).
4. Imposta, se vuoi, il periodo dei KPI.
5. Chiudi il pannello: la disposizione è salvata.
laterale **Personalizza dashboard**; la pagina resta utilizzabile e, sugli schermi larghi almeno 1280 px, si
stringe per lasciare spazio al pannello.
2. Nel pannello, sezione **Widget**, accendi o spegni ciascun widget con l'interruttore; per quelli accesi scegli la
larghezza (*Un quarto*, *Un terzo*, *Metà*, *Due terzi*, *Tutta la riga*) e spostali con le frecce. Un widget
acceso si aggiunge in fondo.
3. Sulla griglia trascina un widget sopra un altro per prenderne il posto. Ogni widget ha anche i pulsanti
**‹ ›** (sposta prima o dopo), **− +** (più stretto o più largo) e **×** (nascondi): tutto si fa anche da tastiera.
4. **Ripristina** cancella la tua disposizione: torna quella predefinita del tuo ruolo o, se non c'è, quella di
Khaemhat. **Fine** (o Esc) chiude il pannello.
Disposizione e scelte sono salvate nelle tue preferenze (sul database dell'azienda): le ritrovi su ogni dispositivo.
Ogni modifica si salva subito nelle tue preferenze: la ritrovi su ogni dispositivo. Il pannello dice da dove viene la
disposizione che stai usando (tua, del ruolo o di Khaemhat).
## Pagina iniziale e dashboard disattivabile
La dashboard si può **spegnere**. Nel pannello *Personalizza* (sezione **Pagina iniziale**) o in
[Il mio profilo → Pagina iniziale](Preferenze-utente) scegli:
- **All'accesso apri**: *Dashboard*, oppure l'*ultima scheda aperta*, un *radar* (ad esempio *Clienti*), la *prima
nota*, l'*agenda CRM*…
- **Pagina da aprire**: *La pagina iniziale* (la dashboard), l'*ultima scheda aperta* o una delle pagine che puoi
aprire (ad esempio *Clienti*).
- **Mostra la dashboard**: se disattivato, la voce *Home* non mostra più i widget e all'accesso si apre la pagina
scelta.
## Layout per ruolo
Gli amministratori possono definire un **layout predefinito per ruolo** (ad esempio un layout per *Vendite*, uno per
*Contabilità*): un nuovo utente parte dal layout del proprio ruolo e può poi modificarlo per sé. La maschera di
gestione dei layout per ruolo sarà definita in sviluppo (vedi [Utenti e permessi](Utenti-e-permessi)).
Chi ha il permesso **Modificare le impostazioni dell'azienda** (`company.settings.write`, ad esempio il ruolo
*Amministrazione*) trova in fondo al pannello la sezione **Predefinito per ruolo**: sceglie un ruolo e preme **Usa
questo layout per il ruolo** per dargli la disposizione che ha sulla pagina in quel momento; **Togli il predefinito**
lo riporta a quello di Khaemhat. I ruoli che hanno un predefinito sono segnati nell'elenco.
Chi non ha mai personalizzato la dashboard parte dal predefinito del suo ruolo (se ha più ruoli, il primo assegnato
che ne ha uno); appena cambia qualcosa la disposizione diventa sua. I predefiniti dei ruoli sono impostazioni
dell'azienda: ogni azienda ha i suoi. La sezione compare solo quando lavori in un'azienda.
## Permessi e licenza
@@ -85,9 +126,10 @@ se l'utente ha i permessi di lettura su quei dati; *Stato sistema* è riservato
- **Un widget non compare nell'elenco.** Il modulo relativo (ad esempio CRM) non è licenziato o non hai il permesso
di vederne i dati.
- **Voglio tornare alla disposizione iniziale.** Un comando per ripristinare il layout del ruolo non è ancora
definito nella specifica; sarà deciso in sviluppo e documentato qui. Nel frattempo riattiva o riordina i widget
da *Personalizza*.
- **Voglio tornare alla disposizione iniziale.** *Personalizza* → **Ripristina**: torna il predefinito del tuo ruolo
o quello di Khaemhat.
- **Ho spento la dashboard e voglio riaccenderla.** La *Home* mostra in alto **Mostra la dashboard**; in alternativa
[Il mio profilo → Pagina iniziale](Preferenze-utente).
- **"Da fare oggi" mostra cose che non riguardano il mio lavoro.** L'elenco segue i tuoi permessi; se vedi voci non
pertinenti, chiedi all'amministratore di verificare il tuo ruolo.
+47 -11
View File
@@ -1,6 +1,6 @@
# Design UI
> **Stato:** bozza · **Ultima revisione:** 2026-11-10 · **Versione software:** non ancora rilasciata (milestone M3)
> **Stato:** completa · **Ultima revisione:** 2026-11-11 · **Versione software:** 0.3.0 (milestone M3)
> **Pagina per chi sviluppa** · **Specifica:** SPEC §10 (in particolare §10.1, §10.6, §10.7, §10.8), Appendice A
Questa pagina è il riferimento visivo per chi sviluppa l'interfaccia di Khaemhat: come si usano i mockup, i token di
@@ -31,7 +31,18 @@ Regole vincolanti (SPEC §10.1):
Solo 23 schermate sono disponibili in alta risoluzione; per le altre si lavora dalla miniatura, da `mockup.css` e
dalla descrizione in SPEC §10-§12 (emendamento E4 in `CLAUDE.md`). Gli screenshot reali in `docs/wiki/img/`
sostituiscono progressivamente i mockup nelle pagine della wiki.
affiancano i mockup nelle pagine della wiki: dalla versione 0.3.0 ci sono la shell, la dashboard, il profilo, l'aiuto,
le notifiche, il documento di prova con allegati e storico e l'anteprima di stampa.
Gli screenshot si rifanno su un'istanza nuova (database SQLite vuoto, azienda DEMO, tema chiaro, finestra
1440x900, telefono 390x844), così non mostrano dati o notifiche di prova; i nomi dei file sono quelli usati dalle
pagine, ad esempio `interfaccia-home.png` o `allegati-pannello.png`.
![Khaemhat 0.3.0 · documento](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/design-documento.png)
*Khaemhat 0.3.0 — i mattoni di 020 e 021 dal vero: toolbar a icone, intestazione documento, schede interne, griglia delle righe.*
![Khaemhat 0.3.0 · tema scuro](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/design-tema-scuro.png)
*Khaemhat 0.3.0 — la dashboard con tema scuro e accento Nilo.*
## Token di design
@@ -91,8 +102,8 @@ Altre preferenze di presentazione: dimensione del testo, carattere numerico tabe
`AccentColor`, `Density`, `MenuState`). `ThemeService` e `MenuStateService` applicano gli attributi senza ricaricare
la pagina.
`mockup.css` **non contiene ancora i valori del tema alto contrasto**: vanno definiti in `tokens.css` rispettando il
contrasto AAA, con gli stessi nomi di token, e documentati in questa pagina.
`mockup.css` non contiene i valori del tema **alto contrasto**: sono definiti in `tokens.css` con gli stessi nomi di
token (testo nero su bianco, bordi neri, un solo accento blu scuro per tutti gli accenti), per il contrasto AAA.
## Classi dei mockup e componenti `Kh*`
@@ -154,6 +165,20 @@ radar, `Ctrl+Invio` apre, creazione al volo; `KhGrid` con colonne tipizzate, ord
server, virtualizzazione, selezione multipla, editing inline, riga dei totali, layout colonne salvato, export,
evidenziazioni, menu di riga.
## File CSS
| File | Contenuto |
|---|---|
| `css/tokens.css` | token `--kh-*` di `mockup.css`, temi (automatico, chiaro, scuro, alto contrasto), accenti, densità, dimensioni del testo; generato da `mockup.css` |
| `css/components.css` | classi dei mockup (shell, toolbar, pannelli, campi, griglie, badge, dialoghi…), riprese da `mockup.css` |
| `css/interactive.css` | ciò che i mockup statici non hanno: reset dei pulsanti, focus, suggerimenti, menu a comparsa, schede, notifiche a scomparsa, interruttori `data-*` |
| `css/print.css` | stampa sempre in chiaro, shell nascosta |
| `app.css` | pagine costruite finora (accesso, home, profilo, messaggi) |
Gli attributi sull'elemento `<html>` comandano l'aspetto: `data-theme` (`auto`, `light`, `dark`, `high-contrast`),
`data-accent`, `data-density`, `data-text-size` (`100`, `110`, `120`), `data-tabular`, `data-motion`,
`data-tooltips`, `data-row-hover`. Il server li scrive dalle preferenze dell'utente; il profilo li cambia dal vivo.
## Shell
- Griglia: barra superiore 46 px, area centrale, barra di stato 24 px; menu 228 px (60 px compresso).
@@ -162,7 +187,9 @@ evidenziazioni, menu di riga.
- **Menu**: sezioni in maiuscoletto (`.sec`), voce attiva su `--kh-accent-soft`; compresso: solo icone 20 px, barretta
d'accento a sinistra della voce attiva, sottomenu in `.flyout` (min 190 px, ombra grande). Pulsante **Comprimi
menu** tratteggiato in fondo. Sotto 1100 px parte compresso; stato salvato per utente.
- **Schede** (`.wtab`): altezza 30 px, massimo 260 px di larghezza, pallino `--kh-warn` se modificata.
- **Schede** (`.wtab`): altezza 30 px, massimo 260 px di larghezza, pallino `--kh-warn` se modificata. Ogni pagina
imposta il titolo della sua scheda con `<KhPageTitle Text="..." Icon="..." />` e segnala le modifiche con il
`KhTab` in cascata (`Tab?.SetModified(true)`).
- **Barra di stato**: testo 11.5 px, pallino `--kh-ok` per la connessione.
Dettagli d'uso in [Interfaccia e scorciatoie](Interfaccia-e-scorciatoie).
@@ -211,17 +238,26 @@ dal testo. Nessuna libreria di icone esterna. L'icona dell'applicazione è descr
**nessun font scaricato**, nessuna CDN.
- **Focus sempre visibile**, etichette collegate ai campi (`<label for>`), contrasto **AA** (AAA nel tema alto
contrasto), tutto operabile da tastiera.
- Desktop-first, usabile da tablet a partire da **768 px**.
- **Testi**: nessun testo hard-coded nei componenti (verificato da un test di architettura); `ITexts` risolve chiavi
come `Sales.Invoice.Title` da `Resources/it-IT/*.json`.
- Desktop-first, usabile da tablet a partire da **768 px** e su telefono con la barra superiore a sole icone (vedi [Interfaccia e scorciatoie](Interfaccia-e-scorciatoie)).
- **Nomi di classe unici**: una classe dei mockup ha un solo significato. Se un componente ha bisogno di una variante, usa un nome nuovo (`kh-…`) invece di riusarne uno esistente: in 0.3.0 `.tl` (timeline) e `.kh-choices` usati in due sensi diversi spostavano l'etichetta del totale documento e le schede dei temi.
- **Testi**: nessun testo hard-coded nei componenti; `ITexts` (iniettato in ogni componente come `T`) risolve chiavi
come `Shell.Menu.Parties` da `src/Khaemhat.Web/Resources/it-IT/*.json` (risorse incorporate). Gli oggetti annidati
danno le chiavi puntate, la proprietà `_` dà il testo all'oggetto che ha figli, una chiave doppia blocca l'avvio e
una mancante appare come `[chiave]`. Uso: `@T["Pages.Profile.Title"]`, `@T.Format("Pages.Home.Coming", "M4")`,
`T.Money(1234.5m)`, `T.Date(...)`. Due test lo garantiscono: nessun testo letterale fra i tag e negli attributi
`title`, `placeholder`, `alt`, `aria-label`, `label` dei `.razor`, e ogni chiave usata esiste (ADR 0020).
- **Formati**: `CultureInfo("it-IT")` per numeri, importi e date; date memorizzate in UTC e mostrate nel fuso
`Europe/Rome`.
## Stampa
Le stampe e i PDF sono **sempre in tema chiaro** (`print.css`), indipendentemente dal tema dell'utente. L'anteprima
usa `.paper` (pagina bianca larga 794 px, cioè un A4 a 96 dpi, margini 40/44 px, tabelle con intestazione in
maiuscoletto e bordo inferiore marcato).
Le stampe e i PDF sono **sempre in tema chiaro** (`print.css`), indipendentemente dal tema dell'utente. L'anteprima di
stampa (`KhPrintPreview`, mockup 025) mostra il documento come foglio `.kh-sheet` largo 210 mm e alto almeno 297 mm,
con ingrandimento 75/100/125%; `@media print` nasconde tutto tranne il foglio e imposta `@page` A4 senza margini.
La classe `.paper` di `mockup.css` resta per le anteprime piccole dentro le pagine.
![Khaemhat 0.3.0 · anteprima di stampa](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/stampa-anteprima.png)
*Khaemhat 0.3.0 — l'anteprima di stampa del documento di prova.*
## Regola di aggiornamento
+1
View File
@@ -189,6 +189,7 @@ obbligatoria, termina con un messaggio che indica quale.
| `KHAEMHAT_SEED_DEMO` | no | `false` | dati di esempio, solo su database vuoto |
| `KHAEMHAT_UPDATE_FEED` | no | `https://gitea.encke-hake.ts.net/api/v1/packages/BalboSoft?type=container&q=khaemhat` | API dei pacchetti Gitea per il controllo aggiornamenti |
| `KHAEMHAT_UPDATE_TOKEN` | no | token Gitea in sola lettura | solo se il pacchetto non è pubblico |
| `KHAEMHAT_HELP_URL` | no | `https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/wiki/` | wiki online aperta da **Apri nel wiki** nell'aiuto; l'aiuto (F1) usa la copia della wiki contenuta nell'immagine e funziona anche senza Internet |
| `TZ` | no | `Europe/Rome` | fuso orario |
| `PUID` / `PGID` | no | `1654` / `1654` (Unraid: `99` / `100`) | utente e gruppo proprietari dei file in `/data`; l'applicazione non gira mai come root |
+82 -22
View File
@@ -1,6 +1,6 @@
# Interfaccia e scorciatoie
> **Stato:** bozza · **Ultima revisione:** 2026-11-10 · **Versione software:** non ancora rilasciata (milestone M3)
> **Stato:** completa · **Ultima revisione:** 2026-11-11 · **Versione software:** 0.3.0 (milestone M3)
> **Modulo di licenza:** CORE · **Specifica:** SPEC §10.2, §10.4, §10.5, §10.7, §17 (aiuto in app)
Questa pagina descrive come è fatta la finestra di Khaemhat e come ci si muove: barra superiore, menu laterale,
@@ -15,6 +15,9 @@ scorciatoia nel suggerimento che compare al passaggio del mouse.
![013 · Clienti · radar con menu compresso e sottomenu a comparsa](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/mockups/png/013-clienti-radar-menu-compresso.png)
*Mockup 013 — la finestra con il menu laterale compresso: barra superiore, sottomenu Anagrafiche a comparsa, schede aperte, radar dei clienti e barra di stato.*
![Khaemhat 0.3.0 · la finestra](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/interfaccia-home.png)
*Khaemhat 0.3.0 — la finestra con il menu espanso: barra superiore, menu, scheda Home con la dashboard predefinita e barra di stato.*
| Zona | Dove | Contenuto |
|---|---|---|
| Barra superiore | in alto, scura | marchio e versione, azienda, ricerca globale, nuovo, recenti, notifiche, tema, aiuto, utente |
@@ -66,9 +69,15 @@ Si passa da uno stato all'altro con il pulsante **Comprimi menu** in fondo al me
**ricordato per utente** (anche fra dispositivi diversi); sotto i 1100 px di larghezza della finestra il menu parte
compresso. Lo stato iniziale si sceglie anche in [Preferenze utente](Preferenze-utente).
Le aree che arrivano con le prossime versioni sono già nel menu, se la licenza e i permessi le concedono: aprendole
compare una pagina che dice con quale milestone arrivano e quali voci conterranno.
![007 · Menu laterale compresso](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/mockups/thumbs/007-menu-compresso.png)
*Mockup 007 — dashboard con il menu compresso a sole icone e accento Turchese (anteprima ridotta).*
![Khaemhat 0.3.0 · menu compresso](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/interfaccia-menu-compresso.png)
*Khaemhat 0.3.0 — lo stesso menu compresso a sole icone; la freccia in basso lo riapre.*
## Area a schede
Ogni maschera aperta (un radar, un documento, una scheda anagrafica, una procedura) diventa una **scheda** in alto.
@@ -76,9 +85,23 @@ Le schede restano "vive": passando da una all'altra non si perde nulla di quanto
- Un **pallino arancione** accanto al titolo indica modifiche non salvate.
- Chiudendo una scheda con modifiche non salvate Khaemhat chiede conferma.
- Si possono tenere aperte al massimo **12 schede**; il comportamento all'apertura della tredicesima sarà definito in
sviluppo.
- `Ctrl+W` chiude la scheda attiva, `Ctrl+Tab` passa alla successiva; il pulsante `+` apre una nuova scheda.
- Si possono tenere aperte al massimo **12 schede**. Aprendone una tredicesima si chiude da sola quella usata meno di
recente fra quelle **senza modifiche**; se tutte hanno modifiche da salvare, Khaemhat lo dice e non apre la nuova.
- Aprire una pagina già aperta porta alla sua scheda invece di crearne un'altra.
- `Ctrl+W` (o `Alt+W`) chiude la scheda attiva, `Ctrl+Tab` (o `Alt+PagGiù`) passa alla successiva,
`Ctrl+Maiusc+Tab` (o `Alt+PagSu`) alla precedente; il pulsante `+` apre la ricerca per aprire una nuova pagina.
Molti browser tengono per sé `Ctrl+W` e `Ctrl+Tab`: le varianti con `Alt` funzionano sempre.
- Il titolo della finestra del browser segue la scheda attiva.
## Su tablet e telefono
La finestra è pensata per lo schermo di un computer, ma resta usabile su tablet (dai 768 px) e su telefono. Sotto i
1.100 px la barra superiore nasconde il nome dell'utente, sotto i 900 px il testo della ricerca; sul telefono il
menu laterale resta a sole icone, la barra superiore mostra solo le icone (il nome dell'azienda resta letto dagli
screen reader) e la barra di stato mostra solo connessione, cache e versione.
![Khaemhat 0.3.0 · su telefono](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/interfaccia-mobile.png)
*Khaemhat 0.3.0 — la Home su un telefono largo 390 px.*
## Barra di stato
@@ -91,6 +114,13 @@ e la **versione** del software con il commit (es. `v1.0.0 (a3f9c1e)`).
![009 · Ricerca globale](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/mockups/thumbs/009-ricerca-globale.png)
*Mockup 009 — ricerca "rossi": risultati raggruppati per clienti, articoli, documenti, contabilità e azioni (anteprima ridotta).*
![Khaemhat 0.3.0 · ricerca globale](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/interfaccia-ricerca.png)
*Khaemhat 0.3.0 — la ricerca "cli": pagine del menu e pagine dell'aiuto. Clienti, articoli e documenti si aggiungono con i rispettivi moduli.*
> **In questa versione** la ricerca trova le **pagine** del menu, i **comandi** (tema, menu, profilo, sessioni,
> scorciatoie) e le **pagine dell'aiuto** (titoli e sezioni, che si aprono al punto giusto). Clienti, articoli e
> documenti si aggiungono con le milestone che li introducono: per ora `#` e `@` dicono con quali moduli arrivano.
Premi `Ctrl+K` (o fai clic sulla casella di ricerca) e digita. I risultati arrivano mentre scrivi, raggruppati per
tipo: **clienti e fornitori**, **articoli**, **documenti**, **registrazioni e conti** contabili, **azioni** (ad
esempio *Nuova fattura per Rossi Impianti*, *Registra incasso*, *Scheda cliente a 360°*).
@@ -103,40 +133,58 @@ esempio *Nuova fattura per Rossi Impianti*, *Registra incasso*, *Scheda cliente
| `@` | persone (contatti, utenti) | `@ verdi` |
Con le frecce `↑` `↓` ti sposti tra i risultati, con `Invio` apri quello evidenziato; il piede della finestra ricorda
anche l'apertura in una nuova scheda (`Ctrl+Invio`) e i prefissi. `Esc` chiude.
i prefissi. `Esc` chiude. Pagine e comandi compaiono subito; gli altri risultati arrivano un attimo dopo che hai
smesso di scrivere, da almeno due caratteri.
## Notifiche
![010 · Pannello notifiche](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/mockups/thumbs/010-notifiche.png)
*Mockup 010 — pannello laterale delle notifiche con filtri e azioni (anteprima ridotta).*
![Khaemhat 0.3.0 · notifiche](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/interfaccia-notifiche.png)
*Khaemhat 0.3.0 — il pannello delle notifiche con i filtri Tutte e Non lette e il pulsante Segna tutte come lette.*
La campanella apre un pannello laterale con le notifiche in app. Le notifiche nascono da automazioni, attività
programmate, SDI (scarti, notifiche), scadenze, magazzino (sottoscorta) e sicurezza (ad esempio un accesso da un
dispositivo sconosciuto). Ogni voce ha icona, titolo, dettaglio e, se serve, un'etichetta d'urgenza (*Nuova*, *Da
gestire*, *Verifica*); un clic apre il documento o la maschera collegata.
In alto i filtri **Tutte**, **Non lette**, **Errori**; in basso **Segna tutte come lette** e **Impostazioni notifiche**
(che porta alla scheda *Notifiche* di [Il mio profilo](Preferenze-utente), dove si attiva anche il riepilogo via
e-mail).
In alto i filtri **Tutte** e **Non lette**, con il numero di voci; in basso **Segna tutte come lette**. Ogni voce ha
il segno di spunta per segnarla come letta; il clic sul titolo la segna e apre la maschera collegata. Il numero
sulla campanella si aggiorna da solo ogni minuto.
Chi legge una notifica rivolta a tutti la segna come letta **solo per sé**: per i colleghi resta da leggere. Gli
account di istanza vedono le notifiche di sistema (backup, attività programmate, licenza), gli utenti aziendali
quelle della propria azienda. Il pannello mostra le ultime 100 notifiche.
> **In questa versione** mancano il filtro *Errori* e *Impostazioni notifiche* (riepilogo via e-mail), che arrivano
> con le automazioni.
## Aiuto in app (F1)
![011 · Aiuto in app](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/mockups/png/011-aiuto-in-app-wiki.png)
*Mockup 011 — l'aiuto della maschera Fatture: indice delle pagine a sinistra, pagina wiki con stato e revisione a destra.*
![Khaemhat 0.3.0 · aiuto in app](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/interfaccia-aiuto.png)
*Khaemhat 0.3.0 — l'aiuto di questa pagina: indice a sinistra, pagina della wiki a destra, Apri nel wiki e Segnala un problema in alto.*
`F1` o il pulsante `?` aprono, in una nuova scheda, **la pagina wiki della maschera** su cui stai lavorando (ogni
maschera ha il proprio collegamento). La pagina mostra in testa lo stato (*bozza*, *completa*), la revisione e la data
di aggiornamento; a sinistra c'è l'indice delle pagine. In alto a destra: **Apri nel wiki** (apre la wiki completa
nel browser) e **Segnala un problema**.
nel browser) e **Segnala un problema** (apre una nuova segnalazione nel repository della wiki).
L'indirizzo della wiki è configurabile; per le installazioni senza accesso a Internet Khaemhat serve una copia della
wiki all'indirizzo `/help` della propria istanza.
L'aiuto è una **copia della wiki contenuta nell'immagine Docker**, all'indirizzo `/aiuto` dell'istanza (`/help` porta
lì): funziona anche senza Internet e corrisponde sempre alla versione installata, immagini comprese. La variabile
`KHAEMHAT_HELP_URL` cambia solo la wiki aperta da *Apri nel wiki* (vedi [Installazione Docker](Installazione-Docker)).
## Toolbar a icone
![020 · Fattura di vendita · righe](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/mockups/thumbs/020-fattura-vendita-righe.png)
*Mockup 020 — fattura di vendita: toolbar a icone con il suggerimento "Salva Ctrl+S", azioni contestuali, intestazione documento e righe (anteprima ridotta).*
![Khaemhat 0.3.0 · toolbar e documento](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/design-documento.png)
*Khaemhat 0.3.0 — il documento di prova degli sviluppatori: toolbar a icone, intestazione a tre blocchi, schede interne e righe modificabili.*
Ogni maschera ha una toolbar su **una sola riga**, con i comandi standard **solo icona** (senza etichetta). Passando
con il mouse compare il suggerimento con nome e scorciatoia (disattivabile in [Preferenze utente](Preferenze-utente)).
@@ -183,6 +231,11 @@ anagrafiche hanno la stessa struttura:
(oppure revisioni o partite, secondo il documento) e **totali**.
6. Gli errori di validazione compaiono accanto al campo e in un riepilogo. Un documento emesso è **in sola lettura**:
campi e azioni non più ammesse sono disattivati.
7. La scheda **Storico** elenca chi ha creato e modificato il record e quando, con i valori di prima (barrati) e
quelli nuovi; serve il permesso di lettura del record.
![Khaemhat 0.3.0 · Storico](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/allegati-storico.png)
*Khaemhat 0.3.0 — la scheda Storico del documento di prova (modifiche di esempio).*
## Radar
@@ -239,13 +292,18 @@ azioni di riga. Gli sconti accettano la forma a cascata (`5+2`).
| Digiti | Ottieni |
|---|---|
| `T` | la data di oggi |
| `F` | la fine del mese (il riferimento esatto, data del campo o mese corrente, sarà fissato in sviluppo) |
| `+` / `-` | un giorno avanti / indietro |
| `T` oppure `O` | la data di oggi |
| `F` | la fine del mese della data già nel campo (del mese corrente se il campo è vuoto) |
| `I` | l'inizio dello stesso mese |
| `+` / `-` | un giorno avanti / indietro rispetto alla data nel campo (o a oggi) |
| `+30` / `-7` | trenta giorni avanti, sette indietro |
| `15` | il 15 del mese corrente |
| `1503` oppure `15/3` | il 15 marzo dell'anno corrente |
| `150326` oppure `15.3.26` | il 15 marzo 2026 |
**Numeri e importi** (formato italiano: virgola per i decimali, punto per le migliaia): si può scrivere un
**calcolo** che inizia con `=`, ad esempio `=10*3` diventa `30`. Altre abbreviazioni eventuali saranno definite in
sviluppo e documentate qui.
**calcolo** che inizia con `=`, ad esempio `=10*3` diventa `30`: valgono le quattro operazioni, le parentesi e il
segno meno davanti a un numero, sempre con la virgola per i decimali (`=(12,5+3)*2` diventa `31`).
## Tabella completa delle scorciatoie
@@ -254,9 +312,10 @@ sviluppo e documentate qui.
| `Ctrl+K` | ricerca globale | ovunque |
| `F1` | aiuto della maschera corrente | ovunque |
| `Ctrl+B` | comprime / espande il menu laterale | ovunque |
| `Ctrl+W` | chiude la scheda attiva | ovunque |
| `Ctrl+Tab` | passa alla scheda successiva | ovunque |
| `Ctrl+N` | nuovo record / documento | maschere e radar |
| `Ctrl+W` o `Alt+W` | chiude la scheda attiva | ovunque |
| `Ctrl+Tab` o `Alt+PagGiù` | passa alla scheda successiva | ovunque |
| `Ctrl+Maiusc+Tab` o `Alt+PagSu` | passa alla scheda precedente | ovunque |
| `Ctrl+N` o `Alt+N` | nuovo record / documento | maschere e radar |
| `Ctrl+S` | salva | maschere |
| `Esc` | annulla le modifiche / chiude la finestra aperta | maschere, finestre |
| `Ctrl+Canc` | elimina il record (se ammesso) | maschere |
@@ -271,11 +330,11 @@ sviluppo e documentate qui.
| `Tab` | cella o filtro successivo | griglia righe, finestra F4 |
| `Spazio` | seleziona la riga | radar |
| `Ctrl+D` | quadra la registrazione | prima nota (vedi [Contabilità](Contabilita)) |
| `T`, `F`, `+`, `-` | oggi, fine mese, giorno dopo/prima | campi data |
| `T` (`O`), `F`, `I`, `+`, `-`, `+n` | oggi, fine mese, inizio mese, giorno dopo/prima, n giorni | campi data |
| `=` | calcolo inline (`=10*3`) | campi numerici |
Le scorciatoie personali si potranno adattare nelle preferenze utente (§11.12 della specifica); l'interfaccia di
personalizzazione sarà definita in sviluppo.
L'elenco è anche in **Il mio profilo → Scorciatoie** ([Preferenze utente](Preferenze-utente)). Le varianti con `Alt`
esistono perché i browser non passano alla pagina `Ctrl+W`, `Ctrl+Tab` e `Ctrl+N` (ADR 0020).
## Permessi e licenza
@@ -289,6 +348,7 @@ un permesso negato.
amministratore.
- **Ho chiuso una scheda per sbaglio.** Se c'erano modifiche non salvate Khaemhat ti ha chiesto conferma; il
documento salvato si ritrova con **Recenti** o con `Ctrl+K`.
- **`Ctrl+W` chiude il browser invece della scheda.** È il browser che tiene per sé la combinazione: usa `Alt+W`.
- **Il menu si è compresso da solo.** Sotto i 1100 px di larghezza il menu parte compresso; allarga la finestra o
premi `Ctrl+B`.
+6 -1
View File
@@ -1,8 +1,13 @@
# Istanza e database
> **Stato:** bozza · **Ultima revisione:** 2026-11-10 · **Versione software:** non ancora rilasciata (milestone M2 e M12)
> **Stato:** parziale · **Ultima revisione:** 2026-11-11 · **Versione software:** 0.2.0 (milestone M2 e M12)
> **Modulo di licenza:** CORE (aziende oltre la prima: MULTI) · **Livello richiesto:** amministratore; azioni distruttive solo super utente · **Specifica:** SPEC §5.3, §5.4, §7.1, §12.1, §13
> **Nella versione 0.2.0** ci sono la creazione della prima azienda al primo avvio, la creazione e il collegamento
> di altre aziende (dal codice, con il modulo MULTI), gli stati *attiva / manutenzione / sola lettura / disattivata*
> con le sessioni chiuse quando un'azienda va in manutenzione e il contesto azienda per pagine e API (header
> `X-Company`). Le schermate descritte qui arrivano in M12.
## A cosa serve
Un'installazione di Khaemhat (una **istanza**, cioè un container) può servire più aziende. Ogni azienda ha il
+6 -1
View File
@@ -1,8 +1,13 @@
# Licenze e moduli
> **Stato:** bozza · **Ultima revisione:** 2026-11-10 · **Versione software:** non ancora rilasciata (milestone M2)
> **Stato:** parziale · **Ultima revisione:** 2026-11-11 · **Versione software:** 0.2.0 (milestone M2)
> **Modulo di licenza:** CORE · **Livello richiesto:** super utente (attivazione); amministratore (consultazione) · **Specifica:** SPEC §1.8, §6, §8, §12.2
> **Nella versione 0.2.0** ci sono verifica e applicazione della licenza: trial di 60 giorni, file `.khl` firmati
> (ECDSA P-256) da `KHAEMHAT_LICENSE` o caricati, codici di attivazione dei moduli, modalità test con i codici
> fittizi, controllo orario della scadenza con notifiche, limite di aziende e di utenti contemporanei. La schermata
> **Licenze e moduli** arriva in M12.
## A cosa serve
Khaemhat è diviso in **moduli** attivabili con licenza. La pagina **Licenze e moduli** mostra la licenza
+6 -1
View File
@@ -1,8 +1,13 @@
# Log
> **Stato:** bozza · **Ultima revisione:** 2026-11-10 · **Versione software:** non ancora rilasciata (milestone M2)
> **Stato:** parziale · **Ultima revisione:** 2026-11-11 · **Versione software:** 0.2.0 (milestone M2)
> **Modulo di licenza:** CORE · **Livello richiesto:** amministratore · **Specifica:** SPEC §7.3, §9.5, §12.7
> **Nella versione 0.2.0** il log è scritto nel database di sistema (`sys_log`) con sezione, livello, utente,
> azienda e identificativo di traccia (header `X-Trace-Id`), oltre che su console in JSON; la retention per livello
> gira ogni notte. La schermata **Log** con filtri e regole di avviso arriva in M12: fino ad allora si legge il log
> del container.
## A cosa serve
Il **log applicativo** registra ciò che succede in Khaemhat: accessi, documenti emessi, invii SDI, backup,
+10 -6
View File
@@ -1,12 +1,13 @@
# Modello dati
> **Stato:** bozza · **Ultima revisione:** 2026-11-10 · **Versione software:** non ancora rilasciata (milestone M1 e seguenti)
> **Stato:** bozza · **Ultima revisione:** 2026-11-11 · **Versione software:** 0.1.0 (strato dati, M1); le tabelle funzionali arrivano con le milestone successive
> **Specifica:** SPEC §5, §11, §13, §14
Come Khaemhat organizza i dati, in sintesi. L'elenco completo di tabelle e colonne è in
[docs/DATA-MODEL.md](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/src/branch/main/docs/DATA-MODEL.md): oggi è
la versione **pianificata**; dalla milestone M1 sarà generato automaticamente dal codice, quindi sempre allineato al
programma.
[docs/DATA-MODEL.md](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/src/branch/main/docs/DATA-MODEL.md). La sua
sezione *Schema attuale* è **generata automaticamente** dalle migrazioni del programma, quindi è sempre allineata a
ciò che il programma crea davvero nei database; le altre sezioni descrivono le tabelle **pianificate**, che compaiono
nello schema attuale man mano che le milestone le realizzano.
## Due tipi di database
@@ -62,8 +63,11 @@ settimana).
Quando una nuova versione cambia la struttura dei dati, Khaemhat applica da solo le **migrazioni**: il database di
sistema all'avvio, le aziende all'avvio o dal pannello **Amministrazione → Istanza e database**, mettendo l'azienda in
manutenzione per il tempo necessario. Non è possibile tornare a una versione precedente dello schema: per questo prima
di ogni aggiornamento conviene un backup ([Aggiornamento](Aggiornamento), [Backup-e-ripristino](Backup-e-ripristino)).
manutenzione per il tempo necessario. Ogni migrazione è applicata
per intero o per niente, e più copie del programma avviate insieme non la applicano due volte. Non è possibile
tornare a una versione precedente dello schema: se il database contiene una migrazione che il programma non conosce
(per esempio dopo aver rimesso un'immagine più vecchia) Khaemhat si rifiuta di partire invece di rischiare i dati.
Per questo prima di ogni aggiornamento conviene un backup ([Aggiornamento](Aggiornamento), [Backup-e-ripristino](Backup-e-ripristino)).
## Pagine correlate
+46 -33
View File
@@ -1,6 +1,6 @@
# Preferenze utente (Il mio profilo)
> **Stato:** bozza · **Ultima revisione:** 2026-11-10 · **Versione software:** non ancora rilasciata (milestone M3)
> **Stato:** completa · **Ultima revisione:** 2026-11-11 · **Versione software:** 0.3.0 (milestone M3)
> **Modulo di licenza:** CORE · **Specifica:** SPEC §7.3, §10.6, §11.12 (preferenze), §12 (Il mio profilo)
**Il mio profilo** raccoglie tutto ciò che riguarda te come utente: aspetto dell'interfaccia (tema, colore di
@@ -9,25 +9,32 @@ salvati e notifiche. Ogni utente può modificare il proprio profilo senza permes
## Dove si trova
Menu utente in alto a destra (iniziali e nome) → **Il mio profilo**. Il percorso mostrato nella maschera è
*Utente → Preferenze*.
Menu utente in alto a destra (iniziali e nome) → **Il mio profilo**, **Aspetto e colori** o **Sessioni attive**;
oppure `Ctrl+K` e il comando corrispondente. L'indirizzo è `/profilo`, con `?scheda=aspetto`, `pagina-iniziale`,
`sessioni` o `scorciatoie` per aprire direttamente una scheda.
![008 · Preferenze utente · tema notturno e 8 colori di accento](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/mockups/png/008-preferenze-tema-colori.png)
*Mockup 008 — scheda Aspetto con tema Scuro (notturno) e accento Ocra selezionati; a destra l'anteprima dal vivo.*
![Khaemhat 0.3.0 · Il mio profilo, Aspetto](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/preferenze-profilo.png)
*Khaemhat 0.3.0 — la scheda Aspetto con tema Automatico e accento Nilo, i valori di partenza. Ogni scelta si applica subito alla finestra.*
## Schede della maschera
| Scheda | Contenuto |
|---|---|
| **Aspetto** | tema, colore di accento, densità, dimensione testo, menu laterale, suggerimenti, animazioni |
| **Dati personali** | nome, e-mail e altri dati del tuo utente |
| **Password e 2FA** | cambio password, attivazione della verifica in due passaggi |
| **Sessioni** | dispositivi collegati con il tuo utente (il numero accanto al titolo indica quante sono) |
| **Pagina iniziale** | cosa aprire all'accesso, dashboard sì/no |
| **Layout salvati** | filtri e disposizioni di colonne memorizzati nei radar e nelle griglie |
| **Notifiche** | quali notifiche ricevere e il riepilogo via e-mail |
| Scheda | Contenuto | Disponibile |
|---|---|---|
| **Aspetto** | tema, colore di accento, densità, dimensione testo, menu laterale, suggerimenti, animazioni | 0.3.0 |
| **Pagina iniziale** | cosa aprire all'accesso, dashboard sì/no | 0.3.0 |
| **Sessioni** | dispositivi collegati con il tuo utente, chiusura | 0.3.0 |
| **Scorciatoie** | l'elenco delle scorciatoie da tastiera | 0.3.0 |
| **Dati personali** | nome, e-mail e altri dati del tuo utente | 0.3.0 |
| **Password e 2FA** | cambio password, attivazione della verifica in due passaggi | 0.3.0 |
| **Layout salvati** | filtri e disposizioni di colonne memorizzati nei radar e nelle griglie | non ancora |
| **Notifiche** | quali notifiche ricevere e il riepilogo via e-mail | non ancora |
In alto a destra: **Ripristina** (torna ai valori predefiniti) e **Salva**.
In alto a destra: **Valori predefiniti**, **Annulla le modifiche** e **Salva**. Ogni scelta si vede **subito** sulla
pagina; solo **Salva** la conserva. Finché non salvi, la scheda mostra il pallino delle modifiche; chiudendola senza
salvare torna l'aspetto di prima.
## Aspetto
@@ -35,12 +42,13 @@ In alto a destra: **Ripristina** (torna ai valori predefiniti) e **Salva**.
| Tema | Descrizione |
|---|---|
| **Chiaro** | sfondo chiaro, barra superiore scura (predefinito) |
| **Automatico** | segue l'impostazione chiaro/scuro del sistema operativo (predefinito) |
| **Chiaro** | sfondo chiaro, barra superiore scura |
| **Scuro (notturno)** | sfondi scuri e colori attenuati, per lavorare con poca luce |
| **Automatico** | segue l'impostazione chiaro/scuro del sistema operativo |
| **Alto contrasto** | contrasto massimo per chi ha esigenze visive (livello AAA) |
Prima dell'accesso (pagina di login) vale il tema del sistema operativo. Le **stampe e i PDF sono sempre in tema
Prima dell'accesso (pagina di login) vale il tema del sistema operativo. Dopo l'accesso il tema scelto è già nella
pagina che arriva dal server, senza lampeggi. Le **stampe e i PDF sono sempre in tema
chiaro**, qualunque sia il tema scelto.
Il cambio tema rapido (sole/luna) nella barra superiore passa tra chiaro e scuro senza aprire il profilo.
@@ -68,9 +76,9 @@ I valori esatti dei colori sono nella pagina [Design UI](Design-UI).
| Impostazione | Valori |
|---|---|
| **Densità** | *Comoda* (righe da 30 px, predefinita) o *Compatta* (righe da 26 px, testo e spaziature più piccoli): con la compatta in una griglia stanno più righe |
| **Dimensione testo** | *Normale* (13 px) e altre misure che saranno definite in sviluppo |
| **Menu laterale** | *Espanso (ricorda l'ultimo stato)* o compresso all'avvio |
| **Carattere numerico tabellare** | cifre di larghezza fissa negli importi, così le colonne restano allineate |
| **Dimensione testo** | *100%* (13 px, predefinita), *110%*, *120%* |
| **Menu laterale** | *Automatico* (compresso sotto i 1100 px, poi ricorda l'ultimo stato), *Espanso*, *Compresso* |
| **Numeri tabellari** | cifre di larghezza fissa negli importi, così le colonne restano allineate (attivo) |
Interruttori:
@@ -78,8 +86,8 @@ Interruttori:
- **Evidenzia riga sotto il cursore nelle griglie**.
- **Animazioni ridotte** — riduce transizioni e movimenti.
Il riquadro **Anteprima** a destra mostra subito l'effetto delle scelte su una toolbar, alcuni campi, una griglia e
i badge di stato (*Bozza*, *Confermato*, *Emessa*, *Attenzione*, *Scartata*).
Al posto del riquadro **Anteprima** del mockup, l'anteprima è la pagina stessa: ogni scelta si applica subito a
tutta l'interfaccia.
## Dati personali
@@ -99,34 +107,39 @@ non si cambiano da qui: li assegna un amministratore ([Utenti e permessi](Utenti
## Sessioni
Elenco delle sessioni aperte con il tuo utente: dispositivo, indirizzo IP, data di inizio e ultima attività. Puoi
**chiudere** (revocare) una sessione che non riconosci. Un accesso da un **nuovo dispositivo** genera una notifica
Elenco delle sessioni aperte con il tuo utente: dispositivo (browser e sistema), indirizzo IP, azienda, data di
accesso e ultima attività; la sessione da cui stai lavorando è segnata come *Questa sessione*. Puoi **chiudere**
(revocare) una sessione che non riconosci, o **chiuderle tutte tranne questa**: il dispositivo dovrà accedere di
nuovo alla richiesta successiva. Un accesso da un **nuovo dispositivo** genera una notifica
di sicurezza. Le sessioni scadono dopo un periodo di inattività (scadenza scorrevole) e contano nel numero di utenti
contemporanei previsto dalla licenza.
## Pagina iniziale
- **All'accesso apri**: *Dashboard*, *ultima scheda aperta*, un *radar* (ad esempio Clienti), la *prima nota*,
l'*agenda*…
- **All'accesso apri**: *la pagina iniziale*, *le schede aperte l'ultima volta* (si riapre quella attiva), oppure
*una pagina a scelta* fra quelle del menu che puoi aprire.
- **Mostra la dashboard**: sì/no. Vedi [Dashboard](Dashboard).
## Layout salvati
Qui trovi i **filtri salvati** (stella nei radar) e le **disposizioni delle colonne** delle griglie che hai
memorizzato, con la possibilità di eliminarli (le altre operazioni, come rinomina o scelta del predefinito, saranno
definite in sviluppo). Il numero accanto al titolo della scheda indica quanti sono.
La scheda raccoglierà i **filtri salvati** (stella nei radar) e le **disposizioni delle colonne** delle griglie che
hai memorizzato, con la possibilità di eliminarli. **In questa versione** filtri e colonne si salvano e si eliminano
direttamente dal radar e dalla griglia; la scheda nel profilo arriva con le prime maschere che li usano davvero
(anagrafiche, M4).
## Notifiche
Scegli quali notifiche ricevere in app (documenti, SDI, scadenze, magazzino, sicurezza, attività programmate…) e se
ricevere anche un **riepilogo via e-mail** (digest). L'elenco preciso delle categorie e quali di esse siano
obbligatorie saranno definiti in sviluppo. Vedi anche
La scheda permetterà di scegliere quali notifiche ricevere in app (documenti, SDI, scadenze, magazzino, sicurezza,
attività programmate…) e se ricevere anche un **riepilogo via e-mail** (digest). **In questa versione** arrivano
tutte le notifiche previste per il tuo ruolo e non c'è il riepilogo via e-mail: categorie e scelte arrivano con
l'invio delle e-mail (M5). Vedi anche
[Interfaccia e scorciatoie](Interfaccia-e-scorciatoie) (pannello notifiche).
## Dove sono salvate le preferenze
Le preferenze sono salvate **nel database dell'azienda** e valgono su ogni dispositivo da cui accedi. Le preferenze
esistono su tre livelli:
Le preferenze sono salvate **nel database**, non nel browser, e valgono su ogni dispositivo da cui accedi: per gli
utenti aziendali nel database dell'azienda (tabella `user_settings`), per gli account di istanza (super utente,
amministratori) nel database di sistema (`sys_user_settings`). Le preferenze esistono su tre livelli:
| Livello | Esempi | Chi le cambia |
|---|---|---|
+28 -14
View File
@@ -1,6 +1,6 @@
# Primi passi
> **Stato:** bozza · **Ultima revisione:** 2026-11-10 · **Versione software:** non ancora rilasciata (milestone M2-M5)
> **Stato:** parziale (passi 1-4 completi) · **Ultima revisione:** 2026-11-11 · **Versione software:** 0.2.0 (passi 1-4), passi successivi M3-M5
> **Modulo di licenza:** CORE · **Livello richiesto:** super utente, poi amministratore · **Specifica:** SPEC §5.4, §7, §8, §12, §14
Questa pagina accompagna chi ha appena installato Khaemhat dal primo avvio del container fino alla prima fattura
@@ -57,15 +57,20 @@ disattivata al primo cambio password.
*Mockup 001 — pagina di accesso: a sinistra marca e funzioni principali, a destra il modulo con azienda, nome utente,
password e l'avviso della modalità Trial (anteprima ridotta).*
1. Nel campo **Azienda** scegli la prima azienda (quella creata dal container, ad esempio *Khaemhat Demo S.r.l.*).
1. Nel campo **Azienda** lascia la prima azienda, già proposta (quella creata dal container, ad esempio
*Khaemhat Demo S.r.l.*). Il super utente e gli amministratori possono anche scegliere **Nessuna (account di
istanza)** per lavorare solo sulle pagine di amministrazione dell'istanza.
2. In **Nome utente** scrivi il nome del super utente (`KHAEMHAT_SUPERUSER`, predefinito `root`).
3. In **Password** scrivi la password iniziale (`KHAEMHAT_SUPERUSER_PASSWORD`).
4. Spunta **Ricordami su questo dispositivo** solo su un computer personale.
5. Premi **Accedi**.
Il riquadro giallo in fondo al modulo ricorda che l'istanza è in **modalità Trial** finché non attivi una licenza
(passo 6). Il collegamento **Password dimenticata?** invia un link monouso all'indirizzo e-mail registrato; funziona
solo dopo aver configurato la posta (SMTP) in **Amministrazione → Impostazioni**.
(passo 6). Il collegamento **Password dimenticata?** invia un link monouso all'indirizzo e-mail registrato; arriva con
la posta (SMTP) in una milestone successiva: nella versione 0.2.0 non è ancora presente.
Dopo 5 tentativi sbagliati l'account resta bloccato per 15 minuti; da uno stesso indirizzo IP sono accettati al
massimo 10 invii al minuto del modulo di accesso.
## Passo 3 — Cambio password obbligatorio
@@ -74,11 +79,15 @@ solo dopo aver configurato la posta (SMTP) in **Amministrazione → Impostazioni
*Mockup 003 — cambio password al primo accesso, con indicatore di robustezza e avviso che la password del container
viene disattivata (anteprima ridotta).*
1. In **Password attuale (provvisoria)** riscrivi la password iniziale.
1. In **Password attuale o provvisoria** riscrivi la password iniziale.
2. In **Nuova password** scrivi la nuova password. La regola predefinita chiede almeno **10 caratteri** e **3 classi**
(lettere, numeri, simboli) e non ammette nessuna delle ultime 5 password usate.
3. Ripetila in **Conferma nuova password** e controlla la barra **Robustezza**.
4. Premi **Imposta password e continua**.
(minuscole, maiuscole, numeri, simboli), non deve contenere il nome utente e non ammette nessuna delle ultime 5
password usate.
3. Ripetila in **Ripeti la nuova password**.
4. Premi **Salva e continua**.
Nella versione 0.2.0 la pagina è più essenziale del mockup 003: l'indicatore di robustezza arriva con l'interfaccia
completa (M3).
Da questo momento la password scritta nelle variabili del container non vale più. Puoi toglierla dal file `.env` o
dal template: non viene più letta.
@@ -87,12 +96,15 @@ dal template: non viene più letta.
Per il super utente e per gli amministratori la verifica in due passaggi è **obbligatoria** (SPEC §7.3). Al primo
accesso Khaemhat chiede di collegare un'app di autenticazione (qualunque app compatibile con lo standard TOTP,
RFC 6238). La schermata di attivazione non è tra i mockup: il formato esatto (chiave testuale e/o codice QR) sarà
definito in sviluppo.
RFC 6238). La schermata **Configura la verifica in due passaggi** non è tra i mockup (ADR 0019): mostra la chiave
in gruppi di quattro caratteri e il collegamento **Apri nell'app di autenticazione** (`otpauth://`), utile sul
telefono. Non c'è un codice QR, perché generarlo richiederebbe una libreria esterna (SPEC §1.2).
1. Apri l'app di autenticazione sul telefono e aggiungi un nuovo account con la chiave mostrata da Khaemhat.
2. Scrivi in Khaemhat il codice a 6 cifre generato dall'app per confermare il collegamento.
3. Conserva in un luogo sicuro le eventuali informazioni di recupero proposte.
1. Apri l'app di autenticazione (Google Authenticator, Microsoft Authenticator, Aegis, 2FAS…) e aggiungi un nuovo
account scrivendo la chiave mostrata da Khaemhat, oppure tocca **Apri nell'app di autenticazione** dal telefono.
2. In **Primo codice dell'app** scrivi le 6 cifre generate dall'app e premi **Attiva**.
3. Khaemhat mostra **10 codici di recupero**: copiali in un luogo sicuro. Ognuno vale una volta sola al posto del
codice dell'app e non verrà mostrato di nuovo. Poi premi **Ho salvato i codici, continua**.
![002 · Accesso · verifica in due passaggi (TOTP)](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/mockups/thumbs/002-accesso-2fa.png)
@@ -102,8 +114,10 @@ ogni 30 secondi (anteprima ridotta).*
Agli accessi successivi, dopo la password, compare la schermata **Verifica in due passaggi**: scrivi le 6 cifre
mostrate dall'app e premi **Verifica**. Il codice cambia ogni 30 secondi.
Al posto delle 6 cifre puoi scrivere uno dei codici di recupero.
> **Attenzione.** Se perdi il telefono con l'app e sei il super utente, nessun altro può reimpostare il tuo accesso
> dall'interfaccia. Tieni una copia sicura della chiave TOTP o delle informazioni di recupero.
> dall'interfaccia. Tieni al sicuro i codici di recupero.
## Passo 5 — Creare un amministratore
+3 -1
View File
@@ -1,6 +1,6 @@
# Roadmap
> **Stato:** bozza · **Ultima revisione:** 2026-11-10 · **Specifica:** SPEC §20
> **Stato:** bozza · **Ultima revisione:** 2026-11-11 · **Specifica:** SPEC §20
Khaemhat si costruisce in **15 milestone**. Ogni milestone si chiude con un tag di versione, un'immagine Docker nel
registro pacchetti di Gitea e la wiki delle funzioni consegnate portata da *bozza* a *completa*.
@@ -10,6 +10,8 @@ Il lavoro di dettaglio è nelle issue di Gitea, raggruppate per
[progetti](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/projects) *Khaemhat 1.0 — Sviluppo* e
*Khaemhat 1.1+ — Fase 2*.
**Completate:** M0 (0.0.1), M1 (0.1.0), M2 (0.2.0), M3 (0.3.0). **In corso:** M4.
| # | Milestone | Contenuto principale | Versione |
|---|---|---|---|
| M0 | Bootstrap | Soluzione e progetti, regole di build e allowlist, Dockerfile e compose con pagina "in costruzione", `/health`, Gitea Actions (`ci.yml`, `release.yml`, `wiki.yml`), script, ADR | 0.0.1 |
+7 -1
View File
@@ -1,8 +1,14 @@
# Utenti e permessi
> **Stato:** bozza · **Ultima revisione:** 2026-11-10 · **Versione software:** non ancora rilasciata (milestone M2)
> **Stato:** parziale · **Ultima revisione:** 2026-11-11 · **Versione software:** 0.2.0 (milestone M2)
> **Modulo di licenza:** CORE · **Livello richiesto:** amministratore (amministratori: solo super utente) · **Permessi principali:** `company.users.manage` · **Specifica:** SPEC §7, §12.3, §12.4
> **Nella versione 0.2.0** ci sono il motore e l'accesso: i tre livelli, gli account di istanza e gli utenti di
> azienda, password con storico e blocco, verifica in due passaggi con codici di recupero, sessioni revocabili, ruoli
> predefiniti e permessi `modulo.area.azione` con override, controlli sulle pagine (`[RequirePermission]`,
> `[RequireLevel]`, `[RequireModule]`). Le schermate **Utenti** e **Ruoli e permessi** descritte qui arrivano in M12:
> fino ad allora gli utenti si gestiscono solo con il super utente creato dal container.
## A cosa serve
Queste due pagine stabiliscono **chi entra** in Khaemhat e **cosa può fare**:
Binary file not shown.

After

Width:  |  Height:  |  Size: 122 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 119 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 84 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 159 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 93 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 89 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 215 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 89 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 74 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 54 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 98 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 101 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 99 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 93 KiB

+7 -6
View File
@@ -1,9 +1,10 @@
#!/usr/bin/env bash
# Regenerates docs/DATA-MODEL.md from the entity maps (SPEC §18).
# scripts/gen-datamodel.sh
# Stub: completed in milestone M1 (SPEC §20). Until then it explains what it will do and exits with an error.
# Regenerates the generated section of docs/DATA-MODEL.md from the migrations (SPEC §18).
# scripts/gen-datamodel.sh rewrite the section
# scripts/gen-datamodel.sh --check only verify it is up to date (exit 1 if not)
set -euo pipefail
echo "gen-datamodel.sh: non ancora disponibile, arriva con la milestone M1." >&2
echo "Uso previsto: scripts/gen-datamodel.sh" >&2
exit 1
root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
cd "$root"
dotnet run --project tools/Khaemhat.DataModelTool -c Release -- "$@" docs/DATA-MODEL.md
+84 -5
View File
@@ -1,9 +1,88 @@
#!/usr/bin/env bash
# Creates a new numbered migration for the system or company schema (SPEC §5.3).
# scripts/new-migration.sh <system|company> <descrizione-breve>
# Stub: completed in milestone M1 (SPEC §20). Until then it explains what it will do and exits with an error.
# scripts/new-migration.sh <system|company> <nome_snake_case> [cartella] [modulo]
# Example: scripts/new-migration.sh system create_sys_users
# The version is today's date plus the next free number of the day across the repository (yyyymmdd_nnn); the
# class is M<yyyymmdd>_<nnn>_<NomePascal> in the given folder (default: the system or company migrations folder).
set -euo pipefail
echo "new-migration.sh: non ancora disponibile, arriva con la milestone M1." >&2
echo "Uso previsto: scripts/new-migration.sh <system|company> <descrizione-breve>" >&2
exit 1
root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
cd "$root"
usage() {
echo "Uso: scripts/new-migration.sh <system|company> <nome_snake_case> [cartella] [modulo]" >&2
exit 2
}
[ $# -ge 2 ] || usage
target="$1"
name="$2"
module="${4:-core}"
case "$target" in
system) dir="${3:-src/Khaemhat.Data/SystemDatabase/Migrations}"; attribute_target="MigrationTarget.System" ;;
company) dir="${3:-src/Khaemhat.Application/Migrations}"; attribute_target="MigrationTarget.Company" ;;
*) usage ;;
esac
if ! [[ "$name" =~ ^[a-z][a-z0-9_]{0,62}$ ]]; then
echo "Il nome deve essere snake_case (lettere minuscole, cifre, _): $name" >&2
exit 2
fi
if ! [[ "$module" =~ ^[a-z][a-z0-9_]{0,39}$ ]]; then
echo "Il modulo deve essere snake_case: $module" >&2
exit 2
fi
if [[ "$dir" != src/* ]]; then
echo "La cartella deve stare sotto src/: $dir" >&2
exit 2
fi
day="$(date +%Y%m%d)"
last="$(grep -rhoE "\[Migration\(${day}_[0-9]{3}" src --include='*.cs' 2>/dev/null | sed -E 's/.*_([0-9]{3})$/\1/' | sort -n | tail -1 || true)"
next=$(printf '%03d' $((10#${last:-0} + 1)))
pascal="$(echo "$name" | awk -F_ '{ for (i = 1; i <= NF; i++) printf "%s%s", toupper(substr($i, 1, 1)), substr($i, 2) }')"
class="M${day}_${next}_${pascal}"
namespace="$(echo "${dir#src/}" | tr '/' '.')"
file="$dir/$class.cs"
mkdir -p "$dir"
if [ -e "$file" ]; then
echo "Esiste già: $file" >&2
exit 1
fi
if [ "$attribute_target" = "MigrationTarget.Company" ]; then
target_argument=""
else
target_argument=", Target = $attribute_target"
fi
if [ "$module" = "core" ]; then
module_argument=""
else
module_argument=", Module = \"$module\""
fi
cat > "$file" <<CS
using Khaemhat.Data.Migrations;
using Khaemhat.Data.Schema;
namespace $namespace;
/// <summary>TODO: what this migration changes and why (SPEC section).</summary>
[Migration(${day}_${next}, "$name"$target_argument$module_argument)]
public sealed class $class : IMigration
{
/// <inheritdoc />
public void Up(ISchemaBuilder schema)
{
ArgumentNullException.ThrowIfNull(schema);
// schema.CreateTable("table_name", t => { t.Id(); t.AuditColumns(); });
}
}
CS
echo "Creata $file (versione ${day}_${next}, modulo $module)."
echo "Dopo averla scritta: aggiornare la mappa dell'entità, eseguire scripts/gen-datamodel.sh e i test."
@@ -0,0 +1,124 @@
using System.Diagnostics;
using System.Globalization;
using System.Reflection;
using System.Text.Json;
using Khaemhat.Core.Entities;
using Khaemhat.Core.Instance;
using Khaemhat.Data;
using Khaemhat.Data.Querying;
namespace Khaemhat.Application.Audit;
/// <summary>What happened to a record.</summary>
public enum AuditAction
{
/// <summary>Created.</summary>
Insert = 0,
/// <summary>Changed.</summary>
Update = 1,
/// <summary>Deleted.</summary>
Delete = 2,
}
/// <summary>
/// The history of the records of a company (SPEC §7.4): every insert, update and delete of master data, documents,
/// entries and settings writes a row in the company's <c>audit_log</c>, in the same unit of work as the change, with the
/// changed fields as JSON <c>{"Field": [old, new]}</c>. Audit columns and secrets are never written.
/// </summary>
public sealed class AuditTrail(TimeProvider clock)
{
private static readonly HashSet<string> Skipped = new(StringComparer.Ordinal)
{
nameof(IAuditable.CreatedAt), nameof(IAuditable.CreatedBy), nameof(IAuditable.UpdatedAt), nameof(IAuditable.UpdatedBy), "RowVersion",
"PasswordHash", "PasswordHistory", "TotpSecret", "TotpRecoveryCodes", "RecoveryTokenHash", "TokenHash", "ConnectionString",
};
/// <summary>Writes the history row of a change, inside the caller's unit of work.</summary>
/// <typeparam name="T">The entity type.</typeparam>
/// <param name="unitOfWork">The company unit of work holding the change.</param>
/// <param name="action">What happened.</param>
/// <param name="entityId">The record.</param>
/// <param name="before">The record before (updates and deletes).</param>
/// <param name="after">The record after (inserts and updates).</param>
/// <param name="userName">Who did it.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns><see langword="true"/> when a row was written (an update that changes nothing writes none).</returns>
public async Task<bool> RecordAsync<T>(
IUnitOfWork unitOfWork, AuditAction action, object entityId, T? before, T? after, string? userName, CancellationToken cancellationToken = default)
where T : class
{
ArgumentNullException.ThrowIfNull(unitOfWork);
ArgumentNullException.ThrowIfNull(entityId);
var diff = Diff(before, after);
if (action == AuditAction.Update && diff.Count == 0)
{
return false;
}
await unitOfWork.Repository<AuditEntry, long>().InsertAsync(
new AuditEntry
{
At = clock.GetUtcNow().UtcDateTime,
Entity = typeof(T).Name,
EntityId = Convert.ToString(entityId, CultureInfo.InvariantCulture) ?? string.Empty,
Action = action.ToString(),
UserName = userName,
Diff = JsonSerializer.Serialize(diff),
TraceId = Activity.Current?.TraceId.ToString(),
},
cancellationToken).ConfigureAwait(false);
return true;
}
/// <summary>The history of a record, newest first (the "Storico" panel).</summary>
/// <param name="unitOfWork">A company unit of work.</param>
/// <param name="entity">The entity name.</param>
/// <param name="entityId">The record.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The rows.</returns>
public static async Task<IReadOnlyList<AuditEntry>> HistoryAsync(IUnitOfWork unitOfWork, string entity, string entityId, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(unitOfWork);
return (await unitOfWork.Repository<AuditEntry, long>().ListAsync(
Query.For<AuditEntry>().Where(a => a.Entity == entity && a.EntityId == entityId).OrderByDescending(a => a.Id), cancellationToken).ConfigureAwait(false)).Items;
}
/// <summary>The changed fields between two versions of a record.</summary>
/// <typeparam name="T">The entity type.</typeparam>
/// <param name="before">The old version, or <see langword="null"/>.</param>
/// <param name="after">The new version, or <see langword="null"/>.</param>
/// <returns>Field name to <c>[old, new]</c>.</returns>
public static IReadOnlyDictionary<string, object?[]> Diff<T>(T? before, T? after)
where T : class
{
var result = new SortedDictionary<string, object?[]>(StringComparer.Ordinal);
foreach (var property in typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance))
{
if (!property.CanRead || property.GetIndexParameters().Length > 0 || Skipped.Contains(property.Name))
{
continue;
}
var old = before is null ? null : Simple(property.GetValue(before));
var current = after is null ? null : Simple(property.GetValue(after));
if (!Equals(old, current))
{
result[property.Name] = [old, current];
}
}
return result;
}
private static object? Simple(object? value) => value switch
{
null => null,
string or bool or int or long or decimal or double => value,
DateTime date => date.ToString("O", CultureInfo.InvariantCulture),
Enum e => e.ToString(),
IFormattable formattable => formattable.ToString(null, CultureInfo.InvariantCulture),
_ => value.ToString(),
};
}
@@ -0,0 +1,103 @@
using System.Text.Json;
using Khaemhat.Application.Security;
using Khaemhat.Core.Instance;
using Khaemhat.Data;
namespace Khaemhat.Application.Audit;
/// <summary>A changed field in the history of a record.</summary>
/// <param name="Field">The field name.</param>
/// <param name="Before">The old value as text; <see langword="null"/> when empty.</param>
/// <param name="After">The new value as text; <see langword="null"/> when empty.</param>
public sealed record AuditChange(string Field, string? Before, string? After);
/// <summary>A row of the history of a record (the <i>Storico</i> tab, <c>KhAuditList</c>).</summary>
/// <param name="Id">The row.</param>
/// <param name="At">When (UTC).</param>
/// <param name="Action">What happened.</param>
/// <param name="UserName">Who did it.</param>
/// <param name="Changes">The changed fields.</param>
public sealed record AuditItem(long Id, DateTime At, AuditAction Action, string? UserName, IReadOnlyList<AuditChange> Changes);
/// <summary>Reads the history written by <see cref="AuditTrail"/> for the interface (SPEC §7.4).</summary>
/// <param name="factory">The units of work.</param>
/// <param name="permissions">The permissions.</param>
public sealed class AuditTrailService(IUnitOfWorkFactory factory, PermissionService permissions)
{
/// <summary>The most rows shown.</summary>
public const int MaxItems = 200;
/// <summary>The history of a record, newest first.</summary>
/// <param name="actor">Who asks.</param>
/// <param name="companyCode">The company.</param>
/// <param name="entity">The entity, as written by the audit trail (the type name, such as <c>Attachment</c>).</param>
/// <param name="entityId">The record.</param>
/// <param name="readPermission">The permission that lets the actor read the record.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>At most <see cref="MaxItems"/> rows.</returns>
public async Task<IReadOnlyList<AuditItem>> HistoryAsync(
Actor actor, string companyCode, string entity, string entityId, string readPermission, CancellationToken cancellationToken = default)
{
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, readPermission, cancellationToken).ConfigureAwait(false);
await using var unitOfWork = await factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
var rows = await AuditTrail.HistoryAsync(unitOfWork, entity, entityId, cancellationToken).ConfigureAwait(false);
return [.. rows.Take(MaxItems).Select(Item)];
}
/// <summary>A row of the history, with the changes read from their JSON.</summary>
/// <param name="entry">The row.</param>
/// <returns>The item.</returns>
public static AuditItem Item(AuditEntry entry)
{
ArgumentNullException.ThrowIfNull(entry);
var action = Enum.TryParse<AuditAction>(entry.Action, out var parsed) ? parsed : AuditAction.Update;
return new AuditItem(entry.Id, entry.At, action, entry.UserName, Changes(entry.Diff));
}
private static List<AuditChange> Changes(string? diff)
{
var changes = new List<AuditChange>();
if (string.IsNullOrWhiteSpace(diff))
{
return changes;
}
try
{
using var document = JsonDocument.Parse(diff);
if (document.RootElement.ValueKind != JsonValueKind.Object)
{
return changes;
}
foreach (var field in document.RootElement.EnumerateObject())
{
var values = field.Value.ValueKind == JsonValueKind.Array ? field.Value.EnumerateArray().ToList() : [];
changes.Add(new AuditChange(field.Name, Text(values.ElementAtOrDefault(0)), Text(values.ElementAtOrDefault(1))));
}
}
catch (JsonException)
{
// A row written by hand or damaged: show the action without the fields.
}
return changes;
}
private static string? Text(JsonElement value) => value.ValueKind switch
{
JsonValueKind.Undefined or JsonValueKind.Null => null,
JsonValueKind.String => value.GetString() is { Length: > 0 } text ? text : null,
JsonValueKind.True => "true",
JsonValueKind.False => "false",
JsonValueKind.Number => value.GetRawText(),
_ => value.GetRawText(),
};
}
@@ -0,0 +1,122 @@
using System.Globalization;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
using Khaemhat.Core.Instance;
using Khaemhat.Data;
using Khaemhat.Data.Querying;
namespace Khaemhat.Application.Audit;
/// <summary>A security or instance action to record.</summary>
/// <param name="Action">The action code, for example <c>login.succeeded</c>, <c>user.created</c>, <c>license.activated</c>.</param>
/// <param name="UserName">Who acted.</param>
/// <param name="CompanyCode">The company concerned.</param>
/// <param name="Target">What the action was about.</param>
/// <param name="Details">Further details, serialized as JSON (never secrets).</param>
/// <param name="IpAddress">The client address.</param>
public sealed record SecurityEvent(
string Action, string? UserName, string? CompanyCode = null, string? Target = null, object? Details = null, string? IpAddress = null);
/// <summary>Writes <c>sys_security_audit</c>.</summary>
public interface ISecurityAuditLog
{
/// <summary>Records an action.</summary>
/// <param name="securityEvent">The action.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
Task WriteAsync(SecurityEvent securityEvent, CancellationToken cancellationToken = default);
}
/// <summary>
/// The immutable security audit (SPEC §7.3): rows are only inserted, each with the SHA-256 of its content chained to
/// the previous row, under an application lock so that two writers never fork the chain. <see cref="VerifyAsync"/>
/// finds a changed or removed row.
/// </summary>
/// <param name="factory">Opens the system database.</param>
/// <param name="clock">The clock.</param>
public sealed class SecurityAuditLog(IUnitOfWorkFactory factory, TimeProvider clock) : ISecurityAuditLog
{
private const string LockKey = "security-audit";
/// <inheritdoc />
public async Task WriteAsync(SecurityEvent securityEvent, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(securityEvent);
var entry = new SecurityAuditEntry
{
At = Truncate(clock.GetUtcNow().UtcDateTime),
Action = Clip(securityEvent.Action, 100)!,
UserName = Clip(securityEvent.UserName, 100),
CompanyCode = Clip(securityEvent.CompanyCode, 20),
Target = Clip(securityEvent.Target, 200),
IpAddress = Clip(securityEvent.IpAddress, 64),
Details = securityEvent.Details is null ? null : JsonSerializer.Serialize(securityEvent.Details),
};
await using var unitOfWork = await factory.CreateAsync(DatabaseScope.System, cancellationToken).ConfigureAwait(false);
await unitOfWork.InTransactionAsync(
async ct =>
{
await unitOfWork.AcquireLockAsync(LockKey, ct).ConfigureAwait(false);
var repository = unitOfWork.Repository<SecurityAuditEntry, long>();
var last = await repository.FindAsync(Query.For<SecurityAuditEntry>().OrderByDescending(e => e.Id).Take(1), ct).ConfigureAwait(false);
entry.PreviousHash = last?.Hash ?? string.Empty;
entry.Hash = ComputeHash(entry);
await repository.InsertAsync(entry, ct).ConfigureAwait(false);
},
cancellationToken).ConfigureAwait(false);
}
/// <summary>Checks the whole chain.</summary>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The identifier of the first row that does not match, or <see langword="null"/> when the chain is intact.</returns>
public async Task<long?> VerifyAsync(CancellationToken cancellationToken = default)
{
await using var unitOfWork = await factory.CreateAsync(DatabaseScope.System, cancellationToken).ConfigureAwait(false);
var previous = string.Empty;
const int PageSize = 1000;
for (var offset = 0; ; offset += PageSize)
{
var page = await unitOfWork.Repository<SecurityAuditEntry, long>()
.ListAsync(Query.For<SecurityAuditEntry>().OrderBy(e => e.Id).Page(offset, PageSize), cancellationToken).ConfigureAwait(false);
foreach (var entry in page.Items)
{
if (entry.PreviousHash != previous || entry.Hash != ComputeHash(entry))
{
return entry.Id;
}
previous = entry.Hash;
}
if (page.Items.Count < PageSize)
{
return null;
}
}
}
/// <summary>The hash of a row: every field and the previous hash, separated so that fields cannot run into each other.</summary>
/// <param name="entry">The row.</param>
/// <returns>64 hexadecimal digits.</returns>
public static string ComputeHash(SecurityAuditEntry entry)
{
ArgumentNullException.ThrowIfNull(entry);
var content = string.Join(
'\u001F',
entry.PreviousHash,
DateTime.SpecifyKind(entry.At, DateTimeKind.Utc).ToString("yyyy-MM-ddTHH:mm:ss.ffffffZ", CultureInfo.InvariantCulture),
entry.Action,
entry.UserName ?? string.Empty,
entry.CompanyCode ?? string.Empty,
entry.IpAddress ?? string.Empty,
entry.Target ?? string.Empty,
entry.Details ?? string.Empty);
return Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(content)));
}
private static DateTime Truncate(DateTime value) => DateTime.SpecifyKind(new DateTime(value.Ticks - (value.Ticks % 10)), DateTimeKind.Utc);
private static string? Clip(string? value, int length) => value is null || value.Length <= length ? value : value[..length];
}
@@ -0,0 +1,116 @@
namespace Khaemhat.Application.Configuration;
/// <summary>
/// Reads the <c>KHAEMHAT_*</c> variables of SPEC §6 into <see cref="KhaemhatOptions"/>, applying the <c>_FILE</c>
/// rule of ADR 0014 to the sensitive ones: when <c>X_FILE</c> is set, the value of <c>X</c> is the content of that file
/// without the final line break; setting both is a configuration error, and so is a file that cannot be read.
/// Problems are collected in <see cref="KhaemhatOptions.ReadErrors"/>; values never appear in messages.
/// </summary>
public sealed class EnvironmentConfigurationReader
{
/// <summary>The variables that accept a <c>_FILE</c> variant (ADR 0014).</summary>
public static readonly IReadOnlySet<string> FileVariables = new HashSet<string>(StringComparer.Ordinal)
{
"KHAEMHAT_SYSTEM_DB", "KHAEMHAT_DB_SERVER", "KHAEMHAT_SECRET_KEY", "KHAEMHAT_SECRET_KEY_NEW",
"KHAEMHAT_SUPERUSER", "KHAEMHAT_SUPERUSER_PASSWORD", "KHAEMHAT_SUPERUSER_EMAIL", "KHAEMHAT_LICENSE",
"KHAEMHAT_REDIS", "KHAEMHAT_SMTP_PASSWORD", "KHAEMHAT_UPDATE_TOKEN",
};
private readonly Func<string, string?> _lookup;
private readonly Func<string, string> _readFile;
/// <summary>Creates a reader.</summary>
/// <param name="lookup">Returns a variable, or <see langword="null"/> when unset (the host configuration: environment and command line).</param>
/// <param name="readFile">Reads a secret file; the default reads from disk.</param>
public EnvironmentConfigurationReader(Func<string, string?> lookup, Func<string, string>? readFile = null)
{
ArgumentNullException.ThrowIfNull(lookup);
_lookup = lookup;
_readFile = readFile ?? File.ReadAllText;
}
/// <summary>Reads every variable.</summary>
/// <returns>The options, with the reading problems in <see cref="KhaemhatOptions.ReadErrors"/>.</returns>
public KhaemhatOptions Read()
{
var errors = new List<string>();
string? Get(string name) => Value(name, errors);
return new KhaemhatOptions
{
SystemDb = Get("KHAEMHAT_SYSTEM_DB"),
DbServer = Get("KHAEMHAT_DB_SERVER"),
SecretKey = Get("KHAEMHAT_SECRET_KEY"),
RotationSecretKey = Get("KHAEMHAT_SECRET_KEY_NEW"),
SuperUser = Get("KHAEMHAT_SUPERUSER"),
SuperUserPassword = Get("KHAEMHAT_SUPERUSER_PASSWORD"),
SuperUserEmail = Get("KHAEMHAT_SUPERUSER_EMAIL"),
CompanyCode = Get("KHAEMHAT_COMPANY_CODE"),
CompanyName = Get("KHAEMHAT_COMPANY_NAME"),
Country = Get("KHAEMHAT_COUNTRY") ?? "IT",
LicenseMode = Get("KHAEMHAT_LICENSE_MODE") ?? "production",
License = Get("KHAEMHAT_LICENSE"),
Redis = Get("KHAEMHAT_REDIS"),
DataDir = Get("KHAEMHAT_DATA_DIR") ?? "/data",
Urls = Get("KHAEMHAT_URLS"),
PublicUrl = Get("KHAEMHAT_PUBLIC_URL"),
SmtpHost = Get("KHAEMHAT_SMTP_HOST"),
SmtpPort = Get("KHAEMHAT_SMTP_PORT"),
SmtpUser = Get("KHAEMHAT_SMTP_USER"),
SmtpPassword = Get("KHAEMHAT_SMTP_PASSWORD"),
SmtpFrom = Get("KHAEMHAT_SMTP_FROM"),
SmtpSecurity = Get("KHAEMHAT_SMTP_SECURITY"),
LogLevel = Get("KHAEMHAT_LOG_LEVEL"),
SeedBase = Get("KHAEMHAT_SEED_BASE"),
SeedDemo = Get("KHAEMHAT_SEED_DEMO"),
UpdateFeed = Get("KHAEMHAT_UPDATE_FEED"),
UpdateToken = Get("KHAEMHAT_UPDATE_TOKEN"),
HelpUrl = Get("KHAEMHAT_HELP_URL"),
TimeZone = Get("TZ"),
ReadErrors = errors,
};
}
private string? Value(string name, List<string> errors)
{
var direct = Normalize(_lookup(name));
if (!FileVariables.Contains(name))
{
return direct;
}
var path = Normalize(_lookup(name + "_FILE"));
if (path is null)
{
return direct;
}
if (direct is not null)
{
errors.Add($"{name} and {name}_FILE are both set: keep only one of them.");
return null;
}
try
{
return Normalize(TrimFinalLineBreak(_readFile(path)));
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or ArgumentException or NotSupportedException)
{
errors.Add($"{name}_FILE points to a file that cannot be read ({ex.GetType().Name}): check the path and the permissions of the secret.");
return null;
}
}
private static string? Normalize(string? value) => string.IsNullOrWhiteSpace(value) ? null : value;
private static string TrimFinalLineBreak(string value)
{
if (value.EndsWith("\r\n", StringComparison.Ordinal))
{
return value[..^2];
}
return value.EndsWith('\n') ? value[..^1] : value;
}
}
@@ -0,0 +1,367 @@
using System.Globalization;
using System.Net.Mail;
using Khaemhat.Application.Security;
using Khaemhat.Data;
using Microsoft.Extensions.Logging;
namespace Khaemhat.Application.Configuration;
/// <summary>How the licences behave (<c>KHAEMHAT_LICENSE_MODE</c>).</summary>
public enum LicenseMode
{
/// <summary>Only signed licences count.</summary>
Production = 0,
/// <summary>The fictitious codes of SPEC §8.3 are accepted too. Never in production.</summary>
Test = 1,
}
/// <summary>The connection security of the mail server.</summary>
public enum SmtpSecurity
{
/// <summary>STARTTLS on a plain connection (port 587).</summary>
StartTls = 0,
/// <summary>TLS from the start (port 465).</summary>
Ssl = 1,
/// <summary>No encryption: only for a local relay.</summary>
None = 2,
}
/// <summary>A configuration that does not let the instance start. The message lists every problem, never a value.</summary>
public sealed class ConfigurationException : Exception
{
/// <summary>Creates the exception.</summary>
public ConfigurationException()
: this([])
{
}
/// <summary>Creates the exception.</summary>
/// <param name="message">The message.</param>
public ConfigurationException(string message)
: base(message) => Errors = [message];
/// <summary>Creates the exception.</summary>
/// <param name="message">The message.</param>
/// <param name="innerException">The cause.</param>
public ConfigurationException(string message, Exception innerException)
: base(message, innerException) => Errors = [message];
/// <summary>Creates the exception from a list of problems.</summary>
/// <param name="errors">The problems.</param>
public ConfigurationException(IReadOnlyList<string> errors)
: base(Describe(errors)) => Errors = errors;
/// <summary>The problems, one per line of the message.</summary>
public IReadOnlyList<string> Errors { get; }
private static string Describe(IReadOnlyList<string> errors) =>
"Khaemhat cannot start: the configuration is not valid (see docs/DEPLOY.md and the wiki page Installazione-Docker)."
+ string.Concat((errors ?? []).Select(e => Environment.NewLine + " - " + e));
}
/// <summary>
/// The instance configuration of SPEC §6, read from the environment by <see cref="EnvironmentConfigurationReader"/>.
/// Values stay in memory: nothing is written to disk. <see cref="Validate"/> checks everything before the host starts;
/// the typed accessors (<see cref="SystemDatabase"/>, <see cref="Mode"/>...) are meant for a validated instance.
/// </summary>
public sealed class KhaemhatOptions
{
/// <summary><c>KHAEMHAT_SYSTEM_DB</c>: the system database URL (required).</summary>
public string? SystemDb { get; init; }
/// <summary><c>KHAEMHAT_DB_SERVER</c>: the PostgreSQL server where company databases are created.</summary>
public string? DbServer { get; init; }
/// <summary><c>KHAEMHAT_SECRET_KEY</c>: base64 of at least 32 bytes (required).</summary>
public string? SecretKey { get; init; }
/// <summary><c>KHAEMHAT_SECRET_KEY_NEW</c>: the new key during a rotation (SPEC §12.9).</summary>
public string? RotationSecretKey { get; init; }
/// <summary><c>KHAEMHAT_SUPERUSER</c>: the super user name, read only while <c>sys_users</c> is empty.</summary>
public string? SuperUser { get; init; }
/// <summary><c>KHAEMHAT_SUPERUSER_PASSWORD</c>: its first password, to change at the first access.</summary>
public string? SuperUserPassword { get; init; }
/// <summary><c>KHAEMHAT_SUPERUSER_EMAIL</c>: its e-mail address.</summary>
public string? SuperUserEmail { get; init; }
/// <summary><c>KHAEMHAT_COMPANY_CODE</c>: the first company, read only while <c>sys_companies</c> is empty.</summary>
public string? CompanyCode { get; init; }
/// <summary><c>KHAEMHAT_COMPANY_NAME</c>: its name.</summary>
public string? CompanyName { get; init; }
/// <summary><c>KHAEMHAT_COUNTRY</c>: the fiscal package of the first company (default <c>IT</c>).</summary>
public string Country { get; init; } = "IT";
/// <summary><c>KHAEMHAT_LICENSE_MODE</c>: <c>production</c> (default) or <c>test</c>.</summary>
public string LicenseMode { get; init; } = "production";
/// <summary><c>KHAEMHAT_LICENSE</c>: the text of a <c>.khl</c> licence; absent means Trial.</summary>
public string? License { get; init; }
/// <summary><c>KHAEMHAT_REDIS</c>: <c>redis://</c> or <c>rediss://</c>; absent means in-memory cache.</summary>
public string? Redis { get; init; }
/// <summary><c>KHAEMHAT_DATA_DIR</c>: the only folder the instance writes to (default <c>/data</c>).</summary>
public string DataDir { get; init; } = "/data";
/// <summary><c>KHAEMHAT_URLS</c>: the listening addresses.</summary>
public string? Urls { get; init; }
/// <summary><c>KHAEMHAT_PUBLIC_URL</c>: the address users reach, for links in e-mails.</summary>
public string? PublicUrl { get; init; }
/// <summary><c>KHAEMHAT_SMTP_HOST</c>.</summary>
public string? SmtpHost { get; init; }
/// <summary><c>KHAEMHAT_SMTP_PORT</c>.</summary>
public string? SmtpPort { get; init; }
/// <summary><c>KHAEMHAT_SMTP_USER</c>.</summary>
public string? SmtpUser { get; init; }
/// <summary><c>KHAEMHAT_SMTP_PASSWORD</c>.</summary>
public string? SmtpPassword { get; init; }
/// <summary><c>KHAEMHAT_SMTP_FROM</c>.</summary>
public string? SmtpFrom { get; init; }
/// <summary><c>KHAEMHAT_SMTP_SECURITY</c>: <c>starttls</c> (default), <c>ssl</c> or <c>none</c>.</summary>
public string? SmtpSecurity { get; init; }
/// <summary><c>KHAEMHAT_LOG_LEVEL</c>: the minimum level on stdout.</summary>
public string? LogLevel { get; init; }
/// <summary><c>KHAEMHAT_SEED_BASE</c>: load the base tables when a company is created (default true).</summary>
public string? SeedBase { get; init; }
/// <summary><c>KHAEMHAT_SEED_DEMO</c>: load the demo data into an empty company (default false).</summary>
public string? SeedDemo { get; init; }
/// <summary><c>KHAEMHAT_UPDATE_FEED</c>: the package list read by the update check.</summary>
public string? UpdateFeed { get; init; }
/// <summary><c>KHAEMHAT_UPDATE_TOKEN</c>: a read-only token for the feed.</summary>
public string? UpdateToken { get; init; }
/// <summary>
/// <c>KHAEMHAT_HELP_URL</c>: the online wiki opened by "Apri nel wiki" (default the project wiki). The help itself
/// is the copy of the wiki shipped in the image, so it works offline.
/// </summary>
public string? HelpUrl { get; init; }
/// <summary><c>TZ</c>: the time zone of the container.</summary>
public string? TimeZone { get; init; }
/// <summary>The problems met while reading (both <c>X</c> and <c>X_FILE</c>, unreadable files).</summary>
public IReadOnlyList<string> ReadErrors { get; init; } = [];
/// <summary>The system database, parsed.</summary>
public DatabaseUrl SystemDatabase => DatabaseUrl.Parse(SystemDb ?? throw new ConfigurationException("KHAEMHAT_SYSTEM_DB is not set."));
/// <summary>
/// Where company databases are created: <see cref="DbServer"/> when set, otherwise the server (PostgreSQL) or the
/// folder (SQLite) of the system database.
/// </summary>
public DatabaseUrl CompanyServer => DbServer is { } server ? DatabaseUrl.Parse(server) : SystemDatabase;
/// <summary>The licence mode, parsed.</summary>
public LicenseMode Mode => string.Equals(LicenseMode, "test", StringComparison.OrdinalIgnoreCase)
? Configuration.LicenseMode.Test
: Configuration.LicenseMode.Production;
/// <summary>Whether base data is loaded into new companies.</summary>
public bool SeedBaseEnabled => ParseBool(SeedBase) ?? true;
/// <summary>Whether demo data is loaded into new, empty companies.</summary>
public bool SeedDemoEnabled => ParseBool(SeedDemo) ?? false;
/// <summary>The SMTP port, defaulting by security mode.</summary>
public int SmtpPortNumber => int.TryParse(SmtpPort, NumberStyles.None, CultureInfo.InvariantCulture, out var port)
? port
: SmtpSecurityMode == Configuration.SmtpSecurity.Ssl ? 465 : 587;
/// <summary>The SMTP security, parsed.</summary>
public SmtpSecurity SmtpSecurityMode => SmtpSecurity?.ToUpperInvariant() switch
{
"SSL" or "TLS" => Configuration.SmtpSecurity.Ssl,
"NONE" => Configuration.SmtpSecurity.None,
_ => Configuration.SmtpSecurity.StartTls,
};
/// <summary>
/// Checks the whole configuration. Messages name the variable and the expected form, never its value.
/// The variables needed only at first start (super user, first company) are checked by the bootstrap, which knows
/// whether the tables are still empty; here only their form is checked when they are set.
/// </summary>
/// <returns>The problems; empty when the instance can start.</returns>
public IReadOnlyList<string> Validate()
{
var errors = new List<string>(ReadErrors);
if (SystemDb is null)
{
if (!ReadErrors.Any(e => e.StartsWith("KHAEMHAT_SYSTEM_DB", StringComparison.Ordinal)))
{
errors.Add("KHAEMHAT_SYSTEM_DB is required: postgres://user:password@host:5432/khaemhat_system or sqlite:///data/system.db.");
}
}
else if (!DatabaseUrl.TryParse(SystemDb, out _))
{
errors.Add("KHAEMHAT_SYSTEM_DB is not a valid database URL: use postgres://user:password@host:5432/khaemhat_system or sqlite:///data/system.db.");
}
if (DbServer is not null && (!DatabaseUrl.TryParse(DbServer, out var server) || server.Engine != DbEngine.PostgreSql))
{
errors.Add("KHAEMHAT_DB_SERVER must be a PostgreSQL server URL: postgres://user:password@host:5432/ (a role with CREATEDB).");
}
CheckKey("KHAEMHAT_SECRET_KEY", SecretKey, required: true, errors);
CheckKey("KHAEMHAT_SECRET_KEY_NEW", RotationSecretKey, required: false, errors);
if (SuperUser is not null && !UserNames.IsValid(SuperUser))
{
errors.Add("KHAEMHAT_SUPERUSER must be 3 to 50 characters: letters, digits, dot, dash or underscore.");
}
if (SuperUserEmail is not null && !IsEmail(SuperUserEmail))
{
errors.Add("KHAEMHAT_SUPERUSER_EMAIL is not a valid e-mail address.");
}
if (CompanyCode is not null && !CompanyCodes.IsValid(CompanyCode.Trim().ToUpperInvariant()))
{
errors.Add("KHAEMHAT_COMPANY_CODE must be 1 to 20 characters: letters, digits or underscore, starting with a letter.");
}
if (CompanyName is { Length: > 200 })
{
errors.Add("KHAEMHAT_COMPANY_NAME is longer than 200 characters.");
}
if (!string.Equals(Country, "IT", StringComparison.OrdinalIgnoreCase))
{
errors.Add("KHAEMHAT_COUNTRY: the only fiscal package available is IT.");
}
if (!string.Equals(LicenseMode, "production", StringComparison.OrdinalIgnoreCase)
&& !string.Equals(LicenseMode, "test", StringComparison.OrdinalIgnoreCase))
{
errors.Add("KHAEMHAT_LICENSE_MODE must be production or test.");
}
if (Redis is not null && !(Uri.TryCreate(Redis, UriKind.Absolute, out var redis) && redis.Scheme is "redis" or "rediss"))
{
errors.Add("KHAEMHAT_REDIS must be redis://[:password@]host:6379/0 or rediss:// for TLS.");
}
if (string.IsNullOrWhiteSpace(DataDir) || !Path.IsPathFullyQualified(DataDir))
{
errors.Add("KHAEMHAT_DATA_DIR must be an absolute path (default /data).");
}
if (PublicUrl is not null && !IsHttpUrl(PublicUrl))
{
errors.Add("KHAEMHAT_PUBLIC_URL must be an absolute http or https address, for example https://gestionale.example.com.");
}
if (HelpUrl is not null && !IsHttpUrl(HelpUrl))
{
errors.Add("KHAEMHAT_HELP_URL must be an absolute http or https address, for example https://gitea.example.com/owner/khaemhat/wiki/.");
}
if (SmtpPort is not null && !(int.TryParse(SmtpPort, NumberStyles.None, CultureInfo.InvariantCulture, out var port) && port is > 0 and < 65536))
{
errors.Add("KHAEMHAT_SMTP_PORT must be a port number between 1 and 65535.");
}
if (SmtpSecurity is not null && SmtpSecurity.ToUpperInvariant() is not ("STARTTLS" or "SSL" or "TLS" or "NONE"))
{
errors.Add("KHAEMHAT_SMTP_SECURITY must be starttls, ssl or none.");
}
if (SmtpFrom is not null && !IsEmail(SmtpFrom))
{
errors.Add("KHAEMHAT_SMTP_FROM is not a valid e-mail address.");
}
if (LogLevel is not null && !(Enum.TryParse<LogLevel>(LogLevel, ignoreCase: true, out var level) && Enum.IsDefined(level)))
{
errors.Add("KHAEMHAT_LOG_LEVEL must be Trace, Debug, Information, Warning, Error, Critical or None.");
}
if (SeedBase is not null && ParseBool(SeedBase) is null)
{
errors.Add("KHAEMHAT_SEED_BASE must be true or false.");
}
if (SeedDemo is not null && ParseBool(SeedDemo) is null)
{
errors.Add("KHAEMHAT_SEED_DEMO must be true or false.");
}
if (UpdateFeed is not null && !IsHttpUrl(UpdateFeed))
{
errors.Add("KHAEMHAT_UPDATE_FEED must be an absolute http or https address.");
}
if (TimeZone is not null && !TimeZoneInfo.TryFindSystemTimeZoneById(TimeZone, out _))
{
errors.Add("TZ is not a known time zone, for example Europe/Rome.");
}
return errors;
}
/// <summary>Throws when <see cref="Validate"/> finds problems.</summary>
/// <exception cref="ConfigurationException">The configuration is not valid.</exception>
public void EnsureValid()
{
var errors = Validate();
if (errors.Count > 0)
{
throw new ConfigurationException(errors);
}
}
private static void CheckKey(string name, string? value, bool required, List<string> errors)
{
if (value is null)
{
if (required)
{
errors.Add($"{name} is required: the base64 of at least 32 random bytes (for example: openssl rand -base64 32).");
}
return;
}
try
{
_ = Infrastructure.Security.SecretKey.FromBase64(value);
}
catch (FormatException ex)
{
errors.Add(ex.Message.Replace("KHAEMHAT_SECRET_KEY", name, StringComparison.Ordinal));
}
}
private static bool? ParseBool(string? value) => value?.Trim().ToUpperInvariant() switch
{
null => null,
"TRUE" or "1" or "YES" or "SI" => true,
"FALSE" or "0" or "NO" => false,
_ => null,
};
private static bool IsHttpUrl(string value) =>
Uri.TryCreate(value, UriKind.Absolute, out var uri) && (uri.Scheme == Uri.UriSchemeHttp || uri.Scheme == Uri.UriSchemeHttps);
private static bool IsEmail(string value) => MailAddress.TryCreate(value, out var address) && address.Address == value.Trim();
}
@@ -0,0 +1,186 @@
using Khaemhat.Application.Security;
using Microsoft.Extensions.Logging;
namespace Khaemhat.Application.Dashboard;
/// <summary>The colour of a line in a dashboard list.</summary>
public enum FeedTone
{
/// <summary>Nothing special.</summary>
Neutral = 0,
/// <summary>Information.</summary>
Info = 1,
/// <summary>Done, fine.</summary>
Ok = 2,
/// <summary>Needs attention.</summary>
Warning = 3,
/// <summary>Something went wrong.</summary>
Error = 4,
}
/// <summary>
/// A line of <em>Da fare oggi</em>, <em>Fatto oggi</em> or <em>Scadenze</em>. The texts are already in the user's
/// language; <see cref="AreaKey"/> is the text key of the area label (Sistema, Vendite, Fiscale…).
/// </summary>
/// <param name="Id">A stable id, unique within the list.</param>
/// <param name="Text">What it is.</param>
/// <param name="AreaKey">The text key of the area.</param>
/// <param name="Tone">The colour.</param>
public sealed record FeedItem(string Id, string Text, string AreaKey, FeedTone Tone = FeedTone.Neutral)
{
/// <summary>A second line, if any.</summary>
public string? Detail { get; init; }
/// <summary>When: the time for what was done, the date for a deadline.</summary>
public DateTimeOffset? When { get; init; }
/// <summary>Where it opens, a local address.</summary>
public string? Href { get; init; }
/// <summary>Higher first, for the things to do.</summary>
public int Priority { get; init; }
}
/// <summary>Who asks and when.</summary>
/// <param name="Actor">The user.</param>
/// <param name="Now">The local time now.</param>
public sealed record FeedContext(Actor Actor, DateTimeOffset Now)
{
/// <summary>Today, local.</summary>
public DateOnly Today => DateOnly.FromDateTime(Now.DateTime);
/// <summary>The start of today, local.</summary>
public DateTimeOffset StartOfToday => new(Now.Date, Now.Offset);
}
/// <summary>A source of things to do today (rejected SDI invoices, VAT settlements, procedures waiting… as the modules come).</summary>
public interface ITodoSource
{
/// <summary>The things to do.</summary>
/// <param name="context">Who and when.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The lines.</returns>
Task<IReadOnlyList<FeedItem>> GetAsync(FeedContext context, CancellationToken cancellationToken);
}
/// <summary>A source of things done today (documents issued, collections, backups, scheduled tasks…).</summary>
public interface IDoneSource
{
/// <summary>The things done.</summary>
/// <param name="context">Who and when.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The lines.</returns>
Task<IReadOnlyList<FeedItem>> GetAsync(FeedContext context, CancellationToken cancellationToken);
}
/// <summary>A source of deadlines (fiscal, sales, treasury, contracts…).</summary>
public interface IDeadlineSource
{
/// <summary>The deadlines from today up to the horizon.</summary>
/// <param name="context">Who and when.</param>
/// <param name="until">The last day included.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The lines, with <see cref="FeedItem.When"/> set.</returns>
Task<IReadOnlyList<FeedItem>> GetAsync(FeedContext context, DateOnly until, CancellationToken cancellationToken);
}
/// <summary>
/// Runs every source of one kind and merges what they say. A source that fails is logged and left out: one broken
/// module must not empty the whole dashboard.
/// </summary>
public abstract class FeedAggregator
{
/// <summary>The most lines a widget shows.</summary>
public const int MaxItems = 50;
/// <summary>Runs the sources one after the other (they share the database connections of the scope).</summary>
/// <param name="sources">The calls.</param>
/// <param name="logger">Where failures go.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>All the lines.</returns>
protected static async Task<List<FeedItem>> CollectAsync(
IEnumerable<(string Name, Func<Task<IReadOnlyList<FeedItem>>> Call)> sources, ILogger logger, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(sources);
var items = new List<FeedItem>();
foreach (var (name, call) in sources)
{
cancellationToken.ThrowIfCancellationRequested();
try
{
items.AddRange(await call().ConfigureAwait(false));
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
logger.LogWarning(ex, "Dashboard source {Source} failed and was left out.", name);
}
}
return items;
}
}
/// <summary>What to do today, the most urgent first.</summary>
/// <param name="sources">The sources.</param>
/// <param name="clock">The clock.</param>
/// <param name="logger">The log.</param>
public sealed class TodoAggregator(IEnumerable<ITodoSource> sources, TimeProvider clock, ILogger<TodoAggregator> logger) : FeedAggregator
{
/// <summary>The things to do.</summary>
/// <param name="actor">The user.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>Higher priority first, then the oldest.</returns>
public async Task<IReadOnlyList<FeedItem>> GetAsync(Actor actor, CancellationToken cancellationToken = default)
{
var context = new FeedContext(actor, clock.GetLocalNow());
var items = await CollectAsync(sources.Select(s => (s.GetType().Name, (Func<Task<IReadOnlyList<FeedItem>>>)(() => s.GetAsync(context, cancellationToken)))), logger, cancellationToken).ConfigureAwait(false);
return [.. items.OrderByDescending(i => i.Priority).ThenBy(i => i.When ?? DateTimeOffset.MaxValue).Take(MaxItems)];
}
}
/// <summary>What was done today, the latest first.</summary>
/// <param name="sources">The sources.</param>
/// <param name="clock">The clock.</param>
/// <param name="logger">The log.</param>
public sealed class DoneAggregator(IEnumerable<IDoneSource> sources, TimeProvider clock, ILogger<DoneAggregator> logger) : FeedAggregator
{
/// <summary>The things done today.</summary>
/// <param name="actor">The user.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The latest first.</returns>
public async Task<IReadOnlyList<FeedItem>> GetAsync(Actor actor, CancellationToken cancellationToken = default)
{
var context = new FeedContext(actor, clock.GetLocalNow());
var items = await CollectAsync(sources.Select(s => (s.GetType().Name, (Func<Task<IReadOnlyList<FeedItem>>>)(() => s.GetAsync(context, cancellationToken)))), logger, cancellationToken).ConfigureAwait(false);
return [.. items.OrderByDescending(i => i.When ?? DateTimeOffset.MinValue).Take(MaxItems)];
}
}
/// <summary>The deadlines of the next days, the nearest first.</summary>
/// <param name="sources">The sources.</param>
/// <param name="clock">The clock.</param>
/// <param name="logger">The log.</param>
public sealed class DeadlineAggregator(IEnumerable<IDeadlineSource> sources, TimeProvider clock, ILogger<DeadlineAggregator> logger) : FeedAggregator
{
/// <summary>How far the widget looks ahead.</summary>
public const int HorizonDays = 30;
/// <summary>The deadlines from today to <see cref="HorizonDays"/> days ahead.</summary>
/// <param name="actor">The user.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The nearest first.</returns>
public async Task<IReadOnlyList<FeedItem>> GetAsync(Actor actor, CancellationToken cancellationToken = default)
{
var context = new FeedContext(actor, clock.GetLocalNow());
var until = context.Today.AddDays(HorizonDays);
var items = await CollectAsync(sources.Select(s => (s.GetType().Name, (Func<Task<IReadOnlyList<FeedItem>>>)(() => s.GetAsync(context, until, cancellationToken)))), logger, cancellationToken).ConfigureAwait(false);
return [.. items
.Where(i => i.When is { } when && DateOnly.FromDateTime(when.DateTime) >= context.Today && DateOnly.FromDateTime(when.DateTime) <= until)
.OrderBy(i => i.When)
.Take(MaxItems)];
}
}
@@ -0,0 +1,166 @@
using System.Text.Json;
using System.Text.Json.Nodes;
namespace Khaemhat.Application.Dashboard;
/// <summary>A widget on the dashboard: which one and how wide.</summary>
/// <param name="Id">The widget id (<see cref="WidgetIds"/>).</param>
/// <param name="Width">The width in columns of twelve: 3, 4, 6, 8 or 12.</param>
public sealed record WidgetPlacement(string Id, int Width);
/// <summary>
/// The widgets shown, in order, with their width (SPEC §10.3). A widget that is not in the list is switched off.
/// Kept as JSON in <c>user_settings</c> (<c>dashboard.layout</c>) and, as the default of a role, in
/// <c>company_settings</c>: <c>{"v":1,"widgets":[{"id":"todo","w":4}]}</c>.
/// </summary>
/// <param name="Widgets">The widgets in order.</param>
public sealed record DashboardLayout(IReadOnlyList<WidgetPlacement> Widgets)
{
/// <summary>The most widgets a layout keeps.</summary>
public const int MaxWidgets = 30;
private const int Version = 1;
/// <summary>Whether a widget is shown.</summary>
/// <param name="id">The widget id.</param>
/// <returns><see langword="true"/> when it is in the layout.</returns>
public bool Contains(string id) => Widgets.Any(w => w.Id == id);
/// <summary>The width of a widget, or its default when not shown.</summary>
/// <param name="id">The widget id.</param>
/// <returns>The width.</returns>
public int WidthOf(string id) =>
Widgets.FirstOrDefault(w => w.Id == id)?.Width ?? WidgetCatalog.Find(id)?.DefaultWidth ?? 4;
/// <summary>Reads a layout saved as JSON.</summary>
/// <param name="json">The JSON, or <see langword="null"/>.</param>
/// <returns>The layout without unknown widgets, duplicates or invalid widths; <see langword="null"/> when there
/// is none or it cannot be read.</returns>
public static DashboardLayout? Parse(string? json)
{
if (string.IsNullOrWhiteSpace(json))
{
return null;
}
try
{
if (JsonNode.Parse(json) is not JsonObject root || root["widgets"] is not JsonArray array)
{
return null;
}
var widgets = new List<WidgetPlacement>();
foreach (var node in array)
{
if (node is JsonObject item && item["id"]?.GetValueKind() == JsonValueKind.String)
{
var width = item["w"]?.GetValueKind() == JsonValueKind.Number ? item["w"]!.GetValue<int>() : 0;
widgets.Add(new WidgetPlacement(item["id"]!.GetValue<string>(), width));
}
}
return new DashboardLayout(widgets).Normalize();
}
catch (Exception ex) when (ex is JsonException or FormatException or InvalidOperationException)
{
return null;
}
}
/// <summary>The layout as JSON.</summary>
/// <returns>The JSON.</returns>
public string ToJson()
{
var array = new JsonArray();
foreach (var widget in Normalize().Widgets)
{
array.Add(new JsonObject { ["id"] = widget.Id, ["w"] = widget.Width });
}
return new JsonObject { ["v"] = Version, ["widgets"] = array }.ToJsonString();
}
/// <summary>Drops unknown widgets and repeated ones and snaps the widths to the allowed ones.</summary>
/// <returns>The clean layout.</returns>
public DashboardLayout Normalize()
{
var seen = new HashSet<string>(StringComparer.Ordinal);
var widgets = new List<WidgetPlacement>();
foreach (var widget in Widgets)
{
if (WidgetCatalog.Find(widget.Id) is { } definition && seen.Add(widget.Id) && widgets.Count < MaxWidgets)
{
widgets.Add(new WidgetPlacement(definition.Id, widget.Width <= 0 ? definition.DefaultWidth : WidgetDefinition.Snap(widget.Width)));
}
}
return new DashboardLayout(widgets);
}
/// <summary>Only the widgets that pass a test, such as those the user may see.</summary>
/// <param name="keep">The test.</param>
/// <returns>The layout.</returns>
public DashboardLayout Where(Func<string, bool> keep)
{
ArgumentNullException.ThrowIfNull(keep);
return new DashboardLayout([.. Widgets.Where(w => keep(w.Id))]);
}
/// <summary>Shows a widget at the end, or hides it.</summary>
/// <param name="id">The widget id.</param>
/// <param name="visible">Whether to show it.</param>
/// <returns>The layout.</returns>
public DashboardLayout Toggle(string id, bool visible)
{
if (visible == Contains(id) || WidgetCatalog.Find(id) is not { } definition)
{
return this;
}
return visible
? new DashboardLayout([.. Widgets, new WidgetPlacement(id, definition.DefaultWidth)])
: new DashboardLayout([.. Widgets.Where(w => w.Id != id)]);
}
/// <summary>Changes the width of a widget.</summary>
/// <param name="id">The widget id.</param>
/// <param name="width">The new width (snapped to the allowed ones).</param>
/// <returns>The layout.</returns>
public DashboardLayout Resize(string id, int width) =>
new([.. Widgets.Select(w => w.Id == id ? w with { Width = WidgetDefinition.Snap(width) } : w)]);
/// <summary>Moves a widget by some places.</summary>
/// <param name="id">The widget id.</param>
/// <param name="offset">-1 before the previous one, +1 after the next one.</param>
/// <returns>The layout.</returns>
public DashboardLayout Move(string id, int offset)
{
var index = Widgets.ToList().FindIndex(w => w.Id == id);
return index < 0 ? this : MoveTo(id, Math.Clamp(index + offset, 0, Widgets.Count - 1));
}
/// <summary>Moves a widget to a position, as dropping it on another widget does.</summary>
/// <param name="id">The widget id.</param>
/// <param name="index">The new position.</param>
/// <returns>The layout.</returns>
public DashboardLayout MoveTo(string id, int index)
{
var list = Widgets.ToList();
var from = list.FindIndex(w => w.Id == id);
if (from < 0)
{
return this;
}
var widget = list[from];
list.RemoveAt(from);
list.Insert(Math.Clamp(index, 0, list.Count), widget);
return new DashboardLayout(list);
}
/// <summary>Whether two layouts show the same widgets in the same order and widths.</summary>
/// <param name="other">The other layout.</param>
/// <returns><see langword="true"/> when they look the same.</returns>
public bool SameAs(DashboardLayout? other) => other is not null && Widgets.SequenceEqual(other.Widgets);
}
@@ -0,0 +1,284 @@
using System.Text.Json;
using System.Text.Json.Nodes;
using Khaemhat.Application.Instance;
using Khaemhat.Application.Licensing;
using Khaemhat.Application.Preferences;
using Khaemhat.Application.Security;
using Khaemhat.Core.Security;
using Khaemhat.Data;
using Khaemhat.Data.Querying;
namespace Khaemhat.Application.Dashboard;
/// <summary>Where the layout shown comes from.</summary>
public enum DashboardLayoutSource
{
/// <summary>The built-in layout of <see cref="WidgetCatalog.BuiltIn"/>.</summary>
BuiltIn = 0,
/// <summary>The default of one of the user's roles.</summary>
Role = 1,
/// <summary>The user's own layout.</summary>
User = 2,
}
/// <summary>The dashboard of a user: the layout and where it comes from.</summary>
/// <param name="Layout">The widgets the user may see, in order.</param>
/// <param name="Source">Where it comes from.</param>
/// <param name="RoleCode">The role whose default is used, when <see cref="Source"/> is <see cref="DashboardLayoutSource.Role"/>.</param>
public sealed record DashboardView(DashboardLayout Layout, DashboardLayoutSource Source, string? RoleCode = null);
/// <summary>A personal reminder of the dashboard.</summary>
/// <param name="Text">What to remember.</param>
/// <param name="Done">Whether it is ticked.</param>
public sealed record PersonalNote(string Text, bool Done);
/// <summary>
/// The dashboard of SPEC §10.3: which widgets a user may see, the layout to show (the user's own, else the default
/// of one of their roles, else the built-in one), the personal reminders and the shortcuts. Everything belongs to the
/// user in <c>user_settings</c>; the role defaults belong to the company in <c>company_settings</c>.
/// </summary>
/// <param name="settings">The user's settings.</param>
/// <param name="company">The company's settings.</param>
/// <param name="factory">Opens the company database, for the roles of a user.</param>
/// <param name="permissions">The user's permissions.</param>
/// <param name="licenses">The licensed modules.</param>
public sealed class DashboardService(
UserSettingsService settings,
CompanySettingsService company,
IUnitOfWorkFactory factory,
PermissionService permissions,
ILicenseGate licenses)
{
/// <summary>The key of the user's layout.</summary>
public const string LayoutKey = "dashboard.layout";
/// <summary>The key of the personal reminders.</summary>
public const string NotesKey = "dashboard.notes";
/// <summary>The key of the shortcuts.</summary>
public const string ShortcutsKey = "dashboard.shortcuts";
/// <summary>The start of the keys of the role defaults in <c>company_settings</c>.</summary>
public const string RolePrefix = "dashboard.layout.role.";
/// <summary>The most reminders kept.</summary>
public const int MaxNotes = 20;
/// <summary>The longest reminder.</summary>
public const int MaxNoteLength = 300;
/// <summary>The most shortcuts kept.</summary>
public const int MaxShortcuts = 12;
/// <summary>The key of the default layout of a role.</summary>
/// <param name="roleCode">The role code.</param>
/// <returns>The key.</returns>
public static string RoleKey(string roleCode) => RolePrefix + roleCode;
/// <summary>The widgets a user may see: licensed module, permission, administrators only.</summary>
/// <param name="actor">The user.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The widgets in catalog order.</returns>
public async Task<IReadOnlyList<WidgetDefinition>> AvailableAsync(Actor actor, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(actor);
var granted = await permissions.GetAsync(actor, cancellationToken).ConfigureAwait(false);
return [.. WidgetCatalog.All.Where(w =>
licenses.IsModuleActive(w.Module)
&& (!w.InstanceOnly || actor.IsInstanceAccount)
&& (w.Permission is null || granted.Allows(w.Permission)))];
}
/// <summary>The dashboard to show.</summary>
/// <param name="actor">The user.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The layout, limited to the widgets the user may see, and where it comes from.</returns>
public async Task<DashboardView> GetAsync(Actor actor, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(actor);
var available = (await AvailableAsync(actor, cancellationToken).ConfigureAwait(false)).Select(w => w.Id).ToHashSet(StringComparer.Ordinal);
if (DashboardLayout.Parse(await settings.GetAsync(actor, LayoutKey, cancellationToken).ConfigureAwait(false)) is { } own)
{
return new DashboardView(own.Where(available.Contains), DashboardLayoutSource.User);
}
if (await RoleDefaultAsync(actor, cancellationToken).ConfigureAwait(false) is { } fromRole)
{
return new DashboardView(fromRole.Layout.Where(available.Contains), DashboardLayoutSource.Role, fromRole.RoleCode);
}
return new DashboardView(WidgetCatalog.BuiltIn.Where(available.Contains), DashboardLayoutSource.BuiltIn);
}
/// <summary>Saves the user's layout.</summary>
/// <param name="actor">The user.</param>
/// <param name="layout">The layout.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
public Task SaveAsync(Actor actor, DashboardLayout layout, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(layout);
return settings.SetAsync(actor, LayoutKey, layout.ToJson(), cancellationToken);
}
/// <summary>Forgets the user's layout: the role default or the built-in one comes back.</summary>
/// <param name="actor">The user.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
public Task ResetAsync(Actor actor, CancellationToken cancellationToken = default) =>
settings.SetAsync(actor, LayoutKey, null, cancellationToken);
/// <summary>The roles of the company with their default layout, if they have one.</summary>
/// <param name="companyCode">The company.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The roles in name order.</returns>
public async Task<IReadOnlyList<(Role Role, DashboardLayout? Layout)>> RoleDefaultsAsync(string companyCode, CancellationToken cancellationToken = default)
{
ArgumentException.ThrowIfNullOrWhiteSpace(companyCode);
var defaults = await company.GetAllAsync(companyCode, RolePrefix, cancellationToken).ConfigureAwait(false);
await using var unitOfWork = await factory.CreateAsync(DatabaseScope.Company(companyCode), cancellationToken).ConfigureAwait(false);
var roles = (await unitOfWork.Repository<Role, long>().ListAsync(Query.For<Role>(), cancellationToken).ConfigureAwait(false)).Items;
return [.. roles.OrderBy(r => r.Name, StringComparer.CurrentCulture)
.Select(r => (r, defaults.TryGetValue(RoleKey(r.Code), out var json) ? DashboardLayout.Parse(json) : null))];
}
/// <summary>Sets or removes (<see langword="null"/>) the default layout of a role.</summary>
/// <param name="actor">Who sets it: needs <c>company.settings.write</c>.</param>
/// <param name="companyCode">The company.</param>
/// <param name="roleCode">The role.</param>
/// <param name="layout">The layout, or <see langword="null"/>.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
public Task SaveRoleDefaultAsync(Actor actor, string companyCode, string roleCode, DashboardLayout? layout, CancellationToken cancellationToken = default)
{
ArgumentException.ThrowIfNullOrWhiteSpace(roleCode);
return company.SetAsync(actor, companyCode, RoleKey(roleCode), layout?.ToJson(), cancellationToken);
}
/// <summary>The personal reminders.</summary>
/// <param name="actor">The user.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The reminders in order.</returns>
public async Task<IReadOnlyList<PersonalNote>> GetNotesAsync(Actor actor, CancellationToken cancellationToken = default)
{
var json = await settings.GetAsync(actor, NotesKey, cancellationToken).ConfigureAwait(false);
var notes = new List<PersonalNote>();
foreach (var node in ReadArray(json))
{
if (node is JsonObject item && item["t"]?.GetValueKind() == JsonValueKind.String)
{
notes.Add(new PersonalNote(item["t"]!.GetValue<string>(), item["d"]?.GetValueKind() == JsonValueKind.True));
}
}
return CleanNotes(notes);
}
/// <summary>Saves the personal reminders (at most <see cref="MaxNotes"/>, each up to <see cref="MaxNoteLength"/> characters).</summary>
/// <param name="actor">The user.</param>
/// <param name="notes">The reminders.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
public Task SaveNotesAsync(Actor actor, IReadOnlyList<PersonalNote> notes, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(notes);
var array = new JsonArray();
foreach (var note in CleanNotes(notes))
{
array.Add(new JsonObject { ["t"] = note.Text, ["d"] = note.Done });
}
return settings.SetAsync(actor, NotesKey, array.Count == 0 ? null : array.ToJsonString(), cancellationToken);
}
/// <summary>The addresses of the shortcut buttons.</summary>
/// <param name="actor">The user.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The addresses in order; <see langword="null"/> when the user never chose them.</returns>
public async Task<IReadOnlyList<string>?> GetShortcutsAsync(Actor actor, CancellationToken cancellationToken = default)
{
var json = await settings.GetAsync(actor, ShortcutsKey, cancellationToken).ConfigureAwait(false);
if (json is null)
{
return null;
}
return CleanShortcuts(ReadArray(json).Where(n => n?.GetValueKind() == JsonValueKind.String).Select(n => n!.GetValue<string>()));
}
/// <summary>Saves the shortcut buttons (local addresses only, at most <see cref="MaxShortcuts"/>).</summary>
/// <param name="actor">The user.</param>
/// <param name="paths">The addresses.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
public Task SaveShortcutsAsync(Actor actor, IReadOnlyList<string> paths, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(paths);
var array = new JsonArray();
foreach (var path in CleanShortcuts(paths))
{
array.Add(path);
}
return settings.SetAsync(actor, ShortcutsKey, array.ToJsonString(), cancellationToken);
}
private static List<PersonalNote> CleanNotes(IEnumerable<PersonalNote> notes) =>
[
.. notes.Select(n => n with { Text = (n.Text ?? string.Empty).Trim() })
.Where(n => n.Text.Length > 0)
.Select(n => n.Text.Length > MaxNoteLength ? n with { Text = n.Text[..MaxNoteLength] } : n)
.Take(MaxNotes),
];
private static List<string> CleanShortcuts(IEnumerable<string> paths) =>
[.. paths.Where(UserPreferences.IsLocalPath).Distinct(StringComparer.OrdinalIgnoreCase).Take(MaxShortcuts)];
private static JsonArray ReadArray(string? json)
{
if (string.IsNullOrWhiteSpace(json))
{
return [];
}
try
{
return JsonNode.Parse(json) as JsonArray ?? [];
}
catch (JsonException)
{
return [];
}
}
// The default of the first of the user's roles (in role order) that has one. Instance accounts have no roles.
private async Task<(DashboardLayout Layout, string RoleCode)?> RoleDefaultAsync(Actor actor, CancellationToken cancellationToken)
{
if (actor.CompanyCode is not { } companyCode || actor.CompanyUserId is not { } userId)
{
return null;
}
var defaults = await company.GetAllAsync(companyCode, RolePrefix, cancellationToken).ConfigureAwait(false);
if (defaults.Count == 0)
{
return null;
}
await using var unitOfWork = await factory.CreateAsync(DatabaseScope.Company(companyCode), cancellationToken).ConfigureAwait(false);
var roleIds = (await unitOfWork.Repository<UserRole, long>().ListAsync(Query.For<UserRole>().Where(r => r.UserId == userId), cancellationToken).ConfigureAwait(false))
.Items.Select(r => r.RoleId).ToHashSet();
var roles = (await unitOfWork.Repository<Role, long>().ListAsync(Query.For<Role>(), cancellationToken).ConfigureAwait(false)).Items;
foreach (var role in roles.Where(r => roleIds.Contains(r.Id)).OrderBy(r => r.Id))
{
if (defaults.TryGetValue(RoleKey(role.Code), out var json) && DashboardLayout.Parse(json) is { } layout)
{
return (layout, role.Code);
}
}
return null;
}
}
@@ -0,0 +1,177 @@
using System.Globalization;
using Khaemhat.Application.Licensing;
using Khaemhat.Application.Localization;
using Khaemhat.Application.Notifications;
using Khaemhat.Application.Preferences;
using Khaemhat.Core.Instance;
using Khaemhat.Data;
using Khaemhat.Data.Querying;
namespace Khaemhat.Application.Dashboard;
/// <summary>Text keys of the dashboard areas (the label at the side of a line).</summary>
public static class FeedAreas
{
/// <summary>System and administration.</summary>
public const string System = "Dashboard.Areas.System";
/// <summary>Messages for the user.</summary>
public const string Notifications = "Dashboard.Areas.Notifications";
}
/// <summary>
/// The licence on the dashboard of the administrators: the expiry among the deadlines, and renewing it among the
/// things to do once it is near, in grace or expired.
/// </summary>
/// <param name="licenses">The licence in force.</param>
/// <param name="texts">The texts.</param>
public sealed class LicenseFeedSource(ILicenseGate licenses, ITexts texts) : ITodoSource, IDeadlineSource
{
/// <summary>Days before the expiry when renewing becomes a thing to do.</summary>
public const int RenewDays = 7;
private const string Href = "/amministrazione/licenze";
/// <inheritdoc />
public Task<IReadOnlyList<FeedItem>> GetAsync(FeedContext context, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(context);
var license = licenses.Current;
if (!context.Actor.IsInstanceAccount || license.IsTestMode)
{
return Task.FromResult<IReadOnlyList<FeedItem>>([]);
}
var days = license.DaysLeft(context.Now.UtcDateTime);
FeedItem? item = license.Status switch
{
LicenseStatus.Expired => new FeedItem("license", texts["Dashboard.Feed.LicenseExpired"], FeedAreas.System, FeedTone.Error) { Priority = 100, Href = Href },
LicenseStatus.Grace => new FeedItem("license", texts["Dashboard.Feed.LicenseGrace"], FeedAreas.System, FeedTone.Error) { Priority = 90, Href = Href },
_ when days is { } left && left <= RenewDays => new FeedItem("license", texts.Format("Dashboard.Feed.LicenseRenew", left), FeedAreas.System, FeedTone.Warning)
{
Priority = 50,
Href = Href,
},
_ => null,
};
return Task.FromResult<IReadOnlyList<FeedItem>>(item is null ? [] : [item]);
}
/// <inheritdoc />
public Task<IReadOnlyList<FeedItem>> GetAsync(FeedContext context, DateOnly until, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(context);
var license = licenses.Current;
if (!context.Actor.IsInstanceAccount || license.IsTestMode || license.ExpiresAt is not { } expires || license.Status != LicenseStatus.Valid)
{
return Task.FromResult<IReadOnlyList<FeedItem>>([]);
}
var when = new DateTimeOffset(DateTime.SpecifyKind(expires, DateTimeKind.Utc)).ToOffset(context.Now.Offset);
if (DateOnly.FromDateTime(when.DateTime) > until)
{
return Task.FromResult<IReadOnlyList<FeedItem>>([]);
}
var key = license.Kind == LicenseKind.Trial ? "Dashboard.Feed.TrialEnds" : "Dashboard.Feed.LicenseEnds";
var near = license.DaysLeft(context.Now.UtcDateTime) <= RenewDays;
return Task.FromResult<IReadOnlyList<FeedItem>>(
[
new FeedItem("license-expiry", texts[key], FeedAreas.System, near ? FeedTone.Warning : FeedTone.Info) { When = when, Href = Href },
]);
}
}
/// <summary>The unread warnings and errors addressed to the user, until they are read.</summary>
/// <param name="notifications">The notifications.</param>
public sealed class NotificationTodoSource(NotificationDispatcher notifications) : ITodoSource
{
/// <inheritdoc />
public async Task<IReadOnlyList<FeedItem>> GetAsync(FeedContext context, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(context);
var unread = await notifications.InboxAsync(context.Actor, unreadOnly: true, cancellationToken).ConfigureAwait(false);
return [.. unread
.Where(n => n.Severity >= NotificationSeverity.Warning)
.Select(n => new FeedItem("notification-" + n.Id.ToString(CultureInfo.InvariantCulture), n.Title, FeedAreas.Notifications,
n.Severity == NotificationSeverity.Warning ? FeedTone.Warning : FeedTone.Error)
{
Detail = n.Body,
Href = UserPreferences.IsLocalPath(n.Link) ? n.Link : null,
Priority = n.Severity == NotificationSeverity.Warning ? 60 : 80,
When = new DateTimeOffset(DateTime.SpecifyKind(n.CreatedAt, DateTimeKind.Utc)).ToOffset(context.Now.Offset),
})];
}
}
/// <summary>
/// The scheduled tasks of today for the administrators: those that ran fine among the things done (one line per task),
/// those that failed among the things to do.
/// </summary>
/// <param name="factory">Opens the system database.</param>
/// <param name="texts">The texts.</param>
public sealed class JobRunFeedSource(IUnitOfWorkFactory factory, ITexts texts) : IDoneSource, ITodoSource
{
private const string Href = "/amministrazione/attivita";
/// <inheritdoc />
async Task<IReadOnlyList<FeedItem>> IDoneSource.GetAsync(FeedContext context, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(context);
if (!context.Actor.IsInstanceAccount)
{
return [];
}
var (runs, names) = await TodayAsync(context, cancellationToken).ConfigureAwait(false);
return [.. runs
.Where(r => r.Outcome == JobOutcome.Succeeded)
.GroupBy(r => r.TaskCode, StringComparer.Ordinal)
.Select(g =>
{
var last = g.MaxBy(r => r.FinishedAt ?? r.StartedAt)!;
var when = Local(last.FinishedAt ?? last.StartedAt, context);
// The widget shows the time of the last run at the side: the detail says how many.
var detail = g.Count() == 1 ? texts["Dashboard.Feed.JobRanOnce"] : texts.Format("Dashboard.Feed.JobRanTimes", g.Count());
return new FeedItem("job-" + g.Key, names.GetValueOrDefault(g.Key, g.Key), FeedAreas.System, FeedTone.Ok) { Detail = detail, When = when, Href = Href };
})];
}
/// <inheritdoc />
async Task<IReadOnlyList<FeedItem>> ITodoSource.GetAsync(FeedContext context, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(context);
if (!context.Actor.IsInstanceAccount)
{
return [];
}
var (runs, names) = await TodayAsync(context, cancellationToken).ConfigureAwait(false);
// A task that failed and has not succeeded since is still a thing to do.
return [.. runs
.GroupBy(r => r.TaskCode, StringComparer.Ordinal)
.Select(g => g.MaxBy(r => r.StartedAt)!)
.Where(r => r.Outcome == JobOutcome.Failed)
.Select(r => new FeedItem("job-failed-" + r.TaskCode, texts.Format("Dashboard.Feed.JobFailed", names.GetValueOrDefault(r.TaskCode, r.TaskCode)), FeedAreas.System, FeedTone.Error)
{
Detail = r.Message,
When = Local(r.StartedAt, context),
Href = Href,
Priority = 70,
})];
}
private static DateTimeOffset Local(DateTime utc, FeedContext context) =>
new DateTimeOffset(DateTime.SpecifyKind(utc, DateTimeKind.Utc)).ToOffset(context.Now.Offset);
private async Task<(IReadOnlyList<JobRun> Runs, IReadOnlyDictionary<string, string> Names)> TodayAsync(FeedContext context, CancellationToken cancellationToken)
{
var since = context.StartOfToday.UtcDateTime;
await using var unitOfWork = await factory.CreateAsync(DatabaseScope.System, cancellationToken).ConfigureAwait(false);
var runs = (await unitOfWork.Repository<JobRun, long>().ListAsync(Query.For<JobRun>().Where(r => r.StartedAt >= since), cancellationToken).ConfigureAwait(false)).Items;
var tasks = (await unitOfWork.Repository<ScheduledTask, long>().ListAsync(Query.For<ScheduledTask>(), cancellationToken).ConfigureAwait(false)).Items;
return (runs, tasks.ToDictionary(t => t.Code, t => t.Name, StringComparer.Ordinal));
}
}
@@ -0,0 +1,42 @@
using Khaemhat.Application.Instance;
using Khaemhat.Core.Instance;
using Khaemhat.Data;
using Khaemhat.Data.Companies;
using Khaemhat.Data.Querying;
namespace Khaemhat.Application.Dashboard;
/// <summary>What the <em>Stato del sistema</em> widget shows besides version, cache and licence.</summary>
/// <param name="Engine">The database engine.</param>
/// <param name="Companies">The companies that are not disabled.</param>
/// <param name="FailedCompanies">Those that failed to open at start-up.</param>
/// <param name="JobsSucceeded">Scheduled task runs of today that succeeded.</param>
/// <param name="JobsFailed">Those that failed.</param>
public sealed record SystemStatus(DbEngine Engine, int Companies, int FailedCompanies, int JobsSucceeded, int JobsFailed);
/// <summary>Reads the state of the instance for the administrators' widget.</summary>
/// <param name="factory">Opens the system database.</param>
/// <param name="system">The system database.</param>
/// <param name="companies">The companies.</param>
/// <param name="bootstrap">What happened at start-up.</param>
/// <param name="clock">The clock.</param>
public sealed class SystemStatusService(IUnitOfWorkFactory factory, DatabaseTarget system, ICompanyRegistry companies, BootstrapState bootstrap, TimeProvider clock)
{
/// <summary>The state now.</summary>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The state.</returns>
public async Task<SystemStatus> GetAsync(CancellationToken cancellationToken = default)
{
var all = await companies.ListAsync(cancellationToken).ConfigureAwait(false);
var now = clock.GetLocalNow();
var since = new DateTimeOffset(now.Date, now.Offset).UtcDateTime;
await using var unitOfWork = await factory.CreateAsync(DatabaseScope.System, cancellationToken).ConfigureAwait(false);
var runs = (await unitOfWork.Repository<JobRun, long>().ListAsync(Query.For<JobRun>().Where(r => r.StartedAt >= since), cancellationToken).ConfigureAwait(false)).Items;
return new SystemStatus(
system.Engine,
all.Count(c => c.Status != CompanyStatus.Disabled),
bootstrap.FailedCompanies.Count,
runs.Count(r => r.Outcome == JobOutcome.Succeeded),
runs.Count(r => r.Outcome == JobOutcome.Failed));
}
}
@@ -0,0 +1,132 @@
using Khaemhat.Application.Modules;
namespace Khaemhat.Application.Dashboard;
/// <summary>
/// A widget of the dashboard (SPEC §10.3, mockup 004): what it is, how wide it starts and who may see it. The
/// <see cref="Milestone"/> of a widget whose data comes from a later module says where its data will come from; until
/// then the widget shows that instead of invented numbers.
/// </summary>
/// <param name="Id">The id, kept in the layouts.</param>
/// <param name="TitleKey">The text key of the title.</param>
/// <param name="Icon">The icon.</param>
/// <param name="DefaultWidth">The starting width in columns of twelve.</param>
/// <param name="Module">The licensed module it needs.</param>
/// <param name="Permission">The permission it needs, if any.</param>
/// <param name="InstanceOnly">Only for administrators of the instance.</param>
/// <param name="Milestone">The milestone that brings its data, if still to come.</param>
public sealed record WidgetDefinition(
string Id,
string TitleKey,
string Icon,
int DefaultWidth,
string Module,
string? Permission = null,
bool InstanceOnly = false,
string? Milestone = null)
{
/// <summary>The widths a widget can take, in columns of twelve.</summary>
public static readonly IReadOnlyList<int> Widths = [3, 4, 6, 8, 12];
/// <summary>The text key of the description shown in the customize panel.</summary>
public string DescriptionKey => TitleKey[..TitleKey.LastIndexOf('.')] + ".Description";
/// <summary>The nearest allowed width.</summary>
/// <param name="width">Any number.</param>
/// <returns>One of <see cref="Widths"/>.</returns>
public static int Snap(int width) => Widths.OrderBy(w => Math.Abs(w - width)).ThenByDescending(w => w).First();
/// <summary>The next width up or down, staying at the ends.</summary>
/// <param name="width">The current width.</param>
/// <param name="step">+1 wider, -1 narrower.</param>
/// <returns>The width.</returns>
public static int Step(int width, int step)
{
var index = Math.Clamp(Widths.ToList().IndexOf(Snap(width)) + Math.Sign(step), 0, Widths.Count - 1);
return Widths[index];
}
}
/// <summary>The ids of the widgets.</summary>
public static class WidgetIds
{
/// <summary>Indicators chosen by the user.</summary>
public const string Kpi = "kpi";
/// <summary>What to do today.</summary>
public const string Todo = "todo";
/// <summary>What was done today.</summary>
public const string Done = "done";
/// <summary>Deadlines of the next 30 days.</summary>
public const string Deadlines = "deadlines";
/// <summary>Orders and delivery notes still to fulfil.</summary>
public const string ToFulfil = "to-fulfil";
/// <summary>Revenue of the last 12 months.</summary>
public const string Revenue = "revenue";
/// <summary>CRM activities.</summary>
public const string CrmActivities = "crm-activities";
/// <summary>Personal reminders.</summary>
public const string Notes = "notes";
/// <summary>Shortcut buttons.</summary>
public const string Shortcuts = "shortcuts";
/// <summary>Items under the minimum stock.</summary>
public const string Understock = "understock";
/// <summary>The CRM pipeline.</summary>
public const string Pipeline = "pipeline";
/// <summary>The last documents.</summary>
public const string RecentDocuments = "recent-documents";
/// <summary>State of the system (administrators).</summary>
public const string SystemStatus = "system";
}
/// <summary>Every widget, in the order of the customize panel (SPEC §10.3).</summary>
public static class WidgetCatalog
{
/// <summary>The widgets.</summary>
public static IReadOnlyList<WidgetDefinition> All { get; } =
[
new(WidgetIds.Kpi, "Dashboard.Widgets.Kpi.Title", "chart", 12, ModuleCodes.Core, "sales.invoice.read", Milestone: "M5"),
new(WidgetIds.Todo, "Dashboard.Widgets.Todo.Title", "check-circle", 4, ModuleCodes.Core),
new(WidgetIds.Done, "Dashboard.Widgets.Done.Title", "check", 4, ModuleCodes.Core),
new(WidgetIds.Deadlines, "Dashboard.Widgets.Deadlines.Title", "calendar", 4, ModuleCodes.Core),
new(WidgetIds.ToFulfil, "Dashboard.Widgets.ToFulfil.Title", "truck", 8, ModuleCodes.Core, "sales.order.read", Milestone: "M5"),
new(WidgetIds.Revenue, "Dashboard.Widgets.Revenue.Title", "chart", 4, ModuleCodes.Core, "sales.invoice.read", Milestone: "M5"),
new(WidgetIds.CrmActivities, "Dashboard.Widgets.CrmActivities.Title", "target", 6, ModuleCodes.Crm, "crm.lead.read", Milestone: "M11"),
new(WidgetIds.Notes, "Dashboard.Widgets.Notes.Title", "edit", 4, ModuleCodes.Core),
new(WidgetIds.Shortcuts, "Dashboard.Widgets.Shortcuts.Title", "zap", 4, ModuleCodes.Core),
new(WidgetIds.Understock, "Dashboard.Widgets.Understock.Title", "box", 6, ModuleCodes.Core, "inventory.stock.read", Milestone: "M6"),
new(WidgetIds.Pipeline, "Dashboard.Widgets.Pipeline.Title", "target", 6, ModuleCodes.Crm, "crm.lead.read", Milestone: "M11"),
new(WidgetIds.RecentDocuments, "Dashboard.Widgets.RecentDocuments.Title", "file", 6, ModuleCodes.Core, "sales.invoice.read", Milestone: "M5"),
new(WidgetIds.SystemStatus, "Dashboard.Widgets.System.Title", "shield", 4, ModuleCodes.Core, InstanceOnly: true),
];
/// <summary>
/// The layout of whoever never customized it and has no default from a role: the widgets that already have data.
/// Those that wait for a later module stay in the panel, ready to be switched on.
/// </summary>
public static DashboardLayout BuiltIn { get; } = new(
[
new(WidgetIds.Todo, 4),
new(WidgetIds.Done, 4),
new(WidgetIds.Deadlines, 4),
new(WidgetIds.Shortcuts, 4),
new(WidgetIds.Notes, 4),
new(WidgetIds.SystemStatus, 4),
]);
/// <summary>Finds a widget.</summary>
/// <param name="id">The id.</param>
/// <returns>The widget, or <see langword="null"/>.</returns>
public static WidgetDefinition? Find(string? id) => All.FirstOrDefault(w => string.Equals(w.Id, id, StringComparison.Ordinal));
}
@@ -0,0 +1,732 @@
using System.Data.Common;
using System.Globalization;
using System.Text.RegularExpressions;
using Khaemhat.Application.Audit;
using Khaemhat.Application.Instance;
using Khaemhat.Application.Security;
using Khaemhat.Core.Files;
using Khaemhat.Data;
using Khaemhat.Data.Querying;
using Khaemhat.Infrastructure.Files;
namespace Khaemhat.Application.Files;
/// <summary>An attachment as the interface shows it.</summary>
/// <param name="Id">The identifier.</param>
/// <param name="Entity">The entity of the owning record.</param>
/// <param name="EntityId">The owning record.</param>
/// <param name="Kind">Uploaded, generated, e-invoice or notification.</param>
/// <param name="Name">The name.</param>
/// <param name="FileName">The download name, with the version suffix from v2 (<c>fattura_v2.pdf</c>).</param>
/// <param name="Mime">The media type.</param>
/// <param name="Size">The size in bytes.</param>
/// <param name="Sha256">The SHA-256 of the content.</param>
/// <param name="Version">The version, from 1.</param>
/// <param name="GeneratedBy">The generator code (generated files).</param>
/// <param name="Locked">Whether it is locked (cannot be deleted).</param>
/// <param name="IsLatest">Whether it is the latest version of its series.</param>
/// <param name="CreatedAt">When it was uploaded or generated (UTC).</param>
/// <param name="CreatedBy">Who uploaded or generated it.</param>
/// <param name="DeletedAt">When it was moved to the trash; <see langword="null"/> if in use.</param>
public sealed record AttachmentView(
long Id, string Entity, long EntityId, AttachmentKind Kind, string Name, string FileName, string Mime, long Size, string Sha256,
int Version, string? GeneratedBy, bool Locked, bool IsLatest, DateTime CreatedAt, string? CreatedBy, DateTime? DeletedAt)
{
/// <summary>How the interface can preview the file.</summary>
public AttachmentPreview Preview => MediaTypes.PreviewOf(Mime);
/// <summary>The version label, <c>v1</c>, <c>v2</c>...</summary>
public string VersionLabel => "v" + Version.ToString(CultureInfo.InvariantCulture);
/// <summary>The view of a row.</summary>
/// <param name="row">The row.</param>
/// <param name="isLatest">Whether it is the latest of its series.</param>
/// <returns>The view.</returns>
public static AttachmentView From(Attachment row, bool isLatest)
{
ArgumentNullException.ThrowIfNull(row);
return new AttachmentView(
row.Id, row.Entity, row.EntityId, row.Kind, row.Name, MediaTypes.VersionedFileName(row.Name, row.Version), row.Mime, row.Size, row.Sha256,
row.Version, row.GeneratedBy, row.Locked, isLatest, row.CreatedAt, row.UserName ?? row.CreatedBy, row.DeletedAt);
}
}
/// <summary>An open attachment: its description and its content. Dispose it to close the file.</summary>
/// <param name="attachment">The attachment.</param>
/// <param name="content">The content, a read-only seekable stream.</param>
public sealed class AttachmentContent(AttachmentView attachment, Stream content) : IAsyncDisposable, IDisposable
{
/// <summary>The attachment.</summary>
public AttachmentView Attachment { get; } = attachment;
/// <summary>The content.</summary>
public Stream Content { get; } = content;
/// <inheritdoc />
public ValueTask DisposeAsync() => Content.DisposeAsync();
/// <inheritdoc />
public void Dispose() => Content.Dispose();
}
/// <summary>A file to attach that is not uploaded by a user: an e-invoice, a notification, a file from a procedure.</summary>
/// <param name="Kind">The kind.</param>
/// <param name="FileName">The file name.</param>
/// <param name="Mime">The media type; from the extension when <see langword="null"/>.</param>
/// <param name="GeneratedBy">The procedure that produced it: the versions count per this code when set, per name otherwise.</param>
/// <param name="Locked">Whether it is locked from the start (for example the XML sent to the SDI).</param>
public sealed record AttachmentFile(AttachmentKind Kind, string FileName, string? Mime = null, string? GeneratedBy = null, bool Locked = false);
/// <summary>
/// The attachments of the company records (SPEC §9.4; wiki <i>Allegati e file</i>): upload, generated files with
/// versions, list, download, ZIP of all, lock, trash and restore. An attachment belongs to exactly one record
/// (<c>entity</c> + <c>entity_id</c>); its bytes are in the <see cref="IFileStore"/>, its row in <c>attachments</c>,
/// and every change writes the history (<see cref="AuditTrail"/>).
/// </summary>
/// <remarks>
/// Permissions: reading needs <c>attachments.read</c>, uploading, generating and locking <c>attachments.write</c>,
/// deleting and restoring <c>attachments.delete</c>. The permission on the owning record is checked by the caller (the
/// document service or page), which knows it. A company user works only in its own company. Deleting moves to the
/// company trash; <see cref="PurgeTrashAsync"/> removes rows and files 30 days later.
/// </remarks>
public sealed partial class AttachmentService
{
/// <summary>Permission to see and download attachments.</summary>
public const string ReadPermission = "attachments.read";
/// <summary>Permission to upload and generate attachments.</summary>
public const string WritePermission = "attachments.write";
/// <summary>Permission to delete and restore attachments.</summary>
public const string DeletePermission = "attachments.delete";
/// <summary>The instance setting with the largest upload in MB (default 25).</summary>
public const string MaxUploadSetting = "files.max-upload-mb";
/// <summary>The instance setting with the space each company may use in MB (default: no quota).</summary>
public const string CompanyQuotaSetting = "files.company-quota-mb";
/// <summary>Error: no such attachment (or not in this company).</summary>
public const string NotFoundError = "attachments.not_found";
/// <summary>Error: the attachment is locked.</summary>
public const string LockedError = "attachments.locked";
/// <summary>Error: the file is larger than the limit.</summary>
public const string TooLargeError = "attachments.file_too_large";
/// <summary>Error: the company has no space left.</summary>
public const string QuotaError = "attachments.quota_exceeded";
/// <summary>Error: the scanner rejected the file.</summary>
public const string RejectedError = "attachments.file_rejected";
/// <summary>Error: the entity or record is not valid.</summary>
public const string InvalidOwnerError = "attachments.owner_invalid";
/// <summary>Error: the file is empty.</summary>
public const string EmptyError = "attachments.file_empty";
/// <summary>How long attachments stay in the trash.</summary>
public static readonly TimeSpan TrashRetention = TimeSpan.FromDays(30);
private const int MaxVersionAttempts = 3;
private const long Megabyte = 1024 * 1024;
private readonly IUnitOfWorkFactory _factory;
private readonly IFileStore _store;
private readonly PermissionService _permissions;
private readonly AuditTrail _audit;
private readonly SystemSettingsStore _settings;
private readonly FileStoreOptions _options;
private readonly TimeProvider _clock;
/// <summary>Creates the service.</summary>
/// <param name="factory">Opens the company databases.</param>
/// <param name="store">The file store.</param>
/// <param name="permissions">Checks permissions.</param>
/// <param name="audit">Writes the history.</param>
/// <param name="settings">Reads the limits set by the administrators.</param>
/// <param name="options">The default limits.</param>
/// <param name="clock">The clock (trash dates).</param>
public AttachmentService(
IUnitOfWorkFactory factory, IFileStore store, PermissionService permissions, AuditTrail audit, SystemSettingsStore settings, FileStoreOptions options, TimeProvider clock)
{
ArgumentNullException.ThrowIfNull(factory);
ArgumentNullException.ThrowIfNull(store);
ArgumentNullException.ThrowIfNull(permissions);
ArgumentNullException.ThrowIfNull(audit);
ArgumentNullException.ThrowIfNull(settings);
ArgumentNullException.ThrowIfNull(options);
ArgumentNullException.ThrowIfNull(clock);
_factory = factory;
_store = store;
_permissions = permissions;
_audit = audit;
_settings = settings;
_options = options;
_clock = clock;
}
/// <summary>The limits in force: the instance settings, else the store defaults (25 MB, no quota).</summary>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The limits for uploads.</returns>
public async Task<FileLimits> GetLimitsAsync(CancellationToken cancellationToken = default)
{
var max = await ReadMegabytesAsync(MaxUploadSetting, cancellationToken).ConfigureAwait(false) ?? _options.MaxFileBytes;
var quota = await ReadMegabytesAsync(CompanyQuotaSetting, cancellationToken).ConfigureAwait(false) ?? _options.CompanyQuotaBytes;
return new FileLimits(max, quota);
}
/// <summary>Uploads a file to a record (streaming; the size limit and the quota apply).</summary>
/// <param name="actor">Who uploads.</param>
/// <param name="companyCode">The company.</param>
/// <param name="entity">The entity of the record, for example <c>sales.invoice</c>.</param>
/// <param name="entityId">The record.</param>
/// <param name="fileName">The file name as received.</param>
/// <param name="declaredMime">The type declared by the client (used only when the extension is unknown).</param>
/// <param name="content">The content.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The new attachment; a file with the same name as an existing one becomes its next version.</returns>
/// <exception cref="AccessDeniedException">The actor may not upload.</exception>
/// <exception cref="ValidationFailedException">The file is empty, too large, over quota or rejected.</exception>
public async Task<AttachmentView> UploadAsync(
Actor actor, string companyCode, string entity, long entityId, string fileName, string? declaredMime, Stream content, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(content);
var company = await DemandAsync(actor, companyCode, WritePermission, cancellationToken).ConfigureAwait(false);
CheckOwner(entity, entityId);
var limits = await GetLimitsAsync(cancellationToken).ConfigureAwait(false);
var stored = await StoreAsync(company, limits, (target, ct) => content.CopyToAsync(target, ct), cancellationToken).ConfigureAwait(false);
var name = MediaTypes.CleanFileName(fileName);
return await RecordAsync(actor, company, entity, entityId, new AttachmentFile(AttachmentKind.Uploaded, name, MediaTypes.Resolve(name, declaredMime)), stored, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Adds a file produced by Khaemhat, written by <paramref name="write"/> straight into the store. Each call adds
/// the next version of the series of <see cref="AttachmentFile.GeneratedBy"/> (or of the name): this is "Rigenera".
/// </summary>
/// <param name="actor">Who generates.</param>
/// <param name="companyCode">The company.</param>
/// <param name="entity">The entity of the record.</param>
/// <param name="entityId">The record.</param>
/// <param name="file">Kind, name, type, generator, lock.</param>
/// <param name="write">Writes the content to the stream it receives (write-only, not seekable).</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The new attachment.</returns>
/// <exception cref="AccessDeniedException">The actor may not add attachments.</exception>
/// <exception cref="ValidationFailedException">The company has no space left, or the file is empty.</exception>
public async Task<AttachmentView> AddAsync(
Actor actor, string companyCode, string entity, long entityId, AttachmentFile file, Func<Stream, CancellationToken, Task> write, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(file);
ArgumentNullException.ThrowIfNull(write);
var company = await DemandAsync(actor, companyCode, WritePermission, cancellationToken).ConfigureAwait(false);
CheckOwner(entity, entityId);
if (file.GeneratedBy is { } generator && (generator.Length is 0 or > 100))
{
throw new ValidationFailedException([InvalidOwnerError]);
}
// Files made by Khaemhat are bounded by their generator: only the quota applies.
var limits = await GetLimitsAsync(cancellationToken).ConfigureAwait(false);
var stored = await StoreAsync(company, new FileLimits(0, limits.QuotaBytes), write, cancellationToken).ConfigureAwait(false);
var name = MediaTypes.CleanFileName(file.FileName);
var normalized = file with { FileName = name, Mime = MediaTypes.Resolve(name, file.Mime) };
return await RecordAsync(actor, company, entity, entityId, normalized, stored, cancellationToken).ConfigureAwait(false);
}
/// <summary>The attachments of a record, newest first (trash excluded).</summary>
/// <param name="actor">Who reads.</param>
/// <param name="companyCode">The company.</param>
/// <param name="entity">The entity.</param>
/// <param name="entityId">The record.</param>
/// <param name="includeOlderVersions">Whether to list the earlier versions too (marked not <see cref="AttachmentView.IsLatest"/>).</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The attachments.</returns>
public async Task<IReadOnlyList<AttachmentView>> ListAsync(
Actor actor, string companyCode, string entity, long entityId, bool includeOlderVersions = false, CancellationToken cancellationToken = default)
{
var company = await DemandAsync(actor, companyCode, ReadPermission, cancellationToken).ConfigureAwait(false);
return Views(await ListRowsAsync(company, entity, entityId, cancellationToken).ConfigureAwait(false), includeOlderVersions);
}
/// <summary>How many attachments a record has (latest versions only): the number on the toolbar icon.</summary>
/// <param name="actor">Who reads.</param>
/// <param name="companyCode">The company.</param>
/// <param name="entity">The entity.</param>
/// <param name="entityId">The record.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The count.</returns>
public async Task<int> CountAsync(Actor actor, string companyCode, string entity, long entityId, CancellationToken cancellationToken = default) =>
(await ListAsync(actor, companyCode, entity, entityId, false, cancellationToken).ConfigureAwait(false)).Count;
/// <summary>One attachment, in use or in the trash.</summary>
/// <param name="actor">Who reads.</param>
/// <param name="companyCode">The company.</param>
/// <param name="attachmentId">The attachment.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The attachment, or <see langword="null"/>.</returns>
public async Task<AttachmentView?> GetAsync(Actor actor, string companyCode, long attachmentId, CancellationToken cancellationToken = default)
{
var company = await DemandAsync(actor, companyCode, ReadPermission, cancellationToken).ConfigureAwait(false);
return (await LoadAsync(company, attachmentId, cancellationToken).ConfigureAwait(false))?.View;
}
/// <summary>Opens an attachment for download or preview.</summary>
/// <param name="actor">Who reads.</param>
/// <param name="companyCode">The company.</param>
/// <param name="attachmentId">The attachment.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The attachment and its content; dispose it.</returns>
/// <exception cref="KeyNotFoundException">No such attachment in use, or its file is missing.</exception>
public async Task<AttachmentContent> OpenAsync(Actor actor, string companyCode, long attachmentId, CancellationToken cancellationToken = default)
{
var company = await DemandAsync(actor, companyCode, ReadPermission, cancellationToken).ConfigureAwait(false);
var loaded = await LoadAsync(company, attachmentId, cancellationToken).ConfigureAwait(false);
if (loaded is not { } found || found.Row.DeletedAt is not null)
{
throw new KeyNotFoundException(NotFoundError);
}
var (row, view) = found;
try
{
return new AttachmentContent(view, _store.OpenRead(company, row.StorageKey));
}
catch (FileStoreException ex) when (ex.Code == FileStoreException.NotFound)
{
throw new KeyNotFoundException(NotFoundError, ex);
}
}
/// <summary>
/// Writes a ZIP with the latest version of every attachment of a record ("Scarica tutto"), streaming: the output
/// can be the HTTP response.
/// </summary>
/// <param name="actor">Who downloads.</param>
/// <param name="companyCode">The company.</param>
/// <param name="entity">The entity.</param>
/// <param name="entityId">The record.</param>
/// <param name="output">The stream that receives the ZIP; it is left open.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>How many files were written.</returns>
public async Task<int> WriteZipAsync(Actor actor, string companyCode, string entity, long entityId, Stream output, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(output);
var company = await DemandAsync(actor, companyCode, ReadPermission, cancellationToken).ConfigureAwait(false);
var rows = await ListRowsAsync(company, entity, entityId, cancellationToken).ConfigureAwait(false);
var keys = rows.ToDictionary(r => r.Id, r => r.StorageKey);
await using var zip = await ZipStreamWriter.CreateAsync(output, leaveOpen: true, cancellationToken).ConfigureAwait(false);
foreach (var attachment in Views(rows, includeOlderVersions: false))
{
var key = keys[attachment.Id];
if (!_store.Exists(company, key))
{
continue;
}
var content = _store.OpenRead(company, key);
await using (content.ConfigureAwait(false))
{
var level = attachment.Mime is "image/jpeg" or "image/png" or MediaTypes.Zip or MediaTypes.Xlsx
? System.IO.Compression.CompressionLevel.NoCompression
: System.IO.Compression.CompressionLevel.Optimal;
await zip.AddAsync(attachment.FileName, content, new DateTimeOffset(DateTime.SpecifyKind(attachment.CreatedAt, DateTimeKind.Utc)), level, cancellationToken).ConfigureAwait(false);
}
}
return zip.Count;
}
/// <summary>Locks an attachment: from now on it cannot be deleted (for example the XML sent to the SDI). Locks are permanent.</summary>
/// <param name="actor">Who locks.</param>
/// <param name="companyCode">The company.</param>
/// <param name="attachmentId">The attachment.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
public Task LockAsync(Actor actor, string companyCode, long attachmentId, CancellationToken cancellationToken = default) =>
ChangeAsync(
actor, companyCode, attachmentId, WritePermission,
row =>
{
if (row.Locked)
{
return false;
}
row.Locked = true;
return true;
},
cancellationToken);
/// <summary>Moves one attachment to the company trash (restorable for 30 days).</summary>
/// <param name="actor">Who deletes.</param>
/// <param name="companyCode">The company.</param>
/// <param name="attachmentId">The attachment.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
/// <exception cref="ValidationFailedException">The attachment is locked (<see cref="LockedError"/>).</exception>
public Task DeleteAsync(Actor actor, string companyCode, long attachmentId, CancellationToken cancellationToken = default)
{
var now = _clock.GetUtcNow().UtcDateTime;
return ChangeAsync(
actor, companyCode, attachmentId, DeletePermission,
row =>
{
if (row.Locked)
{
throw new ValidationFailedException([LockedError]);
}
if (row.DeletedAt is not null)
{
return false;
}
row.DeletedAt = now;
return true;
},
cancellationToken);
}
/// <summary>Takes an attachment back from the trash.</summary>
/// <param name="actor">Who restores.</param>
/// <param name="companyCode">The company.</param>
/// <param name="attachmentId">The attachment.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
public Task RestoreAsync(Actor actor, string companyCode, long attachmentId, CancellationToken cancellationToken = default) =>
ChangeAsync(
actor, companyCode, attachmentId, DeletePermission,
row =>
{
if (row.DeletedAt is null)
{
return false;
}
row.DeletedAt = null;
return true;
},
cancellationToken);
/// <summary>
/// Moves every attachment of a record to the trash: call it in the deletion of the record (the caller has checked
/// that the record may be deleted). Refused when an attachment is locked: a record with a sent e-invoice cannot go.
/// </summary>
/// <param name="actor">Who deletes the record.</param>
/// <param name="companyCode">The company.</param>
/// <param name="entity">The entity.</param>
/// <param name="entityId">The record.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>How many attachments were moved.</returns>
/// <exception cref="ValidationFailedException">An attachment is locked (<see cref="LockedError"/>).</exception>
public Task<int> TrashForEntityAsync(Actor actor, string companyCode, string entity, long entityId, CancellationToken cancellationToken = default) =>
ChangeEntityAsync(actor, companyCode, entity, entityId, toTrash: true, cancellationToken);
/// <summary>Takes back from the trash every attachment of a record (the record was restored).</summary>
/// <param name="actor">Who restores.</param>
/// <param name="companyCode">The company.</param>
/// <param name="entity">The entity.</param>
/// <param name="entityId">The record.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>How many attachments were restored.</returns>
public Task<int> RestoreForEntityAsync(Actor actor, string companyCode, string entity, long entityId, CancellationToken cancellationToken = default) =>
ChangeEntityAsync(actor, companyCode, entity, entityId, toTrash: false, cancellationToken);
/// <summary>The company trash, most recently deleted first.</summary>
/// <param name="actor">Who looks (needs <c>attachments.delete</c>).</param>
/// <param name="companyCode">The company.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The attachments in the trash.</returns>
public async Task<IReadOnlyList<AttachmentView>> ListTrashAsync(Actor actor, string companyCode, CancellationToken cancellationToken = default)
{
var company = await DemandAsync(actor, companyCode, DeletePermission, cancellationToken).ConfigureAwait(false);
await using var unitOfWork = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
var rows = (await unitOfWork.Repository<Attachment, long>().ListAsync(
Query.For<Attachment>().Where(a => a.DeletedAt != null).OrderByDescending(a => a.DeletedAt).Take(1000), cancellationToken).ConfigureAwait(false)).Items;
return rows.Select(r => AttachmentView.From(r, isLatest: false)).ToList();
}
/// <summary>The space the company uses in the file store, with the quota in force.</summary>
/// <param name="actor">Who looks.</param>
/// <param name="companyCode">The company.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The usage.</returns>
public async Task<FileUsage> GetUsageAsync(Actor actor, string companyCode, CancellationToken cancellationToken = default)
{
var company = await DemandAsync(actor, companyCode, ReadPermission, cancellationToken).ConfigureAwait(false);
var limits = await GetLimitsAsync(cancellationToken).ConfigureAwait(false);
return await _store.GetUsageAsync(company, limits.QuotaBytes, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Removes for good the attachments in the trash for more than 30 days, rows and files, and the partial files of
/// interrupted uploads. Run by the scheduled job <see cref="AttachmentTrashPurgeJob"/>.
/// </summary>
/// <param name="companyCode">The company.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>How many attachments were removed.</returns>
public async Task<int> PurgeTrashAsync(string companyCode, CancellationToken cancellationToken = default)
{
var company = CompanyCodes.Normalize(companyCode);
var limit = _clock.GetUtcNow().UtcDateTime - TrashRetention;
await using var unitOfWork = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
var repository = unitOfWork.Repository<Attachment, long>();
var rows = (await repository.ListAsync(Query.For<Attachment>().Where(a => a.DeletedAt != null && a.DeletedAt < limit), cancellationToken).ConfigureAwait(false)).Items;
var removed = 0;
foreach (var row in rows)
{
await unitOfWork.InTransactionAsync(
async ct =>
{
await repository.DeleteAsync(row.Id, ct).ConfigureAwait(false);
await _audit.RecordAsync(unitOfWork, AuditAction.Delete, row.Id, row, null, Actor.System.UserName, ct).ConfigureAwait(false);
},
cancellationToken).ConfigureAwait(false);
// The row is gone: the file follows (a file left behind by a crash here is only wasted space).
if (!await StorageKeyInUseAsync(repository, row.StorageKey, cancellationToken).ConfigureAwait(false))
{
_store.Delete(company, row.StorageKey);
}
removed++;
}
_store.DeleteAbandonedParts(company, TimeSpan.FromDays(1));
return removed;
}
private static List<AttachmentView> Views(IReadOnlyList<Attachment> rows, bool includeOlderVersions)
{
var latest = rows.GroupBy(r => r.VersionKey, StringComparer.Ordinal).ToDictionary(g => g.Key, g => g.Max(r => r.Version), StringComparer.Ordinal);
return rows
.Select(r => AttachmentView.From(r, r.Version == latest[r.VersionKey]))
.Where(v => includeOlderVersions || v.IsLatest)
.ToList();
}
private static void CheckOwner(string entity, long entityId)
{
if (entity is null || entity.Length > 100 || !EntityPattern().IsMatch(entity) || entityId <= 0)
{
throw new ValidationFailedException([InvalidOwnerError]);
}
}
private static string VersionKeyOf(AttachmentFile file) =>
file.GeneratedBy is { } generator ? "gen:" + generator : "name:" + file.FileName.ToLowerInvariant();
private static async Task<bool> IsLatestAsync(IUnitOfWork unitOfWork, Attachment row, CancellationToken cancellationToken)
{
var (entity, id, key, version) = (row.Entity, row.EntityId, row.VersionKey, row.Version);
return await unitOfWork.Repository<Attachment, long>().CountAsync(
Query.For<Attachment>().Where(a => a.Entity == entity && a.EntityId == id && a.VersionKey == key && a.Version > version),
cancellationToken).ConfigureAwait(false) == 0;
}
private static async Task<bool> StorageKeyInUseAsync(IRepository<Attachment, long> repository, string key, CancellationToken cancellationToken) =>
await repository.CountAsync(Query.For<Attachment>().Where(a => a.StorageKey == key), cancellationToken).ConfigureAwait(false) > 0;
[GeneratedRegex("^[a-z][a-z0-9_]*(\\.[a-z][a-z0-9_-]*)*$", RegexOptions.CultureInvariant)]
private static partial Regex EntityPattern();
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;
}
private async Task<long?> ReadMegabytesAsync(string key, CancellationToken cancellationToken)
{
var value = await _settings.GetAsync(key, cancellationToken).ConfigureAwait(false);
return long.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out var megabytes) && megabytes >= 0 ? megabytes * Megabyte : null;
}
private async Task<StoredFile> StoreAsync(string company, FileLimits limits, Func<Stream, CancellationToken, Task> write, CancellationToken cancellationToken)
{
try
{
await using var writer = await _store.CreateAsync(company, limits, cancellationToken).ConfigureAwait(false);
await write(writer.Content, cancellationToken).ConfigureAwait(false);
if (writer.Content.Length == 0)
{
throw new ValidationFailedException([EmptyError]);
}
return await writer.CommitAsync(cancellationToken).ConfigureAwait(false);
}
catch (FileStoreException ex)
{
var code = ex.Code switch
{
FileStoreException.TooLarge => TooLargeError,
FileStoreException.QuotaExceeded => QuotaError,
_ => RejectedError,
};
throw new ValidationFailedException(code, ex);
}
}
private async Task<AttachmentView> RecordAsync(
Actor actor, string company, string entity, long entityId, AttachmentFile file, StoredFile stored, CancellationToken cancellationToken)
{
var key = VersionKeyOf(file);
try
{
for (var attempt = 1; ; attempt++)
{
try
{
return await InsertAsync(actor, company, entity, entityId, file, key, stored, cancellationToken).ConfigureAwait(false);
}
catch (DbException) when (attempt < MaxVersionAttempts)
{
// Two versions of the same series at once: the unique index refused one; take the next number.
}
}
}
catch
{
_store.Delete(company, stored.Key);
throw;
}
}
private async Task<AttachmentView> InsertAsync(
Actor actor, string company, string entity, long entityId, AttachmentFile file, string key, StoredFile stored, CancellationToken cancellationToken)
{
await using var unitOfWork = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
var repository = unitOfWork.Repository<Attachment, long>();
Attachment? row = null;
await unitOfWork.InTransactionAsync(
async ct =>
{
var last = await repository.FindAsync(
Query.For<Attachment>().Where(a => a.Entity == entity && a.EntityId == entityId && a.VersionKey == key).OrderByDescending(a => a.Version).Take(1),
ct).ConfigureAwait(false);
row = new Attachment
{
Entity = entity,
EntityId = entityId,
Kind = file.Kind,
Name = file.FileName,
Mime = file.Mime ?? MediaTypes.OctetStream,
Size = stored.Size,
Sha256 = stored.Sha256,
Version = (last?.Version ?? 0) + 1,
VersionKey = key,
GeneratedBy = file.GeneratedBy,
StorageKey = stored.Key,
UserName = actor.UserName.Length > 100 ? actor.UserName[..100] : actor.UserName,
Locked = file.Locked,
};
await repository.InsertAsync(row, ct).ConfigureAwait(false);
await _audit.RecordAsync(unitOfWork, AuditAction.Insert, row.Id, null, row, actor.UserName, ct).ConfigureAwait(false);
},
cancellationToken).ConfigureAwait(false);
return AttachmentView.From(row!, isLatest: true);
}
private async Task ChangeAsync(Actor actor, string companyCode, long attachmentId, string permission, Func<Attachment, bool> change, CancellationToken cancellationToken)
{
var company = await DemandAsync(actor, companyCode, permission, cancellationToken).ConfigureAwait(false);
await using var unitOfWork = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
var repository = unitOfWork.Repository<Attachment, long>();
await unitOfWork.InTransactionAsync(
async ct =>
{
var row = await repository.GetAsync(attachmentId, ct).ConfigureAwait(false) ?? throw new KeyNotFoundException(NotFoundError);
var before = Copy(row);
if (change(row))
{
await repository.UpdateAsync(row, ct).ConfigureAwait(false);
await _audit.RecordAsync(unitOfWork, AuditAction.Update, row.Id, before, row, actor.UserName, ct).ConfigureAwait(false);
}
},
cancellationToken).ConfigureAwait(false);
}
private async Task<int> ChangeEntityAsync(Actor actor, string companyCode, string entity, long entityId, bool toTrash, 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.");
}
CheckOwner(entity, entityId);
var now = _clock.GetUtcNow().UtcDateTime;
var changed = 0;
await using var unitOfWork = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
var repository = unitOfWork.Repository<Attachment, long>();
await unitOfWork.InTransactionAsync(
async ct =>
{
var query = toTrash
? Query.For<Attachment>().Where(a => a.Entity == entity && a.EntityId == entityId && a.DeletedAt == null)
: Query.For<Attachment>().Where(a => a.Entity == entity && a.EntityId == entityId && a.DeletedAt != null);
var rows = (await repository.ListAsync(query, ct).ConfigureAwait(false)).Items;
if (toTrash && rows.Any(r => r.Locked))
{
throw new ValidationFailedException([LockedError]);
}
foreach (var row in rows)
{
var before = Copy(row);
row.DeletedAt = toTrash ? now : null;
await repository.UpdateAsync(row, ct).ConfigureAwait(false);
await _audit.RecordAsync(unitOfWork, AuditAction.Update, row.Id, before, row, actor.UserName, ct).ConfigureAwait(false);
changed++;
}
},
cancellationToken).ConfigureAwait(false);
return changed;
}
private async Task<IReadOnlyList<Attachment>> ListRowsAsync(string company, string entity, long entityId, CancellationToken cancellationToken)
{
await using var unitOfWork = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
return (await unitOfWork.Repository<Attachment, long>().ListAsync(
Query.For<Attachment>().Where(a => a.Entity == entity && a.EntityId == entityId && a.DeletedAt == null).OrderByDescending(a => a.Id),
cancellationToken).ConfigureAwait(false)).Items;
}
private async Task<(Attachment Row, AttachmentView View)?> LoadAsync(string company, long attachmentId, CancellationToken cancellationToken)
{
await using var unitOfWork = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
var row = await unitOfWork.Repository<Attachment, long>().GetAsync(attachmentId, cancellationToken).ConfigureAwait(false);
return row is null ? null : (row, AttachmentView.From(row, await IsLatestAsync(unitOfWork, row, cancellationToken).ConfigureAwait(false)));
}
private static Attachment Copy(Attachment row) => new()
{
Id = row.Id,
Entity = row.Entity,
EntityId = row.EntityId,
Kind = row.Kind,
Name = row.Name,
Mime = row.Mime,
Size = row.Size,
Sha256 = row.Sha256,
Version = row.Version,
VersionKey = row.VersionKey,
GeneratedBy = row.GeneratedBy,
StorageKey = row.StorageKey,
UserName = row.UserName,
Locked = row.Locked,
DeletedAt = row.DeletedAt,
};
}
@@ -0,0 +1,36 @@
using System.Globalization;
using Khaemhat.Application.Jobs;
using Khaemhat.Core.Instance;
using Khaemhat.Data.Companies;
namespace Khaemhat.Application.Files;
/// <summary>
/// Empties the company trash of attachments (SPEC §9.4): every night, in every company that is not disabled, removes
/// rows and files deleted more than 30 days ago and the partial files of interrupted uploads.
/// </summary>
/// <param name="attachments">The attachments.</param>
/// <param name="companies">The companies.</param>
public sealed class AttachmentTrashPurgeJob(AttachmentService attachments, ICompanyRegistry companies) : IScheduledJob
{
/// <summary>The job type.</summary>
public const string JobType = "system.attachments-trash";
/// <inheritdoc />
public string Type => JobType;
/// <inheritdoc />
public async Task<string?> RunAsync(JobContext context, CancellationToken cancellationToken)
{
var removed = 0;
foreach (var company in await companies.ListAsync(cancellationToken).ConfigureAwait(false))
{
if (company.Status is not CompanyStatus.Disabled)
{
removed += await attachments.PurgeTrashAsync(company.Code, cancellationToken).ConfigureAwait(false);
}
}
return string.Create(CultureInfo.InvariantCulture, $"{removed} allegati eliminati dal cestino.");
}
}
@@ -0,0 +1,238 @@
using System.Globalization;
using Khaemhat.Infrastructure.Files;
namespace Khaemhat.Application.Files;
/// <summary>
/// The <i>documento di prova</i> of issue #34: a clearly fictitious document (entity <see cref="Entity"/>) used to try
/// attachments, generation, versions and print preview before the real documents exist (M5). Every value is invented.
/// </summary>
public static class DemoDocument
{
/// <summary>The entity of the test document.</summary>
public const string Entity = "demo.document";
/// <summary>The title printed on the test document.</summary>
public const string Title = "Documento di prova";
/// <summary>The fictitious lines: code, description, quantity, unit price.</summary>
public static IReadOnlyList<(string Code, string Description, decimal Quantity, decimal UnitPrice)> Lines { get; } =
[
("PROVA-001", "Articolo di prova – vite inventata", 10m, 1.25m),
("PROVA-002", "Servizio fittizio di consulenza (non reale)", 2m, 480m),
("PROVA-003", "Materiale d'esempio: cavo €uro-test 3×1,5", 25.5m, 3.9m),
("PROVA-004", "Riga con accenti: perché, città, più, così", 1m, 1234.56m),
("PROVA-005", "Sconto finto", 1m, -50m),
];
/// <summary>The headers of the line table.</summary>
public static IReadOnlyList<string> Headers { get; } = ["Codice", "Descrizione", "Quantità", "Prezzo unitario", "Importo"];
/// <summary>The amount of a line.</summary>
/// <param name="line">The line.</param>
/// <returns>Quantity times unit price, rounded to cents.</returns>
public static decimal Amount((string Code, string Description, decimal Quantity, decimal UnitPrice) line) =>
Math.Round(line.Quantity * line.UnitPrice, 2, MidpointRounding.AwayFromZero);
/// <summary>The total of the lines.</summary>
public static decimal Total => Lines.Sum(Amount);
/// <summary>An amount in euro as Italians write it: <c>€ 1.234,56</c>.</summary>
/// <param name="value">The amount.</param>
/// <param name="culture">The culture (it-IT).</param>
/// <returns>The text.</returns>
public static string Euro(decimal value, CultureInfo culture) =>
(value < 0 ? "-€ " : "€ ") + Math.Abs(value).ToString("N2", culture);
/// <summary>The file name stem for a record.</summary>
/// <param name="context">The record.</param>
/// <returns>For example <c>documento-di-prova-7</c>.</returns>
public static string Stem(FileGenerationContext context)
{
ArgumentNullException.ThrowIfNull(context);
return "documento-di-prova-" + context.EntityId.ToString(CultureInfo.InvariantCulture);
}
}
/// <summary>The test PDF of the test document: title, a paragraph and the table of lines with amounts aligned right.</summary>
public sealed class DemoPdfGenerator : IFileGenerator
{
/// <summary>The generator code.</summary>
public const string GeneratorCode = "demo.test-pdf";
/// <inheritdoc />
public string Code => GeneratorCode;
/// <inheritdoc />
public string TitleKey => "files.generators.demo_pdf";
/// <inheritdoc />
public string MediaType => PdfWriter.MediaType;
/// <inheritdoc />
public string Extension => ".pdf";
/// <inheritdoc />
public bool Supports(string entity) => entity == DemoDocument.Entity;
/// <inheritdoc />
public string FileName(FileGenerationContext context) => DemoDocument.Stem(context) + Extension;
/// <inheritdoc />
public async Task GenerateAsync(FileGenerationContext context, Stream output, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(context);
var culture = context.Culture;
var accent = PdfColor.FromHex("#1F5F8B");
var muted = PdfColor.Gray(110);
var info = new PdfDocumentInfo
{
Title = DemoDocument.Title + " n. " + context.EntityId.ToString(CultureInfo.InvariantCulture),
Author = context.CompanyCode,
Subject = "Documento fittizio per provare la generazione dei file",
CreationDate = new DateTimeOffset(DateTime.SpecifyKind(context.Now, DateTimeKind.Utc)),
};
await using var pdf = new PdfWriter(output, info, leaveOpen: true);
var page = await pdf.AddPageAsync(cancellationToken: cancellationToken).ConfigureAwait(false);
const double left = 50;
var right = page.Width - 50;
var y = page.Height - 70;
page.DrawText(DemoDocument.Title, left, y, PdfFont.HelveticaBold, 20, accent);
page.DrawTextRight("n. " + context.EntityId.ToString(CultureInfo.InvariantCulture) + " del " + context.Now.ToString("d", culture), right, y, PdfFont.Helvetica, 10, muted);
y -= 12;
page.DrawLine(left, y, right, y, 1, accent);
y -= 22;
y = page.DrawParagraph(
"Questo è un documento di prova generato da Khaemhat: azienda " + context.CompanyCode + ", generato da " + context.Actor.UserName
+ ". Righe, prezzi e importi sono inventati e servono solo a provare stampa, allegati e versioni (v1, v2…).",
left, y, right - left, PdfFont.Helvetica, 10, 13);
y -= 16;
// Table: code, description, quantity, unit price, amount (the last three aligned right).
double[] edges = [left, left + 75, right - 205, right - 135, right - 65, right];
page.DrawRectangle(left, y - 6, right - left, 18, fill: PdfColor.Gray(235));
for (var i = 0; i < DemoDocument.Headers.Count; i++)
{
if (i < 2)
{
page.DrawText(DemoDocument.Headers[i], edges[i] + 4, y, PdfFont.HelveticaBold, 9);
}
else
{
page.DrawTextRight(DemoDocument.Headers[i], edges[i + 1] - 4, y, PdfFont.HelveticaBold, 9);
}
}
y -= 20;
foreach (var line in DemoDocument.Lines)
{
page.DrawText(line.Code, edges[0] + 4, y, PdfFont.Courier, 9);
page.DrawText(PdfTextLayout.Fit(line.Description, PdfFont.Helvetica, 9, edges[2] - edges[1] - 8), edges[1] + 4, y, PdfFont.Helvetica, 9);
page.DrawTextRight(line.Quantity.ToString("#,##0.##", culture), edges[3] - 4, y, PdfFont.Helvetica, 9);
page.DrawTextRight(DemoDocument.Euro(line.UnitPrice, culture), edges[4] - 4, y, PdfFont.Helvetica, 9);
page.DrawTextRight(DemoDocument.Euro(DemoDocument.Amount(line), culture), edges[5] - 4, y, PdfFont.Helvetica, 9);
y -= 6;
page.DrawLine(left, y, right, y, 0.25, PdfColor.Gray(200));
y -= 12;
}
y -= 4;
page.DrawText("Totale", edges[3] + 4, y, PdfFont.HelveticaBold, 11);
page.DrawTextRight(DemoDocument.Euro(DemoDocument.Total, culture), right - 4, y, PdfFont.HelveticaBold, 11, accent);
page.DrawText("Documento fittizio – nessun valore fiscale", left, 40, PdfFont.HelveticaOblique, 8, muted);
page.DrawTextRight("Pagina 1", right, 40, PdfFont.Helvetica, 8, muted);
await pdf.CloseAsync(cancellationToken).ConfigureAwait(false);
}
}
/// <summary>The lines of the test document as CSV (Italian Excel: <c>;</c>, decimal comma, BOM).</summary>
public sealed class DemoCsvGenerator : IFileGenerator
{
/// <summary>The generator code.</summary>
public const string GeneratorCode = "demo.test-csv";
/// <inheritdoc />
public string Code => GeneratorCode;
/// <inheritdoc />
public string TitleKey => "files.generators.demo_csv";
/// <inheritdoc />
public string MediaType => MediaTypes.Csv;
/// <inheritdoc />
public string Extension => ".csv";
/// <inheritdoc />
public bool Supports(string entity) => entity == DemoDocument.Entity;
/// <inheritdoc />
public string FileName(FileGenerationContext context) => DemoDocument.Stem(context) + "-righe" + Extension;
/// <inheritdoc />
public async Task GenerateAsync(FileGenerationContext context, Stream output, CancellationToken cancellationToken)
{
await using var csv = new CsvWriter(output, CsvOptions.Italian, leaveOpen: true);
await csv.WriteRowAsync(DemoDocument.Headers, cancellationToken).ConfigureAwait(false);
foreach (var line in DemoDocument.Lines)
{
await csv.WriteRowAsync([line.Code, line.Description, line.Quantity, line.UnitPrice, DemoDocument.Amount(line)], cancellationToken).ConfigureAwait(false);
}
await csv.FlushAsync(cancellationToken).ConfigureAwait(false);
}
}
/// <summary>The lines of the test document as an XLSX sheet with bold header and euro amounts.</summary>
public sealed class DemoXlsxGenerator : IFileGenerator
{
/// <summary>The generator code.</summary>
public const string GeneratorCode = "demo.test-xlsx";
/// <inheritdoc />
public string Code => GeneratorCode;
/// <inheritdoc />
public string TitleKey => "files.generators.demo_xlsx";
/// <inheritdoc />
public string MediaType => XlsxWriter.MediaType;
/// <inheritdoc />
public string Extension => ".xlsx";
/// <inheritdoc />
public bool Supports(string entity) => entity == DemoDocument.Entity;
/// <inheritdoc />
public string FileName(FileGenerationContext context) => DemoDocument.Stem(context) + "-righe" + Extension;
/// <inheritdoc />
public async Task GenerateAsync(FileGenerationContext context, Stream output, CancellationToken cancellationToken)
{
var xlsx = await XlsxWriter.CreateAsync(output, leaveOpen: true, cancellationToken: cancellationToken).ConfigureAwait(false);
await using (xlsx.ConfigureAwait(false))
{
await xlsx.StartSheetAsync(
"Righe",
[
new XlsxColumn(DemoDocument.Headers[0], 14),
new XlsxColumn(DemoDocument.Headers[1], 48),
new XlsxColumn(DemoDocument.Headers[2], 12, XlsxFormat.TwoDecimals),
new XlsxColumn(DemoDocument.Headers[3], 16, XlsxFormat.Euro),
new XlsxColumn(DemoDocument.Headers[4], 16, XlsxFormat.Euro),
],
cancellationToken).ConfigureAwait(false);
foreach (var line in DemoDocument.Lines)
{
await xlsx.WriteRowAsync([line.Code, line.Description, line.Quantity, line.UnitPrice, DemoDocument.Amount(line)], cancellationToken).ConfigureAwait(false);
}
await xlsx.WriteRowAsync([null, "Totale", null, null, DemoDocument.Total], cancellationToken).ConfigureAwait(false);
await xlsx.CompleteAsync(cancellationToken).ConfigureAwait(false);
}
}
}
@@ -0,0 +1,165 @@
using System.Globalization;
using Khaemhat.Application.Security;
using Khaemhat.Core.Files;
using Khaemhat.Data;
namespace Khaemhat.Application.Files;
/// <summary>What a generator receives besides the output stream.</summary>
/// <param name="Actor">Who asked for the file (the generator reads data on its behalf).</param>
/// <param name="CompanyCode">The company.</param>
/// <param name="Entity">The entity of the record, for example <c>sales.invoice</c>.</param>
/// <param name="EntityId">The record.</param>
/// <param name="Culture">The culture of numbers, dates and texts (it-IT).</param>
/// <param name="Now">When the file is generated (UTC).</param>
public sealed record FileGenerationContext(Actor Actor, string CompanyCode, string Entity, long EntityId, CultureInfo Culture, DateTime Now);
/// <summary>
/// An output of the <i>Genera file</i> section (SPEC §9.4): print PDF, XML FatturaPA, rows in XLSX/CSV, courtesy ZIP...
/// Modules register theirs as <see cref="IFileGenerator"/> singletons; <see cref="FileGenerationService"/> runs them.
/// </summary>
public interface IFileGenerator
{
/// <summary>The unique code, also written in <c>attachments.generated_by</c> (versions count per code), for example <c>sales.invoice.pdf</c>.</summary>
string Code { get; }
/// <summary>The text key of the label shown in the interface (Italian text in the Web resources).</summary>
string TitleKey { get; }
/// <summary>The media type of the output.</summary>
string MediaType { get; }
/// <summary>The extension of the output, with the dot (<c>.pdf</c>).</summary>
string Extension { get; }
/// <summary>Whether the generator applies to records of an entity.</summary>
/// <param name="entity">The entity.</param>
/// <returns><see langword="true"/> if it does.</returns>
bool Supports(string entity);
/// <summary>The file name for a record, with extension (for example <c>Fattura-2026-15.pdf</c>).</summary>
/// <param name="context">The record.</param>
/// <returns>The file name.</returns>
string FileName(FileGenerationContext context);
/// <summary>Writes the file. The stream is write-only and not seekable; write with asynchronous calls.</summary>
/// <param name="context">The record.</param>
/// <param name="output">The stream that receives the file; do not close it.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
Task GenerateAsync(FileGenerationContext context, Stream output, CancellationToken cancellationToken);
}
/// <summary>The registered generators, by code.</summary>
public sealed class FileGeneratorRegistry
{
private readonly Dictionary<string, IFileGenerator> _byCode;
/// <summary>Creates the registry.</summary>
/// <param name="generators">The generators (codes must be unique).</param>
public FileGeneratorRegistry(IEnumerable<IFileGenerator> generators)
{
ArgumentNullException.ThrowIfNull(generators);
_byCode = new Dictionary<string, IFileGenerator>(StringComparer.Ordinal);
foreach (var generator in generators)
{
if (!_byCode.TryAdd(generator.Code, generator))
{
throw new InvalidOperationException($"Two file generators have code {generator.Code}.");
}
}
}
/// <summary>Every generator, by code.</summary>
public IReadOnlyCollection<IFileGenerator> All => _byCode.Values;
/// <summary>The generator with a code.</summary>
/// <param name="code">The code.</param>
/// <returns>The generator, or <see langword="null"/>.</returns>
public IFileGenerator? Find(string code) => _byCode.GetValueOrDefault(code);
/// <summary>The generators that apply to an entity, by code.</summary>
/// <param name="entity">The entity.</param>
/// <returns>The generators.</returns>
public IReadOnlyList<IFileGenerator> For(string entity) =>
_byCode.Values.Where(g => g.Supports(entity)).OrderBy(g => g.Code, StringComparer.Ordinal).ToList();
}
/// <summary>
/// Runs the generators (SPEC §9.4): <see cref="GenerateAsync"/> writes the file straight into the file store and
/// records it as a generated attachment of the record, with the next version (<c>v1</c>, <c>v2</c>... "Rigenera");
/// <see cref="WriteAsync"/> writes it to any stream without keeping it (print preview, direct download).
/// </summary>
/// <param name="registry">The generators.</param>
/// <param name="attachments">Records the generated files.</param>
/// <param name="permissions">Checks permissions for <see cref="WriteAsync"/>.</param>
/// <param name="clock">The clock.</param>
public sealed class FileGenerationService(FileGeneratorRegistry registry, AttachmentService attachments, PermissionService permissions, TimeProvider clock)
{
/// <summary>Error: no generator with that code applies to the record.</summary>
public const string UnknownGeneratorError = "attachments.generator_unknown";
private static readonly CultureInfo Italian = CultureInfo.GetCultureInfo("it-IT");
/// <summary>The generators that apply to an entity (the <i>Genera file</i> list).</summary>
/// <param name="entity">The entity.</param>
/// <returns>The generators.</returns>
public IReadOnlyList<IFileGenerator> AvailableFor(string entity) => registry.For(entity);
/// <summary>Generates a file and attaches it to the record as the next version of the generator's series.</summary>
/// <param name="actor">Who generates (needs <c>attachments.write</c>).</param>
/// <param name="companyCode">The company.</param>
/// <param name="entity">The entity.</param>
/// <param name="entityId">The record.</param>
/// <param name="generatorCode">The generator.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The new attachment.</returns>
/// <exception cref="ValidationFailedException">No such generator for the entity (<see cref="UnknownGeneratorError"/>).</exception>
public Task<AttachmentView> GenerateAsync(
Actor actor, string companyCode, string entity, long entityId, string generatorCode, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(actor);
var generator = Resolve(entity, generatorCode);
var context = Context(actor, companyCode, entity, entityId);
var file = new AttachmentFile(AttachmentKind.Generated, generator.FileName(context), generator.MediaType, generator.Code);
return attachments.AddAsync(actor, companyCode, entity, entityId, file, (output, ct) => generator.GenerateAsync(context, output, ct), cancellationToken);
}
/// <summary>Generates a file into a stream without attaching it (print preview, report download).</summary>
/// <param name="actor">Who asks (needs <c>attachments.read</c>).</param>
/// <param name="companyCode">The company.</param>
/// <param name="entity">The entity.</param>
/// <param name="entityId">The record.</param>
/// <param name="generatorCode">The generator.</param>
/// <param name="output">The stream; left open.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The file name and media type of what was written.</returns>
public async Task<(string FileName, string MediaType)> WriteAsync(
Actor actor, string companyCode, string entity, long entityId, string generatorCode, Stream output, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(actor);
ArgumentNullException.ThrowIfNull(output);
var generator = Resolve(entity, generatorCode);
if (!actor.IsInstanceAccount && !string.Equals(actor.CompanyCode, CompanyCodes.Normalize(companyCode), StringComparison.Ordinal))
{
throw new AccessDeniedException(SecurityErrors.PermissionDenied, "A company user works only in its own company.");
}
await permissions.DemandAsync(actor, AttachmentService.ReadPermission, cancellationToken).ConfigureAwait(false);
var context = Context(actor, companyCode, entity, entityId);
await generator.GenerateAsync(context, output, cancellationToken).ConfigureAwait(false);
return (MediaTypes.CleanFileName(generator.FileName(context)), generator.MediaType);
}
private IFileGenerator Resolve(string entity, string generatorCode)
{
ArgumentNullException.ThrowIfNull(entity);
ArgumentNullException.ThrowIfNull(generatorCode);
return registry.Find(generatorCode) is { } generator && generator.Supports(entity)
? generator
: throw new ValidationFailedException([UnknownGeneratorError]);
}
private FileGenerationContext Context(Actor actor, string companyCode, string entity, long entityId) =>
new(actor, CompanyCodes.Normalize(companyCode), entity, entityId, Italian, clock.GetUtcNow().UtcDateTime);
}
@@ -0,0 +1,355 @@
using System.Globalization;
using System.IO.Compression;
using System.Text;
using System.Xml;
namespace Khaemhat.Application.Files;
/// <summary>What the preview of a text or table file shows (mockup 024: XML, CSV, XLSX).</summary>
/// <param name="Kind">The kind of preview.</param>
/// <param name="Text">The text (XML, plain text), possibly cut.</param>
/// <param name="Rows">The cells (CSV, XLSX), possibly cut.</param>
/// <param name="Truncated">Whether the file goes on after what is shown.</param>
public sealed record FilePreview(AttachmentPreview Kind, string? Text, IReadOnlyList<IReadOnlyList<string>>? Rows, bool Truncated)
{
/// <summary>The most characters of text shown.</summary>
public const int MaxChars = 200_000;
/// <summary>The most rows of a table shown.</summary>
public const int MaxRows = 200;
/// <summary>The most columns of a table shown.</summary>
public const int MaxColumns = 40;
/// <summary>Reads the preview of a file; PDF and images are shown by the browser and give no text.</summary>
/// <param name="kind">The kind, from the media type.</param>
/// <param name="content">The content, readable.</param>
/// <param name="culture">The culture for numbers of spreadsheets.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The preview; with neither text nor rows when the file cannot be read.</returns>
public static async Task<FilePreview> ReadAsync(AttachmentPreview kind, Stream content, CultureInfo culture, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(content);
ArgumentNullException.ThrowIfNull(culture);
try
{
return kind switch
{
AttachmentPreview.Xml or AttachmentPreview.Text => await TextAsync(kind, content, cancellationToken).ConfigureAwait(false),
AttachmentPreview.Csv => await CsvAsync(content, cancellationToken).ConfigureAwait(false),
AttachmentPreview.Xlsx => await XlsxAsync(content, culture, cancellationToken).ConfigureAwait(false),
_ => new FilePreview(kind, null, null, false),
};
}
catch (Exception ex) when (ex is InvalidDataException or XmlException or IOException)
{
return new FilePreview(kind, null, null, false);
}
}
private static async Task<(string Text, bool Truncated)> ReadTextAsync(Stream content, CancellationToken cancellationToken)
{
using var reader = new StreamReader(content, Encoding.UTF8, detectEncodingFromByteOrderMarks: true, leaveOpen: true);
var buffer = new char[MaxChars + 1];
var read = 0;
while (read < buffer.Length)
{
var n = await reader.ReadAsync(buffer.AsMemory(read), cancellationToken).ConfigureAwait(false);
if (n == 0)
{
break;
}
read += n;
}
return read > MaxChars ? (new string(buffer, 0, MaxChars), true) : (new string(buffer, 0, read), false);
}
private static async Task<FilePreview> TextAsync(AttachmentPreview kind, Stream content, CancellationToken cancellationToken)
{
var (text, truncated) = await ReadTextAsync(content, cancellationToken).ConfigureAwait(false);
return new FilePreview(kind, text, null, truncated);
}
private static async Task<FilePreview> CsvAsync(Stream content, CancellationToken cancellationToken)
{
var (text, truncated) = await ReadTextAsync(content, cancellationToken).ConfigureAwait(false);
var rows = Csv(text, out var more);
return new FilePreview(AttachmentPreview.Csv, null, rows, truncated || more);
}
/// <summary>Splits CSV text into cells: separator <c>;</c> or <c>,</c> (the more frequent in the first line), quotes as RFC 4180.</summary>
/// <param name="text">The text.</param>
/// <param name="truncated">Whether there were more rows than <see cref="MaxRows"/>.</param>
/// <returns>The rows.</returns>
public static List<IReadOnlyList<string>> Csv(string text, out bool truncated)
{
ArgumentNullException.ThrowIfNull(text);
var firstLine = text.AsSpan(0, Math.Max(0, text.IndexOf('\n') is var nl and >= 0 ? nl : text.Length));
var separator = firstLine.Count(';') >= firstLine.Count(',') ? ';' : ',';
var rows = new List<IReadOnlyList<string>>();
var row = new List<string>();
var cell = new StringBuilder();
var quoted = false;
truncated = false;
for (var i = 0; i < text.Length; i++)
{
var c = text[i];
if (quoted)
{
if (c == '"' && i + 1 < text.Length && text[i + 1] == '"')
{
cell.Append('"');
i++;
}
else if (c == '"')
{
quoted = false;
}
else
{
cell.Append(c);
}
}
else if (c == '"' && cell.Length == 0)
{
quoted = true;
}
else if (c == separator)
{
AddCell();
}
else if (c == '\n')
{
if (!EndRow())
{
truncated = true;
return rows;
}
}
else if (c != '\r' && c != '')
{
cell.Append(c);
}
}
if (cell.Length > 0 || row.Count > 0)
{
EndRow();
}
return rows;
void AddCell()
{
if (row.Count < MaxColumns)
{
row.Add(cell.ToString());
}
cell.Clear();
}
bool EndRow()
{
AddCell();
if (rows.Count == MaxRows)
{
return false;
}
rows.Add([.. row]);
row.Clear();
return true;
}
}
private static async Task<FilePreview> XlsxAsync(Stream content, CultureInfo culture, CancellationToken cancellationToken)
{
// ZipArchive needs a seekable stream; attachments are files, generated content is copied first.
var source = content;
MemoryStream? copy = null;
if (!content.CanSeek)
{
copy = new MemoryStream();
await content.CopyToAsync(copy, cancellationToken).ConfigureAwait(false);
copy.Position = 0;
source = copy;
}
try
{
using var zip = new ZipArchive(source, ZipArchiveMode.Read, leaveOpen: true);
var shared = zip.GetEntry("xl/sharedStrings.xml") is { } strings ? SharedStrings(strings) : [];
var sheet = zip.GetEntry("xl/worksheets/sheet1.xml")
?? zip.Entries.Where(e => e.FullName.StartsWith("xl/worksheets/", StringComparison.Ordinal) && e.FullName.EndsWith(".xml", StringComparison.Ordinal))
.OrderBy(e => e.FullName, StringComparer.Ordinal).FirstOrDefault();
if (sheet is null)
{
return new FilePreview(AttachmentPreview.Xlsx, null, null, false);
}
var rows = Sheet(sheet, shared, culture, out var truncated);
return new FilePreview(AttachmentPreview.Xlsx, null, rows, truncated);
}
finally
{
if (copy is not null)
{
await copy.DisposeAsync().ConfigureAwait(false);
}
}
}
private static XmlReader Reader(ZipArchiveEntry entry) =>
XmlReader.Create(entry.Open(), new XmlReaderSettings { DtdProcessing = DtdProcessing.Prohibit, XmlResolver = null, IgnoreWhitespace = false, CloseInput = true });
private static List<string> SharedStrings(ZipArchiveEntry entry)
{
var strings = new List<string>();
using var reader = Reader(entry);
StringBuilder? current = null;
while (reader.Read())
{
if (reader.NodeType == XmlNodeType.Element && reader.LocalName == "si")
{
current = new StringBuilder();
if (reader.IsEmptyElement)
{
strings.Add(string.Empty);
current = null;
}
}
else if (reader.NodeType == XmlNodeType.Element && reader.LocalName == "t" && current is not null)
{
current.Append(reader.ReadElementContentAsString());
}
else if (reader.NodeType == XmlNodeType.EndElement && reader.LocalName == "si" && current is not null)
{
strings.Add(current.ToString());
current = null;
}
}
return strings;
}
private static List<IReadOnlyList<string>> Sheet(ZipArchiveEntry entry, List<string> shared, CultureInfo culture, out bool truncated)
{
var rows = new List<IReadOnlyList<string>>();
truncated = false;
using var reader = Reader(entry);
List<string>? row = null;
while (reader.Read())
{
if (reader.NodeType == XmlNodeType.Element && reader.LocalName == "row")
{
if (rows.Count == MaxRows)
{
truncated = true;
break;
}
// Empty rows in between keep their place.
if (int.TryParse(reader.GetAttribute("r"), NumberStyles.Integer, CultureInfo.InvariantCulture, out var number))
{
while (rows.Count < Math.Min(number - 1, MaxRows))
{
rows.Add([]);
}
}
row = [];
if (reader.IsEmptyElement)
{
rows.Add(row);
row = null;
}
}
else if (reader.NodeType == XmlNodeType.Element && reader.LocalName == "c" && row is not null)
{
var column = Column(reader.GetAttribute("r")) ?? row.Count;
var type = reader.GetAttribute("t");
var value = reader.IsEmptyElement ? string.Empty : Cell(reader, type, shared, culture);
if (column < MaxColumns)
{
while (row.Count < column)
{
row.Add(string.Empty);
}
row.Add(value);
}
}
else if (reader.NodeType == XmlNodeType.EndElement && reader.LocalName == "row" && row is not null)
{
rows.Add(row);
row = null;
}
}
return rows;
}
// Reads the content of a <c> element, leaving the reader on its end.
private static string Cell(XmlReader reader, string? type, List<string> shared, CultureInfo culture)
{
var depth = reader.Depth;
var text = new StringBuilder();
string? value = null;
while (reader.Read() && !(reader.NodeType == XmlNodeType.EndElement && reader.Depth == depth))
{
if (reader.NodeType == XmlNodeType.Element && reader.LocalName == "v")
{
value = reader.ReadElementContentAsString();
if (reader.NodeType == XmlNodeType.EndElement && reader.Depth == depth)
{
break;
}
}
else if (reader.NodeType == XmlNodeType.Element && reader.LocalName == "t")
{
text.Append(reader.ReadElementContentAsString());
if (reader.NodeType == XmlNodeType.EndElement && reader.Depth == depth)
{
break;
}
}
}
return type switch
{
"s" => int.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out var index) && index >= 0 && index < shared.Count ? shared[index] : string.Empty,
"inlineStr" => text.ToString(),
"b" or "str" or "e" => value ?? string.Empty,
_ => decimal.TryParse(value, NumberStyles.Float, CultureInfo.InvariantCulture, out var number) ? number.ToString("G", culture) : value ?? string.Empty,
};
}
// "BC12" -> 54 (zero-based column).
private static int? Column(string? reference)
{
if (string.IsNullOrEmpty(reference))
{
return null;
}
var column = 0;
var letters = 0;
foreach (var c in reference)
{
if (c is >= 'A' and <= 'Z')
{
column = (column * 26) + (c - 'A' + 1);
letters++;
}
else
{
break;
}
}
return letters is 0 or > 3 ? null : column - 1;
}
}
@@ -0,0 +1,157 @@
using System.Text;
namespace Khaemhat.Application.Files;
/// <summary>How the interface can show a file in the preview (SPEC §9.4: PDF, images, XML, CSV/XLSX).</summary>
public enum AttachmentPreview
{
/// <summary>No preview: the file can only be downloaded.</summary>
None = 0,
/// <summary>The integrated PDF viewer.</summary>
Pdf = 1,
/// <summary>An image, at full size with zoom.</summary>
Image = 2,
/// <summary>XML, formatted and indented.</summary>
Xml = 3,
/// <summary>CSV, as a grid.</summary>
Csv = 4,
/// <summary>XLSX, as a grid.</summary>
Xlsx = 5,
/// <summary>Plain text.</summary>
Text = 6,
}
/// <summary>
/// Media types and file names of attachments. The media type is taken from the extension when it is known (the type
/// declared by a browser is not trusted), and file names are cleaned so they are safe on every file system and in a
/// ZIP.
/// </summary>
public static class MediaTypes
{
/// <summary>The type of unknown content.</summary>
public const string OctetStream = "application/octet-stream";
/// <summary>PDF.</summary>
public const string Pdf = "application/pdf";
/// <summary>CSV.</summary>
public const string Csv = "text/csv";
/// <summary>XLSX.</summary>
public const string Xlsx = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
/// <summary>ZIP.</summary>
public const string Zip = "application/zip";
/// <summary>XML.</summary>
public const string Xml = "application/xml";
/// <summary>The longest file name kept.</summary>
public const int MaxFileNameLength = 255;
private static readonly Dictionary<string, string> ByExtension = new(StringComparer.OrdinalIgnoreCase)
{
[".pdf"] = Pdf,
[".xml"] = Xml,
[".p7m"] = "application/pkcs7-mime",
[".csv"] = Csv,
[".txt"] = "text/plain",
[".json"] = "application/json",
[".xlsx"] = Xlsx,
[".xls"] = "application/vnd.ms-excel",
[".ods"] = "application/vnd.oasis.opendocument.spreadsheet",
[".docx"] = "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
[".doc"] = "application/msword",
[".odt"] = "application/vnd.oasis.opendocument.text",
[".zip"] = Zip,
[".jpg"] = "image/jpeg",
[".jpeg"] = "image/jpeg",
[".png"] = "image/png",
[".gif"] = "image/gif",
[".webp"] = "image/webp",
[".tif"] = "image/tiff",
[".tiff"] = "image/tiff",
[".eml"] = "message/rfc822",
};
/// <summary>The media type of a file: from its extension when known, else the declared type when well formed.</summary>
/// <param name="fileName">The file name.</param>
/// <param name="declared">The type declared by the client, if any.</param>
/// <returns>The media type.</returns>
public static string Resolve(string fileName, string? declared = null)
{
if (ByExtension.TryGetValue(Path.GetExtension(fileName ?? string.Empty), out var known))
{
return known;
}
return IsWellFormed(declared) ? declared!.Trim().ToLowerInvariant() : OctetStream;
}
/// <summary>How a file can be previewed.</summary>
/// <param name="mime">The media type.</param>
/// <returns>The preview.</returns>
public static AttachmentPreview PreviewOf(string? mime) => mime switch
{
Pdf => AttachmentPreview.Pdf,
"image/jpeg" or "image/png" or "image/gif" or "image/webp" => AttachmentPreview.Image,
Xml or "text/xml" => AttachmentPreview.Xml,
Csv => AttachmentPreview.Csv,
Xlsx => AttachmentPreview.Xlsx,
"text/plain" or "application/json" => AttachmentPreview.Text,
_ => AttachmentPreview.None,
};
/// <summary>
/// Cleans a file name: no folders, no control characters or characters Windows refuses, at most 255 characters
/// keeping the extension; <c>file</c> when nothing is left.
/// </summary>
/// <param name="fileName">The name as received.</param>
/// <returns>The clean name.</returns>
public static string CleanFileName(string? fileName)
{
var name = (fileName ?? string.Empty).Replace('\\', '/');
name = name[(name.LastIndexOf('/') + 1)..];
var builder = new StringBuilder(name.Length);
foreach (var c in name)
{
builder.Append(char.IsControl(c) || c is ':' or '*' or '?' or '"' or '<' or '>' or '|' ? '_' : c);
}
var clean = builder.ToString().Trim().TrimEnd('.').Trim();
if (clean.Length > MaxFileNameLength)
{
var extension = Path.GetExtension(clean);
extension = extension.Length > 20 ? string.Empty : extension;
clean = clean[..(MaxFileNameLength - extension.Length)] + extension;
}
return clean.Length == 0 || clean is "." or ".." ? "file" : clean;
}
/// <summary>The download name of a version: <c>name.pdf</c> for v1, <c>name_v2.pdf</c> after.</summary>
/// <param name="name">The attachment name.</param>
/// <param name="version">The version.</param>
/// <returns>The file name.</returns>
public static string VersionedFileName(string name, int version)
{
ArgumentNullException.ThrowIfNull(name);
if (version <= 1)
{
return name;
}
var extension = Path.GetExtension(name);
return name[..^extension.Length] + "_v" + version.ToString(System.Globalization.CultureInfo.InvariantCulture) + extension;
}
private static bool IsWellFormed(string? mime) =>
mime is { Length: > 2 and <= 150 } && mime.Count(c => c == '/') == 1
&& mime.Trim().All(c => char.IsAsciiLetterOrDigit(c) || c is '/' or '.' or '+' or '-');
}
@@ -0,0 +1,116 @@
using Khaemhat.Application.Security;
using Khaemhat.Core.Instance;
using Khaemhat.Data;
using Khaemhat.Data.Companies;
namespace Khaemhat.Application.Instance;
/// <summary>The outcome of choosing the company a request or a circuit works in.</summary>
public enum CompanyAccess
{
/// <summary>The company can be used.</summary>
Granted = 0,
/// <summary>No company chosen (an instance account on instance pages).</summary>
None = 1,
/// <summary>The company does not exist.</summary>
NotFound = 2,
/// <summary>A company account asked for another company.</summary>
Forbidden = 3,
/// <summary>The company is in maintenance and the account is not an instance account.</summary>
Maintenance = 4,
/// <summary>The company is disabled.</summary>
Disabled = 5,
}
/// <summary>The company of the current request or Blazor circuit (SPEC §5.4).</summary>
/// <param name="Access">Whether the company can be used.</param>
/// <param name="Company">The company, when it exists.</param>
public sealed record CompanyContextResult(CompanyAccess Access, Company? Company)
{
/// <summary>No company.</summary>
public static CompanyContextResult None { get; } = new(CompanyAccess.None, null);
/// <summary>The company code, when granted.</summary>
public string? Code => Access == CompanyAccess.Granted ? Company!.Code : null;
/// <summary>Whether writes are refused (company in <see cref="CompanyStatus.ReadOnly"/>).</summary>
public bool IsReadOnly => Company?.Status == CompanyStatus.ReadOnly;
/// <summary>Whether the company is temporarily unavailable (the API answers 503).</summary>
public bool IsUnavailable => Access is CompanyAccess.Maintenance or CompanyAccess.Disabled;
/// <summary>The database scope of the company.</summary>
/// <returns>The scope.</returns>
/// <exception cref="InvalidOperationException">No company is granted.</exception>
public DatabaseScope Scope() =>
Access == CompanyAccess.Granted ? DatabaseScope.Company(Company!.Code) : throw new InvalidOperationException("No company is available in this context.");
}
/// <summary>The company the current user works in. Scoped: one per request and one per Blazor circuit.</summary>
public interface ICompanyContext
{
/// <summary>Resolves (once) and returns the company.</summary>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The result.</returns>
ValueTask<CompanyContextResult> GetAsync(CancellationToken cancellationToken = default);
}
/// <summary>
/// The rules that choose the company (SPEC §1.4, §5.4): company accounts work only in their own company; instance
/// accounts choose it (session company, or the <c>X-Company</c> header of an API call). A company in maintenance is open
/// only to instance accounts; a disabled company to nobody.
/// </summary>
/// <param name="companies">The company registry.</param>
public sealed class CompanyContextResolver(ICompanyRegistry companies)
{
/// <summary>The header naming the company of an API call.</summary>
public const string Header = "X-Company";
/// <summary>Chooses the company.</summary>
/// <param name="actor">The signed-in user, or <see langword="null"/>.</param>
/// <param name="requested">The company asked by the request (header), or <see langword="null"/>.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The result.</returns>
public async Task<CompanyContextResult> ResolveAsync(Actor? actor, string? requested, CancellationToken cancellationToken = default)
{
if (actor is null)
{
return CompanyContextResult.None;
}
requested = string.IsNullOrWhiteSpace(requested) ? null : requested.Trim().ToUpperInvariant();
string? code;
if (actor.IsInstanceAccount)
{
code = requested ?? actor.CompanyCode;
}
else
{
if (requested is not null && !string.Equals(requested, actor.CompanyCode, StringComparison.OrdinalIgnoreCase))
{
return new CompanyContextResult(CompanyAccess.Forbidden, null);
}
code = actor.CompanyCode;
}
if (code is null)
{
return CompanyContextResult.None;
}
var company = await companies.FindAsync(code, cancellationToken).ConfigureAwait(false);
return company switch
{
null => new CompanyContextResult(CompanyAccess.NotFound, null),
{ Status: CompanyStatus.Disabled } => new CompanyContextResult(CompanyAccess.Disabled, company),
{ Status: CompanyStatus.Maintenance } when !actor.IsInstanceAccount => new CompanyContextResult(CompanyAccess.Maintenance, company),
_ => new CompanyContextResult(CompanyAccess.Granted, company),
};
}
}
@@ -0,0 +1,314 @@
using Khaemhat.Application.Audit;
using Khaemhat.Application.Licensing;
using Khaemhat.Application.Security;
using Khaemhat.Core.Instance;
using Khaemhat.Core.Logging;
using Khaemhat.Data;
using Khaemhat.Data.Companies;
using Khaemhat.Data.Migrations;
using Microsoft.Extensions.Logging;
namespace Khaemhat.Application.Instance;
/// <summary>Where the databases of the instance are and which migrations they get.</summary>
/// <param name="System">The system database (<c>KHAEMHAT_SYSTEM_DB</c>).</param>
/// <param name="CompanyServer">Where new company databases are created (<c>KHAEMHAT_DB_SERVER</c>, or next to the system one).</param>
/// <param name="SystemMigrations">The migrations of the system database.</param>
/// <param name="CompanyMigrations">The migrations of every company database.</param>
public sealed record InstanceDatabases(DatabaseUrl System, DatabaseUrl CompanyServer, MigrationCatalog SystemMigrations, MigrationCatalog CompanyMigrations);
/// <summary>A company to create.</summary>
/// <param name="Code">The code (database <c>khaemhat_&lt;code&gt;</c>).</param>
/// <param name="Name">The company name.</param>
/// <param name="IsDefault">Whether it becomes the default company.</param>
/// <param name="Notes">Notes for administrators.</param>
/// <param name="SeedDemo">Whether to load the demo data.</param>
public sealed record NewCompany(string Code, string Name, bool IsDefault = false, string? Notes = null, bool SeedDemo = false);
/// <summary>
/// Fills a new or migrated company database. Modules register their own: base data at creation (plan of accounts, VAT
/// codes) and demo data when asked (SPEC §5.5). Seeders must be idempotent: they run again at every start.
/// </summary>
public interface ICompanySeeder
{
/// <summary>The order among seeders (lower first).</summary>
int Order { get; }
/// <summary>Fills the database.</summary>
/// <param name="companyCode">The company.</param>
/// <param name="context">What to load.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
Task SeedAsync(string companyCode, CompanySeedContext context, CancellationToken cancellationToken = default);
}
/// <summary>What a seeder is asked to load.</summary>
/// <param name="IsNew">Whether the database was just created.</param>
/// <param name="Base">Whether the base data is wanted (<c>KHAEMHAT_SEED_BASE</c>).</param>
/// <param name="Demo">Whether the demo data is wanted.</param>
public sealed record CompanySeedContext(bool IsNew, bool Base, bool Demo);
/// <summary>The predefined roles of SPEC §7.2, kept equal to their templates in every company.</summary>
/// <param name="roles">The role service.</param>
public sealed class PredefinedRolesSeeder(RoleService roles) : ICompanySeeder
{
/// <inheritdoc />
public int Order => 0;
/// <inheritdoc />
public Task SeedAsync(string companyCode, CompanySeedContext context, CancellationToken cancellationToken = default) =>
roles.SyncPredefinedRolesAsync(companyCode, cancellationToken);
}
/// <summary>
/// Creates, attaches and migrates company databases (SPEC §5.4, §12.1; mockup 080). Creating a company is an
/// instance administration task: super user or administrators. The number of companies is limited by the licence
/// (module MULTI).
/// </summary>
public sealed class CompanyService
{
private readonly ICompanyRegistry _registry;
private readonly DbProviderCatalog _providers;
private readonly MigrationRunner _migrations;
private readonly InstanceDatabases _databases;
private readonly ILicenseGate _licenses;
private readonly SessionStore _sessions;
private readonly ISecurityAuditLog _audit;
private readonly IReadOnlyList<ICompanySeeder> _seeders;
private readonly ILogger<CompanyService> _logger;
/// <summary>Creates the service.</summary>
/// <param name="registry">The company registry.</param>
/// <param name="providers">The database providers.</param>
/// <param name="migrations">Applies migrations.</param>
/// <param name="databases">Where databases are.</param>
/// <param name="licenses">The licence in force.</param>
/// <param name="sessions">The sessions (revoked when a company goes into maintenance).</param>
/// <param name="audit">The security audit.</param>
/// <param name="seeders">The seeders of the modules.</param>
/// <param name="logger">The log.</param>
public CompanyService(
ICompanyRegistry registry, DbProviderCatalog providers, MigrationRunner migrations, InstanceDatabases databases, ILicenseGate licenses,
SessionStore sessions, ISecurityAuditLog audit, IEnumerable<ICompanySeeder> seeders, ILogger<CompanyService> logger)
{
ArgumentNullException.ThrowIfNull(registry);
ArgumentNullException.ThrowIfNull(providers);
ArgumentNullException.ThrowIfNull(migrations);
ArgumentNullException.ThrowIfNull(databases);
ArgumentNullException.ThrowIfNull(licenses);
ArgumentNullException.ThrowIfNull(sessions);
ArgumentNullException.ThrowIfNull(audit);
ArgumentNullException.ThrowIfNull(seeders);
ArgumentNullException.ThrowIfNull(logger);
_registry = registry;
_providers = providers;
_migrations = migrations;
_databases = databases;
_licenses = licenses;
_sessions = sessions;
_audit = audit;
_seeders = [.. seeders.OrderBy(s => s.Order)];
_logger = logger;
}
/// <summary>The companies of the instance.</summary>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The companies by code.</returns>
public Task<IReadOnlyList<Company>> ListAsync(CancellationToken cancellationToken = default) => _registry.ListAsync(cancellationToken);
/// <summary>
/// Creates a company: a new database <c>khaemhat_&lt;code&gt;</c> on the company server, registered, migrated and
/// filled by the seeders.
/// </summary>
/// <param name="actor">Who acts: an instance account.</param>
/// <param name="company">The company.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The registered company.</returns>
/// <exception cref="AccessDeniedException">The actor is not an instance account, or the licence allows no more companies.</exception>
public async Task<Company> CreateAsync(Actor actor, NewCompany company, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(actor);
ArgumentNullException.ThrowIfNull(company);
RequireInstanceAdministrator(actor);
var code = Validate(company.Code, company.Name);
await RequireRoomAsync(cancellationToken).ConfigureAwait(false);
var url = _databases.CompanyServer.WithDatabase(CompanyCodes.DatabaseName(code));
var target = _providers.Resolve(url);
if (!url.IsInMemory && await target.Provider.DatabaseExistsAsync(target.ConnectionString, cancellationToken).ConfigureAwait(false))
{
throw new ValidationFailedException([$"Il database {url.DatabaseName} esiste già: usa «Collega database esistente»."]);
}
await target.Provider.EnsureDatabaseExistsAsync(target.ConnectionString, cancellationToken).ConfigureAwait(false);
var registered = await _registry.RegisterAsync(new CompanyRegistration(code, company.Name, url, company.IsDefault, company.Notes), cancellationToken)
.ConfigureAwait(false);
await PrepareAsync(registered, new CompanySeedContext(IsNew: true, Base: true, Demo: company.SeedDemo), cancellationToken).ConfigureAwait(false);
await _audit.WriteAsync(new SecurityEvent("company.created", actor.UserName, Target: code), cancellationToken).ConfigureAwait(false);
return registered;
}
/// <summary>
/// Attaches an existing company database (restored from a backup or moved from another instance) and migrates it.
/// </summary>
/// <param name="actor">Who acts: an instance account.</param>
/// <param name="code">The company code.</param>
/// <param name="name">The company name.</param>
/// <param name="database">Where the database is.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The registered company.</returns>
public async Task<Company> AttachAsync(Actor actor, string code, string name, DatabaseUrl database, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(actor);
ArgumentNullException.ThrowIfNull(database);
RequireInstanceAdministrator(actor);
var normalized = Validate(code, name);
await RequireRoomAsync(cancellationToken).ConfigureAwait(false);
var target = _providers.Resolve(database);
if (!await target.Provider.DatabaseExistsAsync(target.ConnectionString, cancellationToken).ConfigureAwait(false))
{
throw new ValidationFailedException(["Il database indicato non esiste o non è raggiungibile."]);
}
var registered = await _registry.RegisterAsync(new CompanyRegistration(normalized, name, database), cancellationToken).ConfigureAwait(false);
await PrepareAsync(registered, new CompanySeedContext(IsNew: false, Base: false, Demo: false), cancellationToken).ConfigureAwait(false);
await _audit.WriteAsync(new SecurityEvent("company.attached", actor.UserName, Target: normalized), cancellationToken).ConfigureAwait(false);
return registered;
}
/// <summary>
/// Changes the state of a company. Maintenance and disabling sign out its users at once; instance accounts can still
/// open a company in maintenance.
/// </summary>
/// <param name="actor">Who acts: an instance account.</param>
/// <param name="code">The company.</param>
/// <param name="status">The new state.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
public async Task SetStatusAsync(Actor actor, string code, CompanyStatus status, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(actor);
RequireInstanceAdministrator(actor);
await _registry.SetStatusAsync(code, status, cancellationToken).ConfigureAwait(false);
if (status is CompanyStatus.Maintenance or CompanyStatus.Disabled)
{
var revoked = await _sessions.RevokeCompanyAsync(code, "company-" + status.ToString().ToLowerInvariant(), cancellationToken).ConfigureAwait(false);
_logger.LogInformation("Company {Company} is now {Status}: {Count} sessions closed.", code, status, revoked);
}
await _audit.WriteAsync(
new SecurityEvent("company.status", actor.UserName, Target: CompanyCodes.Normalize(code), Details: status.ToString()), cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Migrates every company that is not disabled and runs the seeders again (at each start). A company whose
/// migration fails is put in maintenance and logged; the others go on.
/// </summary>
/// <param name="seedDemo">Whether demo data is wanted (<c>KHAEMHAT_SEED_DEMO</c>).</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The companies that failed.</returns>
public async Task<IReadOnlyList<string>> PrepareAllAsync(bool seedDemo, CancellationToken cancellationToken = default)
{
var failed = new List<string>();
foreach (var company in await _registry.ListAsync(cancellationToken).ConfigureAwait(false))
{
if (company.Status == CompanyStatus.Disabled)
{
continue;
}
try
{
await PrepareAsync(company, new CompanySeedContext(IsNew: false, Base: false, Demo: seedDemo), cancellationToken).ConfigureAwait(false);
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
failed.Add(company.Code);
using (_logger.BeginScope(LogSections.Scope(LogSection.Migrations)))
{
_logger.LogError(ex, "Company {Company} could not be migrated: it is put in maintenance.", company.Code);
}
await _registry.SetStatusAsync(company.Code, CompanyStatus.Maintenance, cancellationToken).ConfigureAwait(false);
}
}
return failed;
}
private async Task PrepareAsync(Company company, CompanySeedContext context, CancellationToken cancellationToken)
{
var target = await _registry.ResolveAsync(company.Code, cancellationToken).ConfigureAwait(false);
var report = await _migrations.RunAsync(target, _databases.CompanyMigrations, cancellationToken).ConfigureAwait(false);
LogMigrations(_logger, report, company.Code);
foreach (var seeder in _seeders)
{
await seeder.SeedAsync(company.Code, context, cancellationToken).ConfigureAwait(false);
}
}
/// <summary>Writes a migration report in the section <i>Migrazioni</i>.</summary>
/// <param name="logger">The log.</param>
/// <param name="report">The report.</param>
/// <param name="companyCode">The company, or <see langword="null"/> for the system database.</param>
public static void LogMigrations(ILogger logger, MigrationReport report, string? companyCode)
{
ArgumentNullException.ThrowIfNull(logger);
ArgumentNullException.ThrowIfNull(report);
using var section = logger.BeginScope(LogSections.Scope(LogSection.Migrations));
using var company = logger.BeginScope(new Dictionary<string, object?> { [LogSections.CompanyKey] = companyCode });
foreach (var (migration, duration) in report.Applied)
{
logger.LogInformation("Migration {Migration} applied to {Database} in {Milliseconds} ms.", migration.ToString(), report.Database, (long)duration.TotalMilliseconds);
}
foreach (var warning in report.Warnings)
{
logger.LogWarning("Database {Database}: {Warning}", report.Database, warning);
}
if (report.Applied.Count == 0)
{
logger.LogDebug("Database {Database} is up to date ({Count} migrations).", report.Database, report.AlreadyApplied);
}
}
private static string Validate(string code, string name)
{
var errors = new List<string>();
if (!CompanyCodes.IsValid((code ?? string.Empty).Trim().ToUpperInvariant()))
{
errors.Add("Il codice azienda deve avere da 1 a 20 caratteri tra lettere, cifre e trattino basso.");
}
if (string.IsNullOrWhiteSpace(name) || name.Trim().Length > 200)
{
errors.Add("La ragione sociale è obbligatoria (al massimo 200 caratteri).");
}
return errors.Count > 0 ? throw new ValidationFailedException(errors) : CompanyCodes.Normalize(code!);
}
private async Task RequireRoomAsync(CancellationToken cancellationToken)
{
var limit = _licenses.Current.MaxCompanies;
var count = (await _registry.ListAsync(cancellationToken).ConfigureAwait(false)).Count;
if (count >= limit)
{
throw new AccessDeniedException(
SecurityErrors.LicenseLimitReached,
limit <= 1
? "La licenza consente una sola azienda: per gestirne altre serve il modulo Multi-azienda (MULTI)."
: $"La licenza consente al massimo {limit} aziende.");
}
}
private static void RequireInstanceAdministrator(Actor actor)
{
if (!actor.IsInstanceAccount)
{
throw new AccessDeniedException(SecurityErrors.LevelTooLow, "Solo gli account di istanza possono gestire le aziende.");
}
}
}
@@ -0,0 +1,126 @@
using Khaemhat.Application.Security;
using Khaemhat.Core.Instance;
using Khaemhat.Data;
using Khaemhat.Data.Querying;
namespace Khaemhat.Application.Instance;
/// <summary>
/// Reads and writes the preferences of a company as a whole (<c>company_settings</c>, SPEC §11.12): the default
/// dashboard of each role today, the company options of the later modules tomorrow. Reading is open to the company
/// code (the callers check what they show); writing needs <c>company.settings.write</c>.
/// </summary>
/// <param name="factory">Opens the databases.</param>
/// <param name="permissions">Checks the permission to write.</param>
public sealed class CompanySettingsService(IUnitOfWorkFactory factory, PermissionService permissions)
{
/// <summary>The permission to change the settings.</summary>
public const string WritePermission = "company.settings.write";
/// <summary>The longest value accepted (layouts are JSON).</summary>
public const int MaxValueLength = 64 * 1024;
/// <summary>Reads the settings of a company, all or those whose key starts with a prefix.</summary>
/// <param name="companyCode">The company.</param>
/// <param name="prefix">The start of the keys, or <see langword="null"/> for all.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The values by key.</returns>
public async Task<IReadOnlyDictionary<string, string?>> GetAllAsync(string companyCode, string? prefix = null, CancellationToken cancellationToken = default)
{
ArgumentException.ThrowIfNullOrWhiteSpace(companyCode);
await using var unitOfWork = await factory.CreateAsync(DatabaseScope.Company(companyCode), cancellationToken).ConfigureAwait(false);
var rows = await ListAsync(unitOfWork, cancellationToken).ConfigureAwait(false);
return rows.Where(r => prefix is null || r.Key.StartsWith(prefix, StringComparison.Ordinal))
.ToDictionary(r => r.Key, r => r.Value, StringComparer.Ordinal);
}
/// <summary>Reads one setting.</summary>
/// <param name="companyCode">The company.</param>
/// <param name="key">The key.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The value, or <see langword="null"/>.</returns>
public async Task<string?> GetAsync(string companyCode, string key, CancellationToken cancellationToken = default)
{
ArgumentException.ThrowIfNullOrWhiteSpace(key);
var all = await GetAllAsync(companyCode, key, cancellationToken).ConfigureAwait(false);
return all.TryGetValue(key, out var value) ? value : null;
}
/// <summary>Writes one setting; <see langword="null"/> removes it.</summary>
/// <param name="actor">Who writes: needs <see cref="WritePermission"/> in that company.</param>
/// <param name="companyCode">The company.</param>
/// <param name="key">The key.</param>
/// <param name="value">The value.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
public Task SetAsync(Actor actor, string companyCode, string key, string? value, CancellationToken cancellationToken = default) =>
SetManyAsync(actor, companyCode, new Dictionary<string, string?>(StringComparer.Ordinal) { [key] = value }, cancellationToken);
/// <summary>Writes several settings in one transaction; <see langword="null"/> values remove the key.</summary>
/// <param name="actor">Who writes: needs <see cref="WritePermission"/> in that company.</param>
/// <param name="companyCode">The company.</param>
/// <param name="values">The values by key.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
/// <exception cref="AccessDeniedException">The actor may not change this company's settings.</exception>
public async Task SetManyAsync(Actor actor, string companyCode, IReadOnlyDictionary<string, string?> values, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(actor);
ArgumentException.ThrowIfNullOrWhiteSpace(companyCode);
ArgumentNullException.ThrowIfNull(values);
if (!actor.IsInstanceAccount && !string.Equals(actor.CompanyCode, companyCode, StringComparison.OrdinalIgnoreCase))
{
throw new AccessDeniedException("Settings of another company.");
}
await permissions.DemandAsync(actor, WritePermission, cancellationToken).ConfigureAwait(false);
foreach (var (key, value) in values)
{
if (string.IsNullOrWhiteSpace(key) || key.Length > 200)
{
throw new ValidationFailedException("settings.key_invalid");
}
if (value is { Length: > MaxValueLength })
{
throw new ValidationFailedException("settings.value_too_long");
}
}
if (values.Count == 0)
{
return;
}
await using var unitOfWork = await factory.CreateAsync(DatabaseScope.Company(companyCode), cancellationToken).ConfigureAwait(false);
await unitOfWork.InTransactionAsync(ct => WriteAsync(unitOfWork, values, ct), cancellationToken).ConfigureAwait(false);
}
private static async Task<IReadOnlyList<CompanySetting>> ListAsync(IUnitOfWork unitOfWork, CancellationToken cancellationToken) =>
(await unitOfWork.Repository<CompanySetting, long>().ListAsync(Query.For<CompanySetting>(), cancellationToken).ConfigureAwait(false)).Items;
private static async Task WriteAsync(IUnitOfWork unitOfWork, IReadOnlyDictionary<string, string?> values, CancellationToken cancellationToken)
{
var repository = unitOfWork.Repository<CompanySetting, long>();
var existing = (await ListAsync(unitOfWork, cancellationToken).ConfigureAwait(false)).ToDictionary(r => r.Key, StringComparer.Ordinal);
foreach (var (key, value) in values)
{
if (existing.TryGetValue(key, out var row))
{
if (value is null)
{
await repository.DeleteAsync(row.Id, cancellationToken).ConfigureAwait(false);
}
else if (!string.Equals(row.Value, value, StringComparison.Ordinal))
{
row.Value = value;
await repository.UpdateAsync(row, cancellationToken).ConfigureAwait(false);
}
}
else if (value is not null)
{
await repository.InsertAsync(new CompanySetting { Key = key, Value = value }, cancellationToken).ConfigureAwait(false);
}
}
}
}
@@ -0,0 +1,264 @@
using System.Globalization;
using Khaemhat.Application.Configuration;
using Khaemhat.Application.Licensing;
using Khaemhat.Application.Security;
using Khaemhat.Core.Logging;
using Khaemhat.Data;
using Khaemhat.Data.Migrations;
using Khaemhat.Infrastructure.Logging;
using Microsoft.Extensions.Logging;
namespace Khaemhat.Application.Instance;
/// <summary>Where the start of the instance is.</summary>
public enum BootstrapPhase
{
/// <summary>Migrations and first-start setup in progress: <c>/health/ready</c> answers 503.</summary>
Starting = 0,
/// <summary>Ready to serve.</summary>
Ready = 1,
/// <summary>The start failed; the process is stopping.</summary>
Failed = 2,
}
/// <summary>The start state, read by the readiness endpoint and the middleware.</summary>
public sealed class BootstrapState
{
private volatile BootstrapPhase _phase;
/// <summary>The phase.</summary>
public BootstrapPhase Phase => _phase;
/// <summary>Whether the instance serves requests.</summary>
public bool IsReady => _phase == BootstrapPhase.Ready;
/// <summary>Why the start failed (no secrets).</summary>
public string? Error { get; private set; }
/// <summary>Companies put in maintenance because their migration failed.</summary>
public IReadOnlyList<string> FailedCompanies { get; private set; } = [];
/// <summary>Marks the start as completed.</summary>
/// <param name="failedCompanies">The companies that could not be migrated.</param>
public void MarkReady(IReadOnlyList<string> failedCompanies)
{
FailedCompanies = failedCompanies ?? [];
_phase = BootstrapPhase.Ready;
}
/// <summary>Marks the start as failed.</summary>
/// <param name="error">Why.</param>
public void MarkFailed(string error)
{
Error = error;
_phase = BootstrapPhase.Failed;
}
}
/// <summary>
/// The start sequence (SPEC §5.3, §7.1, §8, §23): migrate the system database, start writing the log there, fix the
/// instance identifier and the trial start, seed the role templates, compute the licence, create the super user and the
/// first company from the variables when the tables are empty, then migrate every company. Every step is idempotent: a
/// second start, or two instances starting together, change nothing.
/// </summary>
public sealed class StartupOrchestrator
{
private readonly InstanceDatabases _databases;
private readonly DbProviderCatalog _providers;
private readonly MigrationRunner _migrations;
private readonly SystemSettingsStore _settings;
private readonly RoleService _roles;
private readonly ILicenseGate _licenses;
private readonly SystemUserService _systemUsers;
private readonly CompanyService _companies;
private readonly KhaemhatOptions _options;
private readonly IUnitOfWorkFactory _factory;
private readonly DbLogSink? _logSink;
private readonly BootstrapState _state;
private readonly TimeProvider _clock;
private readonly ILogger<StartupOrchestrator> _logger;
private bool _systemReady;
/// <summary>Creates the orchestrator.</summary>
/// <param name="databases">Where databases are.</param>
/// <param name="providers">The providers.</param>
/// <param name="migrations">Applies migrations.</param>
/// <param name="settings">The instance settings.</param>
/// <param name="roles">The role templates.</param>
/// <param name="licenses">The licence.</param>
/// <param name="systemUsers">The instance accounts.</param>
/// <param name="companies">The companies.</param>
/// <param name="options">The variables.</param>
/// <param name="factory">Opens the databases.</param>
/// <param name="logSink">The database log, started once the system database is ready (absent in some tests).</param>
/// <param name="state">The start state.</param>
/// <param name="clock">The clock.</param>
/// <param name="logger">The log.</param>
public StartupOrchestrator(
InstanceDatabases databases, DbProviderCatalog providers, MigrationRunner migrations, SystemSettingsStore settings, RoleService roles,
ILicenseGate licenses, SystemUserService systemUsers, CompanyService companies, KhaemhatOptions options, IUnitOfWorkFactory factory,
DbLogSink? logSink, BootstrapState state, TimeProvider clock, ILogger<StartupOrchestrator> logger)
{
ArgumentNullException.ThrowIfNull(databases);
ArgumentNullException.ThrowIfNull(providers);
ArgumentNullException.ThrowIfNull(migrations);
ArgumentNullException.ThrowIfNull(settings);
ArgumentNullException.ThrowIfNull(roles);
ArgumentNullException.ThrowIfNull(licenses);
ArgumentNullException.ThrowIfNull(systemUsers);
ArgumentNullException.ThrowIfNull(companies);
ArgumentNullException.ThrowIfNull(options);
ArgumentNullException.ThrowIfNull(factory);
ArgumentNullException.ThrowIfNull(state);
ArgumentNullException.ThrowIfNull(clock);
ArgumentNullException.ThrowIfNull(logger);
_databases = databases;
_providers = providers;
_migrations = migrations;
_settings = settings;
_roles = roles;
_licenses = licenses;
_systemUsers = systemUsers;
_companies = companies;
_options = options;
_factory = factory;
_logSink = logSink;
_state = state;
_clock = clock;
_logger = logger;
}
/// <summary>
/// Creates (when missing) and migrates the system database, then starts writing the log there. It runs before the
/// host starts serving, because DataProtection and sessions read the system database from the first request.
/// </summary>
/// <param name="cancellationToken">Cancellation (host stopping).</param>
/// <returns>A task.</returns>
public async Task PrepareSystemDatabaseAsync(CancellationToken cancellationToken = default)
{
if (_systemReady)
{
return;
}
using var section = _logger.BeginScope(LogSections.Scope(LogSection.System));
var system = _providers.Resolve(_databases.System);
await system.Provider.EnsureDatabaseExistsAsync(system.ConnectionString, cancellationToken).ConfigureAwait(false);
var report = await _migrations.RunAsync(system, _databases.SystemMigrations, cancellationToken).ConfigureAwait(false);
CompanyService.LogMigrations(_logger, report, null);
_logSink?.Start(_factory);
_systemReady = true;
}
/// <summary>Runs the start sequence and marks the state ready.</summary>
/// <param name="cancellationToken">Cancellation (host stopping).</param>
/// <returns>A task.</returns>
/// <exception cref="ConfigurationException">First start without the variables it needs.</exception>
public async Task RunAsync(CancellationToken cancellationToken = default)
{
// 1. System database: created when missing (SQLite file, PostgreSQL database if the role may), then migrated.
await PrepareSystemDatabaseAsync(cancellationToken).ConfigureAwait(false);
using var section = _logger.BeginScope(LogSections.Scope(LogSection.System));
// 2. Instance identity and trial start, fixed at the first start and never changed.
await _settings.GetOrAddAsync(SystemSettingsStore.InstanceIdKey, Guid.NewGuid().ToString("D"), cancellationToken).ConfigureAwait(false);
await _settings.GetOrAddAsync(
SystemSettingsStore.TrialStartedKey, _clock.GetUtcNow().UtcDateTime.ToString("O", CultureInfo.InvariantCulture), cancellationToken).ConfigureAwait(false);
// 3. Role templates and licence.
await _roles.SeedTemplatesAsync(cancellationToken).ConfigureAwait(false);
var license = await _licenses.RefreshAsync(cancellationToken).ConfigureAwait(false);
_logger.LogInformation(
"License: {Kind} {Status}, modules {Modules}, {Users} concurrent users, {Companies} companies.",
license.Kind, license.Status, string.Join(',', license.Modules.Order(StringComparer.Ordinal)), license.MaxConcurrentUsers, license.MaxCompanies);
// 4. Super user, only when there is no instance account at all.
if (!await _systemUsers.AnyAsync(cancellationToken).ConfigureAwait(false))
{
await CreateSuperUserAsync(cancellationToken).ConfigureAwait(false);
}
// 5. First company, only when the registry is empty.
if ((await _companies.ListAsync(cancellationToken).ConfigureAwait(false)).Count == 0)
{
await CreateFirstCompanyAsync(cancellationToken).ConfigureAwait(false);
}
// 6. Every company migrated and seeded again.
var failed = await _companies.PrepareAllAsync(_options.SeedDemoEnabled, cancellationToken).ConfigureAwait(false);
_state.MarkReady(failed);
_logger.LogInformation("Khaemhat is ready.");
}
private async Task CreateSuperUserAsync(CancellationToken cancellationToken)
{
var missing = new List<string>();
if (_options.SuperUser is null)
{
missing.Add("KHAEMHAT_SUPERUSER is required at the first start: the user name of the super user.");
}
if (_options.SuperUserPassword is null)
{
missing.Add("KHAEMHAT_SUPERUSER_PASSWORD (or KHAEMHAT_SUPERUSER_PASSWORD_FILE) is required at the first start: the first password of the super user.");
}
if (missing.Count > 0)
{
throw new ConfigurationException(missing);
}
try
{
var user = await _systemUsers.CreateSuperUserAsync(
new NewSystemUser(_options.SuperUser!, _options.SuperUser!, _options.SuperUserEmail), _options.SuperUserPassword!, cancellationToken).ConfigureAwait(false);
_logger.LogInformation("Super user {UserName} created: change the password and set up the two-step verification at the first access.", user.UserName);
}
catch (ValidationFailedException ex)
{
throw new ConfigurationException([.. ex.Errors.Select(e => "KHAEMHAT_SUPERUSER_PASSWORD does not satisfy the password policy: " + e)]);
}
catch (InvalidOperationException)
{
// Another instance created it a moment ago.
}
}
private async Task CreateFirstCompanyAsync(CancellationToken cancellationToken)
{
var code = _options.CompanyCode?.Trim().ToUpperInvariant();
if (code is null)
{
_logger.LogWarning("No company exists and KHAEMHAT_COMPANY_CODE is not set: create the first company from Amministrazione > Aziende.");
return;
}
try
{
var name = string.IsNullOrWhiteSpace(_options.CompanyName) ? code : _options.CompanyName.Trim();
var url = _databases.CompanyServer.WithDatabase(CompanyCodes.DatabaseName(code));
var target = _providers.Resolve(url);
if (!url.IsInMemory && await target.Provider.DatabaseExistsAsync(target.ConnectionString, cancellationToken).ConfigureAwait(false))
{
// The system database was recreated but the company one survived: attach it instead of refusing.
await _companies.AttachAsync(Actor.System, code, name, url, cancellationToken).ConfigureAwait(false);
_logger.LogWarning("Company database {Database} already existed: attached as company {Company}.", url.DatabaseName, code);
return;
}
await _companies.CreateAsync(Actor.System, new NewCompany(code, name, IsDefault: true, SeedDemo: _options.SeedDemoEnabled), cancellationToken)
.ConfigureAwait(false);
_logger.LogInformation("Company {Company} created.", code);
}
catch (InvalidOperationException)
{
// Another instance registered it a moment ago; anything else is a real failure.
if ((await _companies.ListAsync(cancellationToken).ConfigureAwait(false)).Count == 0)
{
throw;
}
}
}
}
@@ -0,0 +1,82 @@
using Khaemhat.Core.Instance;
using Khaemhat.Core.Security;
using Khaemhat.Data;
using Khaemhat.Data.Querying;
namespace Khaemhat.Application.Instance;
/// <summary>
/// Instance settings in <c>sys_settings</c>. Secret values are encrypted with the instance key and the purpose
/// <c>setting:&lt;key&gt;</c>.
/// </summary>
/// <param name="factory">Opens the system database.</param>
/// <param name="protector">Encrypts secret values.</param>
public sealed class SystemSettingsStore(IUnitOfWorkFactory factory, ISecretProtector protector)
{
/// <summary>The identifier of the instance, created at first start.</summary>
public const string InstanceIdKey = "instance.id";
/// <summary>When the trial started (ISO 8601 UTC), set at first start.</summary>
public const string TrialStartedKey = "license.trial-started-at";
/// <summary>Reads a setting.</summary>
/// <param name="key">The key.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The value (decrypted when secret), or <see langword="null"/>.</returns>
public async Task<string?> GetAsync(string key, CancellationToken cancellationToken = default)
{
ArgumentException.ThrowIfNullOrWhiteSpace(key);
await using var unitOfWork = await factory.CreateAsync(DatabaseScope.System, cancellationToken).ConfigureAwait(false);
var setting = await unitOfWork.Repository<SystemSetting, long>().FindAsync(Query.For<SystemSetting>().Where(s => s.Key == key), cancellationToken)
.ConfigureAwait(false);
if (setting?.Value is null)
{
return null;
}
return setting.IsSecret ? protector.Unprotect(setting.Value, Purpose(key)) : setting.Value;
}
/// <summary>Writes a setting.</summary>
/// <param name="key">The key.</param>
/// <param name="value">The value.</param>
/// <param name="secret">Whether to encrypt it.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
public async Task SetAsync(string key, string? value, bool secret = false, CancellationToken cancellationToken = default)
{
ArgumentException.ThrowIfNullOrWhiteSpace(key);
await using var unitOfWork = await factory.CreateAsync(DatabaseScope.System, cancellationToken).ConfigureAwait(false);
var settings = unitOfWork.Repository<SystemSetting, long>();
var stored = value is null || !secret ? value : protector.Protect(value, Purpose(key));
var setting = await settings.FindAsync(Query.For<SystemSetting>().Where(s => s.Key == key), cancellationToken).ConfigureAwait(false);
if (setting is null)
{
await settings.InsertAsync(new SystemSetting { Key = key, Value = stored, IsSecret = secret }, cancellationToken).ConfigureAwait(false);
return;
}
setting.Value = stored;
setting.IsSecret = secret;
await settings.UpdateAsync(setting, cancellationToken).ConfigureAwait(false);
}
/// <summary>Writes a setting only if it does not exist yet (bootstrap values such as the instance id).</summary>
/// <param name="key">The key.</param>
/// <param name="value">The value.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The value now stored.</returns>
public async Task<string> GetOrAddAsync(string key, string value, CancellationToken cancellationToken = default)
{
var existing = await GetAsync(key, cancellationToken).ConfigureAwait(false);
if (existing is not null)
{
return existing;
}
await SetAsync(key, value, secret: false, cancellationToken).ConfigureAwait(false);
return value;
}
private static string Purpose(string key) => "setting:" + key;
}
@@ -0,0 +1,362 @@
using System.Diagnostics;
using Khaemhat.Application.Instance;
using Khaemhat.Application.Notifications;
using Khaemhat.Core.Instance;
using Khaemhat.Core.Logging;
using Khaemhat.Core.Scheduling;
using Khaemhat.Data;
using Khaemhat.Data.Querying;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
namespace Khaemhat.Application.Jobs;
/// <summary>What a job run receives.</summary>
/// <param name="Task">The task (code, company, parameters).</param>
/// <param name="Attempt">The attempt number, from 1.</param>
/// <param name="TraceId">The trace identifier of the run, also in the log.</param>
public sealed record JobContext(ScheduledTask Task, int Attempt, string TraceId);
/// <summary>
/// A kind of job the scheduler can run (SPEC §9.4). Modules register theirs (e-mail import, SDI polling, reminders,
/// backups); <see cref="Type"/> is what <c>sys_scheduled_tasks.job_type</c> names.
/// </summary>
public interface IScheduledJob
{
/// <summary>The job type.</summary>
string Type { get; }
/// <summary>Runs the job. The token is cancelled at the task timeout or at shutdown.</summary>
/// <param name="context">The run.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A message for the run history, or <see langword="null"/>.</returns>
Task<string?> RunAsync(JobContext context, CancellationToken cancellationToken);
}
/// <summary>A task created at start when missing.</summary>
/// <param name="Code">The task code.</param>
/// <param name="Name">The name shown.</param>
/// <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);
/// <summary>
/// The scheduler (SPEC §9.4; mockup 083): reads <c>sys_scheduled_tasks</c>, runs the due ones with a lock in
/// <c>sys_job_locks</c> (so two instances never run the same task together), applies timeout and retries, writes
/// <c>sys_job_runs</c> and the section <i>Attività programmate</i> of the log, and notifies the instance accounts when a
/// task fails for good.
/// </summary>
public sealed class JobScheduler
{
/// <summary>The system tasks (M2, attachments trash from M3).</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),
];
private readonly IUnitOfWorkFactory _factory;
private readonly Dictionary<string, IScheduledJob> _jobs;
private readonly NotificationDispatcher _notifications;
private readonly TimeProvider _clock;
private readonly ILogger<JobScheduler> _logger;
private readonly string _owner = Environment.MachineName + ":" + Environment.ProcessId;
/// <summary>Creates the scheduler.</summary>
/// <param name="factory">Opens the system database.</param>
/// <param name="jobs">The job types.</param>
/// <param name="notifications">Notifies failures.</param>
/// <param name="clock">The clock.</param>
/// <param name="logger">The log.</param>
public JobScheduler(IUnitOfWorkFactory factory, IEnumerable<IScheduledJob> jobs, NotificationDispatcher notifications, TimeProvider clock, ILogger<JobScheduler> logger)
{
ArgumentNullException.ThrowIfNull(factory);
ArgumentNullException.ThrowIfNull(jobs);
ArgumentNullException.ThrowIfNull(notifications);
ArgumentNullException.ThrowIfNull(clock);
ArgumentNullException.ThrowIfNull(logger);
_factory = factory;
_jobs = jobs.ToDictionary(j => j.Type, StringComparer.Ordinal);
_notifications = notifications;
_clock = clock;
_logger = logger;
}
/// <summary>Creates the system tasks that are missing and computes the next run of every task without one.</summary>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
public async Task EnsureSystemTasksAsync(CancellationToken cancellationToken = default)
{
var now = _clock.GetUtcNow().UtcDateTime;
await using var unitOfWork = await _factory.CreateAsync(DatabaseScope.System, cancellationToken).ConfigureAwait(false);
var tasks = unitOfWork.Repository<ScheduledTask, long>();
await unitOfWork.InTransactionAsync(
async ct =>
{
await unitOfWork.AcquireLockAsync("scheduler-setup", ct).ConfigureAwait(false);
foreach (var definition in SystemTasks)
{
var code = definition.Code;
if (await tasks.CountAsync(Query.For<ScheduledTask>().Where(t => t.Code == code), ct).ConfigureAwait(false) == 0)
{
var task = new ScheduledTask
{
Code = code,
Name = definition.Name,
JobType = definition.JobType,
Cron = definition.Cron,
TimeoutSeconds = definition.TimeoutSeconds,
IsSystem = true,
};
task.NextRunAt = Next(task, now);
await tasks.InsertAsync(task, ct).ConfigureAwait(false);
}
}
},
cancellationToken).ConfigureAwait(false);
}
/// <summary>Runs every enabled task that is due, one after the other.</summary>
/// <param name="cancellationToken">Cancellation (shutdown).</param>
/// <returns>How many tasks ran.</returns>
public async Task<int> RunDueAsync(CancellationToken cancellationToken = default)
{
var now = _clock.GetUtcNow().UtcDateTime;
IReadOnlyList<ScheduledTask> due;
await using (var unitOfWork = await _factory.CreateAsync(DatabaseScope.System, cancellationToken).ConfigureAwait(false))
{
due = (await unitOfWork.Repository<ScheduledTask, long>().ListAsync(
Query.For<ScheduledTask>().Where(t => t.IsEnabled && t.NextRunAt != null && t.NextRunAt <= now).OrderBy(t => t.NextRunAt), cancellationToken)
.ConfigureAwait(false)).Items;
}
var count = 0;
foreach (var task in due)
{
cancellationToken.ThrowIfCancellationRequested();
if (await RunAsync(task.Code, cancellationToken).ConfigureAwait(false) is not JobOutcome.Skipped)
{
count++;
}
}
return count;
}
/// <summary>Runs a task now (also "Esegui ora" from the administration page).</summary>
/// <param name="code">The task code.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The outcome; <see cref="JobOutcome.Skipped"/> when another run holds the lock.</returns>
public async Task<JobOutcome> RunAsync(string code, CancellationToken cancellationToken = default)
{
ScheduledTask? task;
await using (var unitOfWork = await _factory.CreateAsync(DatabaseScope.System, cancellationToken).ConfigureAwait(false))
{
task = await unitOfWork.Repository<ScheduledTask, long>().FindAsync(Query.For<ScheduledTask>().Where(t => t.Code == code), cancellationToken).ConfigureAwait(false);
}
if (task is null)
{
throw new KeyNotFoundException($"No scheduled task has code {code}.");
}
var timeout = TimeSpan.FromSeconds(Math.Max(1, task.TimeoutSeconds));
if (!await TryLockAsync(task.Code, timeout, cancellationToken).ConfigureAwait(false))
{
return JobOutcome.Skipped;
}
try
{
return await RunLockedAsync(task, timeout, cancellationToken).ConfigureAwait(false);
}
finally
{
await UnlockAsync(task.Code).ConfigureAwait(false);
}
}
private async Task<JobOutcome> RunLockedAsync(ScheduledTask task, TimeSpan timeout, CancellationToken cancellationToken)
{
using var section = _logger.BeginScope(LogSections.Scope(LogSection.ScheduledJobs));
var outcome = JobOutcome.Failed;
string? message = null;
for (var attempt = 1; attempt <= task.MaxRetries + 1; attempt++)
{
var traceId = ActivityTraceId.CreateRandom().ToString();
using var scope = _logger.BeginScope(new Dictionary<string, object?> { [LogSections.TraceIdKey] = traceId, [LogSections.CompanyKey] = task.CompanyCode });
var run = new JobRun { TaskCode = task.Code, StartedAt = _clock.GetUtcNow().UtcDateTime, Outcome = JobOutcome.Running, Attempt = attempt, TraceId = traceId };
run.Id = await SaveRunAsync(run, insert: true, cancellationToken).ConfigureAwait(false);
(outcome, message) = await ExecuteAsync(task, new JobContext(task, attempt, traceId), timeout, cancellationToken).ConfigureAwait(false);
run.Outcome = outcome;
run.Message = message is { Length: > 2000 } ? message[..2000] : message;
run.FinishedAt = _clock.GetUtcNow().UtcDateTime;
await SaveRunAsync(run, insert: false, CancellationToken.None).ConfigureAwait(false);
if (outcome == JobOutcome.Succeeded || cancellationToken.IsCancellationRequested)
{
break;
}
}
await FinishAsync(task, outcome, cancellationToken).ConfigureAwait(false);
if (outcome is JobOutcome.Failed or JobOutcome.TimedOut)
{
await _notifications.NotifyInstanceAsync(
new NotificationMessage("jobs", NotificationSeverity.Error, $"Attività «{task.Name}» non riuscita", message, "/amministrazione/attivita"),
cancellationToken: CancellationToken.None).ConfigureAwait(false);
}
return outcome;
}
private async Task<(JobOutcome Outcome, string? Message)> ExecuteAsync(ScheduledTask task, JobContext context, TimeSpan timeout, CancellationToken cancellationToken)
{
if (!_jobs.TryGetValue(task.JobType, out var job))
{
_logger.LogError("Task {Task}: job type {JobType} is not known.", task.Code, task.JobType);
return (JobOutcome.Failed, "Tipo di attività sconosciuto: " + task.JobType);
}
using var timeoutSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
timeoutSource.CancelAfter(timeout);
var started = Stopwatch.GetTimestamp();
try
{
var message = await job.RunAsync(context, timeoutSource.Token).ConfigureAwait(false);
_logger.LogInformation("Task {Task} completed in {Milliseconds} ms. {Message}", task.Code, (long)Stopwatch.GetElapsedTime(started).TotalMilliseconds, message);
return (JobOutcome.Succeeded, message);
}
catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested)
{
_logger.LogError("Task {Task} stopped after the timeout of {Seconds} s (attempt {Attempt}).", task.Code, (int)timeout.TotalSeconds, context.Attempt);
return (JobOutcome.TimedOut, $"Interrotta dopo {(int)timeout.TotalSeconds} secondi.");
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
_logger.LogError(ex, "Task {Task} failed (attempt {Attempt}).", task.Code, context.Attempt);
return (JobOutcome.Failed, ex.Message);
}
}
private async Task FinishAsync(ScheduledTask task, JobOutcome outcome, CancellationToken cancellationToken)
{
var now = _clock.GetUtcNow().UtcDateTime;
await using var unitOfWork = await _factory.CreateAsync(DatabaseScope.System, CancellationToken.None).ConfigureAwait(false);
var tasks = unitOfWork.Repository<ScheduledTask, long>();
var current = await tasks.GetAsync(task.Id, CancellationToken.None).ConfigureAwait(false);
if (current is null)
{
return;
}
current.LastRunAt = now;
current.LastOutcome = outcome;
current.NextRunAt = Next(current, now);
await tasks.UpdateAsync(current, cancellationToken.IsCancellationRequested ? CancellationToken.None : cancellationToken).ConfigureAwait(false);
}
private async Task<long> SaveRunAsync(JobRun run, bool insert, CancellationToken cancellationToken)
{
await using var unitOfWork = await _factory.CreateAsync(DatabaseScope.System, cancellationToken).ConfigureAwait(false);
var runs = unitOfWork.Repository<JobRun, long>();
if (insert)
{
return await runs.InsertAsync(run, cancellationToken).ConfigureAwait(false);
}
await runs.UpdateAsync(run, cancellationToken).ConfigureAwait(false);
return run.Id;
}
// A lock row per task; an expired lock (a process that died) is taken over.
private async Task<bool> TryLockAsync(string code, TimeSpan timeout, CancellationToken cancellationToken)
{
var now = _clock.GetUtcNow().UtcDateTime;
await using var unitOfWork = await _factory.CreateAsync(DatabaseScope.System, cancellationToken).ConfigureAwait(false);
var locks = unitOfWork.Repository<JobLock, string>();
var acquired = false;
await unitOfWork.InTransactionAsync(
async ct =>
{
await unitOfWork.AcquireLockAsync("job-locks", ct).ConfigureAwait(false);
var existing = await locks.GetAsync(code, ct).ConfigureAwait(false);
if (existing is not null && existing.ExpiresAt > now)
{
return;
}
if (existing is not null)
{
await locks.DeleteAsync(code, ct).ConfigureAwait(false);
}
await locks.InsertAsync(new JobLock { Id = code, Owner = _owner, AcquiredAt = now, ExpiresAt = now + timeout + TimeSpan.FromMinutes(1) }, ct).ConfigureAwait(false);
acquired = true;
},
cancellationToken).ConfigureAwait(false);
return acquired;
}
private async Task UnlockAsync(string code)
{
await using var unitOfWork = await _factory.CreateAsync(DatabaseScope.System, CancellationToken.None).ConfigureAwait(false);
var owner = _owner;
await unitOfWork.ExecuteAsync(
SqlFragment.Of($"DELETE FROM {SqlFragment.Identifier("sys_job_locks")} WHERE id = {code} AND owner = {owner}"), CancellationToken.None).ConfigureAwait(false);
}
private DateTime? Next(ScheduledTask task, DateTime now)
{
if (!CronExpression.TryParse(task.Cron, out var cron, out _))
{
_logger.LogError("Task {Task}: the cron expression '{Cron}' is not valid; the task will not run.", task.Code, task.Cron);
return null;
}
var zone = TimeZoneInfo.TryFindSystemTimeZoneById(task.TimeZone, out var found) ? found : TimeZoneInfo.Utc;
return cron.NextAfter(now, zone);
}
}
/// <summary>Runs the scheduler every 30 seconds once the instance is ready.</summary>
/// <param name="scheduler">The scheduler.</param>
/// <param name="state">The start state.</param>
/// <param name="logger">The log.</param>
public sealed class JobSchedulerService(JobScheduler scheduler, BootstrapState state, ILogger<JobSchedulerService> logger) : BackgroundService
{
/// <summary>How often due tasks are looked for.</summary>
public static readonly TimeSpan Interval = TimeSpan.FromSeconds(30);
/// <inheritdoc />
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!state.IsReady)
{
if (state.Phase == BootstrapPhase.Failed)
{
return;
}
await Task.Delay(TimeSpan.FromSeconds(1), stoppingToken).ConfigureAwait(false);
}
await scheduler.EnsureSystemTasksAsync(stoppingToken).ConfigureAwait(false);
using var timer = new PeriodicTimer(Interval);
do
{
try
{
await scheduler.RunDueAsync(stoppingToken).ConfigureAwait(false);
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
using var section = logger.BeginScope(LogSections.Scope(LogSection.ScheduledJobs));
logger.LogError(ex, "The scheduler could not read the tasks.");
}
}
while (await timer.WaitForNextTickAsync(stoppingToken).ConfigureAwait(false));
}
}
+119
View File
@@ -0,0 +1,119 @@
using System.Globalization;
using Khaemhat.Application.Licensing;
using Khaemhat.Application.Notifications;
using Khaemhat.Application.Security;
using Khaemhat.Core.Instance;
using Khaemhat.Data;
using Khaemhat.Data.Companies;
namespace Khaemhat.Application.Jobs;
/// <summary>Deletes sessions expired or revoked more than 30 days ago, in the system database and in every company.</summary>
/// <param name="sessions">The sessions.</param>
/// <param name="companies">The companies.</param>
public sealed class SessionCleanupJob(SessionStore sessions, ICompanyRegistry companies) : IScheduledJob
{
/// <summary>The job type.</summary>
public const string JobType = "system.sessions-cleanup";
/// <summary>How long ended sessions stay for the history.</summary>
public static readonly TimeSpan Keep = TimeSpan.FromDays(30);
/// <inheritdoc />
public string Type => JobType;
/// <inheritdoc />
public async Task<string?> RunAsync(JobContext context, CancellationToken cancellationToken)
{
var deleted = await sessions.PurgeAsync(DatabaseScope.System, Keep, cancellationToken).ConfigureAwait(false);
foreach (var company in await companies.ListAsync(cancellationToken).ConfigureAwait(false))
{
if (company.Status is not CompanyStatus.Disabled)
{
deleted += await sessions.PurgeAsync(DatabaseScope.Company(company.Code), Keep, cancellationToken).ConfigureAwait(false);
}
}
return string.Create(CultureInfo.InvariantCulture, $"{deleted} sessioni eliminate.");
}
}
/// <summary>
/// Computes the licence again every hour (SPEC §8.2) and notifies the instance accounts when it is about to expire or
/// has expired.
/// </summary>
/// <param name="licenses">The licence.</param>
/// <param name="notifications">The notifications.</param>
/// <param name="clock">The clock.</param>
public sealed class LicenseCheckJob(ILicenseGate licenses, NotificationDispatcher notifications, TimeProvider clock) : IScheduledJob
{
/// <summary>The job type.</summary>
public const string JobType = "system.license-check";
/// <inheritdoc />
public string Type => JobType;
/// <inheritdoc />
public async Task<string?> RunAsync(JobContext context, CancellationToken cancellationToken)
{
var state = await licenses.RefreshAsync(cancellationToken).ConfigureAwait(false);
var now = clock.GetUtcNow().UtcDateTime;
var days = state.DaysLeft(now);
if (state.Status != LicenseStatus.Valid)
{
await notifications.NotifyInstanceAsync(
new NotificationMessage("licenses", NotificationSeverity.Error, "Licenza scaduta", "Rinnova la licenza da Amministrazione > Licenze e moduli.", "/amministrazione/licenze"),
cancellationToken: cancellationToken).ConfigureAwait(false);
}
else if (days is 30 or 14 or 7 or 3 or 1 && now.Hour == 9)
{
await notifications.NotifyInstanceAsync(
new NotificationMessage("licenses", NotificationSeverity.Warning, $"La licenza scade tra {days} giorni", null, "/amministrazione/licenze"),
cancellationToken: cancellationToken).ConfigureAwait(false);
}
return $"{state.Kind} {state.Status}, moduli {string.Join(',', state.Modules.Order(StringComparer.Ordinal))}.";
}
}
/// <summary>
/// Deletes old log events (SPEC §9.5): debug and trace after 7 days, information after 90, warnings after 180, errors
/// and critical events after 365.
/// </summary>
/// <param name="factory">Opens the system database.</param>
/// <param name="clock">The clock.</param>
public sealed class LogRetentionJob(IUnitOfWorkFactory factory, TimeProvider clock) : IScheduledJob
{
/// <summary>The job type.</summary>
public const string JobType = "system.log-retention";
/// <summary>How many days each level is kept.</summary>
public static readonly IReadOnlyDictionary<string, int> RetentionDays = new Dictionary<string, int>(StringComparer.Ordinal)
{
["Trace"] = 7,
["Debug"] = 7,
["Information"] = 90,
["Warning"] = 180,
["Error"] = 365,
["Critical"] = 365,
};
/// <inheritdoc />
public string Type => JobType;
/// <inheritdoc />
public async Task<string?> RunAsync(JobContext context, CancellationToken cancellationToken)
{
var now = clock.GetUtcNow().UtcDateTime;
var deleted = 0;
await using var unitOfWork = await factory.CreateAsync(DatabaseScope.System, cancellationToken).ConfigureAwait(false);
foreach (var (level, days) in RetentionDays)
{
var limit = now.AddDays(-days);
deleted += await unitOfWork.ExecuteAsync(
SqlFragment.Of($"DELETE FROM {SqlFragment.Identifier("sys_log")} WHERE level = {level} AND at < {limit}"), cancellationToken).ConfigureAwait(false);
}
return string.Create(CultureInfo.InvariantCulture, $"{deleted} eventi eliminati.");
}
}
@@ -4,6 +4,11 @@
<RootNamespace>Khaemhat.Application</RootNamespace>
</PropertyGroup>
<!-- The ASP.NET Core shared framework (logging, options, DataProtection, hosting): part of .NET, not a package. -->
<ItemGroup>
<FrameworkReference Include="Microsoft.AspNetCore.App" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="../Khaemhat.Core/Khaemhat.Core.csproj" />
<ProjectReference Include="../Khaemhat.Data/Khaemhat.Data.csproj" />
@@ -0,0 +1,384 @@
using System.Globalization;
using Khaemhat.Application.Audit;
using Khaemhat.Application.Configuration;
using Khaemhat.Application.Instance;
using Khaemhat.Application.Modules;
using Khaemhat.Application.Security;
using Khaemhat.Core.Instance;
using Khaemhat.Data;
using Khaemhat.Data.Querying;
using Khaemhat.Infrastructure.Licensing;
using Microsoft.Extensions.Logging;
namespace Khaemhat.Application.Licensing;
/// <summary>The licence in force and the modules it activates.</summary>
public interface ILicenseGate
{
/// <summary>The licence computed at the last refresh.</summary>
LicenseState Current { get; }
/// <summary>Whether a module is licensed.</summary>
/// <param name="moduleCode">The module code.</param>
/// <returns><see langword="true"/> if active.</returns>
bool IsModuleActive(string moduleCode);
/// <summary>Recomputes the licence from the database and the environment.</summary>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The new state.</returns>
Task<LicenseState> RefreshAsync(CancellationToken cancellationToken = default);
}
/// <summary>Where the gate reads the licence from the environment.</summary>
/// <param name="EnvironmentLicense">The text of <c>KHAEMHAT_LICENSE</c>, if set.</param>
/// <param name="Mode">The licence mode.</param>
public sealed record LicenseSettings(string? EnvironmentLicense, LicenseMode Mode);
/// <summary>
/// Computes the licence (SPEC §8): the best signed licence (environment or installed) bound to this instance, else the
/// trial; plus the module activation codes; plus, in test mode only, the fictitious codes. Every signature is checked
/// again at each refresh, so a row changed in the database does not grant anything.
/// </summary>
public sealed class LicenseGate : ILicenseGate
{
private readonly IUnitOfWorkFactory _factory;
private readonly SystemSettingsStore _settings;
private readonly LicenseVerifier _verifier;
private readonly LicenseSettings _licenseSettings;
private readonly TimeProvider _clock;
private readonly ILogger<LicenseGate> _logger;
private volatile LicenseState _current;
/// <summary>Creates the gate. Until the first refresh the state is the trial.</summary>
/// <param name="factory">Opens the system database.</param>
/// <param name="settings">The instance settings.</param>
/// <param name="verifier">Checks signatures.</param>
/// <param name="licenseSettings">The environment licence and mode.</param>
/// <param name="clock">The clock.</param>
/// <param name="logger">The log.</param>
public LicenseGate(
IUnitOfWorkFactory factory, SystemSettingsStore settings, LicenseVerifier verifier, LicenseSettings licenseSettings,
TimeProvider clock, ILogger<LicenseGate> logger)
{
ArgumentNullException.ThrowIfNull(factory);
ArgumentNullException.ThrowIfNull(settings);
ArgumentNullException.ThrowIfNull(verifier);
ArgumentNullException.ThrowIfNull(licenseSettings);
ArgumentNullException.ThrowIfNull(clock);
ArgumentNullException.ThrowIfNull(logger);
_factory = factory;
_settings = settings;
_verifier = verifier;
_licenseSettings = licenseSettings;
_clock = clock;
_logger = logger;
var now = clock.GetUtcNow().UtcDateTime;
_current = Trial(now, now, 0, [], 0, licenseSettings.Mode == LicenseMode.Test);
}
/// <inheritdoc />
public LicenseState Current => _current;
/// <summary>The instance identifier read at the last refresh.</summary>
public string? InstanceId { get; private set; }
/// <inheritdoc />
public bool IsModuleActive(string moduleCode) => _current.Includes(moduleCode);
/// <inheritdoc />
public async Task<LicenseState> RefreshAsync(CancellationToken cancellationToken = default)
{
var now = _clock.GetUtcNow().UtcDateTime;
var testMode = _licenseSettings.Mode == LicenseMode.Test;
InstanceId = await _settings.GetAsync(SystemSettingsStore.InstanceIdKey, cancellationToken).ConfigureAwait(false);
var trialStart = DateTime.TryParse(
await _settings.GetAsync(SystemSettingsStore.TrialStartedKey, cancellationToken).ConfigureAwait(false),
CultureInfo.InvariantCulture,
DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeUniversal,
out var started) ? started : now;
IReadOnlyList<LicenseRecord> records;
await using (var unitOfWork = await _factory.CreateAsync(DatabaseScope.System, cancellationToken).ConfigureAwait(false))
{
records = (await unitOfWork.Repository<LicenseRecord, long>()
.ListAsync(Query.For<LicenseRecord>().Where(r => r.IsActive).OrderBy(r => r.Id), cancellationToken).ConfigureAwait(false)).Items;
}
var documents = records.Where(r => r.Source == LicenseSource.File).Select(r => r.Payload).ToList();
if (_licenseSettings.EnvironmentLicense is { } environment)
{
documents.Insert(0, environment);
}
var license = documents
.Select(text => _verifier.Verify(text).Document)
.Where(d => d is not null && (d.InstanceId is null || string.Equals(d.InstanceId, InstanceId, StringComparison.OrdinalIgnoreCase)))
.OrderByDescending(d => d!.ExpiresAt ?? DateTime.MaxValue)
.FirstOrDefault();
var extraModules = new HashSet<string>(StringComparer.Ordinal);
foreach (var record in records.Where(r => r.Source == LicenseSource.ActivationCode))
{
var (code, _) = _verifier.VerifyActivationCode(record.Payload);
if (code is not null && code.ExpiresAt > now && (InstanceId is null || code.IsFor(InstanceId)))
{
extraModules.Add(code.Module);
}
}
var testUsers = 0;
var trialExtension = 0;
if (testMode)
{
foreach (var test in records.Where(r => r.Source == LicenseSource.TestCode).Select(r => TestLicenseCatalog.Find(r.Payload)).OfType<TestCode>())
{
extraModules.UnionWith(test.Modules);
testUsers = Math.Max(testUsers, test.ConcurrentUsers);
trialExtension += test.TrialExtensionDays;
}
}
var state = license is null
? Trial(now, trialStart, trialExtension, extraModules, testUsers, testMode)
: Licensed(now, license, extraModules, testUsers, testMode);
if (state.Status != _current.Status || state.Kind != _current.Kind)
{
_logger.LogInformation("Licence {Kind} {Status}: modules {Modules}, {Users} users.", state.Kind, state.Status, string.Join(',', state.Modules), state.MaxConcurrentUsers);
}
_current = state;
return state;
}
private static LicenseState Trial(DateTime now, DateTime trialStart, int extensionDays, IEnumerable<string> extra, int testUsers, bool testMode)
{
var modules = new HashSet<string>(LicenseState.TrialModules, StringComparer.Ordinal);
modules.UnionWith(extra);
var expires = trialStart + LicenseState.TrialLength + TimeSpan.FromDays(extensionDays);
return new LicenseState
{
Kind = LicenseKind.Trial,
Status = now <= expires ? LicenseStatus.Valid : LicenseStatus.Expired,
Modules = modules,
MaxConcurrentUsers = Math.Max(LicenseState.TrialUsers, testUsers),
MaxCompanies = modules.Contains(ModuleCodes.MultiCompany) ? int.MaxValue : 1,
ExpiresAt = expires,
GraceEndsAt = expires,
IsTestMode = testMode,
};
}
private static LicenseState Licensed(DateTime now, LicenseDocument license, IEnumerable<string> extra, int testUsers, bool testMode)
{
var modules = new HashSet<string>(license.Modules.Select(m => m.Trim().ToUpperInvariant()), StringComparer.Ordinal) { ModuleCodes.Core };
modules.UnionWith(extra);
var graceEnds = license.ExpiresAt?.AddDays(license.GracePeriodDays);
var status = license.ExpiresAt is not { } expires || now <= expires
? LicenseStatus.Valid
: now <= graceEnds ? LicenseStatus.Grace : LicenseStatus.Expired;
return new LicenseState
{
Kind = LicenseKind.Licensed,
Status = status,
Licensee = license.Licensee,
Modules = modules,
MaxConcurrentUsers = Math.Max(license.MaxConcurrentUsers, testUsers),
MaxCompanies = modules.Contains(ModuleCodes.MultiCompany) ? (license.MaxCompanies > 1 ? license.MaxCompanies : int.MaxValue) : 1,
ExpiresAt = license.ExpiresAt,
GraceEndsAt = graceEnds,
IsTestMode = testMode,
};
}
}
/// <summary>The outcome of an activation.</summary>
/// <param name="Succeeded">Whether the licence or code was installed.</param>
/// <param name="Outcome">The outcome code: <c>ok</c> or one of <see cref="LicenseErrors"/>.</param>
/// <param name="State">The licence in force afterwards.</param>
public sealed record ActivationResult(bool Succeeded, string Outcome, LicenseState State);
/// <summary>Installs and removes licences (SPEC §8.2). Today offline; a remote activation server may come later.</summary>
public interface ILicenseActivationService
{
/// <summary>Installs a <c>.khl</c> licence, a module activation code or, in test mode, a fictitious code.</summary>
/// <param name="actor">Who acts: only the super user.</param>
/// <param name="input">The licence text or the code.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The outcome.</returns>
Task<ActivationResult> ActivateAsync(Actor actor, string input, CancellationToken cancellationToken = default);
/// <summary>Removes an installed licence or code (it stays in the history).</summary>
/// <param name="actor">Who acts: only the super user.</param>
/// <param name="licenseId">The row of <c>sys_licenses</c>.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The licence in force afterwards.</returns>
Task<LicenseState> DeactivateAsync(Actor actor, long licenseId, CancellationToken cancellationToken = default);
}
/// <summary>Activation checked locally with the public key: no network involved.</summary>
public sealed class OfflineActivationService(
IUnitOfWorkFactory factory, LicenseGate gate, LicenseVerifier verifier, LicenseSettings settings, ModuleRegistry modules,
ISecurityAuditLog audit, TimeProvider clock) : ILicenseActivationService
{
/// <inheritdoc />
public async Task<ActivationResult> ActivateAsync(Actor actor, string input, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(actor);
RequireSuperUser(actor);
var text = (input ?? string.Empty).Trim();
var now = clock.GetUtcNow().UtcDateTime;
if (gate.InstanceId is null)
{
await gate.RefreshAsync(cancellationToken).ConfigureAwait(false);
}
var (record, outcome) = Prepare(text, now);
await using (var unitOfWork = await factory.CreateAsync(DatabaseScope.System, cancellationToken).ConfigureAwait(false))
{
await unitOfWork.InTransactionAsync(
async ct =>
{
if (record is not null)
{
var licenses = unitOfWork.Repository<LicenseRecord, long>();
if (record.Source == LicenseSource.File)
{
// A new instance licence replaces the previous one; codes stay.
foreach (var old in (await licenses.ListAsync(
Query.For<LicenseRecord>().Where(r => r.IsActive && r.Source == LicenseSource.File), ct).ConfigureAwait(false)).Items)
{
old.IsActive = false;
await licenses.UpdateAsync(old, ct).ConfigureAwait(false);
}
}
await licenses.InsertAsync(record, ct).ConfigureAwait(false);
}
await unitOfWork.Repository<LicenseActivation, long>().InsertAsync(
new LicenseActivation
{
Action = record is null ? "rejected" : "activated",
Source = record?.Source ?? SourceOf(text),
Modules = record?.Modules,
Outcome = outcome,
},
ct).ConfigureAwait(false);
},
cancellationToken).ConfigureAwait(false);
}
await audit.WriteAsync(
new SecurityEvent(record is null ? "license.rejected" : "license.activated", actor.UserName, Target: record?.Modules, Details: new { outcome }),
cancellationToken).ConfigureAwait(false);
var state = await gate.RefreshAsync(cancellationToken).ConfigureAwait(false);
return new ActivationResult(record is not null, outcome, state);
}
/// <inheritdoc />
public async Task<LicenseState> DeactivateAsync(Actor actor, long licenseId, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(actor);
RequireSuperUser(actor);
string? modules;
await using (var unitOfWork = await factory.CreateAsync(DatabaseScope.System, cancellationToken).ConfigureAwait(false))
{
var licenses = unitOfWork.Repository<LicenseRecord, long>();
var record = await licenses.GetAsync(licenseId, cancellationToken).ConfigureAwait(false)
?? throw new KeyNotFoundException("No installed licence has this identifier.");
record.IsActive = false;
modules = record.Modules;
await licenses.UpdateAsync(record, cancellationToken).ConfigureAwait(false);
await unitOfWork.Repository<LicenseActivation, long>().InsertAsync(
new LicenseActivation { Action = "deactivated", Source = record.Source, Modules = record.Modules, Outcome = "ok" }, cancellationToken)
.ConfigureAwait(false);
}
await audit.WriteAsync(new SecurityEvent("license.deactivated", actor.UserName, Target: modules), cancellationToken).ConfigureAwait(false);
return await gate.RefreshAsync(cancellationToken).ConfigureAwait(false);
}
private (LicenseRecord? Record, string Outcome) Prepare(string text, DateTime now)
{
if (TestLicenseCatalog.LooksLikeTestCode(text))
{
if (settings.Mode != LicenseMode.Test)
{
return (null, LicenseErrors.TestOnly);
}
var test = TestLicenseCatalog.Find(text);
return test is null
? (null, LicenseErrors.FormatInvalid)
: (new LicenseRecord { Source = LicenseSource.TestCode, Payload = text.ToUpperInvariant(), Modules = string.Join(',', test.Modules), Licensee = "Test" }, "ok");
}
if (text.StartsWith(ModuleActivationCode.Prefix + "-", StringComparison.OrdinalIgnoreCase))
{
var (code, error) = verifier.VerifyActivationCode(text);
if (code is null)
{
return (null, error!);
}
if (modules.FindModule(code.Module) is null)
{
return (null, LicenseErrors.UnknownModule);
}
if (code.ExpiresAt <= now)
{
return (null, LicenseErrors.Expired);
}
if (gate.InstanceId is { } instance && !code.IsFor(instance))
{
return (null, LicenseErrors.WrongInstance);
}
return (new LicenseRecord { Source = LicenseSource.ActivationCode, Payload = text.ToUpperInvariant(), Modules = code.Module, ExpiresAt = code.ExpiresAt }, "ok");
}
var verification = verifier.Verify(text);
if (verification.Document is not { } document)
{
return (null, verification.Error!);
}
if (document.InstanceId is not null && !string.Equals(document.InstanceId, gate.InstanceId, StringComparison.OrdinalIgnoreCase))
{
return (null, LicenseErrors.WrongInstance);
}
if (document.ExpiresAt is { } expires && expires.AddDays(document.GracePeriodDays) <= now)
{
return (null, LicenseErrors.Expired);
}
return (new LicenseRecord
{
Source = LicenseSource.File,
Payload = text,
Licensee = document.Licensee.Length > 200 ? document.Licensee[..200] : document.Licensee,
Modules = string.Join(',', document.Modules),
MaxConcurrentUsers = document.MaxConcurrentUsers,
MaxCompanies = document.MaxCompanies,
IssuedAt = document.IssuedAt,
ExpiresAt = document.ExpiresAt,
GracePeriodDays = document.GracePeriodDays,
}, "ok");
}
private static LicenseSource SourceOf(string text) =>
TestLicenseCatalog.LooksLikeTestCode(text) ? LicenseSource.TestCode
: text.StartsWith(ModuleActivationCode.Prefix + "-", StringComparison.OrdinalIgnoreCase) ? LicenseSource.ActivationCode
: LicenseSource.File;
private static void RequireSuperUser(Actor actor)
{
if (!actor.IsSuperUser)
{
throw new AccessDeniedException(SecurityErrors.LevelTooLow, "Only the super user activates licences and modules.");
}
}
}
@@ -0,0 +1,136 @@
using Khaemhat.Application.Modules;
namespace Khaemhat.Application.Licensing;
/// <summary>Where the instance stands with its licence.</summary>
public enum LicenseStatus
{
/// <summary>Valid.</summary>
Valid = 0,
/// <summary>Expired but within the grace period: everything works, with a banner.</summary>
Grace = 1,
/// <summary>Expired beyond the grace period: read-only with a banner (SPEC §8.2).</summary>
Expired = 2,
}
/// <summary>What kind of licence is in force.</summary>
public enum LicenseKind
{
/// <summary>No licence: CORE and ACCT, 3 users, 60 days.</summary>
Trial = 0,
/// <summary>A signed licence.</summary>
Licensed = 1,
}
/// <summary>The licence in force, computed by <see cref="LicenseGate"/>. Immutable.</summary>
public sealed record LicenseState
{
/// <summary>The trial modules (SPEC §6).</summary>
public static readonly IReadOnlyList<string> TrialModules = [ModuleCodes.Core, ModuleCodes.Accounting];
/// <summary>The trial users.</summary>
public const int TrialUsers = 3;
/// <summary>The trial length.</summary>
public static readonly TimeSpan TrialLength = TimeSpan.FromDays(60);
/// <summary>The licence kind.</summary>
public LicenseKind Kind { get; init; }
/// <summary>The status.</summary>
public LicenseStatus Status { get; init; }
/// <summary>The holder.</summary>
public string? Licensee { get; init; }
/// <summary>The active modules.</summary>
public IReadOnlySet<string> Modules { get; init; } = new HashSet<string>(StringComparer.Ordinal);
/// <summary>The concurrent users allowed across all companies.</summary>
public int MaxConcurrentUsers { get; init; }
/// <summary>The companies allowed.</summary>
public int MaxCompanies { get; init; }
/// <summary>When the licence (or the trial) expires.</summary>
public DateTime? ExpiresAt { get; init; }
/// <summary>When the grace period ends.</summary>
public DateTime? GraceEndsAt { get; init; }
/// <summary>Whether the fictitious codes are accepted (<c>KHAEMHAT_LICENSE_MODE=test</c>): the interface shows a banner.</summary>
public bool IsTestMode { get; init; }
/// <summary>Whether data can only be read.</summary>
public bool IsReadOnly => Status == LicenseStatus.Expired;
/// <summary>Whether a module is active.</summary>
/// <param name="module">The module code.</param>
/// <returns><see langword="true"/> if licensed.</returns>
public bool Includes(string module) => Modules.Contains(module);
/// <summary>Days left before the expiry (0 when expired), or <see langword="null"/> without expiry.</summary>
/// <param name="now">The current time.</param>
/// <returns>The days.</returns>
public int? DaysLeft(DateTime now) => ExpiresAt is { } expires ? Math.Max(0, (int)Math.Ceiling((expires - now).TotalDays)) : null;
}
/// <summary>
/// The fictitious licence codes of SPEC §8.3, valid only with <c>KHAEMHAT_LICENSE_MODE=test</c>. Outside test mode they
/// are refused with <c>license_test_only</c>. Automated tests use <see cref="All"/>.
/// </summary>
public static class TestLicenseCatalog
{
/// <summary>Every module.</summary>
public const string All = "KH-TEST-ALL-0000-9999";
/// <summary>25 concurrent users.</summary>
public const string Users25 = "KH-TEST-USERS-0025-0014";
/// <summary>60 more days of trial.</summary>
public const string TrialExtension = "KH-TEST-TRIAL-0060-0015";
private static readonly Dictionary<string, TestCode> Codes = new(StringComparer.Ordinal)
{
["KH-TEST-CORE-0000-0001"] = Module(ModuleCodes.Core),
["KH-TEST-ACCT-0000-0002"] = Module(ModuleCodes.Accounting),
["KH-TEST-ASSET-0000-0003"] = Module(ModuleCodes.Assets),
["KH-TEST-FIN-0000-0004"] = Module(ModuleCodes.Finance),
["KH-TEST-EINV-0000-0005"] = Module(ModuleCodes.EInvoicing),
["KH-TEST-INTRA-0000-0006"] = Module(ModuleCodes.Intrastat),
["KH-TEST-CRM-0000-0007"] = Module(ModuleCodes.Crm),
["KH-TEST-SVC-0000-0008"] = Module(ModuleCodes.Services),
["KH-TEST-CHAN-0000-0009"] = Module(ModuleCodes.Channels),
["KH-TEST-AUTO-0000-0010"] = Module(ModuleCodes.Automation),
["KH-TEST-API-0000-0011"] = Module(ModuleCodes.Api),
["KH-TEST-MULTI-0000-0012"] = Module(ModuleCodes.MultiCompany),
["KH-TEST-REPORT-0000-0013"] = Module(ModuleCodes.Reports),
[All] = new TestCode([.. BuiltInModules.All.Select(m => m.Code)], 0, 0),
[Users25] = new TestCode([], 25, 0),
[TrialExtension] = new TestCode([], 0, 60),
};
/// <summary>Every code.</summary>
public static IReadOnlyCollection<string> AllCodes => Codes.Keys;
/// <summary>Whether the text looks like a fictitious code (to refuse it with the right error outside test mode).</summary>
/// <param name="text">The text.</param>
/// <returns><see langword="true"/> if it starts with <c>KH-TEST-</c>.</returns>
public static bool LooksLikeTestCode(string? text) => text?.Trim().StartsWith("KH-TEST-", StringComparison.OrdinalIgnoreCase) == true;
/// <summary>Finds a code.</summary>
/// <param name="code">The code.</param>
/// <returns>The effect, or <see langword="null"/> when unknown.</returns>
public static TestCode? Find(string code) => Codes.GetValueOrDefault(code.Trim().ToUpperInvariant());
private static TestCode Module(string module) => new([module], 0, 0);
}
/// <summary>The effect of a fictitious code.</summary>
/// <param name="Modules">The modules it activates.</param>
/// <param name="ConcurrentUsers">The users it grants (0 = no change).</param>
/// <param name="TrialExtensionDays">The days it adds to the trial.</param>
public sealed record TestCode(IReadOnlyList<string> Modules, int ConcurrentUsers, int TrialExtensionDays);
@@ -0,0 +1,189 @@
using System.Collections.Frozen;
using System.Globalization;
using System.Reflection;
using System.Text.Json;
namespace Khaemhat.Application.Localization;
/// <summary>
/// The texts of the interface (SPEC §1.9, §10.8): keys such as <c>Shell.Menu.Home</c> resolved from
/// <c>Resources/&lt;culture&gt;/*.json</c>. Components never contain literal texts; they ask this service.
/// </summary>
public interface ITexts
{
/// <summary>The culture of the texts and of number and date formats.</summary>
CultureInfo Culture { get; }
/// <summary>The text of a key; a missing key gives <c>[key]</c>, visible in the page and caught by the tests.</summary>
/// <param name="key">The key, <c>Area.Entity.Text</c>.</param>
/// <returns>The text.</returns>
string this[string key] { get; }
/// <summary>The text of a key with <see cref="string.Format(IFormatProvider, string, object[])"/> placeholders filled in the culture.</summary>
/// <param name="key">The key.</param>
/// <param name="args">The values for <c>{0}</c>, <c>{1}</c>...</param>
/// <returns>The text.</returns>
string Format(string key, params object?[] args);
/// <summary>Whether a key exists.</summary>
/// <param name="key">The key.</param>
/// <returns><see langword="true"/> when it has a text.</returns>
bool Contains(string key);
/// <summary>Every key, for the tests and the documentation.</summary>
IReadOnlyCollection<string> Keys { get; }
}
/// <summary>
/// Reads the texts from JSON files. Nested objects become dotted keys: <c>{"Shell": {"Menu": {"Home": "Home"}}}</c>
/// gives <c>Shell.Menu.Home</c>; the property <c>_</c> gives a text to an object that also has children. The file
/// name is not part of the key; two files defining the same key are an error.
/// </summary>
public sealed class JsonTextProvider : ITexts
{
/// <summary>The prefix of the embedded resources holding the texts: <c>texts/it-IT/Shell.json</c>.</summary>
public const string ResourcePrefix = "texts/";
private readonly FrozenDictionary<string, string> _texts;
/// <summary>Creates the provider from JSON documents.</summary>
/// <param name="culture">The culture.</param>
/// <param name="documents">The documents, by name (used in error messages).</param>
public JsonTextProvider(CultureInfo culture, IEnumerable<KeyValuePair<string, string>> documents)
{
ArgumentNullException.ThrowIfNull(culture);
ArgumentNullException.ThrowIfNull(documents);
Culture = culture;
var texts = new Dictionary<string, string>(StringComparer.Ordinal);
foreach (var (name, json) in documents)
{
using var document = JsonDocument.Parse(json, new JsonDocumentOptions { CommentHandling = JsonCommentHandling.Skip, AllowTrailingCommas = true });
if (document.RootElement.ValueKind != JsonValueKind.Object)
{
throw new InvalidDataException($"The texts file {name} must contain an object.");
}
Flatten(document.RootElement, string.Empty, name, texts);
}
_texts = texts.ToFrozenDictionary(StringComparer.Ordinal);
}
/// <inheritdoc />
public CultureInfo Culture { get; }
/// <inheritdoc />
public IReadOnlyCollection<string> Keys => _texts.Keys;
/// <inheritdoc />
public string this[string key] => key is not null && _texts.TryGetValue(key, out var text) ? text : "[" + key + "]";
/// <summary>Loads the texts of a culture from the embedded resources of an assembly (<see cref="ResourcePrefix"/>).</summary>
/// <param name="assembly">The assembly, usually the web project.</param>
/// <param name="culture">The culture, for example <c>it-IT</c>.</param>
/// <returns>The provider.</returns>
public static JsonTextProvider FromAssembly(Assembly assembly, CultureInfo culture)
{
ArgumentNullException.ThrowIfNull(assembly);
ArgumentNullException.ThrowIfNull(culture);
var prefix = ResourcePrefix + culture.Name + "/";
var documents = new List<KeyValuePair<string, string>>();
foreach (var resource in assembly.GetManifestResourceNames().Order(StringComparer.Ordinal))
{
var name = resource.Replace('\\', '/');
if (!name.StartsWith(prefix, StringComparison.OrdinalIgnoreCase) || !name.EndsWith(".json", StringComparison.OrdinalIgnoreCase))
{
continue;
}
using var stream = assembly.GetManifestResourceStream(resource)!;
using var reader = new StreamReader(stream);
documents.Add(new(name, reader.ReadToEnd()));
}
if (documents.Count == 0)
{
throw new InvalidOperationException($"No texts for {culture.Name} in {assembly.GetName().Name}.");
}
return new JsonTextProvider(culture, documents);
}
/// <inheritdoc />
public string Format(string key, params object?[] args) => string.Format(Culture, this[key], args);
/// <inheritdoc />
public bool Contains(string key) => key is not null && _texts.ContainsKey(key);
private static void Flatten(JsonElement element, string prefix, string file, Dictionary<string, string> texts)
{
foreach (var property in element.EnumerateObject())
{
// "_" gives a text to the object itself: {"Menu": {"Parties": {"_": "Anagrafiche", "Customers": "Clienti"}}}.
var key = property.Name == "_" && prefix.Length > 0 ? prefix : prefix.Length == 0 ? property.Name : prefix + "." + property.Name;
switch (property.Value.ValueKind)
{
case JsonValueKind.Object:
Flatten(property.Value, key, file, texts);
break;
case JsonValueKind.String:
if (!texts.TryAdd(key, property.Value.GetString()!))
{
throw new InvalidDataException($"The text {key} is defined twice ({file}).");
}
break;
default:
throw new InvalidDataException($"The text {key} in {file} must be a string or an object.");
}
}
}
}
/// <summary>Number, money and date formats of the interface, in the culture of <see cref="ITexts"/> (SPEC §10.8).</summary>
public static class TextFormats
{
/// <summary>An amount in euro: <c>€ 1.234,50</c>.</summary>
/// <param name="texts">The texts.</param>
/// <param name="amount">The amount.</param>
/// <returns>The text.</returns>
public static string Money(this ITexts texts, decimal amount)
{
ArgumentNullException.ThrowIfNull(texts);
return "€ " + amount.ToString("#,##0.00", texts.Culture);
}
/// <summary>A number with a fixed count of decimals: <c>1.234,5</c>.</summary>
/// <param name="texts">The texts.</param>
/// <param name="value">The value.</param>
/// <param name="decimals">The decimals.</param>
/// <returns>The text.</returns>
public static string Number(this ITexts texts, decimal value, int decimals = 0)
{
ArgumentNullException.ThrowIfNull(texts);
return value.ToString("N" + decimals.ToString(CultureInfo.InvariantCulture), texts.Culture);
}
/// <summary>A date: <c>13/10/2026</c>.</summary>
/// <param name="texts">The texts.</param>
/// <param name="date">The date.</param>
/// <returns>The text.</returns>
public static string Date(this ITexts texts, DateOnly date)
{
ArgumentNullException.ThrowIfNull(texts);
return date.ToString("dd/MM/yyyy", texts.Culture);
}
/// <summary>A date and time in the given time zone: <c>13/10/2026 14:05</c>.</summary>
/// <param name="texts">The texts.</param>
/// <param name="utc">The moment, in UTC.</param>
/// <param name="zone">The time zone of the user.</param>
/// <returns>The text.</returns>
public static string DateTime(this ITexts texts, DateTime utc, TimeZoneInfo zone)
{
ArgumentNullException.ThrowIfNull(texts);
ArgumentNullException.ThrowIfNull(zone);
var local = TimeZoneInfo.ConvertTimeFromUtc(System.DateTime.SpecifyKind(utc, DateTimeKind.Utc), zone);
return local.ToString("dd/MM/yyyy HH:mm", texts.Culture);
}
}
@@ -0,0 +1,152 @@
namespace Khaemhat.Application.Modules;
/// <summary>
/// The modules of SPEC §8.1 with their permissions. Codes follow <c>area.entity.action</c>; the area is functional
/// (<c>sales</c>, <c>ledger</c>...) while <see cref="PermissionDefinition.Module"/> is the licence code.
/// </summary>
public static class BuiltInModules
{
/// <summary>Every module, in the order of SPEC §8.1.</summary>
public static IReadOnlyList<IModule> All { get; } =
[
Module(ModuleCodes.Core, "Base",
("company.users.manage", "Gestire utenti e ruoli dell'azienda"),
("company.settings.read", "Vedere le impostazioni dell'azienda"),
("company.settings.write", "Modificare le impostazioni dell'azienda"),
("parties.party.read", "Vedere anagrafiche"),
("parties.party.write", "Creare e modificare anagrafiche"),
("parties.party.delete", "Eliminare anagrafiche"),
("parties.party.export", "Esportare anagrafiche"),
("items.item.read", "Vedere articoli e listini"),
("items.item.write", "Creare e modificare articoli e listini"),
("items.item.delete", "Eliminare articoli"),
("items.cost.read", "Vedere costi e margini degli articoli"),
("sales.quote.read", "Vedere preventivi"),
("sales.quote.write", "Creare e modificare preventivi"),
("sales.order.read", "Vedere ordini cliente"),
("sales.order.write", "Creare e modificare ordini cliente"),
("sales.delivery.read", "Vedere DDT di vendita"),
("sales.delivery.write", "Creare e modificare DDT di vendita"),
("sales.invoice.read", "Vedere fatture di vendita"),
("sales.invoice.write", "Creare e modificare fatture in bozza"),
("sales.invoice.issue", "Emettere fatture di vendita"),
("sales.invoice.delete", "Eliminare fatture in bozza"),
("sales.invoice.print", "Stampare fatture di vendita"),
("sales.invoice.export", "Esportare fatture di vendita"),
("purchases.order.read", "Vedere ordini fornitore"),
("purchases.order.write", "Creare e modificare ordini fornitore"),
("purchases.invoice.read", "Vedere fatture di acquisto"),
("purchases.invoice.write", "Registrare fatture di acquisto"),
("inventory.stock.read", "Vedere giacenze"),
("inventory.entry.read", "Vedere movimenti di magazzino"),
("inventory.entry.write", "Creare movimenti di magazzino in bozza"),
("inventory.entry.post", "Confermare movimenti di magazzino"),
("attachments.read", "Vedere e scaricare allegati"),
("attachments.write", "Caricare e generare allegati"),
("attachments.delete", "Eliminare allegati"),
("reports.report.read", "Vedere i report di base")),
Module(ModuleCodes.Accounting, "Contabilità",
("ledger.account.read", "Vedere il piano dei conti"),
("ledger.account.write", "Modificare il piano dei conti"),
("ledger.entry.read", "Vedere la prima nota"),
("ledger.entry.write", "Registrare in prima nota"),
("ledger.entry.finalize", "Rendere definitive le registrazioni"),
("ledger.entry.reopen", "Riaprire registrazioni definitive"),
("ledger.year.close", "Chiudere l'esercizio"),
("vat.register.read", "Vedere i registri IVA"),
("vat.settlement.read", "Vedere le liquidazioni IVA"),
("vat.settlement.confirm", "Confermare le liquidazioni IVA")),
Module(ModuleCodes.Assets, "Cespiti",
("assets.asset.read", "Vedere i cespiti"),
("assets.asset.write", "Gestire i cespiti"),
("assets.depreciation.post", "Registrare gli ammortamenti")),
Module(ModuleCodes.Finance, "Tesoreria",
("finance.schedule.read", "Vedere lo scadenzario"),
("finance.schedule.write", "Modificare lo scadenzario"),
("finance.payment.read", "Vedere incassi e pagamenti"),
("finance.payment.write", "Registrare incassi e pagamenti"),
("finance.bank.reconcile", "Riconciliare i movimenti bancari")),
Module(ModuleCodes.EInvoicing, "Fatturazione elettronica",
("einvoice.document.read", "Vedere i documenti elettronici"),
("einvoice.document.send", "Inviare documenti allo SDI"),
("einvoice.inbox.read", "Vedere le fatture ricevute"),
("einvoice.inbox.import", "Importare le fatture ricevute")),
Module(ModuleCodes.Intrastat, "Intrastat",
("intrastat.list.read", "Vedere gli elenchi Intrastat"),
("intrastat.list.write", "Compilare gli elenchi Intrastat"),
("intrastat.list.export", "Esportare il file per le Dogane")),
Module(ModuleCodes.Crm, "CRM",
("crm.lead.read", "Vedere i lead"),
("crm.lead.write", "Gestire i lead"),
("crm.opportunity.read", "Vedere le opportunità"),
("crm.opportunity.write", "Gestire le opportunità"),
("crm.activity.read", "Vedere attività e agenda"),
("crm.activity.write", "Gestire attività e agenda"),
("crm.campaign.read", "Vedere le campagne"),
("crm.campaign.write", "Gestire le campagne"),
("crm.ticket.read", "Vedere i ticket"),
("crm.ticket.write", "Gestire i ticket")),
Module(ModuleCodes.Services, "Servizi",
("services.contract.read", "Vedere i contratti di assistenza"),
("services.contract.write", "Gestire i contratti di assistenza"),
("services.intervention.read", "Vedere gli interventi"),
("services.intervention.write", "Gestire interventi e rapportini")),
Module(ModuleCodes.Channels, "Canali e-commerce",
("channels.channel.read", "Vedere i canali"),
("channels.channel.write", "Configurare i canali"),
("channels.order.import", "Importare gli ordini web")),
Module(ModuleCodes.Automation, "Automazioni",
("automation.rule.read", "Vedere le regole"),
("automation.rule.write", "Gestire le regole"),
("automation.procedure.run", "Eseguire le procedure")),
Module(ModuleCodes.Api, "Integrazioni",
("api.key.manage", "Gestire le chiavi API dell'azienda"),
("api.webhook.manage", "Gestire i webhook")),
Module(ModuleCodes.MultiCompany, "Multi-azienda"),
Module(ModuleCodes.Reports, "Report avanzati",
("reports.advanced.read", "Vedere i report avanzati"),
("reports.schedule.write", "Pianificare report via e-mail"),
("reports.accountant.export", "Esportare i dati per il commercialista")),
];
private static ModuleDefinition Module(string code, string name, params (string Code, string Description)[] permissions) =>
new(code, name, [.. permissions.Select(p => new PermissionDefinition(p.Code, code, p.Description))]);
}
/// <summary>A predefined role (SPEC §7.2): kept in <c>sys_roles_templates</c> and copied into each company.</summary>
/// <param name="Code">The role code.</param>
/// <param name="Name">The name shown.</param>
/// <param name="Description">What the role is for.</param>
/// <param name="Permissions">The permission patterns.</param>
public sealed record RoleTemplateDefinition(string Code, string Name, string Description, IReadOnlyList<string> Permissions);
/// <summary>The eight predefined roles of SPEC §7.2.</summary>
public static class PredefinedRoles
{
/// <summary>The administration role: every permission.</summary>
public const string Administration = "ADMIN";
/// <summary>The read-only role.</summary>
public const string ReadOnly = "READONLY";
/// <summary>The roles, in display order.</summary>
public static IReadOnlyList<RoleTemplateDefinition> All { get; } =
[
new(Administration, "Amministrazione", "Tutte le funzioni dell'azienda, compresi utenti e impostazioni.", ["*"]),
new("ACCOUNTING", "Contabilità", "Contabilità, IVA, cespiti, tesoreria, fatturazione elettronica e Intrastat.",
["ledger.*", "vat.*", "assets.*", "finance.*", "einvoice.*", "intrastat.*", "parties.party.read", "sales.invoice.read",
"purchases.invoice.*", "reports.report.read", "attachments.read", "attachments.write"]),
new("SALES", "Vendite", "Preventivi, ordini, DDT e fatture di vendita; anagrafiche clienti.",
["sales.*", "parties.*", "items.item.read", "inventory.stock.read", "crm.lead.read", "crm.opportunity.read",
"reports.report.read", "attachments.read", "attachments.write"]),
new("PURCHASES", "Acquisti", "Ordini e fatture fornitore, anagrafiche e articoli.",
["purchases.*", "parties.*", "items.*", "inventory.stock.read", "reports.report.read", "attachments.read", "attachments.write"]),
new("WAREHOUSE", "Magazzino", "Movimenti, giacenze e DDT.",
["inventory.*", "items.item.read", "items.item.write", "sales.delivery.*", "purchases.order.read", "attachments.read"]),
new("CRM", "CRM", "Lead, opportunità, attività, campagne e ticket.",
["crm.*", "parties.*", "sales.quote.*", "attachments.read", "attachments.write"]),
new("SERVICES", "Servizi", "Contratti di assistenza, interventi e ticket.",
["services.*", "parties.party.read", "items.item.read", "crm.ticket.*", "attachments.read", "attachments.write"]),
new(ReadOnly, "Sola lettura", "Vede tutto ciò che la licenza comprende, senza modificare nulla.", ["*.read"]),
];
}
@@ -0,0 +1,166 @@
namespace Khaemhat.Application.Modules;
/// <summary>The module codes of SPEC §8.1, which are also the licence codes.</summary>
public static class ModuleCodes
{
/// <summary>Base: parties, items, documents, warehouse, administration.</summary>
public const string Core = "CORE";
/// <summary>Accounting and VAT.</summary>
public const string Accounting = "ACCT";
/// <summary>Fixed assets.</summary>
public const string Assets = "ASSET";
/// <summary>Treasury.</summary>
public const string Finance = "FIN";
/// <summary>Electronic invoicing.</summary>
public const string EInvoicing = "EINV";
/// <summary>Intrastat.</summary>
public const string Intrastat = "INTRA";
/// <summary>CRM.</summary>
public const string Crm = "CRM";
/// <summary>Services.</summary>
public const string Services = "SVC";
/// <summary>E-commerce channels.</summary>
public const string Channels = "CHAN";
/// <summary>Automations.</summary>
public const string Automation = "AUTO";
/// <summary>API, MCP and webhooks.</summary>
public const string Api = "API";
/// <summary>Companies beyond the first.</summary>
public const string MultiCompany = "MULTI";
/// <summary>Advanced reports.</summary>
public const string Reports = "REPORT";
}
/// <summary>A permission a module declares: a code <c>module.entity.action</c> (SPEC §7.2).</summary>
/// <param name="Code">The code, for example <c>sales.invoice.issue</c>.</param>
/// <param name="Module">The licence code of the module that owns it.</param>
/// <param name="Description">What it allows, in Italian (shown in the permission matrix).</param>
public sealed record PermissionDefinition(string Code, string Module, string Description);
/// <summary>A functional module (SPEC §8.1): its licence code, its name and the permissions it declares.</summary>
public interface IModule
{
/// <summary>The licence code.</summary>
string Code { get; }
/// <summary>The name shown in the interface.</summary>
string Name { get; }
/// <summary>The permissions.</summary>
IReadOnlyList<PermissionDefinition> Permissions { get; }
}
/// <summary>A module declared in code.</summary>
/// <param name="Code">The licence code.</param>
/// <param name="Name">The name shown.</param>
/// <param name="Permissions">The permissions.</param>
public sealed record ModuleDefinition(string Code, string Name, IReadOnlyList<PermissionDefinition> Permissions) : IModule;
/// <summary>
/// The modules of the product and their permissions. The list is static: what the licence does not include stays
/// declared but is filtered by <c>ILicenseGate</c> (menus hidden, permissions denied with
/// <c>module_not_licensed</c>). Each milestone adds the permissions of the screens it delivers.
/// </summary>
public sealed class ModuleRegistry
{
private readonly Dictionary<string, IModule> _modules;
private readonly Dictionary<string, PermissionDefinition> _permissions;
/// <summary>Creates a registry.</summary>
/// <param name="modules">The modules.</param>
/// <exception cref="InvalidOperationException">Two modules share a code, or two permissions share a code.</exception>
public ModuleRegistry(IEnumerable<IModule> modules)
{
ArgumentNullException.ThrowIfNull(modules);
_modules = new Dictionary<string, IModule>(StringComparer.Ordinal);
_permissions = new Dictionary<string, PermissionDefinition>(StringComparer.Ordinal);
foreach (var module in modules)
{
if (!_modules.TryAdd(module.Code, module))
{
throw new InvalidOperationException($"Module {module.Code} is declared twice.");
}
foreach (var permission in module.Permissions)
{
if (!PermissionPattern.IsCode(permission.Code) || permission.Module != module.Code)
{
throw new InvalidOperationException($"Permission {permission.Code} of {module.Code} is not a module.entity.action code of that module.");
}
if (!_permissions.TryAdd(permission.Code, permission))
{
throw new InvalidOperationException($"Permission {permission.Code} is declared twice.");
}
}
}
}
/// <summary>The registry of the product modules.</summary>
public static ModuleRegistry Default { get; } = new(BuiltInModules.All);
/// <summary>The modules, in the order of SPEC §8.1.</summary>
public IReadOnlyCollection<IModule> Modules => _modules.Values;
/// <summary>Every permission.</summary>
public IReadOnlyCollection<PermissionDefinition> Permissions => _permissions.Values;
/// <summary>Finds a module.</summary>
/// <param name="code">The licence code.</param>
/// <returns>The module, or <see langword="null"/>.</returns>
public IModule? FindModule(string code) => _modules.GetValueOrDefault(code);
/// <summary>Finds a permission.</summary>
/// <param name="code">The permission code.</param>
/// <returns>The permission, or <see langword="null"/>.</returns>
public PermissionDefinition? FindPermission(string code) => _permissions.GetValueOrDefault(code);
/// <summary>The permissions a pattern grants (<c>*</c>, <c>sales.*</c>, <c>*.read</c> or a code).</summary>
/// <param name="pattern">The pattern.</param>
/// <returns>The matching permissions.</returns>
public IEnumerable<PermissionDefinition> Expand(string pattern) => _permissions.Values.Where(p => PermissionPattern.Matches(pattern, p.Code));
}
/// <summary>Permission codes and the patterns used by roles: <c>*</c>, <c>module.*</c>, <c>*.action</c> or an exact code.</summary>
public static class PermissionPattern
{
/// <summary>Whether <paramref name="code"/> has the form <c>module.entity.action</c> (two or three lower-case segments).</summary>
/// <param name="code">The code.</param>
/// <returns><see langword="true"/> if valid.</returns>
public static bool IsCode(string? code) =>
code is not null && code.Split('.') is { Length: 2 or 3 } parts
&& parts.All(p => p.Length > 0 && p.All(c => c is (>= 'a' and <= 'z') or (>= '0' and <= '9') or '_'));
/// <summary>Whether a pattern grants a permission code.</summary>
/// <param name="pattern">The pattern.</param>
/// <param name="code">The permission code.</param>
/// <returns><see langword="true"/> if it matches.</returns>
public static bool Matches(string pattern, string code)
{
ArgumentNullException.ThrowIfNull(pattern);
ArgumentNullException.ThrowIfNull(code);
if (pattern == "*" || pattern == code)
{
return true;
}
if (pattern.EndsWith(".*", StringComparison.Ordinal))
{
return code.StartsWith(pattern[..^1], StringComparison.Ordinal);
}
return pattern.StartsWith("*.", StringComparison.Ordinal) && code.EndsWith(pattern[1..], StringComparison.Ordinal);
}
}
@@ -0,0 +1,201 @@
using Khaemhat.Application.Security;
using Khaemhat.Core.Instance;
using Khaemhat.Data;
using Khaemhat.Data.Querying;
using Microsoft.Extensions.Logging;
namespace Khaemhat.Application.Notifications;
/// <summary>A notification to deliver.</summary>
/// <param name="Category">The area: <c>security</c>, <c>jobs</c>, <c>system</c>, <c>licenses</c>...</param>
/// <param name="Severity">The weight.</param>
/// <param name="Title">The title.</param>
/// <param name="Body">The text.</param>
/// <param name="Link">A link inside the application.</param>
public sealed record NotificationMessage(string Category, NotificationSeverity Severity, string Title, string? Body = null, string? Link = null);
/// <summary>A notification as its recipient sees it.</summary>
/// <param name="Id">The id.</param>
/// <param name="Category">The area.</param>
/// <param name="Severity">The weight.</param>
/// <param name="Title">The title.</param>
/// <param name="Body">The text.</param>
/// <param name="Link">A link inside the application.</param>
/// <param name="CreatedAt">When it was sent (UTC).</param>
/// <param name="Read">Whether this user read it.</param>
/// <param name="Personal">Addressed to this user only, not to everyone.</param>
public sealed record InboxItem(long Id, string Category, NotificationSeverity Severity, string Title, string? Body, string? Link, DateTime CreatedAt, bool Read, bool Personal);
/// <summary>
/// Delivers in-app notifications (SPEC §9; mockup 010): to instance accounts in <c>sys_notifications</c>, to company
/// users in the company's <c>notifications</c>. A notification without recipient goes to everyone in the scope.
/// Delivery never breaks the caller: a failure is logged.
/// </summary>
/// <param name="factory">Opens the databases.</param>
/// <param name="clock">The clock.</param>
/// <param name="logger">The log.</param>
public sealed class NotificationDispatcher(IUnitOfWorkFactory factory, TimeProvider clock, ILogger<NotificationDispatcher> logger)
{
/// <summary>Notifies instance accounts.</summary>
/// <param name="message">The notification.</param>
/// <param name="recipientUserId">One account, or <see langword="null"/> for all of them.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
public async Task NotifyInstanceAsync(NotificationMessage message, long? recipientUserId = null, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(message);
try
{
await using var unitOfWork = await factory.CreateAsync(DatabaseScope.System, cancellationToken).ConfigureAwait(false);
await unitOfWork.Repository<SystemNotification, long>().InsertAsync(Fill(new SystemNotification(), message, recipientUserId), cancellationToken).ConfigureAwait(false);
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
logger.LogError(ex, "Notification {Title} not delivered to instance accounts.", message.Title);
}
}
/// <summary>Notifies the users of a company.</summary>
/// <param name="companyCode">The company.</param>
/// <param name="message">The notification.</param>
/// <param name="recipientUserId">One user, or <see langword="null"/> for all of them.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
public async Task NotifyCompanyAsync(string companyCode, NotificationMessage message, long? recipientUserId = null, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(message);
try
{
await using var unitOfWork = await factory.CreateAsync(DatabaseScope.Company(companyCode), cancellationToken).ConfigureAwait(false);
await unitOfWork.Repository<Notification, long>().InsertAsync(Fill(new Notification(), message, recipientUserId), cancellationToken).ConfigureAwait(false);
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
logger.LogError(ex, "Notification {Title} not delivered to company {Company}.", message.Title, companyCode);
}
}
/// <summary>The most notifications a user sees: the newest ones.</summary>
public const int InboxSize = 100;
/// <summary>The notifications of a user, newest first (mockup 010).</summary>
/// <param name="actor">The user: instance accounts read the system ones, company users those of their company.</param>
/// <param name="unreadOnly">Only those not read yet.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The notifications, at most <see cref="InboxSize"/>.</returns>
public Task<IReadOnlyList<InboxItem>> InboxAsync(Actor actor, bool unreadOnly = false, CancellationToken cancellationToken = default) =>
ScopeOf(actor) switch
{
({ } scope, { } user, true) => InboxAsync<SystemNotification, SystemNotificationRead>(scope, user, unreadOnly, cancellationToken),
({ } scope, { } user, false) => InboxAsync<Notification, NotificationRead>(scope, user, unreadOnly, cancellationToken),
_ => Task.FromResult<IReadOnlyList<InboxItem>>([]),
};
/// <summary>Marks a notification as read by the user. A notification for everyone stays unread for the others.</summary>
/// <param name="actor">The user.</param>
/// <param name="notificationId">The notification.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
public Task MarkReadAsync(Actor actor, long notificationId, CancellationToken cancellationToken = default) =>
MarkAsync(actor, [notificationId], cancellationToken);
/// <summary>Marks every notification of the user as read.</summary>
/// <param name="actor">The user.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
public async Task MarkAllReadAsync(Actor actor, CancellationToken cancellationToken = default)
{
var unread = await InboxAsync(actor, unreadOnly: true, cancellationToken).ConfigureAwait(false);
await MarkAsync(actor, [.. unread.Select(n => n.Id)], cancellationToken).ConfigureAwait(false);
}
private Task MarkAsync(Actor actor, IReadOnlyList<long> ids, CancellationToken cancellationToken) =>
ids.Count == 0
? Task.CompletedTask
: ScopeOf(actor) switch
{
({ } scope, { } user, true) => MarkAsync<SystemNotification, SystemNotificationRead>(scope, user, ids, cancellationToken),
({ } scope, { } user, false) => MarkAsync<Notification, NotificationRead>(scope, user, ids, cancellationToken),
_ => Task.CompletedTask,
};
private static (DatabaseScope? Scope, long? User, bool System) ScopeOf(Actor actor)
{
ArgumentNullException.ThrowIfNull(actor);
return actor switch
{
{ SystemUserId: { } id } => (DatabaseScope.System, id, true),
{ CompanyUserId: { } id, CompanyCode: { } company } => (DatabaseScope.Company(company), id, false),
_ => (null, null, false),
};
}
private async Task<IReadOnlyList<InboxItem>> InboxAsync<TNotification, TRead>(DatabaseScope scope, long userId, bool unreadOnly, CancellationToken cancellationToken)
where TNotification : NotificationRecord, new()
where TRead : NotificationReadRecord, new()
{
await using var unitOfWork = await factory.CreateAsync(scope, cancellationToken).ConfigureAwait(false);
var notifications = (await unitOfWork.Repository<TNotification, long>().ListAsync(
Query.For<TNotification>().Where(n => n.RecipientUserId == null || n.RecipientUserId == userId).OrderByDescending(n => n.Id).Take(InboxSize),
cancellationToken).ConfigureAwait(false)).Items;
var everyone = notifications.Where(n => n.RecipientUserId == null).Select(n => n.Id).ToList();
var read = everyone.Count == 0
? []
: (await unitOfWork.Repository<TRead, long>().ListAsync(
Query.For<TRead>().Where(r => r.UserId == userId && everyone.Contains(r.NotificationId)), cancellationToken).ConfigureAwait(false)).Items
.Select(r => r.NotificationId).ToHashSet();
return [.. notifications
.Select(n => new InboxItem(n.Id, n.Category, n.Severity, n.Title, n.Body, n.Link, n.CreatedAt,
n.RecipientUserId is null ? read.Contains(n.Id) : n.ReadAt is not null, n.RecipientUserId is not null))
.Where(n => !unreadOnly || !n.Read)];
}
private async Task MarkAsync<TNotification, TRead>(DatabaseScope scope, long userId, IReadOnlyList<long> ids, CancellationToken cancellationToken)
where TNotification : NotificationRecord, new()
where TRead : NotificationReadRecord, new()
{
await using var unitOfWork = await factory.CreateAsync(scope, cancellationToken).ConfigureAwait(false);
var list = ids.ToList();
var repository = unitOfWork.Repository<TNotification, long>();
var notifications = (await repository.ListAsync(
Query.For<TNotification>().Where(n => list.Contains(n.Id) && (n.RecipientUserId == null || n.RecipientUserId == userId)), cancellationToken).ConfigureAwait(false)).Items;
var reads = unitOfWork.Repository<TRead, long>();
var already = (await reads.ListAsync(Query.For<TRead>().Where(r => r.UserId == userId && list.Contains(r.NotificationId)), cancellationToken).ConfigureAwait(false)).Items
.Select(r => r.NotificationId).ToHashSet();
var now = clock.GetUtcNow().UtcDateTime;
await unitOfWork.InTransactionAsync(
async ct =>
{
foreach (var notification in notifications)
{
if (notification.RecipientUserId is null)
{
if (already.Add(notification.Id))
{
await reads.InsertAsync(new TRead { NotificationId = notification.Id, UserId = userId }, ct).ConfigureAwait(false);
}
}
else if (notification.ReadAt is null)
{
notification.ReadAt = now;
await repository.UpdateAsync(notification, ct).ConfigureAwait(false);
}
}
},
cancellationToken).ConfigureAwait(false);
}
private static T Fill<T>(T notification, NotificationMessage message, long? recipient)
where T : NotificationRecord
{
notification.RecipientUserId = recipient;
notification.Category = Clip(message.Category, 40);
notification.Severity = message.Severity;
notification.Title = Clip(message.Title, 200);
notification.Body = message.Body;
notification.Link = message.Link is null ? null : Clip(message.Link, 400);
return notification;
}
private static string Clip(string value, int length) => value.Length <= length ? value : value[..length];
}
@@ -0,0 +1,241 @@
using System.Globalization;
namespace Khaemhat.Application.Preferences;
/// <summary>The colour theme (SPEC §10.6). <see cref="Auto"/> follows the operating system.</summary>
public enum ThemeMode
{
/// <summary>Follows the operating system.</summary>
Auto = 0,
/// <summary>Light.</summary>
Light = 1,
/// <summary>Dark ("notturno").</summary>
Dark = 2,
/// <summary>High contrast (AAA).</summary>
HighContrast = 3,
}
/// <summary>The row height and spacing of lists and forms.</summary>
public enum Density
{
/// <summary>The default spacing.</summary>
Comfortable = 0,
/// <summary>Shorter rows and smaller gaps.</summary>
Compact = 1,
}
/// <summary>What the user sees after signing in (SPEC §10.3).</summary>
public enum StartPage
{
/// <summary>The dashboard.</summary>
Dashboard = 0,
/// <summary>The tab that was active at the last sign-out.</summary>
LastTab = 1,
/// <summary>A page chosen by the user (<see cref="UserPreferences.StartPath"/>).</summary>
Page = 2,
}
/// <summary>
/// The interface preferences of a user (SPEC §10.6, mockup 008), stored as key/value pairs in <c>user_settings</c>
/// (company users) or <c>sys_user_settings</c> (instance accounts).
/// </summary>
public sealed record UserPreferences
{
/// <summary>The eight accents of <c>mockup.css</c>; <c>nilo</c> is the default.</summary>
public static readonly IReadOnlyList<string> Accents = ["nilo", "lapislazzuli", "malachite", "turchese", "ocra", "corniola", "ametista", "grafite"];
/// <summary>The text sizes offered, in percent of the base size.</summary>
public static readonly IReadOnlyList<int> TextSizes = [100, 110, 120];
/// <summary>The preferences of a new user.</summary>
public static UserPreferences Default { get; } = new();
/// <summary>The theme.</summary>
public ThemeMode Theme { get; init; } = ThemeMode.Auto;
/// <summary>The accent, one of <see cref="Accents"/>.</summary>
public string Accent { get; init; } = "nilo";
/// <summary>The density.</summary>
public Density Density { get; init; } = Density.Comfortable;
/// <summary>The text size in percent, one of <see cref="TextSizes"/>.</summary>
public int TextSize { get; init; } = 100;
/// <summary>Whether numbers use tabular figures everywhere (grids always do).</summary>
public bool TabularNumbers { get; init; } = true;
/// <summary>Whether animations and transitions are turned off.</summary>
public bool ReducedMotion { get; init; }
/// <summary>Whether tooltips appear on hover.</summary>
public bool Tooltips { get; init; } = true;
/// <summary>Whether the grid row under the pointer is highlighted.</summary>
public bool RowHover { get; init; } = true;
/// <summary>Whether the side menu is collapsed; <see langword="null"/> lets the window width decide (collapsed under 1100 px).</summary>
public bool? MenuCollapsed { get; init; }
/// <summary>Whether the dashboard is shown on the home page.</summary>
public bool ShowDashboard { get; init; } = true;
/// <summary>The page opened after signing in.</summary>
public StartPage StartPage { get; init; } = StartPage.Dashboard;
/// <summary>The address opened when <see cref="StartPage"/> is <see cref="Preferences.StartPage.Page"/>.</summary>
public string? StartPath { get; init; }
/// <summary>The value of <c>data-theme</c> on the root element.</summary>
public string ThemeAttribute => ThemeName(Theme);
/// <summary>The value of <c>data-density</c> on the root element.</summary>
public string DensityAttribute => Density == Density.Compact ? "compact" : "comfortable";
/// <summary>The attribute value of a theme.</summary>
/// <param name="theme">The theme.</param>
/// <returns><c>auto</c>, <c>light</c>, <c>dark</c> or <c>high-contrast</c>.</returns>
public static string ThemeName(ThemeMode theme) => theme switch
{
ThemeMode.Light => "light",
ThemeMode.Dark => "dark",
ThemeMode.HighContrast => "high-contrast",
_ => "auto",
};
/// <summary>Reads a theme name; unknown values give <see cref="ThemeMode.Auto"/>.</summary>
/// <param name="value">The name.</param>
/// <returns>The theme.</returns>
public static ThemeMode ParseTheme(string? value) => value switch
{
"light" => ThemeMode.Light,
"dark" => ThemeMode.Dark,
"high-contrast" => ThemeMode.HighContrast,
_ => ThemeMode.Auto,
};
/// <summary>Reads the preferences from stored values; missing or invalid values keep the default.</summary>
/// <param name="values">The stored values by key.</param>
/// <returns>The preferences.</returns>
public static UserPreferences FromSettings(IReadOnlyDictionary<string, string?> values)
{
ArgumentNullException.ThrowIfNull(values);
var d = Default;
return new UserPreferences
{
Theme = values.TryGetValue(PreferenceKeys.Theme, out var theme) ? ParseTheme(theme) : d.Theme,
Accent = values.TryGetValue(PreferenceKeys.Accent, out var accent) && accent is not null && Accents.Contains(accent) ? accent : d.Accent,
Density = values.TryGetValue(PreferenceKeys.Density, out var density) && density == "compact" ? Density.Compact : d.Density,
TextSize = values.TryGetValue(PreferenceKeys.TextSize, out var size)
&& int.TryParse(size, NumberStyles.None, CultureInfo.InvariantCulture, out var s) && TextSizes.Contains(s) ? s : d.TextSize,
TabularNumbers = Bool(values, PreferenceKeys.TabularNumbers) ?? d.TabularNumbers,
ReducedMotion = Bool(values, PreferenceKeys.ReducedMotion) ?? d.ReducedMotion,
Tooltips = Bool(values, PreferenceKeys.Tooltips) ?? d.Tooltips,
RowHover = Bool(values, PreferenceKeys.RowHover) ?? d.RowHover,
MenuCollapsed = Bool(values, PreferenceKeys.MenuCollapsed),
ShowDashboard = Bool(values, PreferenceKeys.ShowDashboard) ?? d.ShowDashboard,
StartPage = values.TryGetValue(PreferenceKeys.StartPage, out var start)
? start switch
{
"last-tab" => StartPage.LastTab,
"page" => StartPage.Page,
_ => StartPage.Dashboard,
}
: d.StartPage,
StartPath = values.TryGetValue(PreferenceKeys.StartPath, out var path) && IsLocalPath(path) ? path : null,
};
}
/// <summary>The values to store.</summary>
/// <returns>The values by key; <see langword="null"/> removes the key.</returns>
public IReadOnlyDictionary<string, string?> ToSettings() => new Dictionary<string, string?>(StringComparer.Ordinal)
{
[PreferenceKeys.Theme] = ThemeAttribute,
[PreferenceKeys.Accent] = Accents.Contains(Accent) ? Accent : Default.Accent,
[PreferenceKeys.Density] = DensityAttribute,
[PreferenceKeys.TextSize] = TextSize.ToString(CultureInfo.InvariantCulture),
[PreferenceKeys.TabularNumbers] = Text(TabularNumbers),
[PreferenceKeys.ReducedMotion] = Text(ReducedMotion),
[PreferenceKeys.Tooltips] = Text(Tooltips),
[PreferenceKeys.RowHover] = Text(RowHover),
[PreferenceKeys.MenuCollapsed] = MenuCollapsed is { } collapsed ? Text(collapsed) : null,
[PreferenceKeys.ShowDashboard] = Text(ShowDashboard),
[PreferenceKeys.StartPage] = StartPage switch
{
StartPage.LastTab => "last-tab",
StartPage.Page => "page",
_ => "dashboard",
},
[PreferenceKeys.StartPath] = IsLocalPath(StartPath) ? StartPath : null,
};
/// <summary>Whether an address is a path inside the application (no scheme, no host): the start page cannot leave the site.</summary>
/// <param name="path">The address.</param>
/// <returns><see langword="true"/> for <c>/something</c>.</returns>
public static bool IsLocalPath(string? path) =>
path is { Length: > 0 and <= 400 }
&& path[0] == '/'
&& (path.Length == 1 || (path[1] != '/' && path[1] != '\\'))
&& !path.Contains("://", StringComparison.Ordinal);
private static bool? Bool(IReadOnlyDictionary<string, string?> values, string key) =>
values.TryGetValue(key, out var value)
? value switch
{
"true" => true,
"false" => false,
_ => null,
}
: null;
private static string Text(bool value) => value ? "true" : "false";
}
/// <summary>The keys of <see cref="UserPreferences"/> in <c>user_settings</c>.</summary>
public static class PreferenceKeys
{
/// <summary>Theme.</summary>
public const string Theme = "ui.theme";
/// <summary>Accent.</summary>
public const string Accent = "ui.accent";
/// <summary>Density.</summary>
public const string Density = "ui.density";
/// <summary>Text size.</summary>
public const string TextSize = "ui.text-size";
/// <summary>Tabular numbers.</summary>
public const string TabularNumbers = "ui.tabular-numbers";
/// <summary>Reduced motion.</summary>
public const string ReducedMotion = "ui.reduced-motion";
/// <summary>Tooltips.</summary>
public const string Tooltips = "ui.tooltips";
/// <summary>Row highlight in grids.</summary>
public const string RowHover = "ui.row-hover";
/// <summary>Menu state.</summary>
public const string MenuCollapsed = "ui.menu-collapsed";
/// <summary>Dashboard on or off.</summary>
public const string ShowDashboard = "home.show-dashboard";
/// <summary>Start page.</summary>
public const string StartPage = "home.start-page";
/// <summary>Start address.</summary>
public const string StartPath = "home.start-path";
/// <summary>The open tabs at the last sign-out (JSON array of addresses).</summary>
public const string OpenTabs = "ui.open-tabs";
}
@@ -0,0 +1,147 @@
using Khaemhat.Application.Security;
using Khaemhat.Core.Instance;
using Khaemhat.Data;
using Khaemhat.Data.Querying;
namespace Khaemhat.Application.Preferences;
/// <summary>
/// Reads and writes the preferences of the signed-in user (SPEC §10.6). Instance accounts keep theirs in the system
/// database, so they follow them in every company; company users keep them in the company database.
/// </summary>
/// <param name="factory">Opens the databases.</param>
public sealed class UserSettingsService(IUnitOfWorkFactory factory)
{
/// <summary>The longest value accepted (dashboard and grid layouts are JSON).</summary>
public const int MaxValueLength = 64 * 1024;
/// <summary>Reads every preference of the actor.</summary>
/// <param name="actor">The signed-in user.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The values by key; empty for the instance itself.</returns>
public async Task<IReadOnlyDictionary<string, string?>> GetAllAsync(Actor actor, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(actor);
if (Owner(actor) is not { } owner)
{
return new Dictionary<string, string?>(StringComparer.Ordinal);
}
await using var unitOfWork = await factory.CreateAsync(owner.Scope, cancellationToken).ConfigureAwait(false);
IReadOnlyList<UserSettingRecord> rows = owner.Scope.IsSystem
? await ListAsync<SystemUserSetting>(unitOfWork, owner.UserId, cancellationToken).ConfigureAwait(false)
: await ListAsync<UserSetting>(unitOfWork, owner.UserId, cancellationToken).ConfigureAwait(false);
return rows.ToDictionary(r => r.Key, r => r.Value, StringComparer.Ordinal);
}
/// <summary>Reads one preference.</summary>
/// <param name="actor">The signed-in user.</param>
/// <param name="key">The key.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The value, or <see langword="null"/>.</returns>
public async Task<string?> GetAsync(Actor actor, string key, CancellationToken cancellationToken = default)
{
ArgumentException.ThrowIfNullOrWhiteSpace(key);
var all = await GetAllAsync(actor, cancellationToken).ConfigureAwait(false);
return all.TryGetValue(key, out var value) ? value : null;
}
/// <summary>Writes one preference; <see langword="null"/> removes it.</summary>
/// <param name="actor">The signed-in user.</param>
/// <param name="key">The key.</param>
/// <param name="value">The value.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
public Task SetAsync(Actor actor, string key, string? value, CancellationToken cancellationToken = default) =>
SetManyAsync(actor, new Dictionary<string, string?>(StringComparer.Ordinal) { [key] = value }, cancellationToken);
/// <summary>Writes several preferences in one transaction; <see langword="null"/> values remove the key.</summary>
/// <param name="actor">The signed-in user.</param>
/// <param name="values">The values by key.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
public async Task SetManyAsync(Actor actor, IReadOnlyDictionary<string, string?> values, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(actor);
ArgumentNullException.ThrowIfNull(values);
foreach (var (key, value) in values)
{
if (string.IsNullOrWhiteSpace(key) || key.Length > 200)
{
throw new ValidationFailedException("settings.key_invalid");
}
if (value is { Length: > MaxValueLength })
{
throw new ValidationFailedException("settings.value_too_long");
}
}
if (Owner(actor) is not { } owner || values.Count == 0)
{
return;
}
await using var unitOfWork = await factory.CreateAsync(owner.Scope, cancellationToken).ConfigureAwait(false);
await unitOfWork.InTransactionAsync(
ct => owner.Scope.IsSystem
? WriteAsync<SystemUserSetting>(unitOfWork, owner.UserId, values, ct)
: WriteAsync<UserSetting>(unitOfWork, owner.UserId, values, ct),
cancellationToken).ConfigureAwait(false);
}
/// <summary>Reads the interface preferences.</summary>
/// <param name="actor">The signed-in user.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The preferences, with defaults for what was never set.</returns>
public async Task<UserPreferences> GetPreferencesAsync(Actor actor, CancellationToken cancellationToken = default) =>
UserPreferences.FromSettings(await GetAllAsync(actor, cancellationToken).ConfigureAwait(false));
/// <summary>Writes the interface preferences.</summary>
/// <param name="actor">The signed-in user.</param>
/// <param name="preferences">The preferences.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
public Task SavePreferencesAsync(Actor actor, UserPreferences preferences, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(preferences);
return SetManyAsync(actor, preferences.ToSettings(), cancellationToken);
}
private static (DatabaseScope Scope, long UserId)? Owner(Actor actor) => actor switch
{
{ SystemUserId: { } id } => (DatabaseScope.System, id),
{ CompanyUserId: { } id, CompanyCode: { } code } => (DatabaseScope.Company(code), id),
_ => null,
};
private static async Task<IReadOnlyList<T>> ListAsync<T>(IUnitOfWork unitOfWork, long userId, CancellationToken cancellationToken)
where T : UserSettingRecord, new() =>
(await unitOfWork.Repository<T, long>().ListAsync(Query.For<T>().Where(s => s.UserId == userId), cancellationToken).ConfigureAwait(false)).Items;
private static async Task WriteAsync<T>(IUnitOfWork unitOfWork, long userId, IReadOnlyDictionary<string, string?> values, CancellationToken cancellationToken)
where T : UserSettingRecord, new()
{
var repository = unitOfWork.Repository<T, long>();
var existing = (await ListAsync<T>(unitOfWork, userId, cancellationToken).ConfigureAwait(false)).ToDictionary(r => r.Key, StringComparer.Ordinal);
foreach (var (key, value) in values)
{
if (existing.TryGetValue(key, out var row))
{
if (value is null)
{
await repository.DeleteAsync(row.Id, cancellationToken).ConfigureAwait(false);
}
else if (!string.Equals(row.Value, value, StringComparison.Ordinal))
{
row.Value = value;
await repository.UpdateAsync(row, cancellationToken).ConfigureAwait(false);
}
}
else if (value is not null)
{
await repository.InsertAsync(new T { UserId = userId, Key = key, Value = value }, cancellationToken).ConfigureAwait(false);
}
}
}
}
@@ -0,0 +1,54 @@
namespace Khaemhat.Application.Querying;
/// <summary>
/// A <see cref="ListSource{T}"/> over rows kept in memory (small tables, catalogs, tests). The rows a request selects
/// are kept until the search, filters or ordering change, so scrolling through the pages of 100,000 rows only cuts
/// slices.
/// </summary>
/// <typeparam name="T">The row type.</typeparam>
/// <param name="rows">The rows.</param>
/// <param name="fields">The fields.</param>
public sealed class InMemoryListSource<T>(IReadOnlyList<T> rows, ListFields<T> fields)
where T : class
{
private readonly Lock _lock = new();
private (ListQuery Query, IReadOnlyList<T> Rows)? _last;
/// <summary>The fields.</summary>
public ListFields<T> Fields => fields;
/// <summary>Answers a request.</summary>
/// <param name="query">The request.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The page.</returns>
public Task<ListPage<T>> QueryAsync(ListQuery query, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(query);
cancellationToken.ThrowIfCancellationRequested();
return Task.FromResult(fields.Page(Selected(query), query));
}
/// <summary>Every row a request selects, in order, for exports.</summary>
/// <param name="query">The request; its page is ignored.</param>
/// <returns>The rows.</returns>
public IReadOnlyList<T> All(ListQuery query) => Selected(query);
private IReadOnlyList<T> Selected(ListQuery query)
{
lock (_lock)
{
if (_last is { } last && last.Query.SameRows(query))
{
return last.Rows;
}
}
var selected = fields.Select(rows, query);
lock (_lock)
{
_last = (query, selected);
}
return selected;
}
}
@@ -0,0 +1,446 @@
using System.Globalization;
using System.Linq.Expressions;
using System.Reflection;
using Khaemhat.Data.Querying;
namespace Khaemhat.Application.Querying;
/// <summary>
/// The fields a list can search, filter, order and total, each bound to a property of the row. One description serves
/// both sides: <see cref="Apply(Query{T}, ListQuery)"/> adds conditions, ordering and page to a repository query (SQL,
/// case-insensitive LIKE for texts), <see cref="Apply(IEnumerable{T}, ListQuery)"/> runs the same request on rows in
/// memory.
/// </summary>
/// <typeparam name="T">The row type.</typeparam>
public sealed class ListFields<T>
where T : class
{
private readonly Dictionary<string, ListField<T>> _fields = new(StringComparer.Ordinal);
private readonly List<ListField<T>> _ordered = [];
/// <summary>The fields, in the order added.</summary>
public IReadOnlyList<ListField<T>> Fields => _ordered;
/// <summary>The ordering used when the request has none, so that pages do not overlap.</summary>
public IReadOnlyList<ListSort> DefaultSort { get; private set; } = [];
/// <summary>Adds a field.</summary>
/// <typeparam name="TValue">The type of the property.</typeparam>
/// <param name="id">The id used in filters and orderings.</param>
/// <param name="selector">The property.</param>
/// <param name="searchable">Whether the search box looks in it (texts only).</param>
/// <param name="total">Whether the page carries its sum (numbers only).</param>
/// <returns>This, to chain.</returns>
public ListFields<T> Add<TValue>(string id, Expression<Func<T, TValue>> selector, bool searchable = false, bool total = false)
{
ArgumentException.ThrowIfNullOrWhiteSpace(id);
ArgumentNullException.ThrowIfNull(selector);
if (searchable && typeof(TValue) != typeof(string))
{
throw new ArgumentException($"Only text fields can be searched: {id}.", nameof(searchable));
}
if (total && ListField<T, TValue>.Numeric is null)
{
throw new ArgumentException($"Only number fields can be totalled: {id}.", nameof(total));
}
var field = new ListField<T, TValue>(id, selector, searchable, total);
_fields.Add(id, field);
_ordered.Add(field);
return this;
}
/// <summary>Sets the ordering used when the request has none.</summary>
/// <param name="sort">The ordering; the last field should be unique (the code or the id).</param>
/// <returns>This, to chain.</returns>
public ListFields<T> OrderByDefault(params ListSort[] sort)
{
foreach (var item in sort)
{
_ = Get(item.Field);
}
DefaultSort = sort;
return this;
}
/// <summary>A field by id.</summary>
/// <param name="id">The id.</param>
/// <returns>The field, or <see langword="null"/>.</returns>
public ListField<T>? Find(string id) => _fields.GetValueOrDefault(id);
/// <summary>Whether a filter can be applied: known field, operator fit for its type, readable values.</summary>
/// <param name="filter">The filter, for example one read from the saved filters.</param>
/// <returns>Whether it is valid.</returns>
public bool IsValid(ListFilter filter)
{
try
{
_ = Condition(Expression.Parameter(typeof(T), "x"), filter, inMemory: true);
return true;
}
catch (ArgumentException)
{
return false;
}
}
/// <summary>Adds the conditions, the ordering and the page of a request to a repository query.</summary>
/// <param name="query">The query, possibly with conditions of its own (the company, the state...).</param>
/// <param name="list">The request.</param>
/// <returns>The query.</returns>
public Query<T> Apply(Query<T> query, ListQuery list)
{
ArgumentNullException.ThrowIfNull(query);
ArgumentNullException.ThrowIfNull(list);
if (Predicate(list, inMemory: false) is { } predicate)
{
query = query.Where(predicate);
}
foreach (var sort in SortOf(list))
{
query = Get(sort.Field).OrderQuery(query, sort.Descending);
}
return query.Page(Math.Max(0, list.Offset), Math.Clamp(list.Limit, 1, ListQuery.MaxLimit));
}
/// <summary>Runs a request on rows in memory: filters, totals, ordering and page.</summary>
/// <param name="source">The rows.</param>
/// <param name="list">The request.</param>
/// <returns>The page.</returns>
public ListPage<T> Apply(IEnumerable<T> source, ListQuery list)
{
var rows = Select(source, list);
return Page(rows, list);
}
/// <summary>The rows a request selects, filtered and ordered, without paging (for exports and caches).</summary>
/// <param name="source">The rows.</param>
/// <param name="list">The request.</param>
/// <returns>The rows.</returns>
public IReadOnlyList<T> Select(IEnumerable<T> source, ListQuery list)
{
ArgumentNullException.ThrowIfNull(source);
ArgumentNullException.ThrowIfNull(list);
if (Predicate(list, inMemory: true) is { } predicate)
{
source = source.Where(predicate.Compile());
}
IOrderedEnumerable<T>? ordered = null;
foreach (var sort in SortOf(list))
{
ordered = Get(sort.Field).OrderMemory(source, ordered, sort.Descending);
}
return [.. ordered ?? source];
}
/// <summary>A page of rows already selected and ordered by <see cref="Select"/>, with the totals.</summary>
/// <param name="rows">The rows.</param>
/// <param name="list">The request.</param>
/// <returns>The page.</returns>
public ListPage<T> Page(IReadOnlyList<T> rows, ListQuery list)
{
ArgumentNullException.ThrowIfNull(rows);
ArgumentNullException.ThrowIfNull(list);
var totals = _ordered.Where(f => f.Total).ToDictionary(f => f.Id, f => f.Sum(rows), StringComparer.Ordinal);
var limit = Math.Clamp(list.Limit, 1, ListQuery.MaxLimit);
IReadOnlyList<T> items = [.. rows.Skip(Math.Max(0, list.Offset)).Take(limit)];
return new ListPage<T>(items, rows.Count, totals);
}
/// <summary>The condition of a request (search and filters), or <see langword="null"/> when it selects everything.</summary>
/// <param name="list">The request.</param>
/// <param name="inMemory">Whether for rows in memory (texts compared ignoring case) or for SQL.</param>
/// <returns>The predicate.</returns>
public Expression<Func<T, bool>>? Predicate(ListQuery list, bool inMemory)
{
ArgumentNullException.ThrowIfNull(list);
var row = Expression.Parameter(typeof(T), "x");
var parts = new List<Expression>();
var search = list.Search?.Trim();
if (!string.IsNullOrEmpty(search))
{
// Every word must appear in some searchable field: "rossi torino" finds Rossi of Torino.
foreach (var word in search.Split(' ', StringSplitOptions.RemoveEmptyEntries).Take(8))
{
var any = _ordered.Where(f => f.Searchable).Select(f => f.Search(row, word, inMemory)).Aggregate((Expression?)null, (a, b) => a is null ? b : Expression.OrElse(a, b));
if (any is not null)
{
parts.Add(any);
}
}
}
parts.AddRange(list.Filters.Select(filter => Condition(row, filter, inMemory)));
return parts.Count == 0 ? null : Expression.Lambda<Func<T, bool>>(parts.Aggregate(Expression.AndAlso), row);
}
private Expression Condition(ParameterExpression row, ListFilter filter, bool inMemory) =>
(Find(filter.Field) ?? throw new ArgumentException($"Unknown field: {filter.Field}.", nameof(filter))).Condition(row, filter, inMemory);
private ListField<T> Get(string id) => Find(id) ?? throw new ArgumentException($"Unknown field: {id}.", nameof(id));
private List<ListSort> SortOf(ListQuery list)
{
var sort = list.Sort.Where(s => _fields.ContainsKey(s.Field)).ToList();
foreach (var fallback in DefaultSort)
{
if (!sort.Any(s => s.Field == fallback.Field))
{
sort.Add(fallback);
}
}
return sort;
}
}
/// <summary>A field of a <see cref="ListFields{T}"/>.</summary>
/// <typeparam name="T">The row type.</typeparam>
public abstract class ListField<T>
where T : class
{
private protected ListField(string id, Type valueType, bool searchable, bool total)
{
Id = id;
ValueType = valueType;
Searchable = searchable;
Total = total;
}
/// <summary>The id.</summary>
public string Id { get; }
/// <summary>The type of the property (nullable included).</summary>
public Type ValueType { get; }
/// <summary>Whether the search box looks in it.</summary>
public bool Searchable { get; }
/// <summary>Whether the page carries its sum.</summary>
public bool Total { get; }
/// <summary>The value of the field in a row.</summary>
/// <param name="row">The row.</param>
/// <returns>The value.</returns>
public abstract object? ValueOf(T row);
internal abstract Expression Condition(ParameterExpression row, ListFilter filter, bool inMemory);
internal abstract Expression Search(ParameterExpression row, string text, bool inMemory);
internal abstract Query<T> OrderQuery(Query<T> query, bool descending);
internal abstract IOrderedEnumerable<T> OrderMemory(IEnumerable<T> source, IOrderedEnumerable<T>? ordered, bool descending);
internal abstract decimal Sum(IEnumerable<T> rows);
}
/// <summary>A field bound to a property of type <typeparamref name="TValue"/>.</summary>
/// <typeparam name="T">The row type.</typeparam>
/// <typeparam name="TValue">The property type.</typeparam>
internal sealed class ListField<T, TValue> : ListField<T>
where T : class
{
private static readonly MethodInfo ContainsIgnoreCase = typeof(string).GetMethod(nameof(string.Contains), [typeof(string), typeof(StringComparison)])!;
private static readonly MethodInfo StartsIgnoreCase = typeof(string).GetMethod(nameof(string.StartsWith), [typeof(string), typeof(StringComparison)])!;
private static readonly MethodInfo ContainsText = typeof(string).GetMethod(nameof(string.Contains), [typeof(string)])!;
private static readonly MethodInfo StartsText = typeof(string).GetMethod(nameof(string.StartsWith), [typeof(string)])!;
private static readonly MethodInfo EnumerableContains = typeof(Enumerable).GetMethods()
.Single(m => m.Name == nameof(Enumerable.Contains) && m.GetParameters().Length == 2).MakeGenericMethod(typeof(TValue));
private static readonly Type Underlying = Nullable.GetUnderlyingType(typeof(TValue)) ?? typeof(TValue);
private readonly Expression<Func<T, TValue>> _selector;
private readonly Func<T, TValue> _compiled;
public ListField(string id, Expression<Func<T, TValue>> selector, bool searchable, bool total)
: base(id, typeof(TValue), searchable, total)
{
_selector = selector;
_compiled = selector.Compile();
}
/// <summary>Converts a value to decimal for the totals, or <see langword="null"/> when the type is not a number.</summary>
public static Func<TValue, decimal?>? Numeric { get; } = Underlying switch
{
var t when t == typeof(decimal) => v => v is null ? null : (decimal)(object)v,
var t when t == typeof(int) => v => v is null ? null : (int)(object)v,
var t when t == typeof(long) => v => v is null ? null : (long)(object)v,
var t when t == typeof(double) => v => v is null ? null : (decimal)(double)(object)v,
_ => null,
};
private static bool IsText => typeof(TValue) == typeof(string);
private static bool IsOrdered => !IsText && Underlying != typeof(bool) && !Underlying.IsEnum && typeof(IComparable).IsAssignableFrom(Underlying);
public override object? ValueOf(T row) => _compiled(row);
internal override Expression Search(ParameterExpression row, string text, bool inMemory) =>
TextCall(Member(row), inMemory ? ContainsIgnoreCase : ContainsText, text, inMemory);
internal override Expression Condition(ParameterExpression row, ListFilter filter, bool inMemory)
{
var member = Member(row);
var values = filter.Values ?? [];
switch (filter.Operator)
{
case ListFilterOperator.IsEmpty or ListFilterOperator.IsNotEmpty:
Expression empty = IsText
? Expression.Call(typeof(string).GetMethod(nameof(string.IsNullOrEmpty))!, member)
: typeof(TValue).IsValueType && Nullable.GetUnderlyingType(typeof(TValue)) is null
? Expression.Constant(false)
: Expression.Equal(member, Expression.Constant(null, typeof(TValue)));
return filter.Operator == ListFilterOperator.IsEmpty ? empty : Expression.Not(empty);
case ListFilterOperator.Contains or ListFilterOperator.StartsWith:
Require(IsText, filter);
var method = filter.Operator == ListFilterOperator.Contains
? (inMemory ? ContainsIgnoreCase : ContainsText)
: (inMemory ? StartsIgnoreCase : StartsText);
return TextCall(member, method, Single(values, filter), inMemory);
case ListFilterOperator.In:
Require(values.Count > 0, filter);
var array = values.Select(v => Convert(v, filter)).ToArray();
return Expression.Call(EnumerableContains, Expression.Constant(array, typeof(TValue[])), member);
case ListFilterOperator.Between:
Require(IsOrdered && values.Count == 2, filter);
return Expression.AndAlso(
Expression.GreaterThanOrEqual(member, Value(values[0], filter)),
Expression.LessThanOrEqual(member, Value(values[1], filter)));
case ListFilterOperator.Equals:
return Equal(member, Single(values, filter), filter, inMemory);
case ListFilterOperator.NotEquals:
return Expression.Not(Equal(member, Single(values, filter), filter, inMemory));
case ListFilterOperator.GreaterThan or ListFilterOperator.GreaterOrEqual or ListFilterOperator.LessThan or ListFilterOperator.LessOrEqual:
Require(IsOrdered, filter);
var value = Value(Single(values, filter), filter);
return filter.Operator switch
{
ListFilterOperator.GreaterThan => Expression.GreaterThan(member, value),
ListFilterOperator.GreaterOrEqual => Expression.GreaterThanOrEqual(member, value),
ListFilterOperator.LessThan => Expression.LessThan(member, value),
_ => Expression.LessThanOrEqual(member, value),
};
default:
throw new ArgumentException($"Unknown operator {filter.Operator} on {Id}.", nameof(filter));
}
}
internal override Query<T> OrderQuery(Query<T> query, bool descending) =>
descending ? query.OrderByDescending(_selector) : query.OrderBy(_selector);
internal override IOrderedEnumerable<T> OrderMemory(IEnumerable<T> source, IOrderedEnumerable<T>? ordered, bool descending)
{
var comparer = IsText ? (IComparer<TValue>)(object)StringComparer.CurrentCultureIgnoreCase : Comparer<TValue>.Default;
return (ordered, descending) switch
{
(null, false) => source.OrderBy(_compiled, comparer),
(null, true) => source.OrderByDescending(_compiled, comparer),
(_, false) => ordered.ThenBy(_compiled, comparer),
_ => ordered.ThenByDescending(_compiled, comparer),
};
}
internal override decimal Sum(IEnumerable<T> rows)
{
var numeric = Numeric ?? throw new InvalidOperationException($"{Id} is not a number.");
return rows.Sum(r => numeric(_compiled(r)) ?? 0m);
}
private static object? ConvertText(string text)
{
if (IsText)
{
return text;
}
var c = CultureInfo.InvariantCulture;
return Underlying switch
{
var t when t == typeof(bool) => bool.Parse(text),
var t when t == typeof(int) => int.Parse(text, NumberStyles.Integer, c),
var t when t == typeof(long) => long.Parse(text, NumberStyles.Integer, c),
var t when t == typeof(decimal) => decimal.Parse(text, NumberStyles.Number, c),
var t when t == typeof(double) => double.Parse(text, NumberStyles.Float, c),
var t when t == typeof(DateOnly) => DateOnly.ParseExact(text, "yyyy-MM-dd", c),
var t when t == typeof(DateTime) => DateTime.Parse(text, c, DateTimeStyles.RoundtripKind),
var t when t == typeof(DateTimeOffset) => DateTimeOffset.Parse(text, c, DateTimeStyles.RoundtripKind),
var t when t == typeof(Guid) => Guid.Parse(text),
var t when t.IsEnum => Enum.Parse(t, text, ignoreCase: false),
_ => throw new FormatException("Unsupported type " + Underlying.Name),
};
}
private Expression Member(ParameterExpression row) => new Rebind(_selector.Parameters[0], row).Visit(_selector.Body);
private Expression Equal(Expression member, string text, ListFilter filter, bool inMemory)
{
if (IsText && inMemory)
{
// Texts are equal ignoring case, as LIKE without wildcards would be.
var equals = typeof(string).GetMethod(nameof(string.Equals), [typeof(string), typeof(string), typeof(StringComparison)])!;
return Expression.Call(equals, member, Expression.Constant(text), Expression.Constant(StringComparison.OrdinalIgnoreCase));
}
return Expression.Equal(member, Value(text, filter));
}
private static Expression TextCall(Expression member, MethodInfo method, string text, bool inMemory)
{
if (!inMemory)
{
return Expression.Call(member, method, Expression.Constant(text));
}
// Null texts never match in memory, as in SQL.
return Expression.AndAlso(
Expression.NotEqual(member, Expression.Constant(null, typeof(string))),
Expression.Call(member, method, Expression.Constant(text), Expression.Constant(StringComparison.OrdinalIgnoreCase)));
}
private ConstantExpression Value(string text, ListFilter filter) => Expression.Constant(Convert(text, filter), typeof(TValue));
private TValue Convert(string text, ListFilter filter)
{
try
{
return (TValue)ConvertText(text)!;
}
catch (Exception e) when (e is FormatException or OverflowException or ArgumentException or InvalidCastException)
{
throw new ArgumentException($"Value '{text}' is not valid for {Id}.", nameof(filter), e);
}
}
private string Single(IReadOnlyList<string> values, ListFilter filter)
{
Require(values.Count == 1, filter);
return values[0];
}
private void Require(bool condition, ListFilter filter)
{
if (!condition)
{
throw new ArgumentException($"{filter.Operator} with {filter.Values?.Count ?? 0} values is not valid on {Id}.", nameof(filter));
}
}
private sealed class Rebind(ParameterExpression from, ParameterExpression to) : ExpressionVisitor
{
protected override Expression VisitParameter(ParameterExpression node) => node == from ? to : base.VisitParameter(node);
}
}
@@ -0,0 +1,156 @@
using System.Globalization;
namespace Khaemhat.Application.Querying;
/// <summary>How a filter compares a field with its values (SPEC §10.7 <c>KhGrid</c>, <c>KhRadar</c>).</summary>
public enum ListFilterOperator
{
/// <summary>Equal to the value.</summary>
Equals = 0,
/// <summary>Different from the value.</summary>
NotEquals = 1,
/// <summary>Text containing the value, ignoring case.</summary>
Contains = 2,
/// <summary>Text starting with the value, ignoring case.</summary>
StartsWith = 3,
/// <summary>Greater than the value.</summary>
GreaterThan = 4,
/// <summary>Greater than or equal to the value.</summary>
GreaterOrEqual = 5,
/// <summary>Less than the value.</summary>
LessThan = 6,
/// <summary>Less than or equal to the value.</summary>
LessOrEqual = 7,
/// <summary>Between the first and the second value, both included.</summary>
Between = 8,
/// <summary>One of the values.</summary>
In = 9,
/// <summary>Empty (null, or an empty text).</summary>
IsEmpty = 10,
/// <summary>Not empty.</summary>
IsNotEmpty = 11,
}
/// <summary>
/// A filter on a field. The values are invariant texts (<c>2026-11-30</c>, <c>1234.5</c>, <c>true</c>, the name of an
/// enum value), so a filter can be saved in the user settings and read back unchanged.
/// </summary>
/// <param name="Field">The field id.</param>
/// <param name="Operator">The comparison.</param>
/// <param name="Values">The values: none for the empty checks, two for <see cref="ListFilterOperator.Between"/>.</param>
public sealed record ListFilter(string Field, ListFilterOperator Operator, IReadOnlyList<string> Values)
{
/// <summary>A filter with its values.</summary>
/// <param name="field">The field id.</param>
/// <param name="op">The comparison.</param>
/// <param name="values">The values.</param>
/// <returns>The filter.</returns>
public static ListFilter Of(string field, ListFilterOperator op, params string[] values) => new(field, op, values);
/// <summary>The invariant text of a value, as filters keep it.</summary>
/// <param name="value">The value.</param>
/// <returns>The text.</returns>
public static string Text(object? value) => value switch
{
null => string.Empty,
DateOnly d => d.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture),
DateTime d => d.ToString("O", CultureInfo.InvariantCulture),
DateTimeOffset d => d.ToString("O", CultureInfo.InvariantCulture),
bool b => b ? "true" : "false",
IFormattable f => f.ToString(null, CultureInfo.InvariantCulture),
_ => value.ToString() ?? string.Empty,
};
/// <inheritdoc />
public bool Equals(ListFilter? other) =>
other is not null && Field == other.Field && Operator == other.Operator && Values.SequenceEqual(other.Values);
/// <inheritdoc />
public override int GetHashCode()
{
var hash = new HashCode();
hash.Add(Field);
hash.Add(Operator);
foreach (var value in Values)
{
hash.Add(value);
}
return hash.ToHashCode();
}
}
/// <summary>An ordering on a field.</summary>
/// <param name="Field">The field id.</param>
/// <param name="Descending">Whether from the largest.</param>
public sealed record ListSort(string Field, bool Descending = false);
/// <summary>
/// What a list or radar asks its source: the text typed in the search box, the filters, the ordering and the page.
/// The source answers with a <see cref="ListPage{T}"/>; with <see cref="ListFields{T}"/> the same request becomes SQL for
/// a repository or runs on rows in memory.
/// </summary>
public sealed record ListQuery
{
/// <summary>The largest page a source returns.</summary>
public const int MaxLimit = 1000;
/// <summary>The text of the search box: every searchable field is checked.</summary>
public string? Search { get; init; }
/// <summary>The filters, all of which must hold.</summary>
public IReadOnlyList<ListFilter> Filters { get; init; } = [];
/// <summary>The ordering, first field first.</summary>
public IReadOnlyList<ListSort> Sort { get; init; } = [];
/// <summary>The rows to skip.</summary>
public int Offset { get; init; }
/// <summary>The rows to return, at most <see cref="MaxLimit"/>.</summary>
public int Limit { get; init; } = 50;
/// <summary>The same request for another page.</summary>
/// <param name="offset">The rows to skip.</param>
/// <param name="limit">The rows to return.</param>
/// <returns>The request.</returns>
public ListQuery WithPage(int offset, int limit) => this with { Offset = Math.Max(0, offset), Limit = Math.Clamp(limit, 1, MaxLimit) };
/// <summary>Whether two requests select and order the same rows, whatever the page.</summary>
/// <param name="other">The other request.</param>
/// <returns>Whether they match.</returns>
public bool SameRows(ListQuery? other) =>
other is not null && string.Equals(Search?.Trim(), other.Search?.Trim(), StringComparison.OrdinalIgnoreCase)
&& Filters.SequenceEqual(other.Filters) && Sort.SequenceEqual(other.Sort);
}
/// <summary>A page of rows with the count and the totals of every row the request selects (not only the page).</summary>
/// <typeparam name="T">The row type.</typeparam>
/// <param name="Items">The rows of the page.</param>
/// <param name="Total">The rows selected.</param>
/// <param name="Totals">The sums by field id, for the totals row of the grid.</param>
public sealed record ListPage<T>(IReadOnlyList<T> Items, long Total, IReadOnlyDictionary<string, decimal> Totals)
{
/// <summary>No rows.</summary>
#pragma warning disable CA1000 // An empty page of the same row type is the natural default.
public static ListPage<T> Empty { get; } = new([], 0, new Dictionary<string, decimal>());
#pragma warning restore CA1000
}
/// <summary>Where a grid or radar reads its rows.</summary>
/// <typeparam name="T">The row type.</typeparam>
/// <param name="query">The request.</param>
/// <param name="cancellationToken">Cancellation, when a newer request replaces this one.</param>
/// <returns>The page.</returns>
public delegate Task<ListPage<T>> ListSource<T>(ListQuery query, CancellationToken cancellationToken);
@@ -0,0 +1,133 @@
using Khaemhat.Application.Security;
using Microsoft.Extensions.Logging;
namespace Khaemhat.Application.Search;
/// <summary>What the search looks for, from the first character of the query (SPEC §10.2, mockup 009).</summary>
public enum SearchScope
{
/// <summary>Everything: pages, records, help.</summary>
All,
/// <summary><c>&gt;</c>: only the commands.</summary>
Commands,
/// <summary><c>#</c>: only the documents.</summary>
Documents,
/// <summary><c>@</c>: only the people.</summary>
People,
}
/// <summary>A search, split into scope and words.</summary>
/// <param name="Scope">What it looks for.</param>
/// <param name="Text">The words, without the prefix.</param>
public sealed record SearchQuery(SearchScope Scope, string Text)
{
/// <summary>The fewest characters before records are searched.</summary>
public const int MinimumLength = 2;
/// <summary>The words of the query.</summary>
public IReadOnlyList<string> Words { get; } = Text.Split(' ', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
/// <summary>Reads what the user typed.</summary>
/// <param name="input">The text of the search box.</param>
/// <returns>The query.</returns>
public static SearchQuery Parse(string? input)
{
var text = (input ?? string.Empty).Trim();
var scope = text.Length == 0 ? SearchScope.All : text[0] switch
{
'>' => SearchScope.Commands,
'#' => SearchScope.Documents,
'@' => SearchScope.People,
_ => SearchScope.All,
};
return new SearchQuery(scope, scope == SearchScope.All ? text : text[1..].Trim());
}
/// <summary>Whether a text contains every word, ignoring case.</summary>
/// <param name="value">The text.</param>
/// <returns><see langword="true"/> if it does; always for an empty query.</returns>
public bool Matches(string? value) =>
Words.Count == 0 || (value is not null && Words.All(w => value.Contains(w, StringComparison.CurrentCultureIgnoreCase)));
}
/// <summary>A search result.</summary>
/// <param name="Group">The text key of the group shown above it, such as <c>Shell.Search.Help</c>.</param>
/// <param name="Icon">The icon.</param>
/// <param name="Title">The title.</param>
/// <param name="Detail">A second line, such as the page a heading belongs to.</param>
/// <param name="Href">Where it opens, relative to the application.</param>
public sealed record SearchHit(string Group, string Icon, string Title, string? Detail, string Href);
/// <summary>A source of search results: each module adds its own (parties, items, documents, accounts...).</summary>
public interface ISearchProvider
{
/// <summary>The scopes it answers: <see cref="SearchScope.All"/> and, for example, <see cref="SearchScope.Documents"/>.</summary>
IReadOnlyCollection<SearchScope> Scopes { get; }
/// <summary>Searches.</summary>
/// <param name="actor">Who searches: results respect permissions and company.</param>
/// <param name="query">The query, at least <see cref="SearchQuery.MinimumLength"/> characters.</param>
/// <param name="cancellationToken">Cancellation: the user typed something else.</param>
/// <returns>At most <see cref="GlobalSearchService.PerProvider"/> results, best first.</returns>
Task<IReadOnlyList<SearchHit>> SearchAsync(Actor actor, SearchQuery query, CancellationToken cancellationToken);
}
/// <summary>
/// The records part of the global search (SPEC §10.2): asks every provider of the scope, in parallel, and puts the
/// results together. A provider that fails or is slow is left out, the others are shown.
/// </summary>
public sealed class GlobalSearchService(IEnumerable<ISearchProvider> providers, ILogger<GlobalSearchService> logger)
{
/// <summary>The most results of one provider.</summary>
public const int PerProvider = 8;
private static readonly TimeSpan Timeout = TimeSpan.FromSeconds(3);
private readonly ISearchProvider[] _providers = [.. providers];
/// <summary>Whether something answers a scope: without, the search says what it will find in a later version.</summary>
/// <param name="scope">The scope.</param>
/// <returns><see langword="true"/> if a provider does.</returns>
public bool Covers(SearchScope scope) => _providers.Any(p => p.Scopes.Contains(scope));
/// <summary>Searches the records.</summary>
/// <param name="actor">Who searches.</param>
/// <param name="query">The query.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The results, grouped by provider in registration order.</returns>
public async Task<IReadOnlyList<SearchHit>> SearchAsync(Actor actor, SearchQuery query, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(actor);
ArgumentNullException.ThrowIfNull(query);
if (query.Scope == SearchScope.Commands || query.Text.Length < SearchQuery.MinimumLength)
{
return [];
}
var results = await Task.WhenAll(_providers.Where(p => p.Scopes.Contains(query.Scope)).Select(p => AskAsync(p, actor, query, cancellationToken))).ConfigureAwait(false);
return [.. results.SelectMany(r => r)];
}
private async Task<IReadOnlyList<SearchHit>> AskAsync(ISearchProvider provider, Actor actor, SearchQuery query, CancellationToken cancellationToken)
{
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
timeout.CancelAfter(Timeout);
try
{
return [.. (await provider.SearchAsync(actor, query, timeout.Token).ConfigureAwait(false)).Take(PerProvider)];
}
catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested)
{
logger.LogWarning("Search provider {Provider} took longer than {Timeout} and was left out", provider.GetType().Name, Timeout);
return [];
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
logger.LogError(ex, "Search provider {Provider} failed", provider.GetType().Name);
return [];
}
}
}
@@ -0,0 +1,380 @@
using System.Text.Json;
using Khaemhat.Core.Security;
using Khaemhat.Infrastructure.Security;
namespace Khaemhat.Application.Security;
/// <summary>The outcome of a password check at sign-in.</summary>
/// <param name="Succeeded">Whether the password was right and the account may go on.</param>
/// <param name="Error">The error code when it did not succeed (<see cref="SecurityErrors"/>).</param>
/// <param name="MustChangePassword">The password must be changed before entering.</param>
public sealed record PasswordCheck(bool Succeeded, string? Error, bool MustChangePassword)
{
/// <summary>A failure.</summary>
/// <param name="error">The error code.</param>
/// <returns>The outcome.</returns>
public static PasswordCheck Fail(string error) => new(false, error, false);
}
/// <summary>
/// The credential rules shared by instance accounts and company users (SPEC §7.3): password check with lockout,
/// password change with policy and history, temporary passwords, recovery tokens, TOTP and recovery codes.
/// The methods change the account in memory; the caller saves it.
/// </summary>
public sealed class AccountSecurity
{
private const string SecretPurpose = "account:totp";
private readonly PasswordPolicy _policy;
private readonly ISecretProtector _protector;
private readonly TimeProvider _clock;
/// <summary>Creates the service.</summary>
/// <param name="policy">The password policy.</param>
/// <param name="protector">Encrypts TOTP secrets.</param>
/// <param name="clock">The clock.</param>
public AccountSecurity(PasswordPolicy policy, ISecretProtector protector, TimeProvider clock)
{
ArgumentNullException.ThrowIfNull(policy);
ArgumentNullException.ThrowIfNull(protector);
ArgumentNullException.ThrowIfNull(clock);
_policy = policy;
_protector = protector;
_clock = clock;
}
/// <summary>The policy settings.</summary>
public SecurityPolicyOptions Options => _policy.Options;
private DateTime Now => _clock.GetUtcNow().UtcDateTime;
/// <summary>Checks the password typed at sign-in, counting failures and locking the account after too many.</summary>
/// <param name="account">The account.</param>
/// <param name="password">The password typed.</param>
/// <returns>The outcome.</returns>
public PasswordCheck CheckPassword(IAccount account, string password)
{
ArgumentNullException.ThrowIfNull(account);
ArgumentNullException.ThrowIfNull(password);
var now = Now;
if (!account.IsActive)
{
return PasswordCheck.Fail(SecurityErrors.AccountDisabled);
}
if (account.LockedUntil is { } locked && locked > now)
{
return PasswordCheck.Fail(SecurityErrors.AccountLocked);
}
var verification = PasswordHasher.Verify(account.PasswordHash, password);
if (verification == PasswordVerification.Failed)
{
account.FailedLoginCount++;
if (account.FailedLoginCount >= Options.MaxFailedAttempts)
{
account.LockedUntil = now + Options.LockoutDuration;
account.FailedLoginCount = 0;
return PasswordCheck.Fail(SecurityErrors.AccountLocked);
}
return PasswordCheck.Fail(SecurityErrors.InvalidCredentials);
}
account.FailedLoginCount = 0;
account.LockedUntil = null;
if (account.TemporaryPasswordExpiresAt is { } expires && expires <= now)
{
return PasswordCheck.Fail(SecurityErrors.TemporaryPasswordExpired);
}
if (verification == PasswordVerification.SucceededRehashNeeded)
{
account.PasswordHash = PasswordHasher.Hash(password, Options.HashIterations);
}
var expired = Options.ExpiryDays is { } days && account.PasswordChangedAt is { } changed && changed.AddDays(days) <= now;
return new PasswordCheck(true, null, account.MustChangePassword || expired);
}
/// <summary>Records a completed sign-in.</summary>
/// <param name="account">The account.</param>
public void RecordSignIn(IAccount account)
{
ArgumentNullException.ThrowIfNull(account);
account.LastLoginAt = Now;
}
/// <summary>Sets a new password chosen by the user, after checking policy and history.</summary>
/// <param name="account">The account.</param>
/// <param name="newPassword">The new password.</param>
/// <returns>The error codes; empty when the password was set.</returns>
public IReadOnlyList<string> ChangePassword(IAccount account, string newPassword)
{
ArgumentNullException.ThrowIfNull(account);
ArgumentNullException.ThrowIfNull(newPassword);
var errors = new List<string>(_policy.Check(newPassword, account.UserName));
if (errors.Count == 0 && IsReused(account, newPassword))
{
errors.Add(SecurityErrors.PasswordReused);
}
if (errors.Count == 0)
{
Store(account, newPassword, temporary: false);
}
return errors;
}
/// <summary>
/// Sets a password without the history check: the first password of the super user, or a temporary password made by
/// an administrator. Both must be changed at the next sign-in.
/// </summary>
/// <param name="account">The account.</param>
/// <param name="password">The password.</param>
/// <param name="temporary">Whether it expires after <see cref="SecurityPolicyOptions.TemporaryPasswordLifetime"/>.</param>
/// <returns>The policy error codes; empty when the password was set.</returns>
public IReadOnlyList<string> SetInitialPassword(IAccount account, string password, bool temporary)
{
ArgumentNullException.ThrowIfNull(account);
ArgumentNullException.ThrowIfNull(password);
var errors = _policy.Check(password, account.UserName);
if (errors.Count == 0)
{
Store(account, password, temporary);
account.MustChangePassword = true;
}
return errors;
}
/// <summary>Creates a temporary password that satisfies the policy and sets it.</summary>
/// <param name="account">The account.</param>
/// <returns>The password to give to the user, once.</returns>
public string IssueTemporaryPassword(IAccount account)
{
ArgumentNullException.ThrowIfNull(account);
// Two readable groups plus a lower-case suffix and a symbol: four classes, 14 characters.
var password = SecureTokenGenerator.CreateReadableCode(2) + "-" + SecureTokenGenerator.CreateReadableCode(1).ToLowerInvariant();
Store(account, password, temporary: true);
account.MustChangePassword = true;
return password;
}
/// <summary>Creates a single-use recovery token, valid for <see cref="SecurityPolicyOptions.RecoveryTokenLifetime"/>.</summary>
/// <param name="account">The account.</param>
/// <returns>The token to send by e-mail; only its hash is stored.</returns>
public string IssueRecoveryToken(IAccount account)
{
ArgumentNullException.ThrowIfNull(account);
var token = SecureTokenGenerator.Create();
account.RecoveryTokenHash = SecureTokenGenerator.Hash(token);
account.RecoveryTokenExpiresAt = Now + Options.RecoveryTokenLifetime;
return token;
}
/// <summary>Uses a recovery token to set a new password. The token stops working whatever the outcome of the policy.</summary>
/// <param name="account">The account.</param>
/// <param name="token">The token from the e-mail.</param>
/// <param name="newPassword">The new password.</param>
/// <returns>The error codes; empty when the password was set.</returns>
public IReadOnlyList<string> RedeemRecoveryToken(IAccount account, string token, string newPassword)
{
ArgumentNullException.ThrowIfNull(account);
ArgumentNullException.ThrowIfNull(token);
var valid = account.RecoveryTokenExpiresAt is { } expires && expires > Now
&& SecureTokenGenerator.HashesEqual(account.RecoveryTokenHash, SecureTokenGenerator.Hash(token));
if (!valid)
{
return [SecurityErrors.RecoveryTokenInvalid];
}
var errors = ChangePassword(account, newPassword);
if (errors.Count == 0)
{
account.RecoveryTokenHash = null;
account.RecoveryTokenExpiresAt = null;
account.LockedUntil = null;
account.FailedLoginCount = 0;
}
return errors;
}
/// <summary>Starts the TOTP setup: a new secret, stored encrypted and not yet active.</summary>
/// <param name="account">The account.</param>
/// <returns>The secret in base32, to show once with <see cref="TotpGenerator.ProvisioningUri"/>.</returns>
public string BeginTotpSetup(IAccount account)
{
ArgumentNullException.ThrowIfNull(account);
var secret = TotpGenerator.CreateSecret();
account.TotpSecret = _protector.Protect(secret, SecretPurpose);
account.TotpEnabled = false;
account.TotpLastStep = null;
return secret;
}
/// <summary>The secret of a setup started and not yet confirmed, so that reloading the page shows the same one.</summary>
/// <param name="account">The account.</param>
/// <returns>The secret in base32, or <see langword="null"/> when no setup is pending.</returns>
public string? PendingTotpSecret(IAccount account)
{
ArgumentNullException.ThrowIfNull(account);
return account is { TotpEnabled: false, TotpSecret: { } secret } ? _protector.Unprotect(secret, SecretPurpose) : null;
}
/// <summary>Completes the TOTP setup with a first code from the app, and creates the recovery codes.</summary>
/// <param name="account">The account.</param>
/// <param name="code">The code shown by the app.</param>
/// <returns>The ten recovery codes to show once; <see langword="null"/> if the code is wrong.</returns>
public IReadOnlyList<string>? ConfirmTotpSetup(IAccount account, string code)
{
ArgumentNullException.ThrowIfNull(account);
if (account.TotpSecret is null || !VerifyCode(account, code))
{
return null;
}
account.TotpEnabled = true;
return NewRecoveryCodes(account);
}
/// <summary>Replaces the recovery codes with ten new ones; the old ones stop working.</summary>
/// <param name="account">The account.</param>
/// <returns>The new codes, to show once.</returns>
public static IReadOnlyList<string> NewRecoveryCodes(IAccount account)
{
ArgumentNullException.ThrowIfNull(account);
var codes = Enumerable.Range(0, 10).Select(_ => SecureTokenGenerator.CreateReadableCode(2)).ToList();
account.TotpRecoveryCodes = JsonSerializer.Serialize(codes.Select(c => SecureTokenGenerator.Hash(c)).ToList());
return codes;
}
/// <summary>How many recovery codes are still unused.</summary>
/// <param name="account">The account.</param>
/// <returns>The number of codes left.</returns>
public static int RecoveryCodesLeft(IAccount account)
{
ArgumentNullException.ThrowIfNull(account);
return account.TotpEnabled ? Deserialize(account.TotpRecoveryCodes).Count : 0;
}
/// <summary>Checks the current password without counting failures (profile changes that ask for it again).</summary>
/// <param name="account">The account.</param>
/// <param name="password">The password typed.</param>
/// <returns>Whether it is right.</returns>
public static bool IsCurrentPassword(IAccount account, string password)
{
ArgumentNullException.ThrowIfNull(account);
ArgumentNullException.ThrowIfNull(password);
return account.PasswordHash is not null && PasswordHasher.Verify(account.PasswordHash, password) != PasswordVerification.Failed;
}
/// <summary>Checks a TOTP code at sign-in. A code is never accepted twice.</summary>
/// <param name="account">The account.</param>
/// <param name="code">The code.</param>
/// <returns>Whether the code is valid.</returns>
public bool VerifyTotp(IAccount account, string code)
{
ArgumentNullException.ThrowIfNull(account);
return account.TotpEnabled && account.TotpSecret is not null && VerifyCode(account, code);
}
/// <summary>Uses one of the recovery codes in place of a TOTP code. Each code works once.</summary>
/// <param name="account">The account.</param>
/// <param name="code">The recovery code.</param>
/// <returns>Whether the code was valid.</returns>
public static bool UseRecoveryCode(IAccount account, string code)
{
ArgumentNullException.ThrowIfNull(account);
ArgumentNullException.ThrowIfNull(code);
var hashes = Deserialize(account.TotpRecoveryCodes);
var hash = SecureTokenGenerator.Hash(code.Trim().ToUpperInvariant());
var index = hashes.FindIndex(h => SecureTokenGenerator.HashesEqual(h, hash));
if (!account.TotpEnabled || index < 0)
{
return false;
}
hashes.RemoveAt(index);
account.TotpRecoveryCodes = JsonSerializer.Serialize(hashes);
return true;
}
/// <summary>Turns the two-step verification off (an administrator resetting a lost phone).</summary>
/// <param name="account">The account.</param>
public static void ResetTotp(IAccount account)
{
ArgumentNullException.ThrowIfNull(account);
account.TotpEnabled = false;
account.TotpSecret = null;
account.TotpLastStep = null;
account.TotpRecoveryCodes = null;
}
private bool VerifyCode(IAccount account, string code)
{
string secret;
try
{
secret = _protector.Unprotect(account.TotpSecret!, SecretPurpose);
}
catch (SecretProtectionException)
{
return false;
}
var step = TotpGenerator.Verify(secret, code, _clock.GetUtcNow(), account.TotpLastStep);
if (step is null)
{
return false;
}
account.TotpLastStep = step;
return true;
}
private bool IsReused(IAccount account, string password)
{
if (PasswordHasher.Verify(account.PasswordHash, password) != PasswordVerification.Failed)
{
return true;
}
return Deserialize(account.PasswordHistory).Take(Options.HistorySize)
.Any(h => PasswordHasher.Verify(h, password) != PasswordVerification.Failed);
}
private void Store(IAccount account, string password, bool temporary)
{
if (account.PasswordHash is not null)
{
var history = Deserialize(account.PasswordHistory);
history.Insert(0, account.PasswordHash);
account.PasswordHistory = JsonSerializer.Serialize(history.Take(Math.Max(Options.HistorySize - 1, 0)).ToList());
}
account.PasswordHash = PasswordHasher.Hash(password, Options.HashIterations);
account.PasswordChangedAt = Now;
account.MustChangePassword = false;
account.TemporaryPasswordExpiresAt = temporary ? Now + Options.TemporaryPasswordLifetime : null;
}
private static List<string> Deserialize(string? json)
{
if (string.IsNullOrWhiteSpace(json))
{
return [];
}
try
{
return JsonSerializer.Deserialize<List<string>>(json) ?? [];
}
catch (JsonException)
{
return [];
}
}
}
@@ -0,0 +1,85 @@
using Khaemhat.Core.Security;
namespace Khaemhat.Application.Security;
/// <summary>
/// Who performs an action: an instance account (super user or administrator) or a company user. Services check the
/// actor; the interface only hides what the actor cannot do.
/// </summary>
/// <param name="UserName">The user name, written in the audit columns and logs.</param>
/// <param name="Level">The level.</param>
/// <param name="SystemUserId">The instance account, for super user and administrators.</param>
/// <param name="CompanyUserId">The company user (or the user an administrator is linked to).</param>
/// <param name="CompanyCode">The company the actor works in.</param>
public sealed record Actor(string UserName, UserLevel Level, long? SystemUserId, long? CompanyUserId, string? CompanyCode)
{
/// <summary>The instance itself: bootstrap, scheduled jobs.</summary>
public static Actor System { get; } = new("system", UserLevel.SuperUser, null, null, null);
/// <summary>Whether the actor is an instance account.</summary>
public bool IsInstanceAccount => Level >= UserLevel.Administrator;
/// <summary>Whether the actor is the super user.</summary>
public bool IsSuperUser => Level == UserLevel.SuperUser;
}
/// <summary>An action the actor may not perform. <see cref="Code"/> is one of <see cref="SecurityErrors"/>.</summary>
public sealed class AccessDeniedException : Exception
{
/// <summary>Creates the exception.</summary>
public AccessDeniedException()
: this(SecurityErrors.PermissionDenied, "Access denied.")
{
}
/// <summary>Creates the exception.</summary>
/// <param name="message">The message.</param>
public AccessDeniedException(string message)
: this(SecurityErrors.PermissionDenied, message)
{
}
/// <summary>Creates the exception.</summary>
/// <param name="message">The message.</param>
/// <param name="innerException">The cause.</param>
public AccessDeniedException(string message, Exception innerException)
: base(message, innerException) => Code = SecurityErrors.PermissionDenied;
/// <summary>Creates the exception.</summary>
/// <param name="code">The error code.</param>
/// <param name="message">The message.</param>
public AccessDeniedException(string code, string message)
: base(message) => Code = code;
/// <summary>The error code.</summary>
public string Code { get; }
}
/// <summary>A request the rules refuse (policy, duplicates); <see cref="Errors"/> holds error codes for the interface.</summary>
public sealed class ValidationFailedException : Exception
{
/// <summary>Creates the exception.</summary>
public ValidationFailedException()
: this([])
{
}
/// <summary>Creates the exception.</summary>
/// <param name="message">The message.</param>
public ValidationFailedException(string message)
: base(message) => Errors = [message];
/// <summary>Creates the exception.</summary>
/// <param name="message">The message.</param>
/// <param name="innerException">The cause.</param>
public ValidationFailedException(string message, Exception innerException)
: base(message, innerException) => Errors = [message];
/// <summary>Creates the exception.</summary>
/// <param name="errors">The error codes.</param>
public ValidationFailedException(IReadOnlyList<string> errors)
: base("The request is not valid: " + string.Join(", ", errors ?? [])) => Errors = errors ?? [];
/// <summary>The error codes.</summary>
public IReadOnlyList<string> Errors { get; }
}
@@ -0,0 +1,165 @@
using System.Text.RegularExpressions;
using Khaemhat.Infrastructure.Security;
namespace Khaemhat.Application.Security;
/// <summary>Sign-in names: 3 to 50 characters, letters, digits, dot, dash and underscore; compared in lower case.</summary>
public static partial class UserNames
{
/// <summary>Whether a name has the allowed form.</summary>
/// <param name="name">The name.</param>
/// <returns><see langword="true"/> if valid.</returns>
public static bool IsValid(string? name) => name is not null && Pattern().IsMatch(name.Trim());
/// <summary>The stored form: trimmed, lower case.</summary>
/// <param name="name">The name.</param>
/// <returns>The normalized name.</returns>
/// <exception cref="ArgumentException">The name is not valid.</exception>
public static string Normalize(string name)
{
ArgumentNullException.ThrowIfNull(name);
return IsValid(name)
? name.Trim().ToLowerInvariant()
: throw new ArgumentException("A user name has 3 to 50 characters: letters, digits, dot, dash or underscore.", nameof(name));
}
[GeneratedRegex(@"^[A-Za-z0-9][A-Za-z0-9._\-]{2,49}$", RegexOptions.CultureInvariant)]
private static partial Regex Pattern();
}
/// <summary>The security settings of accounts (SPEC §7.3). The defaults are those of the specification.</summary>
public sealed record SecurityPolicyOptions
{
/// <summary>Minimum password length.</summary>
public int MinimumLength { get; init; } = 10;
/// <summary>Minimum character classes among lower case, upper case, digits and symbols.</summary>
public int MinimumClasses { get; init; } = 3;
/// <summary>How many previous passwords cannot be reused.</summary>
public int HistorySize { get; init; } = 5;
/// <summary>Days after which a password must be changed; <see langword="null"/> for no expiry.</summary>
public int? ExpiryDays { get; init; }
/// <summary>Failed sign-ins before the account is locked.</summary>
public int MaxFailedAttempts { get; init; } = 5;
/// <summary>How long a locked account stays locked.</summary>
public TimeSpan LockoutDuration { get; init; } = TimeSpan.FromMinutes(15);
/// <summary>How long a temporary password works.</summary>
public TimeSpan TemporaryPasswordLifetime { get; init; } = TimeSpan.FromHours(72);
/// <summary>How long a password-recovery link works.</summary>
public TimeSpan RecoveryTokenLifetime { get; init; } = TimeSpan.FromMinutes(30);
/// <summary>The sliding lifetime of a session.</summary>
public TimeSpan SessionLifetime { get; init; } = TimeSpan.FromMinutes(480);
/// <summary>The lifetime of a session with "remember me on this device".</summary>
public TimeSpan PersistentSessionLifetime { get; init; } = TimeSpan.FromDays(14);
/// <summary>The time to complete a pending sign-in step (TOTP, password change).</summary>
public TimeSpan PendingStepLifetime { get; init; } = TimeSpan.FromMinutes(10);
/// <summary>Whether company users must use the two-step verification.</summary>
public bool TotpRequiredForUsers { get; init; }
/// <summary>PBKDF2 iterations; lowered only by tests.</summary>
public int HashIterations { get; init; } = PasswordHasher.Iterations;
}
/// <summary>Checks new passwords against the policy.</summary>
/// <param name="options">The policy.</param>
public sealed class PasswordPolicy(SecurityPolicyOptions options)
{
/// <summary>The policy settings.</summary>
public SecurityPolicyOptions Options { get; } = options ?? throw new ArgumentNullException(nameof(options));
/// <summary>Checks the form of a password.</summary>
/// <param name="password">The new password.</param>
/// <param name="userName">The user name, which the password must not contain.</param>
/// <returns>Error codes: <c>password_too_short</c>, <c>password_too_simple</c>, <c>password_contains_user_name</c>.</returns>
public IReadOnlyList<string> Check(string password, string? userName)
{
ArgumentNullException.ThrowIfNull(password);
var errors = new List<string>();
if (password.Length < Options.MinimumLength)
{
errors.Add(SecurityErrors.PasswordTooShort);
}
var classes = (password.Any(char.IsLower) ? 1 : 0) + (password.Any(char.IsUpper) ? 1 : 0)
+ (password.Any(char.IsDigit) ? 1 : 0) + (password.Any(c => !char.IsLetterOrDigit(c)) ? 1 : 0);
if (classes < Options.MinimumClasses)
{
errors.Add(SecurityErrors.PasswordTooSimple);
}
if (userName is { Length: >= 3 } && password.Contains(userName, StringComparison.OrdinalIgnoreCase))
{
errors.Add(SecurityErrors.PasswordContainsUserName);
}
return errors;
}
}
/// <summary>The error codes of the security services; the interface turns them into Italian messages.</summary>
public static class SecurityErrors
{
/// <summary>Wrong user, company or password (never says which).</summary>
public const string InvalidCredentials = "invalid_credentials";
/// <summary>Too many failed attempts: the account is locked for a while.</summary>
public const string AccountLocked = "account_locked";
/// <summary>The account is disabled.</summary>
public const string AccountDisabled = "account_disabled";
/// <summary>The temporary password has expired.</summary>
public const string TemporaryPasswordExpired = "temporary_password_expired";
/// <summary>The password is shorter than the policy.</summary>
public const string PasswordTooShort = "password_too_short";
/// <summary>The password uses too few character classes.</summary>
public const string PasswordTooSimple = "password_too_simple";
/// <summary>The password contains the user name.</summary>
public const string PasswordContainsUserName = "password_contains_user_name";
/// <summary>The password was used recently.</summary>
public const string PasswordReused = "password_reused";
/// <summary>The current password is wrong.</summary>
public const string CurrentPasswordWrong = "current_password_wrong";
/// <summary>The TOTP code is wrong or already used.</summary>
public const string TotpInvalid = "totp_invalid";
/// <summary>The recovery token is wrong, used or expired.</summary>
public const string RecoveryTokenInvalid = "recovery_token_invalid";
/// <summary>Too many attempts from this address.</summary>
public const string RateLimited = "rate_limited";
/// <summary>The licence allows no more concurrent users.</summary>
public const string ConcurrentUsersExceeded = "concurrent_users_exceeded";
/// <summary>The level of the account does not allow the action.</summary>
public const string LevelTooLow = "level_too_low";
/// <summary>The permission is missing.</summary>
public const string PermissionDenied = "permission_denied";
/// <summary>The module is not in the licence.</summary>
public const string ModuleNotLicensed = "module_not_licensed";
/// <summary>The company is in maintenance or disabled.</summary>
public const string CompanyUnavailable = "company_unavailable";
/// <summary>The licence allows no more of something (companies, users).</summary>
public const string LicenseLimitReached = "license_limit_reached";
}
@@ -0,0 +1,175 @@
using Khaemhat.Application.Licensing;
using Khaemhat.Application.Modules;
using Khaemhat.Core.Caching;
using Khaemhat.Core.Security;
using Khaemhat.Data;
using Khaemhat.Data.Querying;
namespace Khaemhat.Application.Security;
/// <summary>The per-user flags of SPEC §7.2.</summary>
/// <param name="OwnCustomersOnly">Sees only the customers assigned to the user.</param>
/// <param name="CanSeeCosts">Sees costs and margins.</param>
/// <param name="CanExport">Can export.</param>
/// <param name="CanUseApi">Can use the API.</param>
public sealed record UserFlags(bool OwnCustomersOnly, bool CanSeeCosts, bool CanExport, bool CanUseApi)
{
/// <summary>Everything allowed: instance accounts.</summary>
public static UserFlags Unrestricted { get; } = new(false, true, true, true);
}
/// <summary>What a user may do in a company, before the licence is applied. Cached per user.</summary>
/// <param name="AllAccess">Instance accounts: every permission.</param>
/// <param name="Granted">The patterns granted by roles and overrides.</param>
/// <param name="Denied">The patterns denied by overrides (they win).</param>
/// <param name="Flags">The per-user flags.</param>
public sealed record EffectivePermissions(bool AllAccess, IReadOnlyList<string> Granted, IReadOnlyList<string> Denied, UserFlags Flags)
{
/// <summary>Every permission.</summary>
public static EffectivePermissions All { get; } = new(true, ["*"], [], UserFlags.Unrestricted);
/// <summary>No permission.</summary>
public static EffectivePermissions None { get; } = new(false, [], [], new UserFlags(true, false, false, false));
/// <summary>Whether the roles and overrides allow a code (the licence is checked by <see cref="PermissionService"/>).</summary>
/// <param name="code">The permission code.</param>
/// <returns><see langword="true"/> if allowed.</returns>
public bool Allows(string code) =>
AllAccess || (!Denied.Any(d => PermissionPattern.Matches(d, code)) && Granted.Any(g => PermissionPattern.Matches(g, code)));
}
/// <summary>The outcome of a permission check: <see cref="Error"/> is <c>permission_denied</c>, <c>module_not_licensed</c> or <c>license_read_only</c>.</summary>
/// <param name="Allowed">Whether the action is allowed.</param>
/// <param name="Error">The reason otherwise.</param>
public sealed record PermissionCheck(bool Allowed, string? Error)
{
/// <summary>Allowed.</summary>
public static PermissionCheck Ok { get; } = new(true, null);
}
/// <summary>
/// Resolves permissions (SPEC §7.2): instance accounts have every permission; company users have the union of their
/// roles plus granted overrides, minus denied overrides. A module outside the licence is denied with
/// <c>module_not_licensed</c>; past the licence grace only <c>.read</c> permissions remain. Results are cached per user
/// under <c>kh:{company}:permissions:</c> and invalidated when roles or users change.
/// </summary>
public sealed class PermissionService(IUnitOfWorkFactory factory, ICacheProvider cache, ILicenseGate licenses, ModuleRegistry modules)
{
/// <summary>The error when the licence is expired beyond the grace period.</summary>
public const string LicenseReadOnly = "license_read_only";
private const string Area = "permissions";
private static readonly TimeSpan CacheTime = TimeSpan.FromMinutes(10);
/// <summary>The permissions of an actor in its company.</summary>
/// <param name="actor">The actor.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The permissions.</returns>
public async Task<EffectivePermissions> GetAsync(Actor actor, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(actor);
if (actor.IsInstanceAccount)
{
return EffectivePermissions.All;
}
if (actor.CompanyCode is not { } company || actor.CompanyUserId is not { } userId)
{
return EffectivePermissions.None;
}
return await cache.GetOrCreateAsync(
CacheKeys.For(company, Area, userId.ToString(System.Globalization.CultureInfo.InvariantCulture)),
ct => new ValueTask<EffectivePermissions>(LoadAsync(company, userId, ct)),
CacheTime,
cancellationToken).ConfigureAwait(false);
}
/// <summary>Checks one permission, licence included.</summary>
/// <param name="actor">The actor.</param>
/// <param name="code">The permission code.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The outcome.</returns>
public async Task<PermissionCheck> CheckAsync(Actor actor, string code, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(code);
if (modules.FindPermission(code) is not { } definition)
{
return new PermissionCheck(false, SecurityErrors.PermissionDenied);
}
if (!licenses.IsModuleActive(definition.Module))
{
return new PermissionCheck(false, SecurityErrors.ModuleNotLicensed);
}
if (licenses.Current.IsReadOnly && !code.EndsWith(".read", StringComparison.Ordinal))
{
return new PermissionCheck(false, LicenseReadOnly);
}
var permissions = await GetAsync(actor, cancellationToken).ConfigureAwait(false);
return permissions.Allows(code) ? PermissionCheck.Ok : new PermissionCheck(false, SecurityErrors.PermissionDenied);
}
/// <summary>Throws when the actor may not perform the action.</summary>
/// <param name="actor">The actor.</param>
/// <param name="code">The permission code.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
/// <exception cref="AccessDeniedException">The permission is missing or the module is not licensed.</exception>
public async Task DemandAsync(Actor actor, string code, CancellationToken cancellationToken = default)
{
var check = await CheckAsync(actor, code, cancellationToken).ConfigureAwait(false);
if (!check.Allowed)
{
throw new AccessDeniedException(check.Error!, $"Permission {code} is not granted.");
}
}
/// <summary>Whether the actor holds every permission a set of patterns would grant (roles are never above one's own).</summary>
/// <param name="actor">The actor.</param>
/// <param name="patterns">The patterns.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns><see langword="true"/> when nothing in the patterns exceeds the actor.</returns>
public async Task<bool> CoversAsync(Actor actor, IEnumerable<string> patterns, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(patterns);
var own = await GetAsync(actor, cancellationToken).ConfigureAwait(false);
return own.AllAccess || patterns.SelectMany(modules.Expand).All(p => own.Allows(p.Code));
}
/// <summary>Forgets the cached permissions of a company, here and on the other instances.</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), Area), cancellationToken);
private async Task<EffectivePermissions> LoadAsync(string company, long userId, CancellationToken cancellationToken)
{
await using var unitOfWork = await factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
var user = await unitOfWork.Repository<CompanyUser, long>().GetAsync(userId, cancellationToken).ConfigureAwait(false);
if (user is not { IsActive: true })
{
return EffectivePermissions.None;
}
var roleIds = (await unitOfWork.Repository<UserRole, long>()
.ListAsync(Query.For<UserRole>().Where(r => r.UserId == userId), cancellationToken).ConfigureAwait(false)).Items.Select(r => r.RoleId).ToArray();
var granted = roleIds.Length == 0
? []
: (await unitOfWork.Repository<RoleGrant, long>()
.ListAsync(Query.For<RoleGrant>().Where(g => roleIds.Contains(g.RoleId)), cancellationToken).ConfigureAwait(false)).Items
.Select(g => g.Permission).ToList();
var overrides = (await unitOfWork.Repository<UserPermissionOverride, long>()
.ListAsync(Query.For<UserPermissionOverride>().Where(o => o.UserId == userId), cancellationToken).ConfigureAwait(false)).Items;
granted.AddRange(overrides.Where(o => o.Allowed).Select(o => o.Permission));
var denied = overrides.Where(o => !o.Allowed).Select(o => o.Permission).ToList();
return new EffectivePermissions(
false,
[.. granted.Distinct(StringComparer.Ordinal)],
denied,
new UserFlags(user.OwnCustomersOnly, user.CanSeeCosts, user.CanExport, user.CanUseApi));
}
}
@@ -0,0 +1,270 @@
using System.Net.Mail;
using Khaemhat.Application.Audit;
using Khaemhat.Core.Security;
using Khaemhat.Infrastructure.Security;
namespace Khaemhat.Application.Security;
/// <summary>What the profile page shows about the signed-in account (SPEC §12, mockup 008).</summary>
/// <param name="UserName">The sign-in name.</param>
/// <param name="DisplayName">The name shown in the interface.</param>
/// <param name="Email">The e-mail address.</param>
/// <param name="IsInstanceAccount">Whether it is an instance account (super user or administrator).</param>
/// <param name="TotpEnabled">Whether the two-step verification is active.</param>
/// <param name="TotpRequired">Whether the two-step verification is mandatory, so it cannot be turned off.</param>
/// <param name="RecoveryCodesLeft">Unused recovery codes.</param>
/// <param name="HasPassword">Whether the account signs in with a password (technical users do not).</param>
/// <param name="PasswordChangedAt">When the password was last set (UTC).</param>
/// <param name="LastLoginAt">The last successful sign-in (UTC).</param>
public sealed record ProfileInfo(
string UserName,
string DisplayName,
string? Email,
bool IsInstanceAccount,
bool TotpEnabled,
bool TotpRequired,
int RecoveryCodesLeft,
bool HasPassword,
DateTime? PasswordChangedAt,
DateTime? LastLoginAt);
/// <summary>
/// The changes users make to their own account from the profile (SPEC §12, issue #31): name and e-mail, password,
/// two-step verification and recovery codes. Unlike <see cref="SignInService"/> it works from the session owner, not
/// from the cookie, because the profile runs in the interactive circuit where the cookie cannot be read. Every change is
/// recorded in <c>sys_security_audit</c>; a password change closes the other sessions of the account.
/// </summary>
/// <param name="systemUsers">Instance accounts.</param>
/// <param name="companyUsers">Company users.</param>
/// <param name="security">Credential rules.</param>
/// <param name="sessions">Sessions.</param>
/// <param name="audit">The security audit.</param>
public sealed class ProfileService(
SystemUserService systemUsers,
UserService companyUsers,
AccountSecurity security,
SessionStore sessions,
ISecurityAuditLog audit)
{
/// <summary>The longest display name accepted.</summary>
public const int DisplayNameMaxLength = 100;
/// <summary>The display name is empty or too long.</summary>
public const string DisplayNameInvalid = "display_name_invalid";
/// <summary>The e-mail address is not valid.</summary>
public const string EmailInvalid = "email_invalid";
/// <summary>The two-step verification is mandatory for the account and cannot be turned off.</summary>
public const string TotpRequiredError = "totp_required";
/// <summary>Reads the account of a session owner.</summary>
/// <param name="owner">The session owner.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The profile, or <see langword="null"/> when the account no longer exists or is disabled.</returns>
public async Task<ProfileInfo?> GetAsync(SessionOwner owner, CancellationToken cancellationToken = default)
{
var account = await LoadAsync(owner, cancellationToken).ConfigureAwait(false);
return account is null ? null : InfoOf(account, owner);
}
/// <summary>Changes name and e-mail.</summary>
/// <param name="owner">The session owner.</param>
/// <param name="displayName">The new name.</param>
/// <param name="email">The new e-mail, or empty to remove it.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The error codes; empty when saved.</returns>
public async Task<IReadOnlyList<string>> UpdateAsync(SessionOwner owner, string? displayName, string? email, CancellationToken cancellationToken = default)
{
var name = displayName?.Trim() ?? string.Empty;
var mail = string.IsNullOrWhiteSpace(email) ? null : email.Trim();
var errors = new List<string>();
if (name.Length is 0 or > DisplayNameMaxLength)
{
errors.Add(DisplayNameInvalid);
}
if (mail is not null && !IsEmail(mail))
{
errors.Add(EmailInvalid);
}
if (errors.Count > 0)
{
return errors;
}
var account = await RequireAsync(owner, cancellationToken).ConfigureAwait(false);
account.DisplayName = name;
account.Email = mail;
await SaveAsync(account, owner, cancellationToken).ConfigureAwait(false);
await AuditAsync("user.profile-updated", account, owner, cancellationToken).ConfigureAwait(false);
return [];
}
/// <summary>Changes the password, checking the current one, and closes every other session of the account.</summary>
/// <param name="owner">The session owner.</param>
/// <param name="currentSessionId">The session that stays open.</param>
/// <param name="currentPassword">The current password.</param>
/// <param name="newPassword">The new password.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The error codes (<see cref="SecurityErrors"/>); empty when changed.</returns>
public async Task<IReadOnlyList<string>> ChangePasswordAsync(
SessionOwner owner, long? currentSessionId, string currentPassword, string newPassword, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(currentPassword);
ArgumentNullException.ThrowIfNull(newPassword);
var account = await RequireAsync(owner, cancellationToken).ConfigureAwait(false);
if (!AccountSecurity.IsCurrentPassword(account, currentPassword))
{
await AuditAsync("user.password-change-refused", account, owner, cancellationToken).ConfigureAwait(false);
return [SecurityErrors.CurrentPasswordWrong];
}
var errors = security.ChangePassword(account, newPassword);
if (errors.Count > 0)
{
return errors;
}
await SaveAsync(account, owner, cancellationToken).ConfigureAwait(false);
await sessions.RevokeAllAsync(owner, "password_changed", currentSessionId, cancellationToken).ConfigureAwait(false);
await AuditAsync("user.password-changed", account, owner, cancellationToken).ConfigureAwait(false);
return [];
}
/// <summary>Starts turning on the two-step verification; reloading the page shows the same secret.</summary>
/// <param name="owner">The session owner.</param>
/// <param name="companyCode">The company of the session, shown in the label of the authenticator app.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The secret to show, or <see langword="null"/> when the verification is already active.</returns>
public async Task<TotpSetup?> BeginTotpSetupAsync(SessionOwner owner, string? companyCode, CancellationToken cancellationToken = default)
{
var account = await RequireAsync(owner, cancellationToken).ConfigureAwait(false);
if (account.TotpEnabled)
{
return null;
}
var secret = security.PendingTotpSecret(account);
if (secret is null)
{
secret = security.BeginTotpSetup(account);
await SaveAsync(account, owner, cancellationToken).ConfigureAwait(false);
}
var label = companyCode is null ? account.UserName : account.UserName + "@" + companyCode;
return new TotpSetup(secret, TotpGenerator.ProvisioningUri(secret, label));
}
/// <summary>Completes turning on the two-step verification with the first code from the app.</summary>
/// <param name="owner">The session owner.</param>
/// <param name="code">The code.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The ten recovery codes to show once, or <see langword="null"/> when the code is wrong.</returns>
public async Task<IReadOnlyList<string>?> ConfirmTotpSetupAsync(SessionOwner owner, string code, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(code);
var account = await RequireAsync(owner, cancellationToken).ConfigureAwait(false);
if (account.TotpEnabled)
{
return null;
}
var codes = security.ConfirmTotpSetup(account, code.Trim());
if (codes is null)
{
return null;
}
await SaveAsync(account, owner, cancellationToken).ConfigureAwait(false);
await AuditAsync("user.totp-enabled", account, owner, cancellationToken).ConfigureAwait(false);
return codes;
}
/// <summary>Replaces the recovery codes, asking the password again.</summary>
/// <param name="owner">The session owner.</param>
/// <param name="password">The current password.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The new codes, or <see langword="null"/> when the password is wrong or the verification is off.</returns>
public async Task<IReadOnlyList<string>?> RenewRecoveryCodesAsync(SessionOwner owner, string password, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(password);
var account = await RequireAsync(owner, cancellationToken).ConfigureAwait(false);
if (!account.TotpEnabled || !AccountSecurity.IsCurrentPassword(account, password))
{
return null;
}
var codes = AccountSecurity.NewRecoveryCodes(account);
await SaveAsync(account, owner, cancellationToken).ConfigureAwait(false);
await AuditAsync("user.recovery-codes-renewed", account, owner, cancellationToken).ConfigureAwait(false);
return codes;
}
/// <summary>Turns the two-step verification off, asking the password again; refused when it is mandatory.</summary>
/// <param name="owner">The session owner.</param>
/// <param name="password">The current password.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The error codes; empty when turned off.</returns>
public async Task<IReadOnlyList<string>> DisableTotpAsync(SessionOwner owner, string password, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(password);
var account = await RequireAsync(owner, cancellationToken).ConfigureAwait(false);
if (IsTotpRequired(account, owner))
{
return [TotpRequiredError];
}
if (!AccountSecurity.IsCurrentPassword(account, password))
{
return [SecurityErrors.CurrentPasswordWrong];
}
AccountSecurity.ResetTotp(account);
await SaveAsync(account, owner, cancellationToken).ConfigureAwait(false);
await AuditAsync("user.totp-disabled", account, owner, cancellationToken).ConfigureAwait(false);
return [];
}
private static bool IsEmail(string value) =>
value.Length <= 254 && MailAddress.TryCreate(value, out var address) && address.Address == value && value.Contains('.', StringComparison.Ordinal);
private bool IsTotpRequired(IAccount account, SessionOwner owner) =>
owner.IsInstanceAccount || account is CompanyUser { TotpRequired: true } || security.Options.TotpRequiredForUsers;
private ProfileInfo InfoOf(IAccount account, SessionOwner owner) => new(
account.UserName,
account.DisplayName,
account.Email,
owner.IsInstanceAccount,
account.TotpEnabled,
IsTotpRequired(account, owner),
AccountSecurity.RecoveryCodesLeft(account),
account.PasswordHash is not null,
account.PasswordChangedAt,
account.LastLoginAt);
private async Task<IAccount?> LoadAsync(SessionOwner owner, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(owner);
IAccount? account = owner.IsInstanceAccount
? await systemUsers.GetAsync(owner.UserId, cancellationToken).ConfigureAwait(false)
: await companyUsers.GetAsync(owner.CompanyDatabase!, owner.UserId, cancellationToken).ConfigureAwait(false);
return account is { IsActive: true } ? account : null;
}
private async Task<IAccount> RequireAsync(SessionOwner owner, CancellationToken cancellationToken) =>
await LoadAsync(owner, cancellationToken).ConfigureAwait(false)
?? throw new AccessDeniedException(SecurityErrors.InvalidCredentials, "The account no longer exists or is disabled.");
private Task SaveAsync(IAccount account, SessionOwner owner, CancellationToken cancellationToken) => account switch
{
SystemUser system => systemUsers.SaveAsync(system, cancellationToken),
CompanyUser user => companyUsers.SaveAsync(owner.CompanyDatabase!, user, cancellationToken),
_ => throw new InvalidOperationException("Unknown account type."),
};
private Task AuditAsync(string action, IAccount account, SessionOwner owner, CancellationToken cancellationToken) =>
audit.WriteAsync(new SecurityEvent(action, account.UserName, owner.CompanyDatabase), cancellationToken);
}
@@ -0,0 +1,238 @@
using System.Text.Json;
using Khaemhat.Application.Audit;
using Khaemhat.Application.Modules;
using Khaemhat.Core.Security;
using Khaemhat.Data;
using Khaemhat.Data.Querying;
namespace Khaemhat.Application.Security;
/// <summary>A role with its permission patterns.</summary>
/// <param name="Role">The role.</param>
/// <param name="Permissions">The patterns.</param>
public sealed record RoleWithPermissions(Role Role, IReadOnlyList<string> Permissions);
/// <summary>
/// Roles (SPEC §7.2): the eight predefined roles live as templates in <c>sys_roles_templates</c> and are copied into each
/// company, where they can be cloned but not changed. Users with <c>company.users.manage</c> manage roles never above
/// their own permissions.
/// </summary>
public sealed class RoleService(IUnitOfWorkFactory factory, PermissionService permissions, ISecurityAuditLog audit)
{
/// <summary>Writes or updates the predefined templates in the system database (bootstrap and every start).</summary>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
public async Task SeedTemplatesAsync(CancellationToken cancellationToken = default)
{
await using var unitOfWork = await factory.CreateAsync(DatabaseScope.System, cancellationToken).ConfigureAwait(false);
var templates = unitOfWork.Repository<RoleTemplate, long>();
var existing = (await templates.ListAsync(Query.For<RoleTemplate>(), cancellationToken).ConfigureAwait(false)).Items
.ToDictionary(t => t.Code, StringComparer.Ordinal);
await unitOfWork.InTransactionAsync(
async ct =>
{
var order = 0;
foreach (var definition in PredefinedRoles.All)
{
var json = JsonSerializer.Serialize(definition.Permissions);
order += 10;
if (!existing.TryGetValue(definition.Code, out var template))
{
await templates.InsertAsync(
new RoleTemplate { Code = definition.Code, Name = definition.Name, Description = definition.Description, Permissions = json, SortOrder = order },
ct).ConfigureAwait(false);
}
else if (template.Permissions != json || template.Name != definition.Name || template.Description != definition.Description)
{
template.Name = definition.Name;
template.Description = definition.Description;
template.Permissions = json;
template.SortOrder = order;
await templates.UpdateAsync(template, ct).ConfigureAwait(false);
}
}
},
cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Copies the templates into a company: missing predefined roles are created, existing ones are brought in line
/// with their template (they are not modifiable, so the template wins).
/// </summary>
/// <param name="companyCode">The company.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
public async Task SyncPredefinedRolesAsync(string companyCode, CancellationToken cancellationToken = default)
{
IReadOnlyList<RoleTemplate> templates;
await using (var system = await factory.CreateAsync(DatabaseScope.System, cancellationToken).ConfigureAwait(false))
{
templates = (await system.Repository<RoleTemplate, long>().ListAsync(Query.For<RoleTemplate>().OrderBy(t => t.SortOrder), cancellationToken)
.ConfigureAwait(false)).Items;
}
await using var unitOfWork = await factory.CreateAsync(DatabaseScope.Company(companyCode), cancellationToken).ConfigureAwait(false);
var roles = unitOfWork.Repository<Role, long>();
var grants = unitOfWork.Repository<RoleGrant, long>();
await unitOfWork.InTransactionAsync(
async ct =>
{
foreach (var template in templates)
{
var code = template.Code;
var role = await roles.FindAsync(Query.For<Role>().Where(r => r.Code == code), ct).ConfigureAwait(false);
if (role is null)
{
role = new Role { Code = code, Name = template.Name, Description = template.Description, IsPredefined = true, TemplateCode = code };
role.Id = await roles.InsertAsync(role, ct).ConfigureAwait(false);
}
else if (!role.IsPredefined)
{
continue;
}
var wanted = JsonSerializer.Deserialize<List<string>>(template.Permissions) ?? [];
await ReplaceGrantsAsync(grants, role.Id, wanted, ct).ConfigureAwait(false);
}
},
cancellationToken).ConfigureAwait(false);
await permissions.InvalidateAsync(companyCode, cancellationToken).ConfigureAwait(false);
}
/// <summary>The roles of a company with their permissions.</summary>
/// <param name="companyCode">The company.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The roles, predefined first.</returns>
public async Task<IReadOnlyList<RoleWithPermissions>> ListAsync(string companyCode, CancellationToken cancellationToken = default)
{
await using var unitOfWork = await factory.CreateAsync(DatabaseScope.Company(companyCode), cancellationToken).ConfigureAwait(false);
var roles = (await unitOfWork.Repository<Role, long>().ListAsync(Query.For<Role>().OrderByDescending(r => r.IsPredefined).OrderBy(r => r.Name), cancellationToken)
.ConfigureAwait(false)).Items;
var grants = (await unitOfWork.Repository<RoleGrant, long>().ListAsync(Query.For<RoleGrant>(), cancellationToken).ConfigureAwait(false)).Items
.ToLookup(g => g.RoleId);
return [.. roles.Select(r => new RoleWithPermissions(r, [.. grants[r.Id].Select(g => g.Permission).Order(StringComparer.Ordinal)]))];
}
/// <summary>Clones a role into a new, modifiable one.</summary>
/// <param name="actor">Who acts.</param>
/// <param name="companyCode">The company.</param>
/// <param name="sourceCode">The role to clone.</param>
/// <param name="newCode">The new code.</param>
/// <param name="newName">The new name.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The new role.</returns>
public async Task<Role> CloneAsync(Actor actor, string companyCode, string sourceCode, string newCode, string newName, CancellationToken cancellationToken = default)
{
await DemandManageAsync(actor, companyCode, cancellationToken).ConfigureAwait(false);
ArgumentException.ThrowIfNullOrWhiteSpace(newName);
var code = NormalizeCode(newCode);
await using var unitOfWork = await factory.CreateAsync(DatabaseScope.Company(companyCode), cancellationToken).ConfigureAwait(false);
var roles = unitOfWork.Repository<Role, long>();
var grants = unitOfWork.Repository<RoleGrant, long>();
var source = await roles.FindAsync(Query.For<Role>().Where(r => r.Code == sourceCode), cancellationToken).ConfigureAwait(false)
?? throw new KeyNotFoundException($"No role has code {sourceCode}.");
var sourceId = source.Id;
var patterns = (await grants.ListAsync(Query.For<RoleGrant>().Where(g => g.RoleId == sourceId), cancellationToken).ConfigureAwait(false)).Items
.Select(g => g.Permission).ToList();
if (!await permissions.CoversAsync(actor, patterns, cancellationToken).ConfigureAwait(false))
{
throw new AccessDeniedException(SecurityErrors.PermissionDenied, "A role cannot grant more than the permissions of who creates it.");
}
var role = new Role { Code = code, Name = newName.Trim(), Description = source.Description, IsPredefined = false, TemplateCode = source.Code };
await unitOfWork.InTransactionAsync(
async ct =>
{
if (await roles.CountAsync(Query.For<Role>().Where(r => r.Code == code), ct).ConfigureAwait(false) > 0)
{
throw new ValidationFailedException(["role_code_taken"]);
}
role.Id = await roles.InsertAsync(role, ct).ConfigureAwait(false);
await ReplaceGrantsAsync(grants, role.Id, patterns, ct).ConfigureAwait(false);
},
cancellationToken).ConfigureAwait(false);
await audit.WriteAsync(new SecurityEvent("role.cloned", actor.UserName, companyCode, code, new { from = source.Code }), cancellationToken).ConfigureAwait(false);
return role;
}
/// <summary>Sets the permissions of a cloned role. Predefined roles are refused.</summary>
/// <param name="actor">Who acts.</param>
/// <param name="companyCode">The company.</param>
/// <param name="roleCode">The role.</param>
/// <param name="patterns">The new permission patterns.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
public async Task SetPermissionsAsync(Actor actor, string companyCode, string roleCode, IReadOnlyList<string> patterns, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(patterns);
await DemandManageAsync(actor, companyCode, cancellationToken).ConfigureAwait(false);
if (patterns.Any(p => p != "*" && !PermissionPattern.IsCode(p.Replace("*", "x", StringComparison.Ordinal))))
{
throw new ValidationFailedException(["permission_invalid"]);
}
if (!await permissions.CoversAsync(actor, patterns, cancellationToken).ConfigureAwait(false))
{
throw new AccessDeniedException(SecurityErrors.PermissionDenied, "A role cannot grant more than the permissions of who changes it.");
}
await using var unitOfWork = await factory.CreateAsync(DatabaseScope.Company(companyCode), cancellationToken).ConfigureAwait(false);
var role = await unitOfWork.Repository<Role, long>().FindAsync(Query.For<Role>().Where(r => r.Code == roleCode), cancellationToken).ConfigureAwait(false)
?? throw new KeyNotFoundException($"No role has code {roleCode}.");
if (role.IsPredefined)
{
throw new ValidationFailedException(["role_predefined"]);
}
await unitOfWork.InTransactionAsync(ct => ReplaceGrantsAsync(unitOfWork.Repository<RoleGrant, long>(), role.Id, patterns, ct), cancellationToken).ConfigureAwait(false);
await permissions.InvalidateAsync(companyCode, cancellationToken).ConfigureAwait(false);
await audit.WriteAsync(new SecurityEvent("role.permissions-changed", actor.UserName, companyCode, roleCode, new { patterns }), cancellationToken).ConfigureAwait(false);
}
/// <summary>Checks that the actor may manage users and roles of a company.</summary>
/// <param name="actor">The actor.</param>
/// <param name="companyCode">The company.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
/// <exception cref="AccessDeniedException">The actor may not.</exception>
internal async Task DemandManageAsync(Actor actor, string companyCode, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(actor);
if (actor.IsInstanceAccount)
{
return;
}
if (!string.Equals(actor.CompanyCode, CompanyCodes.Normalize(companyCode), StringComparison.Ordinal))
{
throw new AccessDeniedException(SecurityErrors.PermissionDenied, "A company user works only in its own company.");
}
await permissions.DemandAsync(actor, "company.users.manage", cancellationToken).ConfigureAwait(false);
}
private static string NormalizeCode(string code)
{
ArgumentNullException.ThrowIfNull(code);
var normalized = code.Trim().ToUpperInvariant();
return normalized.Length is >= 2 and <= 50 && normalized.All(c => char.IsAsciiLetterOrDigit(c) || c == '_')
? normalized
: throw new ValidationFailedException(["role_code_invalid"]);
}
private static async Task ReplaceGrantsAsync(IRepository<RoleGrant, long> grants, long roleId, IEnumerable<string> patterns, CancellationToken cancellationToken)
{
var current = (await grants.ListAsync(Query.For<RoleGrant>().Where(g => g.RoleId == roleId), cancellationToken).ConfigureAwait(false)).Items;
var wanted = patterns.Distinct(StringComparer.Ordinal).ToHashSet(StringComparer.Ordinal);
foreach (var grant in current.Where(g => !wanted.Contains(g.Permission)))
{
await grants.DeleteAsync(grant.Id, cancellationToken).ConfigureAwait(false);
}
foreach (var pattern in wanted.Except(current.Select(g => g.Permission)))
{
await grants.InsertAsync(new RoleGrant { RoleId = roleId, Permission = pattern }, cancellationToken).ConfigureAwait(false);
}
}
}
@@ -0,0 +1,468 @@
using Khaemhat.Core.Caching;
using Khaemhat.Core.Security;
using Khaemhat.Data;
using Khaemhat.Data.Companies;
using Khaemhat.Data.Querying;
using Khaemhat.Infrastructure.Security;
namespace Khaemhat.Application.Security;
/// <summary>
/// Who a session belongs to: an instance account (<c>sys_sessions</c>) or a user of a company (<c>user_sessions</c> in
/// that company's database).
/// </summary>
/// <param name="CompanyDatabase">The company whose database holds the user; <see langword="null"/> for instance accounts.</param>
/// <param name="UserId">The account.</param>
public sealed record SessionOwner(string? CompanyDatabase, long UserId)
{
/// <summary>Whether the owner is an instance account.</summary>
public bool IsInstanceAccount => CompanyDatabase is null;
}
/// <summary>What a valid session says about its user, resolved at each request and cached briefly.</summary>
/// <param name="SessionId">The session row.</param>
/// <param name="Owner">The owner.</param>
/// <param name="State">The sign-in state.</param>
/// <param name="UserName">The user name.</param>
/// <param name="DisplayName">The name shown.</param>
/// <param name="Level">The level.</param>
/// <param name="CompanyCode">The company the session works in.</param>
/// <param name="LinkedUserId">For administrators linked to a user of <paramref name="CompanyCode"/>: that user.</param>
/// <param name="ExpiresAt">When the session expires unless used.</param>
/// <param name="Persistent">Whether the cookie survives the browser.</param>
public sealed record SessionIdentity(
long SessionId, SessionOwner Owner, SessionState State, string UserName, string DisplayName, UserLevel Level,
string? CompanyCode, long? LinkedUserId, DateTime ExpiresAt, bool Persistent)
{
/// <summary>The actor for the services.</summary>
/// <returns>The actor.</returns>
public Actor ToActor() => Owner.IsInstanceAccount
? new Actor(UserName, Level, Owner.UserId, LinkedUserId, CompanyCode)
: new Actor(UserName, UserLevel.Standard, null, Owner.UserId, CompanyCode);
}
/// <summary>A session as listed to its user or to administrators.</summary>
/// <param name="Id">The session row.</param>
/// <param name="CreatedAt">The sign-in time.</param>
/// <param name="LastSeenAt">The last request.</param>
/// <param name="IpAddress">The client address.</param>
/// <param name="UserAgent">The browser.</param>
/// <param name="CompanyCode">The company.</param>
public sealed record SessionSummary(long Id, DateTime CreatedAt, DateTime LastSeenAt, string? IpAddress, string? UserAgent, string? CompanyCode);
/// <summary>
/// Sign-in sessions (SPEC §7.3). The cookie value is <c>&lt;scope&gt;.&lt;token&gt;</c>: the scope says which database
/// holds the row (<c>_</c> for the system database, otherwise the company code) and the token is 256 random bits, of which
/// only the SHA-256 hash is stored. Expiry is sliding; revocation takes effect at the next request.
/// </summary>
public sealed class SessionStore
{
private const string SystemScope = "_";
private const string CacheArea = "sessions";
private static readonly TimeSpan TouchInterval = TimeSpan.FromMinutes(1);
private static readonly TimeSpan CacheTime = TimeSpan.FromSeconds(30);
private readonly IUnitOfWorkFactory _factory;
private readonly ICompanyRegistry _companies;
private readonly ICacheProvider _cache;
private readonly SecurityPolicyOptions _policy;
private readonly TimeProvider _clock;
/// <summary>Creates the store.</summary>
/// <param name="factory">Opens the databases.</param>
/// <param name="companies">The company registry.</param>
/// <param name="cache">The cache of resolved sessions.</param>
/// <param name="policy">Session lifetimes.</param>
/// <param name="clock">The clock.</param>
public SessionStore(IUnitOfWorkFactory factory, ICompanyRegistry companies, ICacheProvider cache, SecurityPolicyOptions policy, TimeProvider clock)
{
ArgumentNullException.ThrowIfNull(factory);
ArgumentNullException.ThrowIfNull(companies);
ArgumentNullException.ThrowIfNull(cache);
ArgumentNullException.ThrowIfNull(policy);
ArgumentNullException.ThrowIfNull(clock);
_factory = factory;
_companies = companies;
_cache = cache;
_policy = policy;
_clock = clock;
}
private DateTime Now => DateTime.SpecifyKind(Data.Execution.DataAccessContext.Truncate(_clock.GetUtcNow().UtcDateTime), DateTimeKind.Utc);
/// <summary>Creates a session.</summary>
/// <param name="owner">The owner.</param>
/// <param name="state">The sign-in state.</param>
/// <param name="companyCode">The company the session works in.</param>
/// <param name="ipAddress">The client address.</param>
/// <param name="userAgent">The browser.</param>
/// <param name="persistent">"Remember me on this device".</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The cookie value.</returns>
public async Task<string> CreateAsync(
SessionOwner owner, SessionState state, string? companyCode, string? ipAddress, string? userAgent, bool persistent, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(owner);
var token = SecureTokenGenerator.Create();
var now = Now;
SessionRecord session = owner.IsInstanceAccount ? new SystemSession() : new UserSession();
session.TokenHash = SecureTokenGenerator.Hash(token);
session.UserId = owner.UserId;
session.State = state;
session.CompanyCode = companyCode;
session.IpAddress = Clip(ipAddress, 64);
session.UserAgent = Clip(userAgent, 400);
session.Persistent = persistent;
session.LastSeenAt = now;
session.ExpiresAt = now + Lifetime(state, persistent);
await using var unitOfWork = await OpenAsync(owner, cancellationToken).ConfigureAwait(false);
if (session is SystemSession system)
{
await unitOfWork.Repository<SystemSession, long>().InsertAsync(system, cancellationToken).ConfigureAwait(false);
}
else
{
await unitOfWork.Repository<UserSession, long>().InsertAsync((UserSession)session, cancellationToken).ConfigureAwait(false);
}
return (owner.CompanyDatabase ?? SystemScope) + "." + token;
}
/// <summary>Finds the valid session of a cookie (not revoked, not expired) and slides its expiry.</summary>
/// <param name="cookie">The cookie value.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The session row and owner, or <see langword="null"/>.</returns>
public async Task<(SessionRecord Session, SessionOwner Owner)?> FindAsync(string? cookie, CancellationToken cancellationToken = default)
{
if (!TryParse(cookie, out var owner, out var hash))
{
return null;
}
await using var unitOfWork = await OpenAsync(owner, cancellationToken).ConfigureAwait(false);
var session = owner.IsInstanceAccount
? await unitOfWork.Repository<SystemSession, long>().FindAsync(Query.For<SystemSession>().Where(s => s.TokenHash == hash), cancellationToken).ConfigureAwait(false)
: (SessionRecord?)await unitOfWork.Repository<UserSession, long>().FindAsync(Query.For<UserSession>().Where(s => s.TokenHash == hash), cancellationToken).ConfigureAwait(false);
var now = Now;
if (session is null || session.RevokedAt is not null || session.ExpiresAt <= now)
{
return null;
}
if (now - session.LastSeenAt >= TouchInterval)
{
session.LastSeenAt = now;
session.ExpiresAt = now + Lifetime(session.State, session.Persistent);
await SaveAsync(unitOfWork, session, cancellationToken).ConfigureAwait(false);
}
return (session, owner with { UserId = session.UserId });
}
/// <summary>Moves a session to another sign-in state and gives it a new token (the old cookie stops working).</summary>
/// <param name="cookie">The current cookie value.</param>
/// <param name="state">The new state.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The new cookie value, or <see langword="null"/> when the session is not valid.</returns>
public async Task<string?> AdvanceAsync(string cookie, SessionState state, CancellationToken cancellationToken = default)
{
if (await FindAsync(cookie, cancellationToken).ConfigureAwait(false) is not var (session, owner))
{
return null;
}
var token = SecureTokenGenerator.Create();
var now = Now;
session.TokenHash = SecureTokenGenerator.Hash(token);
session.State = state;
session.LastSeenAt = now;
session.ExpiresAt = now + Lifetime(state, session.Persistent);
await using var unitOfWork = await OpenAsync(owner, cancellationToken).ConfigureAwait(false);
await SaveAsync(unitOfWork, session, cancellationToken).ConfigureAwait(false);
await ForgetAsync(cookie, cancellationToken).ConfigureAwait(false);
return (owner.CompanyDatabase ?? SystemScope) + "." + token;
}
/// <summary>Changes the company a session of an instance account works in.</summary>
/// <param name="cookie">The cookie value.</param>
/// <param name="companyCode">The company, or <see langword="null"/>.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
public async Task SetCompanyAsync(string cookie, string? companyCode, CancellationToken cancellationToken = default)
{
if (await FindAsync(cookie, cancellationToken).ConfigureAwait(false) is not var (session, owner) || !owner.IsInstanceAccount)
{
throw new AccessDeniedException(SecurityErrors.PermissionDenied, "Only instance accounts choose the company.");
}
session.CompanyCode = companyCode is null ? null : CompanyCodes.Normalize(companyCode);
await using var unitOfWork = await OpenAsync(owner, cancellationToken).ConfigureAwait(false);
await SaveAsync(unitOfWork, session, cancellationToken).ConfigureAwait(false);
await ForgetAsync(cookie, cancellationToken).ConfigureAwait(false);
}
/// <summary>Revokes the session of a cookie (sign-out).</summary>
/// <param name="cookie">The cookie value.</param>
/// <param name="reason">Why.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The owner of the revoked session, or <see langword="null"/>.</returns>
public async Task<SessionOwner?> RevokeAsync(string? cookie, string reason, CancellationToken cancellationToken = default)
{
if (await FindAsync(cookie, cancellationToken).ConfigureAwait(false) is not var (session, owner))
{
return null;
}
await RevokeAsync(owner, session.Id, reason, cancellationToken).ConfigureAwait(false);
await ForgetAsync(cookie!, cancellationToken).ConfigureAwait(false);
return owner;
}
/// <summary>Revokes one session of an owner (from the list of sessions).</summary>
/// <param name="owner">The owner.</param>
/// <param name="sessionId">The session row.</param>
/// <param name="reason">Why.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>Whether a session was revoked.</returns>
public async Task<bool> RevokeAsync(SessionOwner owner, long sessionId, string reason, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(owner);
var revoked = await RevokeWhereAsync(owner, s => s.Id == sessionId && s.UserId == owner.UserId, reason, cancellationToken).ConfigureAwait(false);
return revoked > 0;
}
/// <summary>Revokes every session of an owner, except one (password change, administrator action).</summary>
/// <param name="owner">The owner.</param>
/// <param name="reason">Why.</param>
/// <param name="exceptSessionId">The session to keep.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The number of sessions revoked.</returns>
public Task<int> RevokeAllAsync(SessionOwner owner, string reason, long? exceptSessionId = null, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(owner);
var keep = exceptSessionId ?? 0;
return RevokeWhereAsync(owner, s => s.UserId == owner.UserId && s.Id != keep, reason, cancellationToken);
}
/// <summary>
/// Revokes every session of the users of a company (maintenance, disabling): instance accounts keep theirs, also when
/// they work in that company.
/// </summary>
/// <param name="companyCode">The company.</param>
/// <param name="reason">Why.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The number of sessions revoked.</returns>
public async Task<int> RevokeCompanyAsync(string companyCode, string reason, CancellationToken cancellationToken = default)
{
var now = Now;
var why = Clip(reason, 100);
int count;
await using (var unitOfWork = await _factory.CreateAsync(DatabaseScope.Company(companyCode), cancellationToken).ConfigureAwait(false))
{
count = await unitOfWork.ExecuteAsync(
SqlFragment.Of($"UPDATE {SqlFragment.Identifier("user_sessions")} SET revoked_at = {now}, revoked_reason = {why} WHERE revoked_at IS NULL"),
cancellationToken).ConfigureAwait(false);
}
if (count > 0)
{
await _cache.PublishInvalidationAsync(CacheKeys.Prefix(null, CacheArea), cancellationToken).ConfigureAwait(false);
}
return count;
}
/// <summary>Whether a signed-in session is still valid (the periodic check of open Blazor circuits).</summary>
/// <param name="owner">The owner.</param>
/// <param name="sessionId">The session row.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns><see langword="true"/> while the session is active, not revoked and not expired.</returns>
public async Task<bool> IsActiveAsync(SessionOwner owner, long sessionId, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(owner);
var now = Now;
await using var unitOfWork = await OpenAsync(owner, cancellationToken).ConfigureAwait(false);
var userId = owner.UserId;
return owner.IsInstanceAccount
? await unitOfWork.Repository<SystemSession, long>().CountAsync(
Query.For<SystemSession>().Where(s => s.Id == sessionId && s.UserId == userId && s.RevokedAt == null && s.ExpiresAt > now && s.State == SessionState.Active),
cancellationToken).ConfigureAwait(false) > 0
: await unitOfWork.Repository<UserSession, long>().CountAsync(
Query.For<UserSession>().Where(s => s.Id == sessionId && s.UserId == userId && s.RevokedAt == null && s.ExpiresAt > now && s.State == SessionState.Active),
cancellationToken).ConfigureAwait(false) > 0;
}
/// <summary>The active sessions of an owner.</summary>
/// <param name="owner">The owner.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The sessions, most recent first.</returns>
public async Task<IReadOnlyList<SessionSummary>> ListAsync(SessionOwner owner, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(owner);
var now = Now;
var userId = owner.UserId;
await using var unitOfWork = await OpenAsync(owner, cancellationToken).ConfigureAwait(false);
IEnumerable<SessionRecord> sessions = owner.IsInstanceAccount
? (await unitOfWork.Repository<SystemSession, long>().ListAsync(
Query.For<SystemSession>().Where(s => s.UserId == userId && s.RevokedAt == null && s.ExpiresAt > now).OrderByDescending(s => s.LastSeenAt), cancellationToken)
.ConfigureAwait(false)).Items
: (await unitOfWork.Repository<UserSession, long>().ListAsync(
Query.For<UserSession>().Where(s => s.UserId == userId && s.RevokedAt == null && s.ExpiresAt > now).OrderByDescending(s => s.LastSeenAt), cancellationToken)
.ConfigureAwait(false)).Items;
return [.. sessions.Select(s => new SessionSummary(s.Id, s.CreatedAt, s.LastSeenAt, s.IpAddress, s.UserAgent, s.CompanyCode))];
}
/// <summary>Whether an owner has signed in before from the same browser (to warn about new devices).</summary>
/// <param name="owner">The owner.</param>
/// <param name="userAgent">The browser.</param>
/// <param name="exceptSessionId">The session just created.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns><see langword="true"/> if a previous session used the same browser.</returns>
public async Task<bool> IsKnownDeviceAsync(SessionOwner owner, string? userAgent, long exceptSessionId, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(owner);
var agent = Clip(userAgent, 400);
var userId = owner.UserId;
await using var unitOfWork = await OpenAsync(owner, cancellationToken).ConfigureAwait(false);
return owner.IsInstanceAccount
? await unitOfWork.Repository<SystemSession, long>().CountAsync(
Query.For<SystemSession>().Where(s => s.UserId == userId && s.UserAgent == agent && s.Id != exceptSessionId && s.State == SessionState.Active), cancellationToken)
.ConfigureAwait(false) > 0
: await unitOfWork.Repository<UserSession, long>().CountAsync(
Query.For<UserSession>().Where(s => s.UserId == userId && s.UserAgent == agent && s.Id != exceptSessionId && s.State == SessionState.Active), cancellationToken)
.ConfigureAwait(false) > 0;
}
/// <summary>
/// The users with an active session across the system database and every company (the concurrent-user limit of the
/// licence, SPEC §7.3).
/// </summary>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The owners with at least one active session.</returns>
public async Task<IReadOnlySet<SessionOwner>> ActiveOwnersAsync(CancellationToken cancellationToken = default)
{
var now = Now;
var owners = new HashSet<SessionOwner>();
await using (var system = await _factory.CreateAsync(DatabaseScope.System, cancellationToken).ConfigureAwait(false))
{
var rows = await system.QueryAsync<long>(
SqlFragment.Of($"SELECT DISTINCT user_id FROM {SqlFragment.Identifier("sys_sessions")} WHERE revoked_at IS NULL AND expires_at > {now} AND state = {nameof(SessionState.Active)}"),
cancellationToken).ConfigureAwait(false);
owners.UnionWith(rows.Select(id => new SessionOwner(null, id)));
}
foreach (var company in await _companies.ListAsync(cancellationToken).ConfigureAwait(false))
{
if (company.Status is Core.Instance.CompanyStatus.Disabled)
{
continue;
}
await using var unitOfWork = await _factory.CreateAsync(DatabaseScope.Company(company.Code), cancellationToken).ConfigureAwait(false);
var rows = await unitOfWork.QueryAsync<long>(
SqlFragment.Of($"SELECT DISTINCT user_id FROM {SqlFragment.Identifier("user_sessions")} WHERE revoked_at IS NULL AND expires_at > {now} AND state = {nameof(SessionState.Active)}"),
cancellationToken).ConfigureAwait(false);
owners.UnionWith(rows.Select(id => new SessionOwner(company.Code, id)));
}
return owners;
}
/// <summary>Deletes sessions expired or revoked more than <paramref name="age"/> ago (the cleanup job).</summary>
/// <param name="scope">The database.</param>
/// <param name="age">How long to keep them for the history.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The rows deleted.</returns>
public async Task<int> PurgeAsync(DatabaseScope scope, TimeSpan age, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(scope);
var limit = Now - age;
var table = scope.IsSystem ? "sys_sessions" : "user_sessions";
await using var unitOfWork = await _factory.CreateAsync(scope, cancellationToken).ConfigureAwait(false);
return await unitOfWork.ExecuteAsync(
SqlFragment.Of($"DELETE FROM {SqlFragment.Identifier(table)} WHERE expires_at < {limit} OR revoked_at < {limit}"), cancellationToken).ConfigureAwait(false);
}
/// <summary>The cache key of a cookie's resolved identity.</summary>
/// <param name="cookie">The cookie value.</param>
/// <returns>The key.</returns>
public static string CacheKey(string cookie) => CacheKeys.For(null, CacheArea, SecureTokenGenerator.Hash(cookie ?? string.Empty));
/// <summary>Forgets the cached identity of a cookie.</summary>
/// <param name="cookie">The cookie value.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
public ValueTask ForgetAsync(string cookie, CancellationToken cancellationToken = default) => _cache.RemoveAsync(CacheKey(cookie), cancellationToken);
/// <summary>How long a resolved identity may stay cached (revocations by id also clear the whole area).</summary>
public static TimeSpan IdentityCacheTime => CacheTime;
private async Task<int> RevokeWhereAsync(SessionOwner owner, System.Linq.Expressions.Expression<Func<SessionRecord, bool>> filter, string reason, CancellationToken cancellationToken)
{
var now = Now;
var predicate = filter.Compile();
await using var unitOfWork = await OpenAsync(owner, cancellationToken).ConfigureAwait(false);
var userId = owner.UserId;
IEnumerable<SessionRecord> sessions = owner.IsInstanceAccount
? (await unitOfWork.Repository<SystemSession, long>().ListAsync(Query.For<SystemSession>().Where(s => s.UserId == userId && s.RevokedAt == null), cancellationToken).ConfigureAwait(false)).Items
: (await unitOfWork.Repository<UserSession, long>().ListAsync(Query.For<UserSession>().Where(s => s.UserId == userId && s.RevokedAt == null), cancellationToken).ConfigureAwait(false)).Items;
var count = 0;
foreach (var session in sessions.Where(predicate))
{
session.RevokedAt = now;
session.RevokedReason = Clip(reason, 100);
await SaveAsync(unitOfWork, session, cancellationToken).ConfigureAwait(false);
count++;
}
if (count > 0)
{
// The identity cache is keyed by cookie, which is unknown here: drop the whole area (entries live 30 seconds).
await _cache.PublishInvalidationAsync(CacheKeys.Prefix(null, CacheArea), cancellationToken).ConfigureAwait(false);
}
return count;
}
private static async Task SaveAsync(IUnitOfWork unitOfWork, SessionRecord session, CancellationToken cancellationToken)
{
if (session is SystemSession system)
{
await unitOfWork.Repository<SystemSession, long>().UpdateAsync(system, cancellationToken).ConfigureAwait(false);
}
else
{
await unitOfWork.Repository<UserSession, long>().UpdateAsync((UserSession)session, cancellationToken).ConfigureAwait(false);
}
}
private TimeSpan Lifetime(SessionState state, bool persistent) =>
state != SessionState.Active ? _policy.PendingStepLifetime : persistent ? _policy.PersistentSessionLifetime : _policy.SessionLifetime;
private Task<IUnitOfWork> OpenAsync(SessionOwner owner, CancellationToken cancellationToken) =>
_factory.CreateAsync(owner.IsInstanceAccount ? DatabaseScope.System : DatabaseScope.Company(owner.CompanyDatabase!), cancellationToken);
private static bool TryParse(string? cookie, out SessionOwner owner, out string hash)
{
owner = new SessionOwner(null, 0);
hash = string.Empty;
var dot = cookie?.IndexOf('.', StringComparison.Ordinal) ?? -1;
if (dot <= 0 || cookie!.Length - dot < 40)
{
return false;
}
var scope = cookie[..dot];
if (scope != SystemScope && !CompanyCodes.IsValid(scope))
{
return false;
}
owner = new SessionOwner(scope == SystemScope ? null : scope, 0);
hash = SecureTokenGenerator.Hash(cookie[(dot + 1)..]);
return true;
}
private static string? Clip(string? value, int length) => value is null || value.Length <= length ? value : value[..length];
}
@@ -0,0 +1,416 @@
using Khaemhat.Application.Audit;
using Khaemhat.Application.Licensing;
using Khaemhat.Application.Notifications;
using Khaemhat.Core.Instance;
using Khaemhat.Core.Security;
using Khaemhat.Data;
using Khaemhat.Data.Companies;
using Khaemhat.Infrastructure.Security;
using Microsoft.Extensions.Logging;
namespace Khaemhat.Application.Security;
/// <summary>A sign-in attempt from the login page (mockup 001).</summary>
/// <param name="CompanyCode">The company chosen; instance accounts may leave it empty.</param>
/// <param name="UserName">The user name.</param>
/// <param name="Password">The password.</param>
/// <param name="Persistent">"Remember me on this device".</param>
/// <param name="IpAddress">The client address.</param>
/// <param name="UserAgent">The browser.</param>
public sealed record SignInRequest(string? CompanyCode, string UserName, string Password, bool Persistent, string? IpAddress, string? UserAgent);
/// <summary>The outcome of a sign-in step.</summary>
/// <param name="Succeeded">Whether the step succeeded.</param>
/// <param name="Error">The error code otherwise (<see cref="SecurityErrors"/>).</param>
/// <param name="Cookie">The new cookie value to set.</param>
/// <param name="State">The state reached: the page to show next.</param>
public sealed record SignInResult(bool Succeeded, string? Error, string? Cookie, SessionState? State)
{
/// <summary>A failure.</summary>
/// <param name="error">The error code.</param>
/// <returns>The outcome.</returns>
public static SignInResult Fail(string error) => new(false, error, null, null);
}
/// <summary>The data of a TOTP setup, shown once.</summary>
/// <param name="Secret">The secret in base32, for manual entry.</param>
/// <param name="ProvisioningUri">The <c>otpauth://</c> address.</param>
public sealed record TotpSetup(string Secret, string ProvisioningUri);
/// <summary>
/// The sign-in flow (SPEC §7.3; mockups 001-003): password with lockout, then the two-step verification (mandatory for
/// instance accounts), then the forced password change, each step on a session in a pending state whose token is
/// renewed at every step. Instance accounts are found in the system database first; otherwise the company user.
/// Every outcome is recorded in <c>sys_security_audit</c>; the error never says whether the user exists.
/// </summary>
public sealed class SignInService(
SystemUserService systemUsers,
UserService companyUsers,
ICompanyRegistry companies,
AccountSecurity security,
SessionStore sessions,
ILicenseGate licenses,
NotificationDispatcher notifications,
ISecurityAuditLog audit,
ILogger<SignInService> logger)
{
/// <summary>Checks company, user and password and opens a session in the first state.</summary>
/// <param name="request">The attempt.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The outcome and the cookie.</returns>
public async Task<SignInResult> SignInAsync(SignInRequest request, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(request);
var companyCode = string.IsNullOrWhiteSpace(request.CompanyCode) ? null : request.CompanyCode.Trim().ToUpperInvariant();
if (companyCode is not null && !CompanyCodes.IsValid(companyCode))
{
return SignInResult.Fail(SecurityErrors.InvalidCredentials);
}
var company = companyCode is null ? null : await companies.FindAsync(companyCode, cancellationToken).ConfigureAwait(false);
if (companyCode is not null && company is null)
{
await AuditAsync("login.failed", request.UserName, companyCode, request, new { reason = "company_unknown" }, cancellationToken).ConfigureAwait(false);
return SignInResult.Fail(SecurityErrors.InvalidCredentials);
}
var instanceAccount = await systemUsers.FindByNameAsync(request.UserName, cancellationToken).ConfigureAwait(false);
if (instanceAccount is not null)
{
return await CompleteAsync(instanceAccount, new SessionOwner(null, instanceAccount.Id), company?.Code, request,
ct => systemUsers.SaveAsync(instanceAccount, ct), cancellationToken).ConfigureAwait(false);
}
if (company is null)
{
await AuditAsync("login.failed", request.UserName, null, request, new { reason = "company_missing" }, cancellationToken).ConfigureAwait(false);
return SignInResult.Fail(SecurityErrors.InvalidCredentials);
}
if (company.Status is CompanyStatus.Maintenance or CompanyStatus.Disabled)
{
return SignInResult.Fail(SecurityErrors.CompanyUnavailable);
}
var user = await companyUsers.FindByNameAsync(company.Code, request.UserName, cancellationToken).ConfigureAwait(false);
if (user is null || user.Kind == UserKind.Technical)
{
// Hash anyway, so that an unknown user takes as long as a wrong password.
_ = PasswordHasher.Verify(DummyHash.Value, request.Password);
await AuditAsync("login.failed", request.UserName, company.Code, request, new { reason = "user_unknown" }, cancellationToken).ConfigureAwait(false);
return SignInResult.Fail(SecurityErrors.InvalidCredentials);
}
return await CompleteAsync(user, new SessionOwner(company.Code, user.Id), company.Code, request,
ct => companyUsers.SaveAsync(company.Code, user, ct), cancellationToken).ConfigureAwait(false);
}
/// <summary>Checks the TOTP code (or a recovery code) of a session waiting for it.</summary>
/// <param name="cookie">The cookie value.</param>
/// <param name="code">The code.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The outcome and the new cookie.</returns>
public async Task<SignInResult> VerifyTotpAsync(string cookie, string code, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(code);
var pending = await LoadPendingAsync(cookie, SessionState.PendingTotp, cancellationToken).ConfigureAwait(false);
if (pending is null)
{
return SignInResult.Fail(SecurityErrors.InvalidCredentials);
}
var (account, owner, save, company) = pending.Value;
var valid = code.Contains('-', StringComparison.Ordinal) ? AccountSecurity.UseRecoveryCode(account, code) : security.VerifyTotp(account, code);
if (!valid)
{
account.FailedLoginCount++;
var locked = account.FailedLoginCount >= security.Options.MaxFailedAttempts;
if (locked)
{
account.LockedUntil = DateTime.UtcNow + security.Options.LockoutDuration;
account.FailedLoginCount = 0;
await sessions.RevokeAsync(cookie, "totp_locked", cancellationToken).ConfigureAwait(false);
}
await save(cancellationToken).ConfigureAwait(false);
await AuditAsync("login.totp-failed", account.UserName, company, null, null, cancellationToken).ConfigureAwait(false);
return SignInResult.Fail(locked ? SecurityErrors.AccountLocked : SecurityErrors.TotpInvalid);
}
account.FailedLoginCount = 0;
await save(cancellationToken).ConfigureAwait(false);
var next = account.MustChangePassword ? SessionState.PendingPasswordChange : SessionState.Active;
return await AdvanceAsync(cookie, next, account, owner, company, cancellationToken).ConfigureAwait(false);
}
/// <summary>Starts the TOTP setup of a session waiting for it, or of a complete session (profile).</summary>
/// <param name="cookie">The cookie value.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The secret to show, or <see langword="null"/> when the session is not valid.</returns>
public async Task<TotpSetup?> BeginTotpSetupAsync(string cookie, CancellationToken cancellationToken = default)
{
var pending = await LoadPendingAsync(cookie, null, cancellationToken).ConfigureAwait(false);
if (pending is null || pending.Value.Account.TotpEnabled)
{
return null;
}
var (account, _, save, company) = pending.Value;
var secret = security.PendingTotpSecret(account);
if (secret is null)
{
secret = security.BeginTotpSetup(account);
await save(cancellationToken).ConfigureAwait(false);
}
return new TotpSetup(secret, TotpGenerator.ProvisioningUri(secret, company is null ? account.UserName : account.UserName + "@" + company));
}
/// <summary>Completes the TOTP setup with the first code from the app.</summary>
/// <param name="cookie">The cookie value.</param>
/// <param name="code">The code.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The outcome, the new cookie and the recovery codes to show once.</returns>
public async Task<(SignInResult Result, IReadOnlyList<string>? RecoveryCodes)> ConfirmTotpSetupAsync(string cookie, string code, CancellationToken cancellationToken = default)
{
var pending = await LoadPendingAsync(cookie, null, cancellationToken).ConfigureAwait(false);
if (pending is null)
{
return (SignInResult.Fail(SecurityErrors.InvalidCredentials), null);
}
var (account, owner, save, company) = pending.Value;
var codes = security.ConfirmTotpSetup(account, code);
if (codes is null)
{
return (SignInResult.Fail(SecurityErrors.TotpInvalid), null);
}
await save(cancellationToken).ConfigureAwait(false);
await AuditAsync("user.totp-enabled", account.UserName, company, null, null, cancellationToken).ConfigureAwait(false);
var session = await sessions.FindAsync(cookie, cancellationToken).ConfigureAwait(false);
if (session?.Session.State != SessionState.PendingTotpSetup)
{
return (new SignInResult(true, null, cookie, session?.Session.State), codes);
}
return (await AdvanceAsync(cookie, SessionState.Active, account, owner, company, cancellationToken).ConfigureAwait(false), codes);
}
/// <summary>Changes the password: the forced change of mockup 003, or a change from the profile.</summary>
/// <param name="cookie">The cookie value.</param>
/// <param name="currentPassword">The current (or temporary) password.</param>
/// <param name="newPassword">The new password.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The outcome, with every policy error code joined in <see cref="SignInResult.Error"/>.</returns>
public async Task<SignInResult> ChangePasswordAsync(string cookie, string currentPassword, string newPassword, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(currentPassword);
ArgumentNullException.ThrowIfNull(newPassword);
var pending = await LoadPendingAsync(cookie, null, cancellationToken).ConfigureAwait(false);
if (pending is null)
{
return SignInResult.Fail(SecurityErrors.InvalidCredentials);
}
var (account, owner, save, company) = pending.Value;
if (PasswordHasher.Verify(account.PasswordHash, currentPassword) == PasswordVerification.Failed)
{
return SignInResult.Fail(SecurityErrors.CurrentPasswordWrong);
}
var errors = security.ChangePassword(account, newPassword);
if (errors.Count > 0)
{
return SignInResult.Fail(string.Join(',', errors));
}
await save(cancellationToken).ConfigureAwait(false);
var current = await sessions.FindAsync(cookie, cancellationToken).ConfigureAwait(false);
await sessions.RevokeAllAsync(owner, "password_changed", current?.Session.Id, cancellationToken).ConfigureAwait(false);
await AuditAsync("user.password-changed", account.UserName, company, null, null, cancellationToken).ConfigureAwait(false);
if (current?.Session.State != SessionState.PendingPasswordChange)
{
return new SignInResult(true, null, cookie, current?.Session.State);
}
var next = NeedsTotpSetup(account, owner) ? SessionState.PendingTotpSetup : SessionState.Active;
return await AdvanceAsync(cookie, next, account, owner, company, cancellationToken).ConfigureAwait(false);
}
/// <summary>Signs out: the session is revoked.</summary>
/// <param name="cookie">The cookie value.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
public async Task SignOutAsync(string? cookie, CancellationToken cancellationToken = default)
{
var identity = await ResolveAsync(cookie, cancellationToken).ConfigureAwait(false);
var owner = await sessions.RevokeAsync(cookie, "sign_out", cancellationToken).ConfigureAwait(false);
if (owner is not null)
{
var userName = identity?.UserName ?? owner.UserId.ToString(System.Globalization.CultureInfo.InvariantCulture);
await AuditAsync("logout", userName, identity?.CompanyCode ?? owner.CompanyDatabase, null, null, cancellationToken).ConfigureAwait(false);
}
}
/// <summary>Resolves the identity of a cookie for the authentication handler.</summary>
/// <param name="cookie">The cookie value.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The identity, or <see langword="null"/> when the session is not valid or the account cannot sign in anymore.</returns>
public async Task<SessionIdentity?> ResolveAsync(string? cookie, CancellationToken cancellationToken = default)
{
if (await sessions.FindAsync(cookie, cancellationToken).ConfigureAwait(false) is not var (session, owner))
{
return null;
}
if (owner.IsInstanceAccount)
{
var account = await systemUsers.GetAsync(owner.UserId, cancellationToken).ConfigureAwait(false);
if (account is not { IsActive: true })
{
return null;
}
var linked = account.LinkedCompanyCode is not null && account.LinkedCompanyCode == session.CompanyCode ? account.LinkedUserId : null;
return new SessionIdentity(session.Id, owner, session.State, account.UserName, account.DisplayName, account.Level, session.CompanyCode, linked, session.ExpiresAt, session.Persistent);
}
var company = await companies.FindAsync(owner.CompanyDatabase!, cancellationToken).ConfigureAwait(false);
if (company is null || company.Status is CompanyStatus.Maintenance or CompanyStatus.Disabled)
{
return null;
}
var user = await companyUsers.GetAsync(owner.CompanyDatabase!, owner.UserId, cancellationToken).ConfigureAwait(false);
return user is { IsActive: true }
? new SessionIdentity(session.Id, owner, session.State, user.UserName, user.DisplayName, UserLevel.Standard, company.Code, null, session.ExpiresAt, session.Persistent)
: null;
}
private async Task<SignInResult> CompleteAsync(
IAccount account, SessionOwner owner, string? companyCode, SignInRequest request, Func<CancellationToken, Task> save, CancellationToken cancellationToken)
{
var check = security.CheckPassword(account, request.Password);
await save(cancellationToken).ConfigureAwait(false);
if (!check.Succeeded)
{
await AuditAsync("login.failed", account.UserName, companyCode, request, new { reason = check.Error }, cancellationToken).ConfigureAwait(false);
return SignInResult.Fail(check.Error!);
}
await licenses.RefreshAsync(cancellationToken).ConfigureAwait(false);
var isSuperUser = account is SystemUser { Level: UserLevel.SuperUser };
if (!isSuperUser)
{
var active = await sessions.ActiveOwnersAsync(cancellationToken).ConfigureAwait(false);
if (!active.Contains(owner) && active.Count >= licenses.Current.MaxConcurrentUsers)
{
await AuditAsync("login.refused", account.UserName, companyCode, request, new { reason = SecurityErrors.ConcurrentUsersExceeded }, cancellationToken).ConfigureAwait(false);
return SignInResult.Fail(SecurityErrors.ConcurrentUsersExceeded);
}
}
var state = account.TotpEnabled ? SessionState.PendingTotp
: check.MustChangePassword ? SessionState.PendingPasswordChange
: NeedsTotpSetup(account, owner) ? SessionState.PendingTotpSetup
: SessionState.Active;
var cookie = await sessions.CreateAsync(owner, state, companyCode, request.IpAddress, request.UserAgent, request.Persistent, cancellationToken).ConfigureAwait(false);
await AuditAsync("login.password-accepted", account.UserName, companyCode, request, new { next = state.ToString() }, cancellationToken).ConfigureAwait(false);
if (state == SessionState.Active)
{
await OnActiveAsync(cookie, account, owner, companyCode, save, cancellationToken).ConfigureAwait(false);
}
return new SignInResult(true, null, cookie, state);
}
private async Task<SignInResult> AdvanceAsync(string cookie, SessionState next, IAccount account, SessionOwner owner, string? company, CancellationToken cancellationToken)
{
var newCookie = await sessions.AdvanceAsync(cookie, next, cancellationToken).ConfigureAwait(false);
if (newCookie is null)
{
return SignInResult.Fail(SecurityErrors.InvalidCredentials);
}
if (next == SessionState.Active)
{
await OnActiveAsync(newCookie, account, owner, company, SaveFor(account, owner), cancellationToken).ConfigureAwait(false);
}
return new SignInResult(true, null, newCookie, next);
}
private async Task OnActiveAsync(string cookie, IAccount account, SessionOwner owner, string? company, Func<CancellationToken, Task> save, CancellationToken cancellationToken)
{
security.RecordSignIn(account);
await save(cancellationToken).ConfigureAwait(false);
await AuditAsync("login.succeeded", account.UserName, company, null, null, cancellationToken).ConfigureAwait(false);
if (await sessions.FindAsync(cookie, cancellationToken).ConfigureAwait(false) is var (session, _)
&& !await sessions.IsKnownDeviceAsync(owner, session.UserAgent, session.Id, cancellationToken).ConfigureAwait(false))
{
var message = new NotificationMessage(
"security",
NotificationSeverity.Warning,
"Nuovo accesso da un dispositivo non riconosciuto",
$"Accesso da {session.IpAddress ?? "indirizzo sconosciuto"} con {session.UserAgent ?? "browser sconosciuto"}. Se non sei stato tu, cambia la password e chiudi le sessioni dal profilo.",
"/profilo/sessioni");
if (owner.IsInstanceAccount)
{
await notifications.NotifyInstanceAsync(message, owner.UserId, cancellationToken).ConfigureAwait(false);
}
else
{
await notifications.NotifyCompanyAsync(owner.CompanyDatabase!, message, owner.UserId, cancellationToken).ConfigureAwait(false);
}
}
}
private bool NeedsTotpSetup(IAccount account, SessionOwner owner) =>
!account.TotpEnabled && (owner.IsInstanceAccount || account is CompanyUser { TotpRequired: true } || security.Options.TotpRequiredForUsers);
private Func<CancellationToken, Task> SaveFor(IAccount account, SessionOwner owner) => account switch
{
SystemUser system => ct => systemUsers.SaveAsync(system, ct),
CompanyUser user => ct => companyUsers.SaveAsync(owner.CompanyDatabase!, user, ct),
_ => throw new InvalidOperationException("Unknown account type."),
};
private async Task<(IAccount Account, SessionOwner Owner, Func<CancellationToken, Task> Save, string? Company)?> LoadPendingAsync(
string? cookie, SessionState? expected, CancellationToken cancellationToken)
{
if (await sessions.FindAsync(cookie, cancellationToken).ConfigureAwait(false) is not var (session, owner)
|| (expected is not null && session.State != expected))
{
return null;
}
IAccount? account = owner.IsInstanceAccount
? await systemUsers.GetAsync(owner.UserId, cancellationToken).ConfigureAwait(false)
: await companyUsers.GetAsync(owner.CompanyDatabase!, owner.UserId, cancellationToken).ConfigureAwait(false);
if (account is not { IsActive: true })
{
return null;
}
return (account, owner, SaveFor(account, owner), session.CompanyCode);
}
private async Task AuditAsync(string action, string? userName, string? company, SignInRequest? request, object? details, CancellationToken cancellationToken)
{
try
{
await audit.WriteAsync(new SecurityEvent(action, userName, company, null, details, request?.IpAddress), cancellationToken).ConfigureAwait(false);
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
logger.LogError(ex, "Security audit {Action} not written.", action);
}
}
/// <summary>A hash of a random password, compared when the user does not exist so the timing stays the same.</summary>
private static class DummyHash
{
public static readonly string Value = PasswordHasher.Hash(SecureTokenGenerator.Create());
}
}
@@ -0,0 +1,297 @@
using Khaemhat.Application.Audit;
using Khaemhat.Core.Security;
using Khaemhat.Data;
using Khaemhat.Data.Querying;
namespace Khaemhat.Application.Security;
/// <summary>A new instance account.</summary>
/// <param name="UserName">The sign-in name.</param>
/// <param name="DisplayName">The name shown.</param>
/// <param name="Email">The e-mail address.</param>
public sealed record NewSystemUser(string UserName, string DisplayName, string? Email);
/// <summary>
/// Instance accounts (<c>sys_users</c>, SPEC §7.1): one super user, created at first start and never deleted or
/// demoted; administrators, created and managed only by the super user. An administrator manages only its own profile.
/// </summary>
public sealed class SystemUserService
{
private readonly IUnitOfWorkFactory _factory;
private readonly AccountSecurity _security;
private readonly ISecurityAuditLog _audit;
/// <summary>Creates the service.</summary>
/// <param name="factory">Opens the system database.</param>
/// <param name="security">The credential rules.</param>
/// <param name="audit">The security audit.</param>
public SystemUserService(IUnitOfWorkFactory factory, AccountSecurity security, ISecurityAuditLog audit)
{
ArgumentNullException.ThrowIfNull(factory);
ArgumentNullException.ThrowIfNull(security);
ArgumentNullException.ThrowIfNull(audit);
_factory = factory;
_security = security;
_audit = audit;
}
/// <summary>Whether any instance account exists (the bootstrap reads the variables only when none does).</summary>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns><see langword="true"/> when <c>sys_users</c> has rows.</returns>
public async Task<bool> AnyAsync(CancellationToken cancellationToken = default)
{
await using var unitOfWork = await _factory.CreateAsync(DatabaseScope.System, cancellationToken).ConfigureAwait(false);
return await unitOfWork.Repository<SystemUser, long>().CountAsync(Query.For<SystemUser>(), cancellationToken).ConfigureAwait(false) > 0;
}
/// <summary>Lists the instance accounts.</summary>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The accounts, super user first.</returns>
public async Task<IReadOnlyList<SystemUser>> ListAsync(CancellationToken cancellationToken = default)
{
await using var unitOfWork = await _factory.CreateAsync(DatabaseScope.System, cancellationToken).ConfigureAwait(false);
var page = await unitOfWork.Repository<SystemUser, long>()
.ListAsync(Query.For<SystemUser>().OrderByDescending(u => u.Level).OrderBy(u => u.UserName), cancellationToken).ConfigureAwait(false);
return page.Items;
}
/// <summary>Finds an account by sign-in name.</summary>
/// <param name="userName">The name, in any case.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The account, or <see langword="null"/>.</returns>
public async Task<SystemUser?> FindByNameAsync(string userName, CancellationToken cancellationToken = default)
{
if (!UserNames.IsValid(userName))
{
return null;
}
var name = UserNames.Normalize(userName);
await using var unitOfWork = await _factory.CreateAsync(DatabaseScope.System, cancellationToken).ConfigureAwait(false);
return await unitOfWork.Repository<SystemUser, long>().FindAsync(Query.For<SystemUser>().Where(u => u.UserName == name), cancellationToken)
.ConfigureAwait(false);
}
/// <summary>Finds an account.</summary>
/// <param name="id">The identifier.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The account, or <see langword="null"/>.</returns>
public async Task<SystemUser?> GetAsync(long id, CancellationToken cancellationToken = default)
{
await using var unitOfWork = await _factory.CreateAsync(DatabaseScope.System, cancellationToken).ConfigureAwait(false);
return await unitOfWork.Repository<SystemUser, long>().GetAsync(id, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Creates the super user at first start, from <c>KHAEMHAT_SUPERUSER*</c>. Refused when a super user exists.
/// The password must be changed at the first access and the two-step verification set up.
/// </summary>
/// <param name="account">The account.</param>
/// <param name="password">The first password.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The account.</returns>
/// <exception cref="ValidationFailedException">The password does not satisfy the policy.</exception>
public async Task<SystemUser> CreateSuperUserAsync(NewSystemUser account, string password, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(account);
var user = NewAccount(account, UserLevel.SuperUser);
var errors = _security.SetInitialPassword(user, password, temporary: false);
if (errors.Count > 0)
{
throw new ValidationFailedException(errors);
}
await using var unitOfWork = await _factory.CreateAsync(DatabaseScope.System, cancellationToken).ConfigureAwait(false);
var users = unitOfWork.Repository<SystemUser, long>();
await unitOfWork.InTransactionAsync(
async ct =>
{
await unitOfWork.AcquireLockAsync("sys-users", ct).ConfigureAwait(false);
if (await users.CountAsync(Query.For<SystemUser>().Where(u => u.Level == UserLevel.SuperUser), ct).ConfigureAwait(false) > 0)
{
throw new InvalidOperationException("The super user already exists.");
}
await users.InsertAsync(user, ct).ConfigureAwait(false);
},
cancellationToken).ConfigureAwait(false);
await _audit.WriteAsync(new SecurityEvent("user.superuser-created", Actor.System.UserName, Target: user.UserName), cancellationToken).ConfigureAwait(false);
return user;
}
/// <summary>Creates an administrator with a temporary password. Only the super user may.</summary>
/// <param name="actor">Who acts.</param>
/// <param name="account">The account.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The account and its temporary password, to give once.</returns>
public async Task<(SystemUser User, string TemporaryPassword)> CreateAdministratorAsync(
Actor actor, NewSystemUser account, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(actor);
ArgumentNullException.ThrowIfNull(account);
RequireSuperUser(actor);
var user = NewAccount(account, UserLevel.Administrator);
var password = _security.IssueTemporaryPassword(user);
await using var unitOfWork = await _factory.CreateAsync(DatabaseScope.System, cancellationToken).ConfigureAwait(false);
var users = unitOfWork.Repository<SystemUser, long>();
await unitOfWork.InTransactionAsync(
async ct =>
{
if (await users.CountAsync(Query.For<SystemUser>().Where(u => u.UserName == user.UserName), ct).ConfigureAwait(false) > 0)
{
throw new ValidationFailedException(["user_name_taken"]);
}
await users.InsertAsync(user, ct).ConfigureAwait(false);
},
cancellationToken).ConfigureAwait(false);
await _audit.WriteAsync(new SecurityEvent("user.administrator-created", actor.UserName, Target: user.UserName), cancellationToken).ConfigureAwait(false);
return (user, password);
}
/// <summary>Changes name, e-mail and state of an account.</summary>
/// <param name="actor">Who acts: the super user, or an administrator on its own profile.</param>
/// <param name="id">The account.</param>
/// <param name="displayName">The new name.</param>
/// <param name="email">The new e-mail.</param>
/// <param name="isActive">The new state; the super user cannot be disabled.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
public async Task UpdateAsync(Actor actor, long id, string displayName, string? email, bool isActive, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(actor);
ArgumentException.ThrowIfNullOrWhiteSpace(displayName);
await ChangeAsync(
actor,
id,
"user.updated",
user =>
{
if (user.Level == UserLevel.SuperUser && !isActive)
{
throw new AccessDeniedException(SecurityErrors.LevelTooLow, "The super user cannot be disabled.");
}
if (!actor.IsSuperUser && user.IsActive != isActive)
{
throw new AccessDeniedException(SecurityErrors.LevelTooLow, "Only the super user enables or disables administrators.");
}
user.DisplayName = displayName.Trim();
user.Email = string.IsNullOrWhiteSpace(email) ? null : email.Trim();
user.IsActive = isActive;
},
allowSelf: true,
cancellationToken).ConfigureAwait(false);
}
/// <summary>Gives an administrator a new temporary password. Only the super user may.</summary>
/// <param name="actor">Who acts.</param>
/// <param name="id">The account.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The temporary password.</returns>
public async Task<string> ResetPasswordAsync(Actor actor, long id, CancellationToken cancellationToken = default)
{
string? password = null;
await ChangeAsync(actor, id, "user.password-reset", user => password = _security.IssueTemporaryPassword(user), allowSelf: false, cancellationToken)
.ConfigureAwait(false);
return password!;
}
/// <summary>Turns off the two-step verification of an administrator who lost the phone. Only the super user may.</summary>
/// <param name="actor">Who acts.</param>
/// <param name="id">The account.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
public Task ResetTotpAsync(Actor actor, long id, CancellationToken cancellationToken = default) =>
ChangeAsync(actor, id, "user.totp-reset", AccountSecurity.ResetTotp, allowSelf: false, cancellationToken);
/// <summary>Links an administrator to a company user, to work as that user without a second sign-in.</summary>
/// <param name="actor">Who acts: the super user, or the administrator itself.</param>
/// <param name="id">The administrator.</param>
/// <param name="companyCode">The company, or <see langword="null"/> to remove the link.</param>
/// <param name="companyUserId">The company user.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
public Task LinkAsync(Actor actor, long id, string? companyCode, long? companyUserId, CancellationToken cancellationToken = default) =>
ChangeAsync(
actor,
id,
"user.linked",
user =>
{
user.LinkedCompanyCode = companyCode is null ? null : CompanyCodes.Normalize(companyCode);
user.LinkedUserId = companyCode is null ? null : companyUserId;
},
allowSelf: true,
cancellationToken);
/// <summary>Deletes an administrator. Only the super user may; the super user itself cannot be deleted.</summary>
/// <param name="actor">Who acts.</param>
/// <param name="id">The account.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
public async Task DeleteAsync(Actor actor, long id, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(actor);
RequireSuperUser(actor);
await using var unitOfWork = await _factory.CreateAsync(DatabaseScope.System, cancellationToken).ConfigureAwait(false);
var users = unitOfWork.Repository<SystemUser, long>();
var user = await users.GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException("No instance account has this identifier.");
if (user.Level == UserLevel.SuperUser)
{
throw new AccessDeniedException(SecurityErrors.LevelTooLow, "The super user cannot be deleted.");
}
await users.DeleteAsync(id, cancellationToken).ConfigureAwait(false);
await _audit.WriteAsync(new SecurityEvent("user.deleted", actor.UserName, Target: user.UserName), cancellationToken).ConfigureAwait(false);
}
/// <summary>Saves an account changed by the sign-in flow (failures, lockout, TOTP step, password).</summary>
/// <param name="user">The account.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
public async Task SaveAsync(SystemUser user, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(user);
await using var unitOfWork = await _factory.CreateAsync(DatabaseScope.System, cancellationToken).ConfigureAwait(false);
await unitOfWork.Repository<SystemUser, long>().UpdateAsync(user, cancellationToken).ConfigureAwait(false);
}
private static SystemUser NewAccount(NewSystemUser account, UserLevel level) => new()
{
UserName = UserNames.Normalize(account.UserName),
DisplayName = string.IsNullOrWhiteSpace(account.DisplayName) ? account.UserName.Trim() : account.DisplayName.Trim(),
Email = string.IsNullOrWhiteSpace(account.Email) ? null : account.Email.Trim(),
Level = level,
IsActive = true,
};
private static void RequireSuperUser(Actor actor)
{
if (!actor.IsSuperUser)
{
throw new AccessDeniedException(SecurityErrors.LevelTooLow, "Only the super user manages administrators.");
}
}
private async Task ChangeAsync(Actor actor, long id, string action, Action<SystemUser> change, bool allowSelf, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(actor);
var self = actor.SystemUserId == id;
if (!actor.IsSuperUser && !(allowSelf && self))
{
throw new AccessDeniedException(SecurityErrors.LevelTooLow, "Only the super user manages other instance accounts.");
}
await using var unitOfWork = await _factory.CreateAsync(DatabaseScope.System, cancellationToken).ConfigureAwait(false);
var users = unitOfWork.Repository<SystemUser, long>();
var user = await users.GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException("No instance account has this identifier.");
change(user);
await users.UpdateAsync(user, cancellationToken).ConfigureAwait(false);
await _audit.WriteAsync(new SecurityEvent(action, actor.UserName, Target: user.UserName), cancellationToken).ConfigureAwait(false);
}
}
@@ -0,0 +1,274 @@
using Khaemhat.Application.Audit;
using Khaemhat.Core.Security;
using Khaemhat.Data;
using Khaemhat.Data.Querying;
namespace Khaemhat.Application.Security;
/// <summary>A new company user.</summary>
/// <param name="UserName">The sign-in name.</param>
/// <param name="DisplayName">The name shown.</param>
/// <param name="Email">The e-mail address.</param>
/// <param name="Kind">A person or a technical user for the API.</param>
/// <param name="Roles">The role codes.</param>
/// <param name="Flags">The per-user flags.</param>
public sealed record NewCompanyUser(string UserName, string DisplayName, string? Email, UserKind Kind, IReadOnlyList<string> Roles, UserFlags Flags);
/// <summary>
/// Company users (<c>users</c>, SPEC §7.1): created by instance accounts or by company users holding
/// <c>company.users.manage</c>, who can never give roles above their own permissions.
/// </summary>
public sealed class UserService(IUnitOfWorkFactory factory, AccountSecurity security, PermissionService permissions, RoleService roles, ISecurityAuditLog audit)
{
/// <summary>Lists the users of a company.</summary>
/// <param name="companyCode">The company.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The users by name.</returns>
public async Task<IReadOnlyList<CompanyUser>> ListAsync(string companyCode, CancellationToken cancellationToken = default)
{
await using var unitOfWork = await factory.CreateAsync(DatabaseScope.Company(companyCode), cancellationToken).ConfigureAwait(false);
return (await unitOfWork.Repository<CompanyUser, long>().ListAsync(Query.For<CompanyUser>().OrderBy(u => u.UserName), cancellationToken).ConfigureAwait(false)).Items;
}
/// <summary>Finds a user by sign-in name.</summary>
/// <param name="companyCode">The company.</param>
/// <param name="userName">The name, in any case.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The user, or <see langword="null"/>.</returns>
public async Task<CompanyUser?> FindByNameAsync(string companyCode, string userName, CancellationToken cancellationToken = default)
{
if (!UserNames.IsValid(userName))
{
return null;
}
var name = UserNames.Normalize(userName);
await using var unitOfWork = await factory.CreateAsync(DatabaseScope.Company(companyCode), cancellationToken).ConfigureAwait(false);
return await unitOfWork.Repository<CompanyUser, long>().FindAsync(Query.For<CompanyUser>().Where(u => u.UserName == name), cancellationToken).ConfigureAwait(false);
}
/// <summary>Finds a user.</summary>
/// <param name="companyCode">The company.</param>
/// <param name="id">The identifier.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The user, or <see langword="null"/>.</returns>
public async Task<CompanyUser?> GetAsync(string companyCode, long id, CancellationToken cancellationToken = default)
{
await using var unitOfWork = await factory.CreateAsync(DatabaseScope.Company(companyCode), cancellationToken).ConfigureAwait(false);
return await unitOfWork.Repository<CompanyUser, long>().GetAsync(id, cancellationToken).ConfigureAwait(false);
}
/// <summary>Creates a user with a temporary password (people) or none (technical users).</summary>
/// <param name="actor">Who acts.</param>
/// <param name="companyCode">The company.</param>
/// <param name="request">The user.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The user and its temporary password (<see langword="null"/> for technical users).</returns>
public async Task<(CompanyUser User, string? TemporaryPassword)> CreateAsync(
Actor actor, string companyCode, NewCompanyUser request, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(request);
await roles.DemandManageAsync(actor, companyCode, cancellationToken).ConfigureAwait(false);
var user = new CompanyUser
{
UserName = UserNames.Normalize(request.UserName),
DisplayName = string.IsNullOrWhiteSpace(request.DisplayName) ? request.UserName.Trim() : request.DisplayName.Trim(),
Email = string.IsNullOrWhiteSpace(request.Email) ? null : request.Email.Trim(),
Kind = request.Kind,
IsActive = true,
OwnCustomersOnly = request.Flags.OwnCustomersOnly,
CanSeeCosts = request.Flags.CanSeeCosts,
CanExport = request.Flags.CanExport,
CanUseApi = request.Kind == UserKind.Technical || request.Flags.CanUseApi,
TotpRequired = security.Options.TotpRequiredForUsers,
};
var password = request.Kind == UserKind.Human ? security.IssueTemporaryPassword(user) : null;
await using var unitOfWork = await factory.CreateAsync(DatabaseScope.Company(companyCode), cancellationToken).ConfigureAwait(false);
var users = unitOfWork.Repository<CompanyUser, long>();
await unitOfWork.InTransactionAsync(
async ct =>
{
if (await users.CountAsync(Query.For<CompanyUser>().Where(u => u.UserName == user.UserName), ct).ConfigureAwait(false) > 0)
{
throw new ValidationFailedException(["user_name_taken"]);
}
user.Id = await users.InsertAsync(user, ct).ConfigureAwait(false);
await AssignRolesAsync(unitOfWork, actor, user.Id, request.Roles, ct).ConfigureAwait(false);
},
cancellationToken).ConfigureAwait(false);
await audit.WriteAsync(new SecurityEvent("user.created", actor.UserName, companyCode, user.UserName, new { roles = request.Roles, kind = request.Kind.ToString() }), cancellationToken)
.ConfigureAwait(false);
return (user, password);
}
/// <summary>Replaces the roles of a user.</summary>
/// <param name="actor">Who acts.</param>
/// <param name="companyCode">The company.</param>
/// <param name="userId">The user.</param>
/// <param name="roleCodes">The role codes.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
public async Task SetRolesAsync(Actor actor, string companyCode, long userId, IReadOnlyList<string> roleCodes, CancellationToken cancellationToken = default)
{
await roles.DemandManageAsync(actor, companyCode, cancellationToken).ConfigureAwait(false);
await using var unitOfWork = await factory.CreateAsync(DatabaseScope.Company(companyCode), cancellationToken).ConfigureAwait(false);
await unitOfWork.InTransactionAsync(ct => AssignRolesAsync(unitOfWork, actor, userId, roleCodes, ct), cancellationToken).ConfigureAwait(false);
await permissions.InvalidateAsync(companyCode, cancellationToken).ConfigureAwait(false);
await audit.WriteAsync(new SecurityEvent("user.roles-changed", actor.UserName, companyCode, userId.ToString(System.Globalization.CultureInfo.InvariantCulture), new { roles = roleCodes }), cancellationToken)
.ConfigureAwait(false);
}
/// <summary>Grants or denies single permissions to a user over its roles. Denials win.</summary>
/// <param name="actor">Who acts.</param>
/// <param name="companyCode">The company.</param>
/// <param name="userId">The user.</param>
/// <param name="overrides">Permission code and whether it is allowed.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
public async Task SetOverridesAsync(Actor actor, string companyCode, long userId, IReadOnlyDictionary<string, bool> overrides, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(overrides);
await roles.DemandManageAsync(actor, companyCode, cancellationToken).ConfigureAwait(false);
if (!await permissions.CoversAsync(actor, overrides.Where(o => o.Value).Select(o => o.Key), cancellationToken).ConfigureAwait(false))
{
throw new AccessDeniedException(SecurityErrors.PermissionDenied, "A user cannot grant permissions it does not hold.");
}
await using var unitOfWork = await factory.CreateAsync(DatabaseScope.Company(companyCode), cancellationToken).ConfigureAwait(false);
var repository = unitOfWork.Repository<UserPermissionOverride, long>();
await unitOfWork.InTransactionAsync(
async ct =>
{
foreach (var old in (await repository.ListAsync(Query.For<UserPermissionOverride>().Where(o => o.UserId == userId), ct).ConfigureAwait(false)).Items)
{
await repository.DeleteAsync(old.Id, ct).ConfigureAwait(false);
}
foreach (var (code, allowed) in overrides)
{
await repository.InsertAsync(new UserPermissionOverride { UserId = userId, Permission = code, Allowed = allowed }, ct).ConfigureAwait(false);
}
},
cancellationToken).ConfigureAwait(false);
await permissions.InvalidateAsync(companyCode, cancellationToken).ConfigureAwait(false);
await audit.WriteAsync(new SecurityEvent("user.overrides-changed", actor.UserName, companyCode, userId.ToString(System.Globalization.CultureInfo.InvariantCulture), overrides), cancellationToken)
.ConfigureAwait(false);
}
/// <summary>Changes name, e-mail, flags and state of a user.</summary>
/// <param name="actor">Who acts.</param>
/// <param name="companyCode">The company.</param>
/// <param name="userId">The user.</param>
/// <param name="displayName">The name.</param>
/// <param name="email">The e-mail.</param>
/// <param name="flags">The flags.</param>
/// <param name="isActive">Whether it can sign in.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
public async Task UpdateAsync(
Actor actor, string companyCode, long userId, string displayName, string? email, UserFlags flags, bool isActive, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(flags);
ArgumentException.ThrowIfNullOrWhiteSpace(displayName);
await ChangeAsync(actor, companyCode, userId, "user.updated", user =>
{
user.DisplayName = displayName.Trim();
user.Email = string.IsNullOrWhiteSpace(email) ? null : email.Trim();
user.OwnCustomersOnly = flags.OwnCustomersOnly;
user.CanSeeCosts = flags.CanSeeCosts;
user.CanExport = flags.CanExport;
user.CanUseApi = user.Kind == UserKind.Technical || flags.CanUseApi;
user.IsActive = isActive;
}, cancellationToken).ConfigureAwait(false);
}
/// <summary>Gives a user a new temporary password.</summary>
/// <param name="actor">Who acts.</param>
/// <param name="companyCode">The company.</param>
/// <param name="userId">The user.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The temporary password.</returns>
public async Task<string> ResetPasswordAsync(Actor actor, string companyCode, long userId, CancellationToken cancellationToken = default)
{
string? password = null;
await ChangeAsync(actor, companyCode, userId, "user.password-reset", user =>
{
if (user.Kind == UserKind.Technical)
{
throw new ValidationFailedException(["technical_user_has_no_password"]);
}
password = security.IssueTemporaryPassword(user);
}, cancellationToken).ConfigureAwait(false);
return password!;
}
/// <summary>Turns off the two-step verification of a user who lost the phone.</summary>
/// <param name="actor">Who acts.</param>
/// <param name="companyCode">The company.</param>
/// <param name="userId">The user.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
public Task ResetTotpAsync(Actor actor, string companyCode, long userId, CancellationToken cancellationToken = default) =>
ChangeAsync(actor, companyCode, userId, "user.totp-reset", AccountSecurity.ResetTotp, cancellationToken);
/// <summary>Saves a user changed by the sign-in flow.</summary>
/// <param name="companyCode">The company.</param>
/// <param name="user">The user.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
public async Task SaveAsync(string companyCode, CompanyUser user, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(user);
await using var unitOfWork = await factory.CreateAsync(DatabaseScope.Company(companyCode), cancellationToken).ConfigureAwait(false);
await unitOfWork.Repository<CompanyUser, long>().UpdateAsync(user, cancellationToken).ConfigureAwait(false);
}
private async Task ChangeAsync(Actor actor, string companyCode, long userId, string action, Action<CompanyUser> change, CancellationToken cancellationToken)
{
await roles.DemandManageAsync(actor, companyCode, cancellationToken).ConfigureAwait(false);
await using var unitOfWork = await factory.CreateAsync(DatabaseScope.Company(companyCode), cancellationToken).ConfigureAwait(false);
var users = unitOfWork.Repository<CompanyUser, long>();
var user = await users.GetAsync(userId, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException("No user has this identifier.");
change(user);
await users.UpdateAsync(user, cancellationToken).ConfigureAwait(false);
await permissions.InvalidateAsync(companyCode, cancellationToken).ConfigureAwait(false);
await audit.WriteAsync(new SecurityEvent(action, actor.UserName, companyCode, user.UserName), cancellationToken).ConfigureAwait(false);
}
private async Task AssignRolesAsync(IUnitOfWork unitOfWork, Actor actor, long userId, IReadOnlyList<string> roleCodes, CancellationToken cancellationToken)
{
var codes = roleCodes.Select(r => r.Trim().ToUpperInvariant()).Distinct(StringComparer.Ordinal).ToArray();
var found = codes.Length == 0
? []
: (await unitOfWork.Repository<Role, long>().ListAsync(Query.For<Role>().Where(r => codes.Contains(r.Code)), cancellationToken).ConfigureAwait(false)).Items;
if (found.Count != codes.Length)
{
throw new ValidationFailedException(["role_unknown"]);
}
var roleIds = found.Select(r => r.Id).ToArray();
var patterns = roleIds.Length == 0
? []
: (await unitOfWork.Repository<RoleGrant, long>().ListAsync(Query.For<RoleGrant>().Where(g => roleIds.Contains(g.RoleId)), cancellationToken).ConfigureAwait(false)).Items
.Select(g => g.Permission);
if (!await permissions.CoversAsync(actor, patterns, cancellationToken).ConfigureAwait(false))
{
throw new AccessDeniedException(SecurityErrors.PermissionDenied, "A user cannot assign roles above its own permissions.");
}
var userRoles = unitOfWork.Repository<UserRole, long>();
foreach (var old in (await userRoles.ListAsync(Query.For<UserRole>().Where(r => r.UserId == userId), cancellationToken).ConfigureAwait(false)).Items)
{
await userRoles.DeleteAsync(old.Id, cancellationToken).ConfigureAwait(false);
}
foreach (var roleId in roleIds)
{
await userRoles.InsertAsync(new UserRole { UserId = userId, RoleId = roleId }, cancellationToken).ConfigureAwait(false);
}
}
}
@@ -0,0 +1,80 @@
namespace Khaemhat.Core.Caching;
/// <summary>
/// The application cache (SPEC §9): in memory, or Redis when <c>KHAEMHAT_REDIS</c> is set. Values are stored as JSON
/// in both cases, so the behaviour is the same with and without Redis. Keys follow <see cref="CacheKeys.For"/>.
/// </summary>
public interface ICacheProvider
{
/// <summary>Whether the cache is shared between instances (Redis reachable).</summary>
bool IsDistributed { get; }
/// <summary>Reads a value.</summary>
/// <typeparam name="T">The value type.</typeparam>
/// <param name="key">The key.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The value, or <see langword="default"/> when missing or expired.</returns>
ValueTask<T?> GetAsync<T>(string key, CancellationToken cancellationToken = default);
/// <summary>Stores a value.</summary>
/// <typeparam name="T">The value type.</typeparam>
/// <param name="key">The key.</param>
/// <param name="value">The value.</param>
/// <param name="timeToLive">How long it stays.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
ValueTask SetAsync<T>(string key, T value, TimeSpan timeToLive, CancellationToken cancellationToken = default);
/// <summary>Removes a value.</summary>
/// <param name="key">The key.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
ValueTask RemoveAsync(string key, CancellationToken cancellationToken = default);
/// <summary>Removes every key that starts with <paramref name="prefix"/>.</summary>
/// <param name="prefix">The prefix, for example <c>kh:DEMO:permissions:</c>.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
ValueTask RemoveByPrefixAsync(string prefix, CancellationToken cancellationToken = default);
/// <summary>Reads a value, or creates and stores it.</summary>
/// <typeparam name="T">The value type.</typeparam>
/// <param name="key">The key.</param>
/// <param name="factory">Creates the value when missing.</param>
/// <param name="timeToLive">How long it stays.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The value.</returns>
ValueTask<T> GetOrCreateAsync<T>(string key, Func<CancellationToken, ValueTask<T>> factory, TimeSpan timeToLive, CancellationToken cancellationToken = default);
/// <summary>
/// Removes the keys with <paramref name="prefix"/> here and tells the other instances to do the same (Redis pub/sub).
/// </summary>
/// <param name="prefix">The prefix.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
ValueTask PublishInvalidationAsync(string prefix, CancellationToken cancellationToken = default);
}
/// <summary>Cache keys: <c>kh:{company}:{area}:{key}</c>, with <c>_</c> for the instance (SPEC §9).</summary>
public static class CacheKeys
{
/// <summary>The instance scope.</summary>
public const string Instance = "_";
/// <summary>A key.</summary>
/// <param name="company">The company code, or <see langword="null"/> for the instance.</param>
/// <param name="area">The area, for example <c>permissions</c>.</param>
/// <param name="key">The key inside the area.</param>
/// <returns>The full key.</returns>
public static string For(string? company, string area, string key) => Prefix(company, area) + key;
/// <summary>The prefix of an area, for <see cref="ICacheProvider.RemoveByPrefixAsync"/>.</summary>
/// <param name="company">The company code, or <see langword="null"/> for the instance.</param>
/// <param name="area">The area.</param>
/// <returns>The prefix, ending with a colon.</returns>
public static string Prefix(string? company, string area)
{
ArgumentException.ThrowIfNullOrWhiteSpace(area);
return "kh:" + (string.IsNullOrEmpty(company) ? Instance : company) + ":" + area + ":";
}
}
Loaded 100 of 394 files, more files were not shown because too many files have changed in this diff. Show more