Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4ecf15b609 | ||
|
|
b4a2802bed | ||
|
|
8198e0a754 | ||
|
|
f415dc37a8 | ||
|
|
acb7e598d1 | ||
|
|
75d60ee4c4 | ||
|
|
d0f9d0e651 | ||
|
|
d958e7372d | ||
|
|
b341ade9e9 | ||
|
|
cf6f849cc1 | ||
|
|
1c30054e3d | ||
|
|
4502526f4d | ||
|
|
032c602b49 | ||
|
|
4582837b70 | ||
|
|
edce4702da | ||
|
|
6eef15c487 | ||
|
|
738c43ba0a | ||
|
|
28e7a6e18a | ||
|
|
12277733f5 |
No files matched your search
@@ -0,0 +1,21 @@
|
|||||||
|
# Build context for docker/Dockerfile: sources and build files only.
|
||||||
|
**/bin/
|
||||||
|
**/obj/
|
||||||
|
.git/
|
||||||
|
.gitea/
|
||||||
|
.vs/
|
||||||
|
.vscode/
|
||||||
|
.idea/
|
||||||
|
.claude/
|
||||||
|
.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
|
||||||
|
**/*.user
|
||||||
|
**/.env
|
||||||
@@ -0,0 +1,81 @@
|
|||||||
|
# Khaemhat code style (SPEC §1.11, §19). Build enforces analyzers and code style (EnforceCodeStyleInBuild).
|
||||||
|
root = true
|
||||||
|
|
||||||
|
[*]
|
||||||
|
charset = utf-8
|
||||||
|
end_of_line = lf
|
||||||
|
insert_final_newline = true
|
||||||
|
trim_trailing_whitespace = true
|
||||||
|
indent_style = space
|
||||||
|
indent_size = 4
|
||||||
|
|
||||||
|
[*.{csproj,props,targets,xml,json,yml,yaml,razor.css,css,js,html,svg}]
|
||||||
|
indent_size = 2
|
||||||
|
|
||||||
|
[*.razor]
|
||||||
|
indent_size = 4
|
||||||
|
|
||||||
|
[*.md]
|
||||||
|
trim_trailing_whitespace = false
|
||||||
|
|
||||||
|
[*.sh]
|
||||||
|
end_of_line = lf
|
||||||
|
|
||||||
|
[*.cs]
|
||||||
|
# Namespaces and usings
|
||||||
|
csharp_style_namespace_declarations = file_scoped:warning
|
||||||
|
dotnet_sort_system_directives_first = true
|
||||||
|
csharp_using_directive_placement = outside_namespace:warning
|
||||||
|
|
||||||
|
# var and expression style
|
||||||
|
csharp_style_var_for_built_in_types = true:suggestion
|
||||||
|
csharp_style_var_when_type_is_apparent = true:suggestion
|
||||||
|
csharp_style_var_elsewhere = true:suggestion
|
||||||
|
csharp_style_expression_bodied_methods = when_on_single_line:suggestion
|
||||||
|
csharp_style_expression_bodied_properties = true:suggestion
|
||||||
|
csharp_prefer_braces = when_multiline:suggestion
|
||||||
|
dotnet_style_qualification_for_field = false:warning
|
||||||
|
dotnet_style_qualification_for_property = false:warning
|
||||||
|
dotnet_style_qualification_for_method = false:warning
|
||||||
|
dotnet_style_predefined_type_for_locals_parameters_members = true:warning
|
||||||
|
dotnet_style_readonly_field = true:warning
|
||||||
|
csharp_style_prefer_primary_constructors = true:suggestion
|
||||||
|
|
||||||
|
# Naming: private fields _camelCase, constants PascalCase
|
||||||
|
dotnet_naming_rule.private_fields.symbols = private_fields
|
||||||
|
dotnet_naming_rule.private_fields.style = underscore_camel
|
||||||
|
dotnet_naming_rule.private_fields.severity = warning
|
||||||
|
dotnet_naming_symbols.private_fields.applicable_kinds = field
|
||||||
|
dotnet_naming_symbols.private_fields.applicable_accessibilities = private
|
||||||
|
dotnet_naming_style.underscore_camel.required_prefix = _
|
||||||
|
dotnet_naming_style.underscore_camel.capitalization = camel_case
|
||||||
|
dotnet_naming_rule.constants.symbols = constants
|
||||||
|
dotnet_naming_rule.constants.style = pascal
|
||||||
|
dotnet_naming_rule.constants.severity = warning
|
||||||
|
dotnet_naming_symbols.constants.applicable_kinds = field
|
||||||
|
dotnet_naming_symbols.constants.required_modifiers = const
|
||||||
|
dotnet_naming_style.pascal.capitalization = pascal_case
|
||||||
|
|
||||||
|
# Analyzer adjustments (each with its reason)
|
||||||
|
# CA1515 (make types internal): Khaemhat is an application, but its libraries are consumed across projects.
|
||||||
|
dotnet_diagnostic.CA1515.severity = none
|
||||||
|
# CA1848/CA1873 (LoggerMessage delegates): adopted where logging is hot (Infrastructure/Logging, M2), not everywhere.
|
||||||
|
dotnet_diagnostic.CA1848.severity = suggestion
|
||||||
|
dotnet_diagnostic.CA1873.severity = suggestion
|
||||||
|
# CA2007 (ConfigureAwait): ASP.NET Core has no synchronization context.
|
||||||
|
dotnet_diagnostic.CA2007.severity = none
|
||||||
|
# IDE0005 (unnecessary using) needs GenerateDocumentationFile, which is on: keep it as an error-free warning.
|
||||||
|
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
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
# Parses each YAML file given on the command line and fails on the first syntax error (Gitea rejects a workflow that
|
||||||
|
# does not parse, Docker Compose a compose file). Workflows must also declare "on" and "jobs".
|
||||||
|
require "yaml"
|
||||||
|
|
||||||
|
failed = false
|
||||||
|
ARGV.each do |path|
|
||||||
|
begin
|
||||||
|
document = YAML.safe_load(File.read(path), aliases: true)
|
||||||
|
if path.include?(".gitea/workflows/")
|
||||||
|
# YAML 1.1 reads the bare key "on" as true.
|
||||||
|
missing = []
|
||||||
|
missing << "on" unless document.key?("on") || document.key?(true)
|
||||||
|
missing << "jobs" unless document.key?("jobs")
|
||||||
|
raise "missing #{missing.join(', ')}" unless missing.empty?
|
||||||
|
end
|
||||||
|
puts "ok #{path}"
|
||||||
|
rescue StandardError => e
|
||||||
|
failed = true
|
||||||
|
puts "ERROR #{path}: #{e.message}"
|
||||||
|
end
|
||||||
|
end
|
||||||
|
exit(failed ? 1 : 0)
|
||||||
@@ -0,0 +1,186 @@
|
|||||||
|
name: CI
|
||||||
|
|
||||||
|
# Gitea Actions (ADR 0009). The runner is act_runner in Docker mode on the server that also runs Gitea: one job at a
|
||||||
|
# time, so the triggers are frugal. The .NET jobs use the SDK image and check out with git (the image has no Node.js
|
||||||
|
# for JavaScript actions); nothing is cached or uploaded. Builds use BUILD_CPUS cores so the host keeps room for Gitea.
|
||||||
|
on:
|
||||||
|
pull_request:
|
||||||
|
branches: [main]
|
||||||
|
push:
|
||||||
|
branches: [main]
|
||||||
|
tags: ["v*"]
|
||||||
|
paths-ignore: ["docs/**", "*.md", "assets/**", "deploy/**"]
|
||||||
|
workflow_dispatch:
|
||||||
|
|
||||||
|
concurrency:
|
||||||
|
group: ci-${{ github.ref }}
|
||||||
|
cancel-in-progress: true
|
||||||
|
|
||||||
|
env:
|
||||||
|
DOTNET_NOLOGO: "1"
|
||||||
|
DOTNET_CLI_TELEMETRY_OPTOUT: "1"
|
||||||
|
DOTNET_SKIP_FIRST_TIME_EXPERIENCE: "1"
|
||||||
|
BUILD_CPUS: "4"
|
||||||
|
KHAEMHAT_LICENSE_MODE: test
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
build:
|
||||||
|
name: Build and test (SQLite)
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
container:
|
||||||
|
image: mcr.microsoft.com/dotnet/sdk:10.0
|
||||||
|
timeout-minutes: 30
|
||||||
|
defaults:
|
||||||
|
run:
|
||||||
|
shell: bash
|
||||||
|
steps:
|
||||||
|
- name: Checkout
|
||||||
|
env:
|
||||||
|
TOKEN: ${{ github.token }}
|
||||||
|
run: |
|
||||||
|
git config --global --add safe.directory "$PWD"
|
||||||
|
git init -q .
|
||||||
|
git remote add origin "${{ github.server_url }}/${{ github.repository }}.git"
|
||||||
|
git -c http.extraheader="Authorization: basic $(printf 'x-access-token:%s' "$TOKEN" | base64 -w0)" fetch -q --depth=1 origin "${{ github.sha }}"
|
||||||
|
git checkout -q FETCH_HEAD
|
||||||
|
git log -1 --format='%h %s'
|
||||||
|
|
||||||
|
- name: Package allowlist
|
||||||
|
run: bash scripts/check-packages.sh
|
||||||
|
|
||||||
|
- name: Build (warnings are errors)
|
||||||
|
run: dotnet build Khaemhat.sln -c Release -warnaserror -m:"$BUILD_CPUS"
|
||||||
|
|
||||||
|
- name: Test
|
||||||
|
run: dotnet test Khaemhat.sln -c Release --no-build
|
||||||
|
|
||||||
|
# PostgreSQL integration (SPEC §20): only on release tags and manual runs, against the two supported servers.
|
||||||
|
postgres:
|
||||||
|
name: PostgreSQL ${{ matrix.pg }} integration
|
||||||
|
needs: build
|
||||||
|
if: startsWith(github.ref, 'refs/tags/v') || github.event_name == 'workflow_dispatch'
|
||||||
|
strategy:
|
||||||
|
fail-fast: false
|
||||||
|
matrix:
|
||||||
|
pg: ["16", "17"]
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
container:
|
||||||
|
image: mcr.microsoft.com/dotnet/sdk:10.0
|
||||||
|
timeout-minutes: 30
|
||||||
|
services:
|
||||||
|
postgres:
|
||||||
|
image: postgres:${{ matrix.pg }}
|
||||||
|
env:
|
||||||
|
POSTGRES_USER: khaemhat
|
||||||
|
POSTGRES_PASSWORD: khaemhat-ci
|
||||||
|
POSTGRES_DB: khaemhat_test
|
||||||
|
defaults:
|
||||||
|
run:
|
||||||
|
shell: bash
|
||||||
|
env:
|
||||||
|
KHAEMHAT_TEST_PG: postgres://khaemhat:khaemhat-ci@postgres:5432/khaemhat_test
|
||||||
|
steps:
|
||||||
|
- name: Checkout
|
||||||
|
env:
|
||||||
|
TOKEN: ${{ github.token }}
|
||||||
|
run: |
|
||||||
|
git config --global --add safe.directory "$PWD"
|
||||||
|
git init -q .
|
||||||
|
git remote add origin "${{ github.server_url }}/${{ github.repository }}.git"
|
||||||
|
git -c http.extraheader="Authorization: basic $(printf 'x-access-token:%s' "$TOKEN" | base64 -w0)" fetch -q --depth=1 origin "${{ github.sha }}"
|
||||||
|
git checkout -q FETCH_HEAD
|
||||||
|
|
||||||
|
- name: Test · Data (PostgreSQL)
|
||||||
|
run: dotnet test tests/Khaemhat.Data.Tests -c Release -m:"$BUILD_CPUS"
|
||||||
|
|
||||||
|
# The image builds and answers /health/live (issue #2). The runner's own image has the docker CLI and talks to the
|
||||||
|
# host's daemon; the job joins a network of its own to reach the container. Everything is labelled with the job
|
||||||
|
# container's id: a cancelled job skips its clean-up, so the next one removes what a vanished job left on the host.
|
||||||
|
# Release tags skip it: release.yml builds and tests the same image.
|
||||||
|
docker:
|
||||||
|
name: Docker image
|
||||||
|
needs: build
|
||||||
|
if: "!startsWith(github.ref, 'refs/tags/')"
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
timeout-minutes: 30
|
||||||
|
steps:
|
||||||
|
- name: Remove what cancelled jobs left
|
||||||
|
run: |
|
||||||
|
echo "NAME=khaemhat-ci-$(hostname)" >> "$GITHUB_ENV"
|
||||||
|
for c in $(docker ps -aq --filter label=khaemhat-ci.job); do
|
||||||
|
job="$(docker inspect -f '{{index .Config.Labels "khaemhat-ci.job"}}' "$c")"
|
||||||
|
docker inspect "$job" > /dev/null 2>&1 || docker rm -f -v "$c"
|
||||||
|
done
|
||||||
|
for n in $(docker network ls -q --filter label=khaemhat-ci.job); do
|
||||||
|
job="$(docker network inspect -f '{{index .Labels "khaemhat-ci.job"}}' "$n")"
|
||||||
|
docker inspect "$job" > /dev/null 2>&1 || docker network rm "$n"
|
||||||
|
done
|
||||||
|
for i in $(docker image ls -q --filter label=khaemhat-ci.job | sort -u); do
|
||||||
|
job="$(docker image inspect -f '{{index .Config.Labels "khaemhat-ci.job"}}' "$i")"
|
||||||
|
docker inspect "$job" > /dev/null 2>&1 || docker image rm -f "$i"
|
||||||
|
done
|
||||||
|
|
||||||
|
- name: Checkout
|
||||||
|
env:
|
||||||
|
TOKEN: ${{ github.token }}
|
||||||
|
run: |
|
||||||
|
git config --global --add safe.directory "$PWD"
|
||||||
|
git init -q .
|
||||||
|
git remote add origin "${{ github.server_url }}/${{ github.repository }}.git"
|
||||||
|
git -c http.extraheader="Authorization: basic $(printf 'x-access-token:%s' "$TOKEN" | base64 -w0)" fetch -q --depth=1 origin "${{ github.sha }}"
|
||||||
|
git checkout -q FETCH_HEAD
|
||||||
|
|
||||||
|
- name: Build image
|
||||||
|
run: |
|
||||||
|
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 (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 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
|
||||||
|
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
|
||||||
|
|
||||||
|
- name: Container logs and clean-up
|
||||||
|
if: always()
|
||||||
|
run: |
|
||||||
|
docker logs "$NAME-app" || true
|
||||||
|
docker rm -f -v "$NAME-app" || true
|
||||||
|
docker network disconnect "$NAME" "$(hostname)" || true
|
||||||
|
docker network rm "$NAME" || true
|
||||||
|
docker image rm "$NAME:image" || true
|
||||||
|
|
||||||
|
# Gitea fails a workflow that does not parse. The Ruby image has no git: the sources come as an archive.
|
||||||
|
yaml:
|
||||||
|
name: YAML check
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
container:
|
||||||
|
image: ruby:3.3-alpine
|
||||||
|
timeout-minutes: 10
|
||||||
|
steps:
|
||||||
|
- name: Workflows and compose files
|
||||||
|
env:
|
||||||
|
TOKEN: ${{ github.token }}
|
||||||
|
run: |
|
||||||
|
wget -q --header "Authorization: token $TOKEN" -O /tmp/sources.tar.gz \
|
||||||
|
"${{ github.server_url }}/api/v1/repos/${{ github.repository }}/archive/${{ github.sha }}.tar.gz"
|
||||||
|
mkdir -p /tmp/sources && tar -xzf /tmp/sources.tar.gz -C /tmp/sources
|
||||||
|
cd /tmp/sources/*/
|
||||||
|
ruby .gitea/scripts/check-yaml.rb .gitea/workflows/*.yml deploy/*.yml
|
||||||
@@ -0,0 +1,187 @@
|
|||||||
|
name: Release
|
||||||
|
|
||||||
|
# A tag vX.Y.Z[-pre] publishes the image gitea.encke-hake.ts.net/balbosoft/khaemhat:X.Y.Z (ADR 0009, 0010, 0015) and a
|
||||||
|
# Gitea release whose notes are the CHANGELOG.md section of that version (no binaries). When the version is already
|
||||||
|
# in the registry (published by scripts/publish-image.sh) the build is skipped and only the release is created.
|
||||||
|
# The runner's own image has the docker CLI and builds with the host's daemon.
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
tags: ["v*"]
|
||||||
|
workflow_dispatch:
|
||||||
|
inputs:
|
||||||
|
tag:
|
||||||
|
description: "Tag esistente da (ri)pubblicare, es. v0.0.1"
|
||||||
|
required: true
|
||||||
|
arm64:
|
||||||
|
description: "Anche linux/arm64 (richiede QEMU e buildx sull'host)"
|
||||||
|
type: boolean
|
||||||
|
default: false
|
||||||
|
|
||||||
|
permissions:
|
||||||
|
contents: write
|
||||||
|
packages: write
|
||||||
|
|
||||||
|
env:
|
||||||
|
TAG: ${{ github.event.inputs.tag || github.ref_name }}
|
||||||
|
# Where people and programs reach Gitea (the runner itself uses github.server_url). Variable PUBLIC_URL overrides it.
|
||||||
|
PUBLIC_URL: ${{ vars.PUBLIC_URL || 'https://gitea.encke-hake.ts.net' }}
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
release:
|
||||||
|
name: Image and release
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
timeout-minutes: 60
|
||||||
|
steps:
|
||||||
|
- name: Remove what cancelled jobs left
|
||||||
|
run: |
|
||||||
|
echo "NAME=khaemhat-rel-$(hostname)" >> "$GITHUB_ENV"
|
||||||
|
for c in $(docker ps -aq --filter label=khaemhat-ci.job); do
|
||||||
|
job="$(docker inspect -f '{{index .Config.Labels "khaemhat-ci.job"}}' "$c")"
|
||||||
|
docker inspect "$job" > /dev/null 2>&1 || docker rm -f -v "$c"
|
||||||
|
done
|
||||||
|
for n in $(docker network ls -q --filter label=khaemhat-ci.job); do
|
||||||
|
job="$(docker network inspect -f '{{index .Labels "khaemhat-ci.job"}}' "$n")"
|
||||||
|
docker inspect "$job" > /dev/null 2>&1 || docker network rm "$n"
|
||||||
|
done
|
||||||
|
|
||||||
|
- name: Version
|
||||||
|
run: |
|
||||||
|
case "$TAG" in
|
||||||
|
v[0-9]*.[0-9]*.[0-9]*) ;;
|
||||||
|
*) echo "::error title=Tag::$TAG is not vX.Y.Z[-pre]"; exit 1 ;;
|
||||||
|
esac
|
||||||
|
version="${TAG#v}"
|
||||||
|
prerelease=false
|
||||||
|
case "$version" in *-*) prerelease=true ;; esac
|
||||||
|
major_minor="${version%%-*}"
|
||||||
|
major_minor="${major_minor%.*}"
|
||||||
|
owner="$(printf '%s' "${{ github.repository_owner }}" | tr '[:upper:]' '[:lower:]')"
|
||||||
|
registry="${{ vars.REGISTRY }}"
|
||||||
|
registry="${registry:-$(printf '%s' "$PUBLIC_URL" | sed -E 's#^[a-z]+://##; s#/.*$##')}"
|
||||||
|
{
|
||||||
|
echo "VERSION=$version"
|
||||||
|
echo "PRERELEASE=$prerelease"
|
||||||
|
echo "MAJOR_MINOR=$major_minor"
|
||||||
|
echo "REGISTRY_HOST=$registry"
|
||||||
|
echo "IMAGE=$registry/$owner/khaemhat"
|
||||||
|
} >> "$GITHUB_ENV"
|
||||||
|
echo "Tag $TAG -> image $registry/$owner/khaemhat:$version (prerelease: $prerelease)"
|
||||||
|
|
||||||
|
- name: Checkout
|
||||||
|
env:
|
||||||
|
TOKEN: ${{ github.token }}
|
||||||
|
run: |
|
||||||
|
git config --global --add safe.directory "$PWD"
|
||||||
|
git init -q .
|
||||||
|
git remote add origin "${{ github.server_url }}/${{ github.repository }}.git"
|
||||||
|
git -c http.extraheader="Authorization: basic $(printf 'x-access-token:%s' "$TOKEN" | base64 -w0)" fetch -q --depth=1 origin "refs/tags/$TAG:refs/tags/$TAG"
|
||||||
|
git checkout -q "refs/tags/$TAG"
|
||||||
|
echo "GIT_SHA=$(git rev-parse --short HEAD)" >> "$GITHUB_ENV"
|
||||||
|
|
||||||
|
- name: Sign in to the registry
|
||||||
|
env:
|
||||||
|
USER: ${{ vars.REGISTRY_USER || github.actor }}
|
||||||
|
TOKEN: ${{ secrets.REGISTRY_TOKEN }}
|
||||||
|
run: |
|
||||||
|
if [ -z "$TOKEN" ] || ! printf '%s' "$TOKEN" | docker login "$REGISTRY_HOST" -u "$USER" --password-stdin; then
|
||||||
|
echo "::error title=Registry::Sign-in to $REGISTRY_HOST refused. The organisation secret REGISTRY_TOKEN must be an access token with package read and write."
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
status="$(curl -s -o /dev/null -w '%{http_code}' -H "Authorization: token $TOKEN" \
|
||||||
|
"${{ github.server_url }}/api/v1/packages/${{ github.repository_owner }}/container/khaemhat/$VERSION")"
|
||||||
|
if [ "$status" = "200" ]; then
|
||||||
|
echo "Version $VERSION is already in the registry: build and push skipped (ADR 0015)."
|
||||||
|
echo "PUBLISHED=true" >> "$GITHUB_ENV"
|
||||||
|
else
|
||||||
|
echo "PUBLISHED=false" >> "$GITHUB_ENV"
|
||||||
|
fi
|
||||||
|
|
||||||
|
- name: Build image
|
||||||
|
if: env.PUBLISHED != 'true'
|
||||||
|
run: |
|
||||||
|
icon="$PUBLIC_URL/${{ github.repository }}/raw/branch/main/assets/icon-256.png"
|
||||||
|
if [ -f "assets/icon-v$MAJOR_MINOR-256.png" ]; then
|
||||||
|
icon="$PUBLIC_URL/${{ github.repository }}/raw/branch/main/assets/icon-v$MAJOR_MINOR-256.png"
|
||||||
|
fi
|
||||||
|
echo "ICON_URL=$icon" >> "$GITHUB_ENV"
|
||||||
|
docker build -f docker/Dockerfile \
|
||||||
|
--build-arg VERSION="$VERSION" \
|
||||||
|
--build-arg GIT_SHA="$GIT_SHA" \
|
||||||
|
--build-arg CREATED="$(date -u +%Y-%m-%dT%H:%M:%SZ)" \
|
||||||
|
--build-arg SOURCE_URL="$PUBLIC_URL/${{ github.repository }}" \
|
||||||
|
--build-arg ICON_URL="$icon" \
|
||||||
|
--label khaemhat-ci.job="$(hostname)" \
|
||||||
|
-t "$IMAGE:$VERSION" .
|
||||||
|
|
||||||
|
- 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 \
|
||||||
|
-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")"
|
||||||
|
echo "$report"
|
||||||
|
echo "$report" | grep -q "\"version\":\"$VERSION\""
|
||||||
|
|
||||||
|
- name: Push
|
||||||
|
if: env.PUBLISHED != 'true'
|
||||||
|
run: |
|
||||||
|
docker push "$IMAGE:$VERSION"
|
||||||
|
if [ "$PRERELEASE" != "true" ]; then
|
||||||
|
docker tag "$IMAGE:$VERSION" "$IMAGE:latest"
|
||||||
|
docker push "$IMAGE:latest"
|
||||||
|
fi
|
||||||
|
echo "Image: $IMAGE:$VERSION$([ "$PRERELEASE" != "true" ] && echo " and :latest")"
|
||||||
|
|
||||||
|
- name: Multi-architecture push (arm64)
|
||||||
|
if: env.PUBLISHED != 'true' && github.event.inputs.arm64 == 'true'
|
||||||
|
run: |
|
||||||
|
docker buildx build --platform linux/amd64,linux/arm64 -f docker/Dockerfile \
|
||||||
|
--build-arg VERSION="$VERSION" --build-arg GIT_SHA="$GIT_SHA" \
|
||||||
|
--build-arg SOURCE_URL="$PUBLIC_URL/${{ github.repository }}" --build-arg ICON_URL="$ICON_URL" \
|
||||||
|
-t "$IMAGE:$VERSION" --push .
|
||||||
|
|
||||||
|
# Notes: the "## [X.Y.Z]" section of CHANGELOG.md. The release is created or, when it exists, left as it is.
|
||||||
|
- name: Gitea release
|
||||||
|
env:
|
||||||
|
TOKEN: ${{ github.token }}
|
||||||
|
run: |
|
||||||
|
api="${{ github.server_url }}/api/v1/repos/${{ github.repository }}"
|
||||||
|
if curl -fs -o /dev/null -H "Authorization: token $TOKEN" "$api/releases/tags/$TAG"; then
|
||||||
|
echo "Release $TAG already exists."
|
||||||
|
exit 0
|
||||||
|
fi
|
||||||
|
awk -v v="$VERSION" '
|
||||||
|
index($0, "## [" v "]") == 1 { on = 1; next }
|
||||||
|
on && /^## \[/ { exit }
|
||||||
|
on { print }
|
||||||
|
' CHANGELOG.md > "$RUNNER_TEMP/notes.md"
|
||||||
|
if [ ! -s "$RUNNER_TEMP/notes.md" ]; then
|
||||||
|
echo "::warning title=Changelog::No section [$VERSION] in CHANGELOG.md"
|
||||||
|
echo "Vedi CHANGELOG.md." > "$RUNNER_TEMP/notes.md"
|
||||||
|
fi
|
||||||
|
printf '\nImmagine: `%s:%s`\n' "$IMAGE" "$VERSION" >> "$RUNNER_TEMP/notes.md"
|
||||||
|
body="$(awk 'BEGIN { ORS = "\\n" } { gsub(/\r/, ""); gsub(/\\/, "\\\\"); gsub(/"/, "\\\""); gsub(/\t/, "\\t"); print }' "$RUNNER_TEMP/notes.md")"
|
||||||
|
printf '{"tag_name":"%s","name":"Khaemhat %s","body":"%s","draft":false,"prerelease":%s}' \
|
||||||
|
"$TAG" "$VERSION" "$body" "$PRERELEASE" > "$RUNNER_TEMP/release.json"
|
||||||
|
curl -fsS -X POST -H "Authorization: token $TOKEN" -H "Content-Type: application/json" \
|
||||||
|
--data-binary "@$RUNNER_TEMP/release.json" "$api/releases" > /dev/null
|
||||||
|
echo "Release $TAG created."
|
||||||
|
|
||||||
|
- name: Clean up
|
||||||
|
if: always()
|
||||||
|
run: |
|
||||||
|
docker logs "$NAME-app" 2> /dev/null || true
|
||||||
|
docker rm -f -v "$NAME-app" 2> /dev/null || true
|
||||||
|
docker network disconnect "$NAME" "$(hostname)" 2> /dev/null || true
|
||||||
|
docker network rm "$NAME" 2> /dev/null || true
|
||||||
|
docker image rm "$IMAGE:$VERSION" "$IMAGE:latest" 2> /dev/null || true
|
||||||
|
docker logout "$REGISTRY_HOST" || true
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
name: Wiki
|
||||||
|
|
||||||
|
# docs/wiki/ is the source of the Gitea wiki (ADR 0009): every push to main that touches it publishes it with
|
||||||
|
# scripts/publish-wiki.sh, which makes Khaemhat.wiki.git an exact copy. The secret WIKI_TOKEN (an access token with
|
||||||
|
# repository write) overrides the workflow's own token if that one cannot push to the wiki.
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches: [main]
|
||||||
|
paths: ["docs/wiki/**"]
|
||||||
|
workflow_dispatch:
|
||||||
|
|
||||||
|
concurrency:
|
||||||
|
group: wiki
|
||||||
|
cancel-in-progress: false
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
publish:
|
||||||
|
name: Publish the wiki
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
timeout-minutes: 10
|
||||||
|
steps:
|
||||||
|
- name: Checkout
|
||||||
|
env:
|
||||||
|
TOKEN: ${{ github.token }}
|
||||||
|
run: |
|
||||||
|
git config --global --add safe.directory "$PWD"
|
||||||
|
git init -q .
|
||||||
|
git remote add origin "${{ github.server_url }}/${{ github.repository }}.git"
|
||||||
|
git -c http.extraheader="Authorization: basic $(printf 'x-access-token:%s' "$TOKEN" | base64 -w0)" fetch -q --depth=1 origin "${{ github.sha }}"
|
||||||
|
git checkout -q FETCH_HEAD
|
||||||
|
|
||||||
|
- name: Publish docs/wiki
|
||||||
|
env:
|
||||||
|
GITEA_TOKEN: ${{ secrets.WIKI_TOKEN || github.token }}
|
||||||
|
WIKI_REMOTE: ${{ github.server_url }}/${{ github.repository }}.wiki.git
|
||||||
|
GIT_AUTHOR_NAME: Khaemhat CI
|
||||||
|
GIT_AUTHOR_EMAIL: ci@khaemhat.invalid
|
||||||
|
run: bash scripts/publish-wiki.sh
|
||||||
@@ -414,3 +414,14 @@ FodyWeavers.xsd
|
|||||||
# Built Visual Studio Code Extensions
|
# Built Visual Studio Code Extensions
|
||||||
*.vsix
|
*.vsix
|
||||||
|
|
||||||
|
|
||||||
|
# Khaemhat
|
||||||
|
# Real deploy settings and secrets never go to the repository (deploy/.env.example is the template).
|
||||||
|
.env
|
||||||
|
deploy/.env
|
||||||
|
# Local development data (scripts/run-dev.sh) and test output.
|
||||||
|
.data/
|
||||||
|
out/
|
||||||
|
# License signing keys (tools/Khaemhat.LicenseTool): the private key never enters the repository (ADR 0008).
|
||||||
|
*.khkey
|
||||||
|
*.pem
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
{
|
||||||
|
"recommendations": [
|
||||||
|
"ms-dotnettools.csdevkit",
|
||||||
|
"ms-dotnettools.csharp",
|
||||||
|
"editorconfig.editorconfig",
|
||||||
|
"ms-azuretools.vscode-docker"
|
||||||
|
]
|
||||||
|
}
|
||||||
@@ -0,0 +1,70 @@
|
|||||||
|
{
|
||||||
|
// Debug di Khaemhat da Visual Studio Code (estensione C# / C# Dev Kit, vedi extensions.json).
|
||||||
|
// Le variabili sono quelle di scripts/run-dev.sh: SQLite in .data/dev, licenze di test, solo per sviluppo.
|
||||||
|
"version": "0.2.0",
|
||||||
|
"configurations": [
|
||||||
|
{
|
||||||
|
"name": "Khaemhat (web, SQLite)",
|
||||||
|
"type": "coreclr",
|
||||||
|
"request": "launch",
|
||||||
|
"preLaunchTask": "build",
|
||||||
|
"program": "${workspaceFolder}/src/Khaemhat.Web/bin/Debug/net10.0/Khaemhat.Web.dll",
|
||||||
|
"args": ["--urls", "http://localhost:5080"],
|
||||||
|
"cwd": "${workspaceFolder}/src/Khaemhat.Web",
|
||||||
|
"stopAtEntry": false,
|
||||||
|
"console": "internalConsole",
|
||||||
|
"serverReadyAction": {
|
||||||
|
"action": "openExternally",
|
||||||
|
"pattern": "Now listening on:\\s+(https?://\\S+)"
|
||||||
|
},
|
||||||
|
"env": {
|
||||||
|
"ASPNETCORE_ENVIRONMENT": "Development",
|
||||||
|
"KHAEMHAT_DATA_DIR": "${workspaceFolder}/.data/dev",
|
||||||
|
"KHAEMHAT_SYSTEM_DB": "sqlite:///${workspaceFolder}/.data/dev/system.db",
|
||||||
|
"KHAEMHAT_SECRET_KEY": "a2hhZW1oYXQtZGV2ZWxvcG1lbnQtb25seS1ub3QtYS1zZWNyZXQ=",
|
||||||
|
"KHAEMHAT_SUPERUSER": "root",
|
||||||
|
"KHAEMHAT_SUPERUSER_PASSWORD": "Khaemhat-dev-1",
|
||||||
|
"KHAEMHAT_COMPANY_CODE": "DEMO",
|
||||||
|
"KHAEMHAT_COMPANY_NAME": "Khaemhat Demo S.r.l.",
|
||||||
|
"KHAEMHAT_LICENSE_MODE": "test",
|
||||||
|
"KHAEMHAT_SEED_DEMO": "true",
|
||||||
|
"KHAEMHAT_LOG_LEVEL": "Debug"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Khaemhat (web, PostgreSQL)",
|
||||||
|
"type": "coreclr",
|
||||||
|
"request": "launch",
|
||||||
|
"preLaunchTask": "build",
|
||||||
|
"program": "${workspaceFolder}/src/Khaemhat.Web/bin/Debug/net10.0/Khaemhat.Web.dll",
|
||||||
|
"args": ["--urls", "http://localhost:5080"],
|
||||||
|
"cwd": "${workspaceFolder}/src/Khaemhat.Web",
|
||||||
|
"console": "internalConsole",
|
||||||
|
"serverReadyAction": {
|
||||||
|
"action": "openExternally",
|
||||||
|
"pattern": "Now listening on:\\s+(https?://\\S+)"
|
||||||
|
},
|
||||||
|
// Server locale, ad esempio: docker run -d --name khaemhat-pg -p 5432:5432 -e POSTGRES_USER=khaemhat
|
||||||
|
// -e POSTGRES_PASSWORD=khaemhat-dev -e POSTGRES_DB=khaemhat_system postgres:17
|
||||||
|
"env": {
|
||||||
|
"ASPNETCORE_ENVIRONMENT": "Development",
|
||||||
|
"KHAEMHAT_DATA_DIR": "${workspaceFolder}/.data/dev-pg",
|
||||||
|
"KHAEMHAT_SYSTEM_DB": "postgres://khaemhat:khaemhat-dev@localhost:5432/khaemhat_system",
|
||||||
|
"KHAEMHAT_DB_SERVER": "postgres://khaemhat:khaemhat-dev@localhost:5432/",
|
||||||
|
"KHAEMHAT_SECRET_KEY": "a2hhZW1oYXQtZGV2ZWxvcG1lbnQtb25seS1ub3QtYS1zZWNyZXQ=",
|
||||||
|
"KHAEMHAT_SUPERUSER": "root",
|
||||||
|
"KHAEMHAT_SUPERUSER_PASSWORD": "Khaemhat-dev-1",
|
||||||
|
"KHAEMHAT_COMPANY_CODE": "DEMO",
|
||||||
|
"KHAEMHAT_COMPANY_NAME": "Khaemhat Demo S.r.l.",
|
||||||
|
"KHAEMHAT_LICENSE_MODE": "test",
|
||||||
|
"KHAEMHAT_SEED_DEMO": "true",
|
||||||
|
"KHAEMHAT_LOG_LEVEL": "Debug"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Collega a un processo",
|
||||||
|
"type": "coreclr",
|
||||||
|
"request": "attach"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
@@ -0,0 +1,51 @@
|
|||||||
|
{
|
||||||
|
// Attività di Visual Studio Code: Terminale > Esegui attività. "build" è quella usata dal debug (launch.json).
|
||||||
|
"version": "2.0.0",
|
||||||
|
"tasks": [
|
||||||
|
{
|
||||||
|
"label": "build",
|
||||||
|
"type": "process",
|
||||||
|
"command": "dotnet",
|
||||||
|
"args": ["build", "${workspaceFolder}/Khaemhat.sln", "-c", "Debug", "/property:GenerateFullPaths=true", "/consoleloggerparameters:NoSummary"],
|
||||||
|
"group": { "kind": "build", "isDefault": true },
|
||||||
|
"problemMatcher": "$msCompile"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"label": "test",
|
||||||
|
"type": "process",
|
||||||
|
"command": "dotnet",
|
||||||
|
"args": ["test", "${workspaceFolder}/Khaemhat.sln", "-c", "Debug", "/property:GenerateFullPaths=true"],
|
||||||
|
"options": { "env": { "KHAEMHAT_LICENSE_MODE": "test" } },
|
||||||
|
"group": { "kind": "test", "isDefault": true },
|
||||||
|
"problemMatcher": "$msCompile"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"label": "watch (web)",
|
||||||
|
"type": "process",
|
||||||
|
"command": "dotnet",
|
||||||
|
"args": ["watch", "run", "--project", "${workspaceFolder}/src/Khaemhat.Web", "--", "--urls", "http://localhost:5080"],
|
||||||
|
"options": {
|
||||||
|
"env": {
|
||||||
|
"ASPNETCORE_ENVIRONMENT": "Development",
|
||||||
|
"KHAEMHAT_DATA_DIR": "${workspaceFolder}/.data/dev",
|
||||||
|
"KHAEMHAT_SYSTEM_DB": "sqlite:///${workspaceFolder}/.data/dev/system.db",
|
||||||
|
"KHAEMHAT_LICENSE_MODE": "test"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"isBackground": true,
|
||||||
|
"problemMatcher": "$msCompile"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"label": "check-packages",
|
||||||
|
"type": "shell",
|
||||||
|
"command": "bash scripts/check-packages.sh",
|
||||||
|
"problemMatcher": []
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"label": "docker build",
|
||||||
|
"type": "shell",
|
||||||
|
"command": "docker build -f docker/Dockerfile -t khaemhat:dev .",
|
||||||
|
"problemMatcher": []
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
@@ -7,6 +7,178 @@ un'immagine `gitea.encke-hake.ts.net/balbosoft/khaemhat:X.Y.Z`.
|
|||||||
|
|
||||||
## [Unreleased]
|
## [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.
|
||||||
|
|
||||||
|
### Added
|
||||||
|
- Soluzione `Khaemhat.sln` con i progetti di SPEC §3 e i relativi progetti di test (MSTest); regole di build comuni,
|
||||||
|
warning come errori, analyzer, `.editorconfig`, Central Package Management con l'allowlist dei pacchetti.
|
||||||
|
- Test architetturali: riferimenti fra progetti ammessi da SPEC §3 e pacchetti ammessi da SPEC §1.2;
|
||||||
|
`scripts/check-packages.sh` fa lo stesso controllo prima di ogni build.
|
||||||
|
- Pagina "in costruzione" in italiano con marca, icone e versione; pagine di errore e 404.
|
||||||
|
- Endpoint di salute `/health/live`, `/health/ready` e `/health` con stato e versione (ADR 0012).
|
||||||
|
- Variabili `KHAEMHAT_URLS` e `KHAEMHAT_LOG_LEVEL`; log JSON su stdout fuori dallo sviluppo.
|
||||||
|
- Immagine Docker `gitea.encke-hake.ts.net/balbosoft/khaemhat`: multi-stage, utente non root con `PUID`/`PGID`
|
||||||
|
(ADR 0013), `pg_dump` 17, `HEALTHCHECK`, etichette OCI e Unraid, `restore-system.sh` incluso (ADR 0017).
|
||||||
|
- `deploy/docker-compose.yml` (PostgreSQL 17, Redis facoltativo) e `deploy/docker-compose.sqlite.yml` (demo);
|
||||||
|
versione dell'immagine scelta con `KHAEMHAT_VERSION`.
|
||||||
|
- Gitea Actions: `ci.yml` (build, test, immagine con smoke test, PostgreSQL 16/17 sui tag, controllo YAML),
|
||||||
|
`release.yml` (immagine e release dal tag, ADR 0015), `wiki.yml` (pubblicazione della wiki).
|
||||||
|
- Script `build.sh`, `test.sh`, `run-dev.sh`, `publish-image.sh`, `publish-wiki.sh` e stub delle milestone successive.
|
||||||
|
- Configurazioni di Visual Studio Code per debug, attività ed estensioni consigliate (`.vscode/`).
|
||||||
|
- ADR 0012-0017 sui punti aperti di M0 (salute, utente, varianti `_FILE`, tag e pubblicazione, icona versionata,
|
||||||
|
script di ripristino).
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
- I file di `deploy/` puntano alla versione `0.0.1` e all'icona non versionata fino alla 1.0 (ADR 0016).
|
||||||
|
|
||||||
|
## Preparazione - 2026-11-10
|
||||||
|
|
||||||
|
Documentazione e pianificazione, nessun codice e nessun tag.
|
||||||
|
|
||||||
### Added
|
### Added
|
||||||
- Specifica di progetto in `docs/SPEC.md` ed emendamenti in `CLAUDE.md` (Gitea al posto di GitHub, solo Docker).
|
- Specifica di progetto in `docs/SPEC.md` ed emendamenti in `CLAUDE.md` (Gitea al posto di GitHub, solo Docker).
|
||||||
- ADR 0001-0011 sulle decisioni di base.
|
- ADR 0001-0011 sulle decisioni di base.
|
||||||
|
|||||||
@@ -0,0 +1,38 @@
|
|||||||
|
<Project>
|
||||||
|
<!-- Shared build rules for every project (SPEC §1.1, §1.11, §2 Versioning; ADR 0001). -->
|
||||||
|
<PropertyGroup>
|
||||||
|
<TargetFramework>net10.0</TargetFramework>
|
||||||
|
<LangVersion>14</LangVersion>
|
||||||
|
<Nullable>enable</Nullable>
|
||||||
|
<ImplicitUsings>enable</ImplicitUsings>
|
||||||
|
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
|
||||||
|
<AnalysisLevel>latest</AnalysisLevel>
|
||||||
|
<AnalysisMode>Recommended</AnalysisMode>
|
||||||
|
<EnforceCodeStyleInBuild>true</EnforceCodeStyleInBuild>
|
||||||
|
<GenerateDocumentationFile>true</GenerateDocumentationFile>
|
||||||
|
<Deterministic>true</Deterministic>
|
||||||
|
<InvariantGlobalization>false</InvariantGlobalization>
|
||||||
|
<SatelliteResourceLanguages>it;en</SatelliteResourceLanguages>
|
||||||
|
<NeutralLanguage>it-IT</NeutralLanguage>
|
||||||
|
|
||||||
|
<Company>BalboSoft</Company>
|
||||||
|
<Product>Khaemhat</Product>
|
||||||
|
<Copyright>BalboSoft</Copyright>
|
||||||
|
<RepositoryUrl>https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat</RepositoryUrl>
|
||||||
|
|
||||||
|
<!--
|
||||||
|
Version: SemVer from the git tag (vX.Y.Z). Release builds pass it explicitly
|
||||||
|
(/p:Version=X.Y.Z /p:SourceRevisionId=<sha>, see docker/Dockerfile and scripts/build.sh);
|
||||||
|
a plain local build asks git through the KhaemhatGitVersion target below.
|
||||||
|
-->
|
||||||
|
<Version Condition="'$(Version)' == ''">0.0.0-dev</Version>
|
||||||
|
<IncludeSourceRevisionInInformationalVersion>true</IncludeSourceRevisionInInformationalVersion>
|
||||||
|
</PropertyGroup>
|
||||||
|
|
||||||
|
<PropertyGroup Condition="$(MSBuildProjectName.EndsWith('.Tests'))">
|
||||||
|
<IsPackable>false</IsPackable>
|
||||||
|
<IsTestProject>true</IsTestProject>
|
||||||
|
<!-- Test methods are public by MSTest convention; XML docs are not required on them (the file stays on for IDE0005). -->
|
||||||
|
<NoWarn>$(NoWarn);CS1591</NoWarn>
|
||||||
|
</PropertyGroup>
|
||||||
|
</Project>
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
<Project>
|
||||||
|
<!--
|
||||||
|
Local builds without an explicit version read it from git: the nearest tag vX.Y.Z (as X.Y.Z) and the short
|
||||||
|
commit. Release builds pass /p:Version, and the Docker build context has no .git, so they skip this target.
|
||||||
|
-->
|
||||||
|
<Target Name="KhaemhatGitVersion" BeforeTargets="GetAssemblyVersion;GenerateAssemblyInfo"
|
||||||
|
Condition="'$(Version)' == '0.0.0-dev' And Exists('$(MSBuildThisFileDirectory).git')">
|
||||||
|
<Exec Command="git describe --tags --match v[0-9]* --abbrev=0" ConsoleToMSBuild="true" IgnoreExitCode="true"
|
||||||
|
StandardOutputImportance="low" StandardErrorImportance="low" WorkingDirectory="$(MSBuildThisFileDirectory)">
|
||||||
|
<Output TaskParameter="ConsoleOutput" PropertyName="_KhGitTag" />
|
||||||
|
<Output TaskParameter="ExitCode" PropertyName="_KhGitTagExit" />
|
||||||
|
</Exec>
|
||||||
|
<Exec Command="git rev-parse --short HEAD" ConsoleToMSBuild="true" IgnoreExitCode="true"
|
||||||
|
StandardOutputImportance="low" StandardErrorImportance="low" WorkingDirectory="$(MSBuildThisFileDirectory)">
|
||||||
|
<Output TaskParameter="ConsoleOutput" PropertyName="_KhGitSha" />
|
||||||
|
</Exec>
|
||||||
|
<PropertyGroup>
|
||||||
|
<Version Condition="'$(_KhGitTagExit)' == '0' And '$(_KhGitTag)' != ''">$(_KhGitTag.TrimStart('v'))-dev</Version>
|
||||||
|
<SourceRevisionId Condition="'$(SourceRevisionId)' == ''">$(_KhGitSha)</SourceRevisionId>
|
||||||
|
</PropertyGroup>
|
||||||
|
</Target>
|
||||||
|
</Project>
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
<Project>
|
||||||
|
<!--
|
||||||
|
Central Package Management: the ONLY packages Khaemhat may use (SPEC §1.2, ADR 0002).
|
||||||
|
Anything else is written in the repository. scripts/check-packages.sh and the architecture tests
|
||||||
|
fail the build if a PackageReference outside this list appears, or a test package lands outside tests/.
|
||||||
|
-->
|
||||||
|
<PropertyGroup>
|
||||||
|
<ManagePackageVersionsCentrally>true</ManagePackageVersionsCentrally>
|
||||||
|
<CentralPackageTransitivePinningEnabled>false</CentralPackageTransitivePinningEnabled>
|
||||||
|
</PropertyGroup>
|
||||||
|
<ItemGroup Label="Database providers (runtime)">
|
||||||
|
<PackageVersion Include="Npgsql" Version="10.0.3" />
|
||||||
|
<PackageVersion Include="Microsoft.Data.Sqlite" Version="10.0.15" />
|
||||||
|
</ItemGroup>
|
||||||
|
<ItemGroup Label="Tests only (never in the image)">
|
||||||
|
<PackageVersion Include="Microsoft.NET.Test.Sdk" Version="18.11.1" />
|
||||||
|
<PackageVersion Include="MSTest" Version="4.5.2" />
|
||||||
|
</ItemGroup>
|
||||||
|
</Project>
|
||||||
@@ -0,0 +1,283 @@
|
|||||||
|
|
||||||
|
Microsoft Visual Studio Solution File, Format Version 12.00
|
||||||
|
# Visual Studio Version 17
|
||||||
|
VisualStudioVersion = 17.0.31903.59
|
||||||
|
MinimumVisualStudioVersion = 10.0.40219.1
|
||||||
|
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{827E0CD3-B72D-47B6-A68D-7590B98EB39B}"
|
||||||
|
EndProject
|
||||||
|
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Khaemhat.Application", "src\Khaemhat.Application\Khaemhat.Application.csproj", "{6A70BA3E-47A7-40EC-AF2A-FB6FA9BFD6C5}"
|
||||||
|
EndProject
|
||||||
|
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Khaemhat.Core", "src\Khaemhat.Core\Khaemhat.Core.csproj", "{B212CA0C-F7FF-4223-8FC5-961116D937B8}"
|
||||||
|
EndProject
|
||||||
|
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Khaemhat.Data", "src\Khaemhat.Data\Khaemhat.Data.csproj", "{6A4CD6EB-E529-4A76-B028-CFF8F5D59E2F}"
|
||||||
|
EndProject
|
||||||
|
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Khaemhat.Infrastructure", "src\Khaemhat.Infrastructure\Khaemhat.Infrastructure.csproj", "{4E7F3565-DD8A-4B25-BB27-7090F1144F4C}"
|
||||||
|
EndProject
|
||||||
|
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Khaemhat.Fiscal.Abstractions", "src\Khaemhat.Fiscal.Abstractions\Khaemhat.Fiscal.Abstractions.csproj", "{F0A94F81-8CAB-4803-A209-C7E350160726}"
|
||||||
|
EndProject
|
||||||
|
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Khaemhat.Data.PostgreSql", "src\Khaemhat.Data.PostgreSql\Khaemhat.Data.PostgreSql.csproj", "{37AAC975-29AB-4649-A961-4115005042F1}"
|
||||||
|
EndProject
|
||||||
|
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Khaemhat.Data.Sqlite", "src\Khaemhat.Data.Sqlite\Khaemhat.Data.Sqlite.csproj", "{EF1EDA79-1E49-41CB-AF44-1C1ACC94611F}"
|
||||||
|
EndProject
|
||||||
|
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Khaemhat.Fiscal.Italy", "src\Khaemhat.Fiscal.Italy\Khaemhat.Fiscal.Italy.csproj", "{0CAFB3CA-3C92-4816-A63A-4670D7AD2302}"
|
||||||
|
EndProject
|
||||||
|
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Khaemhat.Web", "src\Khaemhat.Web\Khaemhat.Web.csproj", "{64DD5604-A3E4-45C0-9588-A1E38363C0C9}"
|
||||||
|
EndProject
|
||||||
|
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "tests", "tests", "{0AB3BF05-4346-4AA6-1389-037BE0695223}"
|
||||||
|
EndProject
|
||||||
|
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Khaemhat.Application.Tests", "tests\Khaemhat.Application.Tests\Khaemhat.Application.Tests.csproj", "{8BE00CC7-FE33-412E-8CE5-86425869D301}"
|
||||||
|
EndProject
|
||||||
|
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Khaemhat.Core.Tests", "tests\Khaemhat.Core.Tests\Khaemhat.Core.Tests.csproj", "{F6C68A01-8C27-47D5-8C45-E2D00D9BC32D}"
|
||||||
|
EndProject
|
||||||
|
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Khaemhat.Data.Tests", "tests\Khaemhat.Data.Tests\Khaemhat.Data.Tests.csproj", "{AD3903F9-037E-48AE-B555-84345C4895E0}"
|
||||||
|
EndProject
|
||||||
|
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Khaemhat.Fiscal.Italy.Tests", "tests\Khaemhat.Fiscal.Italy.Tests\Khaemhat.Fiscal.Italy.Tests.csproj", "{ECD0F91C-C8D7-4686-9609-56F2A93F4113}"
|
||||||
|
EndProject
|
||||||
|
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Khaemhat.Infrastructure.Tests", "tests\Khaemhat.Infrastructure.Tests\Khaemhat.Infrastructure.Tests.csproj", "{C5C8124F-3B12-43A9-BD0F-5AA5F7261699}"
|
||||||
|
EndProject
|
||||||
|
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Khaemhat.Web.Tests", "tests\Khaemhat.Web.Tests\Khaemhat.Web.Tests.csproj", "{FDCAC352-BB40-4B5E-948A-2CDAA48B9E6A}"
|
||||||
|
EndProject
|
||||||
|
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "tools", "tools", "{07C2787E-EAC7-C090-1BA3-A61EC2A24D84}"
|
||||||
|
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
|
||||||
|
Debug|x64 = Debug|x64
|
||||||
|
Debug|x86 = Debug|x86
|
||||||
|
Release|Any CPU = Release|Any CPU
|
||||||
|
Release|x64 = Release|x64
|
||||||
|
Release|x86 = Release|x86
|
||||||
|
EndGlobalSection
|
||||||
|
GlobalSection(ProjectConfigurationPlatforms) = postSolution
|
||||||
|
{6A70BA3E-47A7-40EC-AF2A-FB6FA9BFD6C5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||||
|
{6A70BA3E-47A7-40EC-AF2A-FB6FA9BFD6C5}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||||
|
{6A70BA3E-47A7-40EC-AF2A-FB6FA9BFD6C5}.Debug|x64.ActiveCfg = Debug|Any CPU
|
||||||
|
{6A70BA3E-47A7-40EC-AF2A-FB6FA9BFD6C5}.Debug|x64.Build.0 = Debug|Any CPU
|
||||||
|
{6A70BA3E-47A7-40EC-AF2A-FB6FA9BFD6C5}.Debug|x86.ActiveCfg = Debug|Any CPU
|
||||||
|
{6A70BA3E-47A7-40EC-AF2A-FB6FA9BFD6C5}.Debug|x86.Build.0 = Debug|Any CPU
|
||||||
|
{6A70BA3E-47A7-40EC-AF2A-FB6FA9BFD6C5}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||||
|
{6A70BA3E-47A7-40EC-AF2A-FB6FA9BFD6C5}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||||
|
{6A70BA3E-47A7-40EC-AF2A-FB6FA9BFD6C5}.Release|x64.ActiveCfg = Release|Any CPU
|
||||||
|
{6A70BA3E-47A7-40EC-AF2A-FB6FA9BFD6C5}.Release|x64.Build.0 = Release|Any CPU
|
||||||
|
{6A70BA3E-47A7-40EC-AF2A-FB6FA9BFD6C5}.Release|x86.ActiveCfg = Release|Any CPU
|
||||||
|
{6A70BA3E-47A7-40EC-AF2A-FB6FA9BFD6C5}.Release|x86.Build.0 = Release|Any CPU
|
||||||
|
{B212CA0C-F7FF-4223-8FC5-961116D937B8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||||
|
{B212CA0C-F7FF-4223-8FC5-961116D937B8}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||||
|
{B212CA0C-F7FF-4223-8FC5-961116D937B8}.Debug|x64.ActiveCfg = Debug|Any CPU
|
||||||
|
{B212CA0C-F7FF-4223-8FC5-961116D937B8}.Debug|x64.Build.0 = Debug|Any CPU
|
||||||
|
{B212CA0C-F7FF-4223-8FC5-961116D937B8}.Debug|x86.ActiveCfg = Debug|Any CPU
|
||||||
|
{B212CA0C-F7FF-4223-8FC5-961116D937B8}.Debug|x86.Build.0 = Debug|Any CPU
|
||||||
|
{B212CA0C-F7FF-4223-8FC5-961116D937B8}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||||
|
{B212CA0C-F7FF-4223-8FC5-961116D937B8}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||||
|
{B212CA0C-F7FF-4223-8FC5-961116D937B8}.Release|x64.ActiveCfg = Release|Any CPU
|
||||||
|
{B212CA0C-F7FF-4223-8FC5-961116D937B8}.Release|x64.Build.0 = Release|Any CPU
|
||||||
|
{B212CA0C-F7FF-4223-8FC5-961116D937B8}.Release|x86.ActiveCfg = Release|Any CPU
|
||||||
|
{B212CA0C-F7FF-4223-8FC5-961116D937B8}.Release|x86.Build.0 = Release|Any CPU
|
||||||
|
{6A4CD6EB-E529-4A76-B028-CFF8F5D59E2F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||||
|
{6A4CD6EB-E529-4A76-B028-CFF8F5D59E2F}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||||
|
{6A4CD6EB-E529-4A76-B028-CFF8F5D59E2F}.Debug|x64.ActiveCfg = Debug|Any CPU
|
||||||
|
{6A4CD6EB-E529-4A76-B028-CFF8F5D59E2F}.Debug|x64.Build.0 = Debug|Any CPU
|
||||||
|
{6A4CD6EB-E529-4A76-B028-CFF8F5D59E2F}.Debug|x86.ActiveCfg = Debug|Any CPU
|
||||||
|
{6A4CD6EB-E529-4A76-B028-CFF8F5D59E2F}.Debug|x86.Build.0 = Debug|Any CPU
|
||||||
|
{6A4CD6EB-E529-4A76-B028-CFF8F5D59E2F}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||||
|
{6A4CD6EB-E529-4A76-B028-CFF8F5D59E2F}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||||
|
{6A4CD6EB-E529-4A76-B028-CFF8F5D59E2F}.Release|x64.ActiveCfg = Release|Any CPU
|
||||||
|
{6A4CD6EB-E529-4A76-B028-CFF8F5D59E2F}.Release|x64.Build.0 = Release|Any CPU
|
||||||
|
{6A4CD6EB-E529-4A76-B028-CFF8F5D59E2F}.Release|x86.ActiveCfg = Release|Any CPU
|
||||||
|
{6A4CD6EB-E529-4A76-B028-CFF8F5D59E2F}.Release|x86.Build.0 = Release|Any CPU
|
||||||
|
{4E7F3565-DD8A-4B25-BB27-7090F1144F4C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||||
|
{4E7F3565-DD8A-4B25-BB27-7090F1144F4C}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||||
|
{4E7F3565-DD8A-4B25-BB27-7090F1144F4C}.Debug|x64.ActiveCfg = Debug|Any CPU
|
||||||
|
{4E7F3565-DD8A-4B25-BB27-7090F1144F4C}.Debug|x64.Build.0 = Debug|Any CPU
|
||||||
|
{4E7F3565-DD8A-4B25-BB27-7090F1144F4C}.Debug|x86.ActiveCfg = Debug|Any CPU
|
||||||
|
{4E7F3565-DD8A-4B25-BB27-7090F1144F4C}.Debug|x86.Build.0 = Debug|Any CPU
|
||||||
|
{4E7F3565-DD8A-4B25-BB27-7090F1144F4C}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||||
|
{4E7F3565-DD8A-4B25-BB27-7090F1144F4C}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||||
|
{4E7F3565-DD8A-4B25-BB27-7090F1144F4C}.Release|x64.ActiveCfg = Release|Any CPU
|
||||||
|
{4E7F3565-DD8A-4B25-BB27-7090F1144F4C}.Release|x64.Build.0 = Release|Any CPU
|
||||||
|
{4E7F3565-DD8A-4B25-BB27-7090F1144F4C}.Release|x86.ActiveCfg = Release|Any CPU
|
||||||
|
{4E7F3565-DD8A-4B25-BB27-7090F1144F4C}.Release|x86.Build.0 = Release|Any CPU
|
||||||
|
{F0A94F81-8CAB-4803-A209-C7E350160726}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||||
|
{F0A94F81-8CAB-4803-A209-C7E350160726}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||||
|
{F0A94F81-8CAB-4803-A209-C7E350160726}.Debug|x64.ActiveCfg = Debug|Any CPU
|
||||||
|
{F0A94F81-8CAB-4803-A209-C7E350160726}.Debug|x64.Build.0 = Debug|Any CPU
|
||||||
|
{F0A94F81-8CAB-4803-A209-C7E350160726}.Debug|x86.ActiveCfg = Debug|Any CPU
|
||||||
|
{F0A94F81-8CAB-4803-A209-C7E350160726}.Debug|x86.Build.0 = Debug|Any CPU
|
||||||
|
{F0A94F81-8CAB-4803-A209-C7E350160726}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||||
|
{F0A94F81-8CAB-4803-A209-C7E350160726}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||||
|
{F0A94F81-8CAB-4803-A209-C7E350160726}.Release|x64.ActiveCfg = Release|Any CPU
|
||||||
|
{F0A94F81-8CAB-4803-A209-C7E350160726}.Release|x64.Build.0 = Release|Any CPU
|
||||||
|
{F0A94F81-8CAB-4803-A209-C7E350160726}.Release|x86.ActiveCfg = Release|Any CPU
|
||||||
|
{F0A94F81-8CAB-4803-A209-C7E350160726}.Release|x86.Build.0 = Release|Any CPU
|
||||||
|
{37AAC975-29AB-4649-A961-4115005042F1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||||
|
{37AAC975-29AB-4649-A961-4115005042F1}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||||
|
{37AAC975-29AB-4649-A961-4115005042F1}.Debug|x64.ActiveCfg = Debug|Any CPU
|
||||||
|
{37AAC975-29AB-4649-A961-4115005042F1}.Debug|x64.Build.0 = Debug|Any CPU
|
||||||
|
{37AAC975-29AB-4649-A961-4115005042F1}.Debug|x86.ActiveCfg = Debug|Any CPU
|
||||||
|
{37AAC975-29AB-4649-A961-4115005042F1}.Debug|x86.Build.0 = Debug|Any CPU
|
||||||
|
{37AAC975-29AB-4649-A961-4115005042F1}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||||
|
{37AAC975-29AB-4649-A961-4115005042F1}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||||
|
{37AAC975-29AB-4649-A961-4115005042F1}.Release|x64.ActiveCfg = Release|Any CPU
|
||||||
|
{37AAC975-29AB-4649-A961-4115005042F1}.Release|x64.Build.0 = Release|Any CPU
|
||||||
|
{37AAC975-29AB-4649-A961-4115005042F1}.Release|x86.ActiveCfg = Release|Any CPU
|
||||||
|
{37AAC975-29AB-4649-A961-4115005042F1}.Release|x86.Build.0 = Release|Any CPU
|
||||||
|
{EF1EDA79-1E49-41CB-AF44-1C1ACC94611F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||||
|
{EF1EDA79-1E49-41CB-AF44-1C1ACC94611F}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||||
|
{EF1EDA79-1E49-41CB-AF44-1C1ACC94611F}.Debug|x64.ActiveCfg = Debug|Any CPU
|
||||||
|
{EF1EDA79-1E49-41CB-AF44-1C1ACC94611F}.Debug|x64.Build.0 = Debug|Any CPU
|
||||||
|
{EF1EDA79-1E49-41CB-AF44-1C1ACC94611F}.Debug|x86.ActiveCfg = Debug|Any CPU
|
||||||
|
{EF1EDA79-1E49-41CB-AF44-1C1ACC94611F}.Debug|x86.Build.0 = Debug|Any CPU
|
||||||
|
{EF1EDA79-1E49-41CB-AF44-1C1ACC94611F}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||||
|
{EF1EDA79-1E49-41CB-AF44-1C1ACC94611F}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||||
|
{EF1EDA79-1E49-41CB-AF44-1C1ACC94611F}.Release|x64.ActiveCfg = Release|Any CPU
|
||||||
|
{EF1EDA79-1E49-41CB-AF44-1C1ACC94611F}.Release|x64.Build.0 = Release|Any CPU
|
||||||
|
{EF1EDA79-1E49-41CB-AF44-1C1ACC94611F}.Release|x86.ActiveCfg = Release|Any CPU
|
||||||
|
{EF1EDA79-1E49-41CB-AF44-1C1ACC94611F}.Release|x86.Build.0 = Release|Any CPU
|
||||||
|
{0CAFB3CA-3C92-4816-A63A-4670D7AD2302}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||||
|
{0CAFB3CA-3C92-4816-A63A-4670D7AD2302}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||||
|
{0CAFB3CA-3C92-4816-A63A-4670D7AD2302}.Debug|x64.ActiveCfg = Debug|Any CPU
|
||||||
|
{0CAFB3CA-3C92-4816-A63A-4670D7AD2302}.Debug|x64.Build.0 = Debug|Any CPU
|
||||||
|
{0CAFB3CA-3C92-4816-A63A-4670D7AD2302}.Debug|x86.ActiveCfg = Debug|Any CPU
|
||||||
|
{0CAFB3CA-3C92-4816-A63A-4670D7AD2302}.Debug|x86.Build.0 = Debug|Any CPU
|
||||||
|
{0CAFB3CA-3C92-4816-A63A-4670D7AD2302}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||||
|
{0CAFB3CA-3C92-4816-A63A-4670D7AD2302}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||||
|
{0CAFB3CA-3C92-4816-A63A-4670D7AD2302}.Release|x64.ActiveCfg = Release|Any CPU
|
||||||
|
{0CAFB3CA-3C92-4816-A63A-4670D7AD2302}.Release|x64.Build.0 = Release|Any CPU
|
||||||
|
{0CAFB3CA-3C92-4816-A63A-4670D7AD2302}.Release|x86.ActiveCfg = Release|Any CPU
|
||||||
|
{0CAFB3CA-3C92-4816-A63A-4670D7AD2302}.Release|x86.Build.0 = Release|Any CPU
|
||||||
|
{64DD5604-A3E4-45C0-9588-A1E38363C0C9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||||
|
{64DD5604-A3E4-45C0-9588-A1E38363C0C9}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||||
|
{64DD5604-A3E4-45C0-9588-A1E38363C0C9}.Debug|x64.ActiveCfg = Debug|Any CPU
|
||||||
|
{64DD5604-A3E4-45C0-9588-A1E38363C0C9}.Debug|x64.Build.0 = Debug|Any CPU
|
||||||
|
{64DD5604-A3E4-45C0-9588-A1E38363C0C9}.Debug|x86.ActiveCfg = Debug|Any CPU
|
||||||
|
{64DD5604-A3E4-45C0-9588-A1E38363C0C9}.Debug|x86.Build.0 = Debug|Any CPU
|
||||||
|
{64DD5604-A3E4-45C0-9588-A1E38363C0C9}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||||
|
{64DD5604-A3E4-45C0-9588-A1E38363C0C9}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||||
|
{64DD5604-A3E4-45C0-9588-A1E38363C0C9}.Release|x64.ActiveCfg = Release|Any CPU
|
||||||
|
{64DD5604-A3E4-45C0-9588-A1E38363C0C9}.Release|x64.Build.0 = Release|Any CPU
|
||||||
|
{64DD5604-A3E4-45C0-9588-A1E38363C0C9}.Release|x86.ActiveCfg = Release|Any CPU
|
||||||
|
{64DD5604-A3E4-45C0-9588-A1E38363C0C9}.Release|x86.Build.0 = Release|Any CPU
|
||||||
|
{8BE00CC7-FE33-412E-8CE5-86425869D301}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||||
|
{8BE00CC7-FE33-412E-8CE5-86425869D301}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||||
|
{8BE00CC7-FE33-412E-8CE5-86425869D301}.Debug|x64.ActiveCfg = Debug|Any CPU
|
||||||
|
{8BE00CC7-FE33-412E-8CE5-86425869D301}.Debug|x64.Build.0 = Debug|Any CPU
|
||||||
|
{8BE00CC7-FE33-412E-8CE5-86425869D301}.Debug|x86.ActiveCfg = Debug|Any CPU
|
||||||
|
{8BE00CC7-FE33-412E-8CE5-86425869D301}.Debug|x86.Build.0 = Debug|Any CPU
|
||||||
|
{8BE00CC7-FE33-412E-8CE5-86425869D301}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||||
|
{8BE00CC7-FE33-412E-8CE5-86425869D301}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||||
|
{8BE00CC7-FE33-412E-8CE5-86425869D301}.Release|x64.ActiveCfg = Release|Any CPU
|
||||||
|
{8BE00CC7-FE33-412E-8CE5-86425869D301}.Release|x64.Build.0 = Release|Any CPU
|
||||||
|
{8BE00CC7-FE33-412E-8CE5-86425869D301}.Release|x86.ActiveCfg = Release|Any CPU
|
||||||
|
{8BE00CC7-FE33-412E-8CE5-86425869D301}.Release|x86.Build.0 = Release|Any CPU
|
||||||
|
{F6C68A01-8C27-47D5-8C45-E2D00D9BC32D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||||
|
{F6C68A01-8C27-47D5-8C45-E2D00D9BC32D}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||||
|
{F6C68A01-8C27-47D5-8C45-E2D00D9BC32D}.Debug|x64.ActiveCfg = Debug|Any CPU
|
||||||
|
{F6C68A01-8C27-47D5-8C45-E2D00D9BC32D}.Debug|x64.Build.0 = Debug|Any CPU
|
||||||
|
{F6C68A01-8C27-47D5-8C45-E2D00D9BC32D}.Debug|x86.ActiveCfg = Debug|Any CPU
|
||||||
|
{F6C68A01-8C27-47D5-8C45-E2D00D9BC32D}.Debug|x86.Build.0 = Debug|Any CPU
|
||||||
|
{F6C68A01-8C27-47D5-8C45-E2D00D9BC32D}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||||
|
{F6C68A01-8C27-47D5-8C45-E2D00D9BC32D}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||||
|
{F6C68A01-8C27-47D5-8C45-E2D00D9BC32D}.Release|x64.ActiveCfg = Release|Any CPU
|
||||||
|
{F6C68A01-8C27-47D5-8C45-E2D00D9BC32D}.Release|x64.Build.0 = Release|Any CPU
|
||||||
|
{F6C68A01-8C27-47D5-8C45-E2D00D9BC32D}.Release|x86.ActiveCfg = Release|Any CPU
|
||||||
|
{F6C68A01-8C27-47D5-8C45-E2D00D9BC32D}.Release|x86.Build.0 = Release|Any CPU
|
||||||
|
{AD3903F9-037E-48AE-B555-84345C4895E0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||||
|
{AD3903F9-037E-48AE-B555-84345C4895E0}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||||
|
{AD3903F9-037E-48AE-B555-84345C4895E0}.Debug|x64.ActiveCfg = Debug|Any CPU
|
||||||
|
{AD3903F9-037E-48AE-B555-84345C4895E0}.Debug|x64.Build.0 = Debug|Any CPU
|
||||||
|
{AD3903F9-037E-48AE-B555-84345C4895E0}.Debug|x86.ActiveCfg = Debug|Any CPU
|
||||||
|
{AD3903F9-037E-48AE-B555-84345C4895E0}.Debug|x86.Build.0 = Debug|Any CPU
|
||||||
|
{AD3903F9-037E-48AE-B555-84345C4895E0}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||||
|
{AD3903F9-037E-48AE-B555-84345C4895E0}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||||
|
{AD3903F9-037E-48AE-B555-84345C4895E0}.Release|x64.ActiveCfg = Release|Any CPU
|
||||||
|
{AD3903F9-037E-48AE-B555-84345C4895E0}.Release|x64.Build.0 = Release|Any CPU
|
||||||
|
{AD3903F9-037E-48AE-B555-84345C4895E0}.Release|x86.ActiveCfg = Release|Any CPU
|
||||||
|
{AD3903F9-037E-48AE-B555-84345C4895E0}.Release|x86.Build.0 = Release|Any CPU
|
||||||
|
{ECD0F91C-C8D7-4686-9609-56F2A93F4113}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||||
|
{ECD0F91C-C8D7-4686-9609-56F2A93F4113}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||||
|
{ECD0F91C-C8D7-4686-9609-56F2A93F4113}.Debug|x64.ActiveCfg = Debug|Any CPU
|
||||||
|
{ECD0F91C-C8D7-4686-9609-56F2A93F4113}.Debug|x64.Build.0 = Debug|Any CPU
|
||||||
|
{ECD0F91C-C8D7-4686-9609-56F2A93F4113}.Debug|x86.ActiveCfg = Debug|Any CPU
|
||||||
|
{ECD0F91C-C8D7-4686-9609-56F2A93F4113}.Debug|x86.Build.0 = Debug|Any CPU
|
||||||
|
{ECD0F91C-C8D7-4686-9609-56F2A93F4113}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||||
|
{ECD0F91C-C8D7-4686-9609-56F2A93F4113}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||||
|
{ECD0F91C-C8D7-4686-9609-56F2A93F4113}.Release|x64.ActiveCfg = Release|Any CPU
|
||||||
|
{ECD0F91C-C8D7-4686-9609-56F2A93F4113}.Release|x64.Build.0 = Release|Any CPU
|
||||||
|
{ECD0F91C-C8D7-4686-9609-56F2A93F4113}.Release|x86.ActiveCfg = Release|Any CPU
|
||||||
|
{ECD0F91C-C8D7-4686-9609-56F2A93F4113}.Release|x86.Build.0 = Release|Any CPU
|
||||||
|
{C5C8124F-3B12-43A9-BD0F-5AA5F7261699}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||||
|
{C5C8124F-3B12-43A9-BD0F-5AA5F7261699}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||||
|
{C5C8124F-3B12-43A9-BD0F-5AA5F7261699}.Debug|x64.ActiveCfg = Debug|Any CPU
|
||||||
|
{C5C8124F-3B12-43A9-BD0F-5AA5F7261699}.Debug|x64.Build.0 = Debug|Any CPU
|
||||||
|
{C5C8124F-3B12-43A9-BD0F-5AA5F7261699}.Debug|x86.ActiveCfg = Debug|Any CPU
|
||||||
|
{C5C8124F-3B12-43A9-BD0F-5AA5F7261699}.Debug|x86.Build.0 = Debug|Any CPU
|
||||||
|
{C5C8124F-3B12-43A9-BD0F-5AA5F7261699}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||||
|
{C5C8124F-3B12-43A9-BD0F-5AA5F7261699}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||||
|
{C5C8124F-3B12-43A9-BD0F-5AA5F7261699}.Release|x64.ActiveCfg = Release|Any CPU
|
||||||
|
{C5C8124F-3B12-43A9-BD0F-5AA5F7261699}.Release|x64.Build.0 = Release|Any CPU
|
||||||
|
{C5C8124F-3B12-43A9-BD0F-5AA5F7261699}.Release|x86.ActiveCfg = Release|Any CPU
|
||||||
|
{C5C8124F-3B12-43A9-BD0F-5AA5F7261699}.Release|x86.Build.0 = Release|Any CPU
|
||||||
|
{FDCAC352-BB40-4B5E-948A-2CDAA48B9E6A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||||
|
{FDCAC352-BB40-4B5E-948A-2CDAA48B9E6A}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||||
|
{FDCAC352-BB40-4B5E-948A-2CDAA48B9E6A}.Debug|x64.ActiveCfg = Debug|Any CPU
|
||||||
|
{FDCAC352-BB40-4B5E-948A-2CDAA48B9E6A}.Debug|x64.Build.0 = Debug|Any CPU
|
||||||
|
{FDCAC352-BB40-4B5E-948A-2CDAA48B9E6A}.Debug|x86.ActiveCfg = Debug|Any CPU
|
||||||
|
{FDCAC352-BB40-4B5E-948A-2CDAA48B9E6A}.Debug|x86.Build.0 = Debug|Any CPU
|
||||||
|
{FDCAC352-BB40-4B5E-948A-2CDAA48B9E6A}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||||
|
{FDCAC352-BB40-4B5E-948A-2CDAA48B9E6A}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||||
|
{FDCAC352-BB40-4B5E-948A-2CDAA48B9E6A}.Release|x64.ActiveCfg = Release|Any CPU
|
||||||
|
{FDCAC352-BB40-4B5E-948A-2CDAA48B9E6A}.Release|x64.Build.0 = Release|Any CPU
|
||||||
|
{FDCAC352-BB40-4B5E-948A-2CDAA48B9E6A}.Release|x86.ActiveCfg = Release|Any CPU
|
||||||
|
{FDCAC352-BB40-4B5E-948A-2CDAA48B9E6A}.Release|x86.Build.0 = Release|Any CPU
|
||||||
|
{4317FFD0-9473-43FD-8543-F80EF9BA812A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||||
|
{4317FFD0-9473-43FD-8543-F80EF9BA812A}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||||
|
{4317FFD0-9473-43FD-8543-F80EF9BA812A}.Debug|x64.ActiveCfg = Debug|Any CPU
|
||||||
|
{4317FFD0-9473-43FD-8543-F80EF9BA812A}.Debug|x64.Build.0 = Debug|Any CPU
|
||||||
|
{4317FFD0-9473-43FD-8543-F80EF9BA812A}.Debug|x86.ActiveCfg = Debug|Any CPU
|
||||||
|
{4317FFD0-9473-43FD-8543-F80EF9BA812A}.Debug|x86.Build.0 = Debug|Any CPU
|
||||||
|
{4317FFD0-9473-43FD-8543-F80EF9BA812A}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||||
|
{4317FFD0-9473-43FD-8543-F80EF9BA812A}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||||
|
{4317FFD0-9473-43FD-8543-F80EF9BA812A}.Release|x64.ActiveCfg = Release|Any CPU
|
||||||
|
{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
|
||||||
|
EndGlobalSection
|
||||||
|
GlobalSection(NestedProjects) = preSolution
|
||||||
|
{6A70BA3E-47A7-40EC-AF2A-FB6FA9BFD6C5} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B}
|
||||||
|
{B212CA0C-F7FF-4223-8FC5-961116D937B8} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B}
|
||||||
|
{6A4CD6EB-E529-4A76-B028-CFF8F5D59E2F} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B}
|
||||||
|
{4E7F3565-DD8A-4B25-BB27-7090F1144F4C} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B}
|
||||||
|
{F0A94F81-8CAB-4803-A209-C7E350160726} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B}
|
||||||
|
{37AAC975-29AB-4649-A961-4115005042F1} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B}
|
||||||
|
{EF1EDA79-1E49-41CB-AF44-1C1ACC94611F} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B}
|
||||||
|
{0CAFB3CA-3C92-4816-A63A-4670D7AD2302} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B}
|
||||||
|
{64DD5604-A3E4-45C0-9588-A1E38363C0C9} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B}
|
||||||
|
{8BE00CC7-FE33-412E-8CE5-86425869D301} = {0AB3BF05-4346-4AA6-1389-037BE0695223}
|
||||||
|
{F6C68A01-8C27-47D5-8C45-E2D00D9BC32D} = {0AB3BF05-4346-4AA6-1389-037BE0695223}
|
||||||
|
{AD3903F9-037E-48AE-B555-84345C4895E0} = {0AB3BF05-4346-4AA6-1389-037BE0695223}
|
||||||
|
{ECD0F91C-C8D7-4686-9609-56F2A93F4113} = {0AB3BF05-4346-4AA6-1389-037BE0695223}
|
||||||
|
{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
|
||||||
@@ -8,7 +8,8 @@
|
|||||||
Blazor Server, PostgreSQL (o SQLite per demo e test) e **nessuna libreria esterna**. Si installa **solo con Docker**:
|
Blazor Server, PostgreSQL (o SQLite per demo e test) e **nessuna libreria esterna**. Si installa **solo con Docker**:
|
||||||
l'unico artefatto distribuito è l'immagine nel registro pacchetti di Gitea.
|
l'unico artefatto distribuito è l'immagine nel registro pacchetti di Gitea.
|
||||||
|
|
||||||
> **Stato:** progettazione completata, sviluppo non ancora avviato. Vedi [`docs/STATUS.md`](docs/STATUS.md) e la
|
> **Stato:** sviluppo avviato. M0 (struttura, immagine Docker, CI) consegna la versione 0.0.1 con una pagina
|
||||||
|
> "in costruzione"; le funzioni arrivano milestone dopo milestone. Vedi [`docs/STATUS.md`](docs/STATUS.md) e la
|
||||||
> [Roadmap](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/wiki/Roadmap).
|
> [Roadmap](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/wiki/Roadmap).
|
||||||
|
|
||||||
Il nome viene da Khaemhat (Mahu), scriba reale e sovrintendente al doppio granaio dell'Alto e del Basso Egitto sotto
|
Il nome viene da Khaemhat (Mahu), scriba reale e sovrintendente al doppio granaio dell'Alto e del Basso Egitto sotto
|
||||||
@@ -25,18 +26,34 @@ Amenhotep III: un contabile e un magazziniere dell'antichità. Vedi
|
|||||||
- Più aziende sulla stessa istanza (un database di sistema + un database per azienda), moduli attivabili con
|
- Più aziende sulla stessa istanza (un database di sistema + un database per azienda), moduli attivabili con
|
||||||
licenza, temi chiaro/scuro, dashboard a widget.
|
licenza, temi chiaro/scuro, dashboard a widget.
|
||||||
|
|
||||||
## Installazione (dalla prima versione rilasciata)
|
## Installazione
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
docker pull gitea.encke-hake.ts.net/balbosoft/khaemhat:<versione>
|
docker pull gitea.encke-hake.ts.net/balbosoft/khaemhat:<versione>
|
||||||
```
|
```
|
||||||
|
|
||||||
|
- Qualunque host Docker: [`deploy/docker-compose.yml`](deploy/docker-compose.yml) (con PostgreSQL) e
|
||||||
|
[`deploy/.env.example`](deploy/.env.example); per una prova veloce
|
||||||
|
[`deploy/docker-compose.sqlite.yml`](deploy/docker-compose.sqlite.yml).
|
||||||
- Unraid: template [`deploy/unraid/khaemhat.xml`](deploy/unraid/khaemhat.xml) o
|
- Unraid: template [`deploy/unraid/khaemhat.xml`](deploy/unraid/khaemhat.xml) o
|
||||||
[`deploy/docker-compose.unraid.yml`](deploy/docker-compose.unraid.yml) con [`deploy/.env.example`](deploy/.env.example).
|
[`deploy/docker-compose.unraid.yml`](deploy/docker-compose.unraid.yml) con [`deploy/.env.example`](deploy/.env.example).
|
||||||
- Guide: [Installazione Unraid](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/wiki/Installazione-Unraid) ·
|
- Guide: [Installazione Unraid](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/wiki/Installazione-Unraid) ·
|
||||||
[Installazione Docker](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/wiki/Installazione-Docker) ·
|
[Installazione Docker](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/wiki/Installazione-Docker) ·
|
||||||
[Primi passi](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/wiki/Primi-passi).
|
[Primi passi](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/wiki/Primi-passi).
|
||||||
|
|
||||||
|
## Sviluppo
|
||||||
|
|
||||||
|
Serve l'SDK .NET 10 (`global.json`); Docker solo per costruire e provare l'immagine.
|
||||||
|
|
||||||
|
```bash
|
||||||
|
scripts/build.sh # allowlist dei pacchetti + build con warning come errori
|
||||||
|
scripts/test.sh # tutti i test (PostgreSQL con KHAEMHAT_TEST_PG, Redis con KHAEMHAT_TEST_REDIS)
|
||||||
|
scripts/run-dev.sh # avvio locale su http://localhost:5080 con SQLite in .data/dev
|
||||||
|
docker build -f docker/Dockerfile -t khaemhat:dev .
|
||||||
|
```
|
||||||
|
|
||||||
|
Processo, rami e Definition of Done in [`docs/DEVELOPMENT.md`](docs/DEVELOPMENT.md).
|
||||||
|
|
||||||
## Documentazione
|
## Documentazione
|
||||||
|
|
||||||
| Cosa | Dove |
|
| Cosa | Dove |
|
||||||
|
|||||||
@@ -1,4 +1,6 @@
|
|||||||
# Copia in .env accanto a docker-compose.unraid.yml (mai committare .env)
|
# Copia in .env accanto al file compose (docker-compose.yml o docker-compose.unraid.yml); mai committare .env.
|
||||||
|
# Versione dell'immagine: sempre esplicita, mai latest in produzione (ADR 0015).
|
||||||
|
KHAEMHAT_VERSION=0.0.1
|
||||||
POSTGRES_PASSWORD=cambiami-subito
|
POSTGRES_PASSWORD=cambiami-subito
|
||||||
KHAEMHAT_SECRET_KEY= # openssl rand -base64 48
|
KHAEMHAT_SECRET_KEY= # openssl rand -base64 48
|
||||||
KHAEMHAT_SUPERUSER=root
|
KHAEMHAT_SUPERUSER=root
|
||||||
@@ -11,3 +13,5 @@ KHAEMHAT_LICENSE_MODE=production
|
|||||||
KHAEMHAT_SEED_DEMO=false
|
KHAEMHAT_SEED_DEMO=false
|
||||||
# KHAEMHAT_REDIS=redis://:cambiami@khaemhat-redis:6379/0
|
# KHAEMHAT_REDIS=redis://:cambiami@khaemhat-redis:6379/0
|
||||||
# REDIS_PASSWORD=cambiami
|
# REDIS_PASSWORD=cambiami
|
||||||
|
# PUID=99 # utente e gruppo proprietari di /data (ADR 0013); predefiniti 1654 = utente app dell'immagine
|
||||||
|
# PGID=100
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
# Demo autonoma: un solo container, database SQLite nel volume /data, dati di esempio al primo avvio.
|
||||||
|
# Solo per prove: per lavorare con più utenti serve PostgreSQL (docker-compose.yml).
|
||||||
|
# docker compose -f docker-compose.sqlite.yml up
|
||||||
|
services:
|
||||||
|
khaemhat:
|
||||||
|
image: gitea.encke-hake.ts.net/balbosoft/khaemhat:${KHAEMHAT_VERSION:-0.0.1}
|
||||||
|
ports:
|
||||||
|
- "${KHAEMHAT_PORT:-8080}:8080"
|
||||||
|
environment:
|
||||||
|
KHAEMHAT_SYSTEM_DB: sqlite:///data/system.db
|
||||||
|
KHAEMHAT_SECRET_KEY: ${KHAEMHAT_SECRET_KEY:-}
|
||||||
|
KHAEMHAT_SUPERUSER: root
|
||||||
|
KHAEMHAT_SUPERUSER_PASSWORD: ${KHAEMHAT_SUPERUSER_PASSWORD:-}
|
||||||
|
KHAEMHAT_COMPANY_CODE: DEMO
|
||||||
|
KHAEMHAT_COMPANY_NAME: Khaemhat Demo S.r.l.
|
||||||
|
KHAEMHAT_SEED_DEMO: "true"
|
||||||
|
KHAEMHAT_LICENSE_MODE: test
|
||||||
|
TZ: ${TZ:-Europe/Rome}
|
||||||
|
volumes:
|
||||||
|
- khaemhat-demo:/data
|
||||||
|
healthcheck:
|
||||||
|
test: ["CMD", "curl", "-fs", "http://localhost:8080/health/live"]
|
||||||
|
interval: 30s
|
||||||
|
timeout: 5s
|
||||||
|
retries: 3
|
||||||
|
start_period: 30s
|
||||||
|
|
||||||
|
volumes:
|
||||||
|
khaemhat-demo:
|
||||||
@@ -3,7 +3,7 @@
|
|||||||
# Le etichette net.unraid.docker.* mostrano icona e link WebUI nella pagina Docker di Unraid.
|
# Le etichette net.unraid.docker.* mostrano icona e link WebUI nella pagina Docker di Unraid.
|
||||||
services:
|
services:
|
||||||
khaemhat:
|
khaemhat:
|
||||||
image: gitea.encke-hake.ts.net/balbosoft/khaemhat:1.0.0
|
image: gitea.encke-hake.ts.net/balbosoft/khaemhat:${KHAEMHAT_VERSION:-0.0.1}
|
||||||
container_name: khaemhat
|
container_name: khaemhat
|
||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
depends_on:
|
depends_on:
|
||||||
@@ -32,7 +32,7 @@ services:
|
|||||||
labels:
|
labels:
|
||||||
net.unraid.docker.managed: composeman
|
net.unraid.docker.managed: composeman
|
||||||
net.unraid.docker.webui: "http://[IP]:[PORT:8080]/"
|
net.unraid.docker.webui: "http://[IP]:[PORT:8080]/"
|
||||||
net.unraid.docker.icon: "https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/assets/icon-v1.0-256.png"
|
net.unraid.docker.icon: "https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/assets/icon-256.png"
|
||||||
healthcheck:
|
healthcheck:
|
||||||
test: ["CMD", "curl", "-fs", "http://localhost:8080/health/live"]
|
test: ["CMD", "curl", "-fs", "http://localhost:8080/health/live"]
|
||||||
interval: 30s
|
interval: 30s
|
||||||
|
|||||||
@@ -0,0 +1,65 @@
|
|||||||
|
# Khaemhat con PostgreSQL su qualunque host Docker (installazione consigliata, wiki Installazione-Docker).
|
||||||
|
# Copia accanto a questo file .env.example come .env e compila i valori. Usa sempre una versione esplicita.
|
||||||
|
# docker compose up -d applicazione + PostgreSQL
|
||||||
|
# docker compose --profile redis up -d anche Redis (poi imposta KHAEMHAT_REDIS nel .env)
|
||||||
|
services:
|
||||||
|
khaemhat:
|
||||||
|
image: gitea.encke-hake.ts.net/balbosoft/khaemhat:${KHAEMHAT_VERSION:-0.0.1}
|
||||||
|
restart: unless-stopped
|
||||||
|
depends_on:
|
||||||
|
khaemhat-db:
|
||||||
|
condition: service_healthy
|
||||||
|
ports:
|
||||||
|
- "${KHAEMHAT_PORT:-8080}:8080"
|
||||||
|
environment:
|
||||||
|
KHAEMHAT_SYSTEM_DB: postgres://khaemhat:${POSTGRES_PASSWORD:?imposta POSTGRES_PASSWORD nel .env}@khaemhat-db:5432/khaemhat_system
|
||||||
|
KHAEMHAT_DB_SERVER: postgres://khaemhat:${POSTGRES_PASSWORD}@khaemhat-db:5432/
|
||||||
|
KHAEMHAT_SECRET_KEY: ${KHAEMHAT_SECRET_KEY:-}
|
||||||
|
KHAEMHAT_SUPERUSER: ${KHAEMHAT_SUPERUSER:-root}
|
||||||
|
KHAEMHAT_SUPERUSER_PASSWORD: ${KHAEMHAT_SUPERUSER_PASSWORD:-}
|
||||||
|
KHAEMHAT_SUPERUSER_EMAIL: ${KHAEMHAT_SUPERUSER_EMAIL:-}
|
||||||
|
KHAEMHAT_COMPANY_CODE: ${KHAEMHAT_COMPANY_CODE:-DEMO}
|
||||||
|
KHAEMHAT_COMPANY_NAME: ${KHAEMHAT_COMPANY_NAME:-La mia azienda S.r.l.}
|
||||||
|
KHAEMHAT_PUBLIC_URL: ${KHAEMHAT_PUBLIC_URL:-http://localhost:8080}
|
||||||
|
KHAEMHAT_REDIS: ${KHAEMHAT_REDIS:-}
|
||||||
|
KHAEMHAT_LICENSE_MODE: ${KHAEMHAT_LICENSE_MODE:-production}
|
||||||
|
KHAEMHAT_LICENSE: ${KHAEMHAT_LICENSE:-}
|
||||||
|
KHAEMHAT_SEED_DEMO: ${KHAEMHAT_SEED_DEMO:-false}
|
||||||
|
KHAEMHAT_LOG_LEVEL: ${KHAEMHAT_LOG_LEVEL:-Information}
|
||||||
|
TZ: ${TZ:-Europe/Rome}
|
||||||
|
PUID: ${PUID:-1654}
|
||||||
|
PGID: ${PGID:-1654}
|
||||||
|
volumes:
|
||||||
|
- khaemhat-data:/data
|
||||||
|
healthcheck:
|
||||||
|
test: ["CMD", "curl", "-fs", "http://localhost:8080/health/live"]
|
||||||
|
interval: 30s
|
||||||
|
timeout: 5s
|
||||||
|
retries: 3
|
||||||
|
start_period: 30s
|
||||||
|
|
||||||
|
khaemhat-db:
|
||||||
|
image: postgres:17
|
||||||
|
restart: unless-stopped
|
||||||
|
environment:
|
||||||
|
POSTGRES_DB: khaemhat_system
|
||||||
|
POSTGRES_USER: khaemhat
|
||||||
|
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}
|
||||||
|
TZ: ${TZ:-Europe/Rome}
|
||||||
|
volumes:
|
||||||
|
- khaemhat-pg:/var/lib/postgresql/data
|
||||||
|
healthcheck:
|
||||||
|
test: ["CMD-SHELL", "pg_isready -U khaemhat -d khaemhat_system"]
|
||||||
|
interval: 10s
|
||||||
|
timeout: 5s
|
||||||
|
retries: 10
|
||||||
|
|
||||||
|
khaemhat-redis:
|
||||||
|
image: redis:7
|
||||||
|
restart: unless-stopped
|
||||||
|
profiles: ["redis"]
|
||||||
|
command: ["redis-server", "--requirepass", "${REDIS_PASSWORD:-cambiami}", "--save", "", "--appendonly", "no"]
|
||||||
|
|
||||||
|
volumes:
|
||||||
|
khaemhat-data:
|
||||||
|
khaemhat-pg:
|
||||||
@@ -1,10 +1,10 @@
|
|||||||
<?xml version="1.0"?>
|
<?xml version="1.0"?>
|
||||||
<!-- Template Unraid (formato Community Applications) per Khaemhat.
|
<!-- Template Unraid (formato Community Applications) per Khaemhat.
|
||||||
Importalo da Docker › Add Container › Template. Immagine dal registro pacchetti di Gitea (ADR 0009).
|
Importalo da Docker → Add Container → Template. Immagine dal registro pacchetti di Gitea (ADR 0009).
|
||||||
Icona e template sono serviti come file raw dal repository pubblico BalboSoft/Khaemhat. -->
|
Icona e template sono serviti come file raw dal repository pubblico BalboSoft/Khaemhat. -->
|
||||||
<Container version="2">
|
<Container version="2">
|
||||||
<Name>khaemhat</Name>
|
<Name>khaemhat</Name>
|
||||||
<Repository>gitea.encke-hake.ts.net/balbosoft/khaemhat:1.0.0</Repository>
|
<Repository>gitea.encke-hake.ts.net/balbosoft/khaemhat:0.0.1</Repository>
|
||||||
<Registry>https://gitea.encke-hake.ts.net/BalboSoft/-/packages/container/khaemhat</Registry>
|
<Registry>https://gitea.encke-hake.ts.net/BalboSoft/-/packages/container/khaemhat</Registry>
|
||||||
<Network>khaemhat-net</Network>
|
<Network>khaemhat-net</Network>
|
||||||
<Privileged>false</Privileged>
|
<Privileged>false</Privileged>
|
||||||
@@ -14,7 +14,7 @@
|
|||||||
<Category>Productivity: Tools:</Category>
|
<Category>Productivity: Tools:</Category>
|
||||||
<WebUI>http://[IP]:[PORT:8080]/</WebUI>
|
<WebUI>http://[IP]:[PORT:8080]/</WebUI>
|
||||||
<TemplateURL>https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/deploy/unraid/khaemhat.xml</TemplateURL>
|
<TemplateURL>https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/deploy/unraid/khaemhat.xml</TemplateURL>
|
||||||
<Icon>https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/assets/icon-v1.0-256.png</Icon>
|
<Icon>https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/assets/icon-256.png</Icon>
|
||||||
<ExtraParams>--health-cmd="curl -fs http://localhost:8080/health/live || exit 1" --health-interval=30s --health-timeout=5s --health-retries=3</ExtraParams>
|
<ExtraParams>--health-cmd="curl -fs http://localhost:8080/health/live || exit 1" --health-interval=30s --health-timeout=5s --health-retries=3</ExtraParams>
|
||||||
<Requires>Un database PostgreSQL 16 o 17 raggiungibile (consigliato il template ufficiale postgres sulla rete khaemhat-net) e un ruolo con permesso CREATEDB.</Requires>
|
<Requires>Un database PostgreSQL 16 o 17 raggiungibile (consigliato il template ufficiale postgres sulla rete khaemhat-net) e un ruolo con permesso CREATEDB.</Requires>
|
||||||
<Config Name="Porta web" Target="8080" Default="8080" Mode="tcp" Description="Interfaccia web (dietro reverse proxy TLS)" Type="Port" Display="always" Required="true" Mask="false">8080</Config>
|
<Config Name="Porta web" Target="8080" Default="8080" Mode="tcp" Description="Interfaccia web (dietro reverse proxy TLS)" Type="Port" Display="always" Required="true" Mask="false">8080</Config>
|
||||||
@@ -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_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_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_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&q=khaemhat)" 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&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="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>
|
<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>
|
||||||
|
|||||||
@@ -0,0 +1,90 @@
|
|||||||
|
# syntax=docker/dockerfile:1
|
||||||
|
# Khaemhat image (SPEC §16.1, ADR 0009, 0010, 0013, 0015, 0016, 0017). Build from the repository root:
|
||||||
|
# docker build -f docker/Dockerfile --build-arg VERSION=0.0.1 --build-arg GIT_SHA=$(git rev-parse --short HEAD) .
|
||||||
|
|
||||||
|
ARG DOTNET_VERSION=10.0
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------------------------------------------------
|
||||||
|
FROM mcr.microsoft.com/dotnet/sdk:${DOTNET_VERSION} AS build
|
||||||
|
ARG VERSION=0.0.0-dev
|
||||||
|
ARG GIT_SHA=unknown
|
||||||
|
ARG RUN_TESTS=false
|
||||||
|
ENV DOTNET_NOLOGO=1 DOTNET_CLI_TELEMETRY_OPTOUT=1 DOTNET_SKIP_FIRST_TIME_EXPERIENCE=1
|
||||||
|
WORKDIR /src
|
||||||
|
|
||||||
|
# Restore first, from the build files only, so the layer is reused while no project or package changes.
|
||||||
|
COPY global.json Directory.Build.props Directory.Build.targets Directory.Packages.props .editorconfig ./
|
||||||
|
COPY src/Khaemhat.Core/Khaemhat.Core.csproj src/Khaemhat.Core/
|
||||||
|
COPY src/Khaemhat.Fiscal.Abstractions/Khaemhat.Fiscal.Abstractions.csproj src/Khaemhat.Fiscal.Abstractions/
|
||||||
|
COPY src/Khaemhat.Fiscal.Italy/Khaemhat.Fiscal.Italy.csproj src/Khaemhat.Fiscal.Italy/
|
||||||
|
COPY src/Khaemhat.Data/Khaemhat.Data.csproj src/Khaemhat.Data/
|
||||||
|
COPY src/Khaemhat.Data.Sqlite/Khaemhat.Data.Sqlite.csproj src/Khaemhat.Data.Sqlite/
|
||||||
|
COPY src/Khaemhat.Data.PostgreSql/Khaemhat.Data.PostgreSql.csproj src/Khaemhat.Data.PostgreSql/
|
||||||
|
COPY src/Khaemhat.Infrastructure/Khaemhat.Infrastructure.csproj src/Khaemhat.Infrastructure/
|
||||||
|
COPY src/Khaemhat.Application/Khaemhat.Application.csproj src/Khaemhat.Application/
|
||||||
|
COPY src/Khaemhat.Web/Khaemhat.Web.csproj src/Khaemhat.Web/
|
||||||
|
RUN dotnet restore src/Khaemhat.Web/Khaemhat.Web.csproj
|
||||||
|
|
||||||
|
COPY . .
|
||||||
|
RUN bash scripts/check-packages.sh
|
||||||
|
RUN if [ "$RUN_TESTS" = "true" ]; then \
|
||||||
|
dotnet test Khaemhat.sln -c Release /p:Version="$VERSION" /p:SourceRevisionId="$GIT_SHA"; \
|
||||||
|
fi
|
||||||
|
RUN dotnet publish src/Khaemhat.Web/Khaemhat.Web.csproj -c Release -o /app --no-restore \
|
||||||
|
/p:Version="$VERSION" /p:SourceRevisionId="$GIT_SHA" /p:UseAppHost=false
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------------------------------------------------
|
||||||
|
FROM mcr.microsoft.com/dotnet/aspnet:${DOTNET_VERSION} AS runtime
|
||||||
|
ARG VERSION=0.0.0-dev
|
||||||
|
ARG GIT_SHA=unknown
|
||||||
|
ARG CREATED=unknown
|
||||||
|
ARG SOURCE_URL=https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat
|
||||||
|
ARG ICON_URL=https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/assets/icon-256.png
|
||||||
|
|
||||||
|
# OS tools allowed by SPEC §1.2 (not application components): pg_dump/pg_restore 17 from the PGDG repository (a
|
||||||
|
# client >= the server: works with PostgreSQL 16 and 17), curl for the health check, tzdata for TZ.
|
||||||
|
RUN set -eux; \
|
||||||
|
apt-get update; \
|
||||||
|
DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends ca-certificates curl tzdata; \
|
||||||
|
. /etc/os-release; \
|
||||||
|
install -d /usr/share/postgresql-common/pgdg; \
|
||||||
|
curl -fsSL -o /usr/share/postgresql-common/pgdg/apt.postgresql.org.asc https://www.postgresql.org/media/keys/ACCC4CF8.asc; \
|
||||||
|
echo "deb [signed-by=/usr/share/postgresql-common/pgdg/apt.postgresql.org.asc] https://apt.postgresql.org/pub/repos/apt ${VERSION_CODENAME}-pgdg main" \
|
||||||
|
> /etc/apt/sources.list.d/pgdg.list; \
|
||||||
|
apt-get update; \
|
||||||
|
DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends postgresql-client-17; \
|
||||||
|
rm -rf /var/lib/apt/lists/*; \
|
||||||
|
pg_dump --version
|
||||||
|
|
||||||
|
ENV ASPNETCORE_ENVIRONMENT=Production \
|
||||||
|
ASPNETCORE_HTTP_PORTS=8080 \
|
||||||
|
KHAEMHAT_DATA_DIR=/data \
|
||||||
|
DOTNET_NOLOGO=1 \
|
||||||
|
TZ=Europe/Rome
|
||||||
|
|
||||||
|
WORKDIR /app
|
||||||
|
COPY --from=build /app ./
|
||||||
|
COPY docker/entrypoint.sh /app/entrypoint.sh
|
||||||
|
COPY scripts/restore-system.sh /app/scripts/restore-system.sh
|
||||||
|
RUN chmod 0755 /app/entrypoint.sh /app/scripts/restore-system.sh \
|
||||||
|
&& install -d -o app -g app -m 0750 /data
|
||||||
|
|
||||||
|
LABEL org.opencontainers.image.title="Khaemhat" \
|
||||||
|
org.opencontainers.image.description="Gestionale ERP e CRM per PMI italiane" \
|
||||||
|
org.opencontainers.image.vendor="BalboSoft" \
|
||||||
|
org.opencontainers.image.version="${VERSION}" \
|
||||||
|
org.opencontainers.image.revision="${GIT_SHA}" \
|
||||||
|
org.opencontainers.image.created="${CREATED}" \
|
||||||
|
org.opencontainers.image.source="${SOURCE_URL}" \
|
||||||
|
org.opencontainers.image.url="${SOURCE_URL}" \
|
||||||
|
org.opencontainers.image.documentation="${SOURCE_URL}/wiki" \
|
||||||
|
net.unraid.docker.icon="${ICON_URL}" \
|
||||||
|
net.unraid.docker.webui="http://[IP]:[PORT:8080]/"
|
||||||
|
|
||||||
|
VOLUME /data
|
||||||
|
EXPOSE 8080
|
||||||
|
HEALTHCHECK --interval=30s --timeout=5s --start-period=20s --retries=3 \
|
||||||
|
CMD curl -fs http://localhost:8080/health/live || exit 1
|
||||||
|
|
||||||
|
# Starts as root only to align the app user with PUID/PGID; the .NET process runs as "app" (ADR 0013).
|
||||||
|
ENTRYPOINT ["/app/entrypoint.sh"]
|
||||||
@@ -0,0 +1,84 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# Container entrypoint (docs/DEPLOY.md §2.4, ADR 0013, ADR 0014). It only prepares the user, waits for the system
|
||||||
|
# database and starts the app: migrations and bootstrap live in the .NET code.
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
APP_DLL=/app/Khaemhat.Web.dll
|
||||||
|
DATA_DIR="${KHAEMHAT_DATA_DIR:-/data}"
|
||||||
|
DB_WAIT_SECONDS=120
|
||||||
|
|
||||||
|
log() { printf '%s khaemhat-entrypoint: %s\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)" "$*" >&2; }
|
||||||
|
fail() { log "ERRORE: $*"; exit 1; }
|
||||||
|
|
||||||
|
# The system database URL, from KHAEMHAT_SYSTEM_DB or KHAEMHAT_SYSTEM_DB_FILE (ADR 0014). Only host and port are used.
|
||||||
|
system_db() {
|
||||||
|
if [[ -n "${KHAEMHAT_SYSTEM_DB:-}" && -n "${KHAEMHAT_SYSTEM_DB_FILE:-}" ]]; then
|
||||||
|
fail "KHAEMHAT_SYSTEM_DB e KHAEMHAT_SYSTEM_DB_FILE sono entrambe impostate: usane una sola."
|
||||||
|
fi
|
||||||
|
if [[ -n "${KHAEMHAT_SYSTEM_DB_FILE:-}" ]]; then
|
||||||
|
[[ -r "$KHAEMHAT_SYSTEM_DB_FILE" ]] || fail "KHAEMHAT_SYSTEM_DB_FILE: file non leggibile ($KHAEMHAT_SYSTEM_DB_FILE)."
|
||||||
|
head -n 1 "$KHAEMHAT_SYSTEM_DB_FILE" | tr -d '\r\n'
|
||||||
|
else
|
||||||
|
printf '%s' "${KHAEMHAT_SYSTEM_DB:-}"
|
||||||
|
fi
|
||||||
|
}
|
||||||
|
|
||||||
|
# Waits until the PostgreSQL server of the system database accepts connections. SQLite needs no wait.
|
||||||
|
wait_for_database() {
|
||||||
|
local url host port rest deadline
|
||||||
|
url="$(system_db)"
|
||||||
|
case "$url" in
|
||||||
|
postgres://* | postgresql://*) ;;
|
||||||
|
*) return 0 ;;
|
||||||
|
esac
|
||||||
|
|
||||||
|
rest="${url#*://}" # user:pwd@host:port/db?x
|
||||||
|
rest="${rest##*@}" # host:port/db?x
|
||||||
|
rest="${rest%%/*}" # host:port
|
||||||
|
rest="${rest%%\?*}"
|
||||||
|
host="${rest%%:*}"
|
||||||
|
port=5432
|
||||||
|
[[ "$rest" == *:* ]] && port="${rest##*:}"
|
||||||
|
[[ -n "$host" ]] || fail "KHAEMHAT_SYSTEM_DB: host mancante."
|
||||||
|
|
||||||
|
deadline=$((SECONDS + DB_WAIT_SECONDS))
|
||||||
|
until pg_isready -q -h "$host" -p "$port" -t 3; do
|
||||||
|
if (( SECONDS >= deadline )); then
|
||||||
|
fail "il database di sistema su $host:$port non risponde dopo ${DB_WAIT_SECONDS}s."
|
||||||
|
fi
|
||||||
|
log "attendo il database di sistema su $host:$port..."
|
||||||
|
sleep 2
|
||||||
|
done
|
||||||
|
log "database di sistema raggiungibile su $host:$port."
|
||||||
|
}
|
||||||
|
|
||||||
|
# Aligns the "app" user with PUID/PGID and gives it /data (ADR 0013). Only when started as root.
|
||||||
|
prepare_user() {
|
||||||
|
local puid="${PUID:-$(id -u app)}" pgid="${PGID:-$(id -g app)}"
|
||||||
|
[[ "$puid" =~ ^[0-9]+$ && "$pgid" =~ ^[0-9]+$ ]] || fail "PUID e PGID devono essere numeri (PUID=$puid, PGID=$pgid)."
|
||||||
|
(( puid != 0 && pgid != 0 )) || fail "PUID e PGID non possono essere 0: l'applicazione non gira come root."
|
||||||
|
|
||||||
|
if [[ "$(id -g app)" != "$pgid" ]]; then
|
||||||
|
groupmod -o -g "$pgid" app
|
||||||
|
fi
|
||||||
|
if [[ "$(id -u app)" != "$puid" ]]; then
|
||||||
|
usermod -o -u "$puid" app
|
||||||
|
fi
|
||||||
|
|
||||||
|
mkdir -p "$DATA_DIR"
|
||||||
|
if [[ "$(stat -c '%u:%g' "$DATA_DIR")" != "$puid:$pgid" ]]; then
|
||||||
|
log "assegno $DATA_DIR a $puid:$pgid..."
|
||||||
|
chown -R "$puid:$pgid" "$DATA_DIR"
|
||||||
|
fi
|
||||||
|
}
|
||||||
|
|
||||||
|
wait_for_database
|
||||||
|
|
||||||
|
if [[ "$(id -u)" == "0" ]]; then
|
||||||
|
prepare_user
|
||||||
|
log "avvio Khaemhat come utente app ($(id -u app):$(id -g app))."
|
||||||
|
exec setpriv --reuid=app --regid=app --init-groups -- dotnet "$APP_DLL" "$@"
|
||||||
|
fi
|
||||||
|
|
||||||
|
log "avvio Khaemhat come utente $(id -u):$(id -g)."
|
||||||
|
exec dotnet "$APP_DLL" "$@"
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
-- Optional init script for the official postgres image (mount it in /docker-entrypoint-initdb.d/): it runs once,
|
||||||
|
-- when the data directory is empty. Khaemhat creates every table itself (migrations in .NET, one database per
|
||||||
|
-- company), so this only sets defaults for the application role.
|
||||||
|
--
|
||||||
|
-- The role must be able to create databases (CREATEDB): the POSTGRES_USER of the official image is a superuser and
|
||||||
|
-- already can; for an existing server see docs/DEPLOY.md.
|
||||||
|
|
||||||
|
DO $$
|
||||||
|
BEGIN
|
||||||
|
-- Timestamps are stored as timestamptz and handled in UTC by the application.
|
||||||
|
EXECUTE format('ALTER ROLE %I SET timezone TO %L', current_user, 'UTC');
|
||||||
|
EXECUTE format('ALTER ROLE %I SET client_encoding TO %L', current_user, 'UTF8');
|
||||||
|
END
|
||||||
|
$$;
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
# Architettura di Khaemhat
|
# Architettura di Khaemhat
|
||||||
|
|
||||||
> Stato: bozza · Revisione 2026-11-10 · Fonte: SPEC §1, §2, §3, §4, §5, §7, §9, §13, §15, §19, §21; ADR 0009-0011
|
> 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,
|
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
|
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.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 |
|
| `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.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 |
|
| `tests/*` | `Core`, `Data`, `Infrastructure`, `Fiscal.Italy`, `Application`, `Web` (MSTest) | ogni milestone |
|
||||||
|
|
||||||
## 3. Regole di dipendenza
|
## 3. Regole di dipendenza
|
||||||
@@ -171,11 +172,11 @@ tabelle è in [DATA-MODEL.md](DATA-MODEL.md).
|
|||||||
|
|
||||||
| Tipo | Progetto | Responsabilità |
|
| Tipo | Progetto | Responsabilità |
|
||||||
|---|---|---|
|
|---|---|---|
|
||||||
| `IDbProvider` | Data | motore (`DbEngine`), dialetto, `SchemaBuilder`, creazione connessioni, `EnsureDatabaseExistsAsync`, `DropDatabaseAsync`, `GetServerInfoAsync` |
|
| `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`, `AdvisoryLock`, conversioni `ColumnType` |
|
| `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)` |
|
| `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` |
|
| `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`) |
|
| `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 |
|
| `SecretProtector` | Infrastructure | AES-256-GCM con chiave derivata da `KHAEMHAT_SECRET_KEY` per connection string e credenziali |
|
||||||
|
|
||||||
@@ -391,8 +392,12 @@ Khaemhat/
|
|||||||
Differenze rispetto a SPEC §4: `.gitea/workflows/` al posto di `.github/workflows/`; registro pacchetti Gitea al
|
Differenze rispetto a SPEC §4: `.gitea/workflows/` al posto di `.github/workflows/`; registro pacchetti Gitea al
|
||||||
posto di GHCR; nessun repository `khaemhat-assets` (icona servita come file raw del repository pubblico);
|
posto di GHCR; nessun repository `khaemhat-assets` (icona servita come file raw del repository pubblico);
|
||||||
`docs/SPEC.md` contiene la specifica e `CLAUDE.md` è breve (ADR 0011); `docs/mockups/thumbs/` aggiunta;
|
`docs/SPEC.md` contiene la specifica e `CLAUDE.md` è breve (ADR 0011); `docs/mockups/thumbs/` aggiunta;
|
||||||
`scripts/restore-system.sh` è citato in SPEC §13 e qui riportato nell'albero. Nessun installer né binario
|
`scripts/restore-system.sh` è citato in SPEC §13 e qui riportato nell'albero; è copiato nell'immagine in
|
||||||
distribuito (ADR 0010).
|
`/app/scripts/` (ADR 0017). Nessun installer né binario distribuito (ADR 0010). In più `.vscode/` (debug e attività
|
||||||
|
di Visual Studio Code) e `.gitea/scripts/check-yaml.rb` (controllo YAML della CI).
|
||||||
|
|
||||||
|
Le regole di dipendenza della §3 e l'allowlist dei pacchetti sono verificate da test: `Khaemhat.Core.Tests`,
|
||||||
|
cartella `Architecture/`, legge i file di progetto e fallisce su ogni riferimento non ammesso.
|
||||||
|
|
||||||
## 10. Classi principali per progetto
|
## 10. Classi principali per progetto
|
||||||
|
|
||||||
@@ -436,11 +441,11 @@ stando fuori dal pacchetto fiscale: è la collocazione indicata da SPEC §21.
|
|||||||
|
|
||||||
| Area | Classi |
|
| Area | Classi |
|
||||||
|---|---|
|
|---|---|
|
||||||
| Contratti | `IDbProvider`, `ISqlDialect`, `ISchemaBuilder`, `IUnitOfWork`, `IUnitOfWorkFactory`, `IRepository<,>`, `Repository<,>` |
|
| Contratti | `IDbProvider`, `ISqlDialect`, `ISchemaBuilder`, `IUnitOfWork`, `IUnitOfWorkFactory`, `IRepository<,>`, `Repository<,>`, `DatabaseUrl`, `DatabaseTarget`, `DbProviderCatalog` |
|
||||||
| Registro database | `ICompanyRegistry`, `CompanyRegistry`, `DatabaseScope` |
|
| Registro database | `ICompanyRegistry`, `CompanyRegistry`, `IDatabaseLocator`, `DatabaseLocator`, `DatabaseScope`, `CompanyCodes` |
|
||||||
| Mappe e query | `EntityMap<T>`, `ColumnMap`, `ColumnType`, `MapRegistry`, `QueryBuilder<T>`, `Query<T>`, `PagedResult<T>`, `SqlFragment`, `ExpressionTranslator` |
|
| Mappe e query | `EntityMap<T>`, `ColumnMap`, `ColumnType`, `MapRegistry`, `QueryBuilder<T>`, `Query<T>`, `PagedResult<T>`, `SqlFragment`, `ExpressionTranslator` |
|
||||||
| Esecuzione | `DbExecutor`, `ReaderMapper<T>`, `CommandCache`, `TransientRetryPolicy` |
|
| Esecuzione | `UnitOfWork`, `UnitOfWorkFactory`, `DataAccessContext` (orologio, utente, tentativi), `DbExecutor`, `ReaderMapper`, `CommandCache`, `TransientRetryPolicy` |
|
||||||
| Migrazioni | `IMigration`, `MigrationAttribute`, `MigrationRunner`, `MigrationCatalog` (System/Company), `SchemaVersionStore`, `TableDefinition`, `ColumnDefinition`, `IndexDefinition`, `ForeignKeyDefinition`, `DdlGenerator` |
|
| Migrazioni | `IMigration`, `MigrationAttribute`, `MigrationRunner`, `MigrationReport`, `MigrationCatalog` (`ForSystem`/`ForCompany`), `SchemaVersionStore`, `SchemaModel`, `DataModelDocument`, `TableDefinition`, `ColumnDefinition`, `IndexDefinition`, `ForeignKeyDefinition`, `DdlGenerator` |
|
||||||
| SQLite | `SqliteProvider`, `SqliteDialect`, `SqliteSchemaBuilder`, `SqliteWriteLock`, `SqliteDecimalConverter` |
|
| SQLite | `SqliteProvider`, `SqliteDialect`, `SqliteSchemaBuilder`, `SqliteWriteLock`, `SqliteDecimalConverter` |
|
||||||
| PostgreSQL | `PostgresProvider`, `PostgresDialect`, `PostgresSchemaBuilder`, `PostgresDatabaseCreator`, `PostgresAdvisoryLocks`, `PostgresPartitioning`, `PostgresServerInfo` |
|
| PostgreSQL | `PostgresProvider`, `PostgresDialect`, `PostgresSchemaBuilder`, `PostgresDatabaseCreator`, `PostgresAdvisoryLocks`, `PostgresPartitioning`, `PostgresServerInfo` |
|
||||||
|
|
||||||
|
|||||||
@@ -1,12 +1,13 @@
|
|||||||
# Modello dati
|
# 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`
|
> **Due parti.** La sezione [8. Schema attuale](#8-schema-attuale-generato) è **generata** da
|
||||||
> leggendo le mappe `XxxMap : EntityMap<Xxx>` e le migrazioni: non andrà più modificato a mano. Finché il codice non
|
> `scripts/gen-datamodel.sh` leggendo le migrazioni: non si modifica a mano e un test fallisce se non è aggiornata.
|
||||||
> esiste, questa è la versione pianificata ricavata dalla specifica: nomi e colonne sono indicativi e verranno
|
> Le sezioni 3-4 sono la **pianificazione** ricavata dalla specifica: nomi e colonne sono indicativi e vengono
|
||||||
> confermati (o corretti) dalla prima generazione. I nomi di tabella contrassegnati con **†** non compaiono
|
> confermati (o corretti) dalla migrazione che crea ciascuna tabella, milestone dopo milestone. I nomi di tabella
|
||||||
> letteralmente in SPEC: sono derivati dal nome dell'entità di SPEC §21 secondo la convenzione snake_case plurale.
|
> 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).
|
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 |
|
| `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` | |
|
| `Text` | `text` | `TEXT` | |
|
||||||
| `Int32` | `int` | `INTEGER` | |
|
| `Int32` | `integer` | `INTEGER` | |
|
||||||
| `Int64` | `bigint` | `INTEGER` | chiavi primarie ed esterne |
|
| `Int64` | `bigint` | `INTEGER` | chiavi primarie ed esterne |
|
||||||
| `Decimal(19,6)` | `numeric(19,6)` | `INTEGER` scalato x10⁶ | vedi §1.3 |
|
| `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# |
|
| `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` | |
|
| `Guid` | `uuid` | `TEXT` | |
|
||||||
| `Bytes` | `bytea` | `BLOB` | |
|
| `Bytes` | `bytea` | `BLOB` | |
|
||||||
| `Json` | `jsonb` | `TEXT` | diff di audit, payload dei canali, dati di log |
|
| `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
|
### 1.3 Decimali scalati su SQLite
|
||||||
|
|
||||||
SQLite non ha un tipo decimale esatto: i valori `Decimal(19,6)` sono memorizzati come **interi moltiplicati per
|
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:
|
10⁶** (`SqliteDecimalConverter`). Conseguenze per chi scrive query:
|
||||||
|
|
||||||
- `ISqlDialect.ToDbValue` / `FromDbValue` convertono in scrittura e in lettura; i parametri passano già scalati;
|
- `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
|
- le **somme in SQL** (`SUM`, `GROUP BY`) operano sugli interi scalati e vengono **riscalate in lettura**: niente
|
||||||
aritmetica in virgola mobile;
|
aritmetica in virgola mobile;
|
||||||
- prodotti e divisioni fra due colonne decimali non vanno fatti in SQL su SQLite (il fattore di scala si
|
- 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
|
- Ogni entità ha una mappa `XxxMap : EntityMap<Xxx>` (tabella, colonne, chiave, indici, FK, conversioni); nessuna
|
||||||
riflessione a runtime oltre la costruzione iniziale (`MapRegistry`).
|
riflessione a runtime oltre la costruzione iniziale (`MapRegistry`).
|
||||||
- `QueryBuilder<T>`: uguaglianza, confronto, `Contains`/`StartsWith`, `In`, `And`/`Or`/`Not`, `IsNull`; il resto come
|
- `Query.For<T>().Where(x => ...)`: uguaglianza, confronto, `== null`, `Contains`/`StartsWith`/`EndsWith` (LIKE
|
||||||
`SqlFragment` parametrizzato. Mai concatenare input utente in SQL.
|
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`.
|
- 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,
|
- PostgreSQL: pool separato per database (`MaxPoolSize` da impostazioni), `statement_timeout` per sessione,
|
||||||
`pg_advisory_xact_lock` per numeratori, chiusure e scheduler.
|
`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)
|
## 2. Migrazioni (SPEC §5.3)
|
||||||
|
|
||||||
```csharp
|
```csharp
|
||||||
[Migration(20261013_001, "create_parties")]
|
[Migration(20261013_001, "create_parties")] // Target = MigrationTarget.Company se omesso
|
||||||
public sealed class M20261013_001 : IMigration
|
public sealed class M20261013_001_CreateParties : IMigration
|
||||||
{
|
{
|
||||||
public void Up(ISchemaBuilder sb) { /* tabelle, colonne, indici, FK in forma neutra */ }
|
public void Up(ISchemaBuilder schema) { /* tabelle, colonne, indici, FK in forma neutra */ }
|
||||||
public string? UpSql(ISqlDialect d) => null; // SQL specifico del dialetto, se serve
|
public string? UpSql(ISqlDialect dialect) => null; // SQL specifico del dialetto, se serve
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
| Regola | Dettaglio |
|
| Regola | Dettaglio |
|
||||||
|---|---|
|
|---|---|
|
||||||
| Due cataloghi | `MigrationCatalog.System` (database di sistema) e `MigrationCatalog.Company` (ogni azienda) |
|
| Due cataloghi | `MigrationCatalog.ForSystem()` (database di sistema) e `MigrationCatalog.ForCompany(assembly dei moduli)` |
|
||||||
| Versioni | `schema_version(module, version, name, applied_at, checksum)` in **ogni** database |
|
| 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 in transazione, è idempotente, registra l'esito nella sezione di log *Migrazioni* |
|
| 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) |
|
||||||
| Downgrade | non supportato: se trova versioni applicate non note rifiuta di partire |
|
| 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 |
|
| 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 |
|
| Test obbligatorio | tutte le migrazioni da zero su SQLite e PostgreSQL, `schema_version` coerente, riapplicazione senza effetti |
|
||||||
|
|
||||||
## 3. Database di sistema (`khaemhat_system`)
|
## 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
|
- 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.
|
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
|
## 7. Segreti nel database
|
||||||
|
|
||||||
Cifrati con AES-256-GCM e chiave derivata da `KHAEMHAT_SECRET_KEY` (`SecretProtector`): connection string delle
|
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
|
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
|
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.
|
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 -->
|
||||||
@@ -103,7 +103,8 @@ Note:
|
|||||||
### 2.3 Utente e `PUID`/`PGID`
|
### 2.3 Utente e `PUID`/`PGID`
|
||||||
|
|
||||||
Le immagini `aspnet:10.0` includono già un utente non root `app`. SPEC chiede che i file in `/data` appartengano a
|
Le immagini `aspnet:10.0` includono già un utente non root `app`. SPEC chiede che i file in `/data` appartengano a
|
||||||
`PUID`/`PGID` (predefiniti 99/100 per Unraid). Due realizzazioni possibili, da fissare con un ADR in M0:
|
`PUID`/`PGID` (99/100 per Unraid). Le due realizzazioni valutate; **ADR 0013 sceglie la 1** (predefiniti `1654`,
|
||||||
|
l'utente `app` dell'immagine; la 2 resta possibile perché l'entrypoint salta la preparazione se non è root):
|
||||||
|
|
||||||
1. **avvio come root e cessione dei privilegi** in `entrypoint.sh`: allinea UID/GID di `app` a `PUID`/`PGID`,
|
1. **avvio come root e cessione dei privilegi** in `entrypoint.sh`: allinea UID/GID di `app` a `PUID`/`PGID`,
|
||||||
esegue `chown` su `/data` solo se necessario e rilancia il processo come `app` con `setpriv` (util-linux, già
|
esegue `chown` su `/data` solo se necessario e rilancia il processo come `app` con `setpriv` (util-linux, già
|
||||||
@@ -118,7 +119,8 @@ gira mai come root.
|
|||||||
|
|
||||||
Sequenza (SPEC §4, §5.4):
|
Sequenza (SPEC §4, §5.4):
|
||||||
|
|
||||||
1. legge le varianti `_FILE` delle variabili e le esporta (§5);
|
1. legge `KHAEMHAT_SYSTEM_DB` (o `KHAEMHAT_SYSTEM_DB_FILE`) solo per ricavarne host e porta: le varianti `_FILE` le
|
||||||
|
risolve l'applicazione, senza esportare segreti nell'ambiente (ADR 0014, §5);
|
||||||
2. se previsto, allinea utente e permessi (§2.3);
|
2. se previsto, allinea utente e permessi (§2.3);
|
||||||
3. attende che `KHAEMHAT_SYSTEM_DB` sia raggiungibile (retry con backoff, timeout esplicito, messaggio chiaro);
|
3. attende che `KHAEMHAT_SYSTEM_DB` sia raggiungibile (retry con backoff, timeout esplicito, messaggio chiaro);
|
||||||
4. avvia l'applicazione (`exec dotnet Khaemhat.Web.dll`), che in `StartupOrchestrator` valida le opzioni
|
4. avvia l'applicazione (`exec dotnet Khaemhat.Web.dll`), che in `StartupOrchestrator` valida le opzioni
|
||||||
@@ -128,7 +130,7 @@ Sequenza (SPEC §4, §5.4):
|
|||||||
|
|
||||||
Le migrazioni restano nel codice .NET (`MigrationRunner`), non nello script shell: l'entrypoint fa solo attesa,
|
Le migrazioni restano nel codice .NET (`MigrationRunner`), non nello script shell: l'entrypoint fa solo attesa,
|
||||||
ambiente e `exec`. `docker/postgres/init.sql` è uno script di inizializzazione opzionale per il container PostgreSQL
|
ambiente e `exec`. `docker/postgres/init.sql` è uno script di inizializzazione opzionale per il container PostgreSQL
|
||||||
(contenuto da definire in M0).
|
(montato in `/docker-entrypoint-initdb.d/`: imposta per il ruolo dell'applicazione fuso `UTC` e codifica `UTF8`).
|
||||||
|
|
||||||
## 3. File in `deploy/`
|
## 3. File in `deploy/`
|
||||||
|
|
||||||
@@ -182,8 +184,8 @@ L'elenco completo e normativo delle variabili è SPEC §6 con le modifiche di E1
|
|||||||
- `KHAEMHAT_SECRET_KEY` è obbligatoria (≥ 32 byte base64): cifra con AES-256-GCM i segreti in `sys_companies`,
|
- `KHAEMHAT_SECRET_KEY` è obbligatoria (≥ 32 byte base64): cifra con AES-256-GCM i segreti in `sys_companies`,
|
||||||
`sys_settings` ecc. e i file di backup. Senza chiave l'app non parte.
|
`sys_settings` ecc. e i file di backup. Senza chiave l'app non parte.
|
||||||
- `KHAEMHAT_SUPERUSER*`, `KHAEMHAT_COMPANY_*` sono lette solo se le tabelle corrispondenti sono vuote.
|
- `KHAEMHAT_SUPERUSER*`, `KHAEMHAT_COMPANY_*` sono lette solo se le tabelle corrispondenti sono vuote.
|
||||||
- Varianti `_FILE` (Docker secrets): SPEC le prevede per `KHAEMHAT_SYSTEM_DB` e `KHAEMHAT_SUPERUSER_*`. Proposta da
|
- Varianti `_FILE` (Docker secrets): SPEC le prevede per `KHAEMHAT_SYSTEM_DB` e `KHAEMHAT_SUPERUSER_*`. **Deciso con
|
||||||
confermare in M2: supportarle per **tutte** le variabili sensibili (`KHAEMHAT_SECRET_KEY`,
|
ADR 0014**: sono supportate per **tutte** le variabili sensibili (`KHAEMHAT_SECRET_KEY`,
|
||||||
`KHAEMHAT_SECRET_KEY_NEW`, `KHAEMHAT_DB_SERVER`, `KHAEMHAT_REDIS`, `KHAEMHAT_LICENSE`, `KHAEMHAT_SMTP_PASSWORD`,
|
`KHAEMHAT_SECRET_KEY_NEW`, `KHAEMHAT_DB_SERVER`, `KHAEMHAT_REDIS`, `KHAEMHAT_LICENSE`, `KHAEMHAT_SMTP_PASSWORD`,
|
||||||
`KHAEMHAT_UPDATE_TOKEN`) con una sola regola in `EnvironmentConfigurationReader`: se esiste `X_FILE`, il valore è il
|
`KHAEMHAT_UPDATE_TOKEN`) con una sola regola in `EnvironmentConfigurationReader`: se esiste `X_FILE`, il valore è il
|
||||||
contenuto del file senza il fine riga finale; `X` e `X_FILE` insieme sono un errore di configurazione.
|
contenuto del file senza il fine riga finale; `X` e `X_FILE` insieme sono un errore di configurazione.
|
||||||
@@ -206,8 +208,8 @@ Regole (SPEC §16.6, E1):
|
|||||||
`https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/assets/icon-v<major.minor>-256.png`;
|
`https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/assets/icon-v<major.minor>-256.png`;
|
||||||
il file deve quindi essere **committato su `main` prima** del rilascio che lo referenzia;
|
il file deve quindi essere **committato su `main` prima** del rilascio che lo referenzia;
|
||||||
- la conversione SVG → PNG richiede un rasterizzatore che l'applicazione non contiene (né deve contenere): si esegue
|
- la conversione SVG → PNG richiede un rasterizzatore che l'applicazione non contiene (né deve contenere): si esegue
|
||||||
sulla macchina di sviluppo con uno strumento di sistema e il PNG si committa. La scelta dello strumento va
|
sulla macchina di sviluppo con uno strumento di sistema e il PNG si committa. Strumenti accettati:
|
||||||
registrata in un ADR;
|
`rsvg-convert`, `inkscape`, `magick` (ADR 0016);
|
||||||
- finché manca la variante della nuova versione si usa `icon-256.png` (non versionata).
|
- finché manca la variante della nuova versione si usa `icon-256.png` (non versionata).
|
||||||
|
|
||||||
## 7. Versioning
|
## 7. Versioning
|
||||||
@@ -226,7 +228,7 @@ Regole (SPEC §16.6, E1):
|
|||||||
|---|---|---|
|
|---|---|---|
|
||||||
| `GET /health/live` | liveness: il processo risponde. Usato da `HEALTHCHECK`, dal compose e da `<ExtraParams>` del template. Non deve dipendere dal database, altrimenti un DB lento fa riavviare il container | previsto da SPEC (§16.1, App. C) |
|
| `GET /health/live` | liveness: il processo risponde. Usato da `HEALTHCHECK`, dal compose e da `<ExtraParams>` del template. Non deve dipendere dal database, altrimenti un DB lento fa riavviare il container | previsto da SPEC (§16.1, App. C) |
|
||||||
| `GET /health` | endpoint di base introdotto in M0 | previsto da SPEC (§20, M0) |
|
| `GET /health` | endpoint di base introdotto in M0 | previsto da SPEC (§20, M0) |
|
||||||
| readiness (proposta `GET /health/ready`) | database di sistema raggiungibile, migrazioni di sistema applicate, bootstrap concluso; `503` durante l'avvio | da definire con `HealthEndpoints` |
|
| readiness (proposta `GET /health/ready`) | database di sistema raggiungibile, migrazioni di sistema applicate, bootstrap concluso; `503` durante l'avvio | ADR 0012: in M0 sempre `200`, i controlli arrivano in M1-M2 |
|
||||||
| metriche (`MetricsEndpoint`) | formato e percorso | da definire |
|
| metriche (`MetricsEndpoint`) | formato e percorso | da definire |
|
||||||
|
|
||||||
Regole: risposte senza autenticazione e senza dati sensibili (niente versioni dei componenti, connection string o
|
Regole: risposte senza autenticazione e senza dati sensibili (niente versioni dei componenti, connection string o
|
||||||
@@ -278,9 +280,9 @@ Differenze rispetto all'Appendice D (ADR 0009): registro pacchetti di Gitea, var
|
|||||||
`GITEA_TOKEN`, tag immagine senza `v`. La rigenerazione dell'icona sta in `scripts/build.sh` (§6).
|
`GITEA_TOKEN`, tag immagine senza `v`. La rigenerazione dell'icona sta in `scripts/build.sh` (§6).
|
||||||
|
|
||||||
**Tag git e doppio build.** Se lo script creasse e spingesse anche il tag `vX.Y.Z`, il push farebbe partire
|
**Tag git e doppio build.** Se lo script creasse e spingesse anche il tag `vX.Y.Z`, il push farebbe partire
|
||||||
`release.yml` e l'immagine verrebbe costruita due volte. Proposta: lo script **non** crea tag; il tag si crea alla
|
`release.yml` e l'immagine verrebbe costruita due volte. **Deciso con ADR 0015**: lo script **non** crea tag; il tag si crea alla
|
||||||
chiusura della milestone (E6). In alternativa `release.yml` controlla prima del build se la versione esiste già nel
|
chiusura della milestone (E6). In più `release.yml` controlla prima del build se la versione esiste già nel
|
||||||
registro (`GET /api/v1/packages/BalboSoft/container/khaemhat/<X.Y.Z>` → `200`) e in quel caso salta il push.
|
registro (`GET /api/v1/packages/BalboSoft/container/khaemhat/<X.Y.Z>` → `200`) e in quel caso salta build e push e crea solo la release.
|
||||||
|
|
||||||
## 10. Checklist di rilascio
|
## 10. Checklist di rilascio
|
||||||
|
|
||||||
@@ -307,7 +309,7 @@ registro (`GET /api/v1/packages/BalboSoft/container/khaemhat/<X.Y.Z>` → `200`)
|
|||||||
- `MigrationRunner` rifiuta di partire se trova in `schema_version` versioni non note: il **downgrade non è
|
- `MigrationRunner` rifiuta di partire se trova in `schema_version` versioni non note: il **downgrade non è
|
||||||
supportato**.
|
supportato**.
|
||||||
- Rollback: tag precedente; se la versione nuova ha applicato migrazioni, prima si ripristinano database di sistema
|
- Rollback: tag precedente; se la versione nuova ha applicato migrazioni, prima si ripristinano database di sistema
|
||||||
(`scripts/restore-system.sh`, istanza ferma) e aziende dai backup fatti prima dell'aggiornamento.
|
(`/app/scripts/restore-system.sh` nell'immagine, ADR 0017, istanza ferma) e aziende dai backup fatti prima dell'aggiornamento.
|
||||||
- Per questo ogni voce del changelog dichiara se contiene migrazioni.
|
- Per questo ogni voce del changelog dichiara se contiene migrazioni.
|
||||||
|
|
||||||
Procedura per l'utente: wiki *Aggiornamento*.
|
Procedura per l'utente: wiki *Aggiornamento*.
|
||||||
@@ -346,11 +348,11 @@ documentazione utente chiede di conservare la vecchia chiave per tutta la retent
|
|||||||
|
|
||||||
| Punto | Proposta | Quando |
|
| Punto | Proposta | Quando |
|
||||||
|---|---|---|
|
|---|---|---|
|
||||||
| `PUID`/`PGID` con utente non root | avvio root + `setpriv` nell'entrypoint (§2.3) | ADR in M0 |
|
| `PUID`/`PGID` con utente non root | avvio root + `setpriv` nell'entrypoint (§2.3) | **deciso: ADR 0013** |
|
||||||
| Elenco delle variabili con `_FILE` | tutte le sensibili (§5) | M2 |
|
| Elenco delle variabili con `_FILE` | tutte le sensibili (§5) | **deciso: ADR 0014**; implementazione in M1-M2 |
|
||||||
| Endpoint di readiness e metriche | `/health/ready`; metriche da definire (§8) | M0/M2 |
|
| Endpoint di readiness e metriche | `/health/ready` (**ADR 0012**); metriche da definire (§8) | M2 |
|
||||||
| Doppio build tag + script | lo script non crea tag (§9.2) | M0 |
|
| Doppio build tag + script | lo script non crea tag (§9.2) | **deciso: ADR 0015** |
|
||||||
| Rasterizzazione dell'icona versionata | strumento di sistema sulla macchina di sviluppo, PNG committato (§6) | M13 |
|
| Rasterizzazione dell'icona versionata | strumento di sistema sulla macchina di sviluppo, PNG committato (§6) | **deciso: ADR 0016** |
|
||||||
| Backup cifrati dopo la rotazione della chiave | registro delle chiavi storiche o ri-cifratura (§13) | M12 |
|
| Backup cifrati dopo la rotazione della chiave | registro delle chiavi storiche o ri-cifratura (§13) | M12 |
|
||||||
| Connection string delle aziende e rotazione della password PostgreSQL | per le aziende create su `KHAEMHAT_DB_SERVER`, salvare un riferimento "credenziali del server" invece della stringa completa | M1/M2 |
|
| Connection string delle aziende e rotazione della password PostgreSQL | per le aziende create su `KHAEMHAT_DB_SERVER`, salvare un riferimento "credenziali del server" invece della stringa completa | M1/M2 |
|
||||||
| Decifratura dei backup fuori dall'applicazione | comando in `restore-system.sh` o sottocomando dedicato | M12 |
|
| Decifratura dei backup fuori dall'applicazione | comando in `restore-system.sh` o sottocomando dedicato | M12 |
|
||||||
@@ -1,10 +1,9 @@
|
|||||||
# Processo di sviluppo
|
# Processo di sviluppo
|
||||||
|
|
||||||
> Stato: bozza · Revisione 2026-11-10 · Fonte: SPEC §17-§20, §23, `CLAUDE.md`
|
> Stato: completo per M0 · Revisione 2026-11-11 · Fonte: SPEC §17-§20, §23, `CLAUDE.md`
|
||||||
|
|
||||||
Questo documento dice **come** si lavora su Khaemhat: unità di lavoro, rami, commit, verifica, chiusura delle
|
Questo documento dice **come** si lavora su Khaemhat: unità di lavoro, rami, commit, verifica, chiusura delle
|
||||||
milestone. Le regole di prodotto stanno in [`SPEC.md`](SPEC.md) e negli emendamenti di [`CLAUDE.md`](../CLAUDE.md).
|
milestone. Le regole di prodotto stanno in [`SPEC.md`](SPEC.md) e negli emendamenti di [`CLAUDE.md`](../CLAUDE.md).
|
||||||
I comandi di build e test reali verranno completati in M0, quando esisterà il codice.
|
|
||||||
|
|
||||||
## 1. Prerequisiti
|
## 1. Prerequisiti
|
||||||
|
|
||||||
@@ -16,7 +15,53 @@ I comandi di build e test reali verranno completati in M0, quando esisterà il c
|
|||||||
| PostgreSQL | 16 o 17 | facoltativo in locale: `KHAEMHAT_TEST_PG` attiva i test sul motore reale |
|
| PostgreSQL | 16 o 17 | facoltativo in locale: `KHAEMHAT_TEST_PG` attiva i test sul motore reale |
|
||||||
| Redis | 7 | facoltativo: `KHAEMHAT_TEST_REDIS` attiva i test del client RESP |
|
| Redis | 7 | facoltativo: `KHAEMHAT_TEST_REDIS` attiva i test del client RESP |
|
||||||
|
|
||||||
Se manca l'SDK 10 ci si ferma e lo si chiede al titolare (SPEC §23).
|
Se manca l'SDK 10 ci si ferma e lo si chiede al titolare (SPEC §23). Su Windows gli script si eseguono da Git Bash.
|
||||||
|
|
||||||
|
### 1.1 Comandi
|
||||||
|
|
||||||
|
| Comando | Cosa fa |
|
||||||
|
|---|---|
|
||||||
|
| `scripts/build.sh` | `check-packages.sh` + `dotnet build Khaemhat.sln -c Release -warnaserror` |
|
||||||
|
| `scripts/build.sh --icon [X.Y]` | anche l'icona versionata `assets/icon-vX.Y.svg` e, se c'è un rasterizzatore, i PNG (ADR 0016) |
|
||||||
|
| `scripts/test.sh [argomenti di dotnet test]` | allowlist + tutti i test; PostgreSQL con `KHAEMHAT_TEST_PG`, Redis con `KHAEMHAT_TEST_REDIS` |
|
||||||
|
| `scripts/run-dev.sh` | avvio locale su `http://localhost:5080`, SQLite in `.data/dev`, licenze di test |
|
||||||
|
| `scripts/check-packages.sh` | fallisce se un file MSBuild usa un pacchetto fuori allowlist o fuori dal suo progetto |
|
||||||
|
| `docker build -f docker/Dockerfile -t khaemhat:dev .` | immagine locale (`--build-arg RUN_TESTS=true` per eseguire i test nel build) |
|
||||||
|
| `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 `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
|
||||||
|
|
||||||
|
La cartella `.vscode/` è nel repository:
|
||||||
|
|
||||||
|
- `launch.json`: **Khaemhat (web, SQLite)** compila (attività `build`) e avvia `Khaemhat.Web` in debug su
|
||||||
|
`http://localhost:5080` con le stesse variabili di `scripts/run-dev.sh` (SQLite in `.data/dev`, licenze di test,
|
||||||
|
log `Debug`) e apre il browser quando il server è pronto; **Khaemhat (web, PostgreSQL)** fa lo stesso contro un
|
||||||
|
PostgreSQL locale (comando per avviarlo nel commento); **Collega a un processo** si aggancia a un'istanza già avviata;
|
||||||
|
- `tasks.json`: `build` (predefinita, `Ctrl+Shift+B`), `test`, `watch (web)` con ricaricamento a caldo,
|
||||||
|
`check-packages`, `docker build`;
|
||||||
|
- `extensions.json`: C# Dev Kit, C#, EditorConfig, Docker.
|
||||||
|
|
||||||
|
Si apre la cartella del repository, si sceglie la configurazione nel pannello *Esegui e debug* e si preme `F5`. Le
|
||||||
|
chiavi e le password di `launch.json` valgono solo per lo sviluppo locale.
|
||||||
|
|
||||||
|
I test architetturali (`Khaemhat.Core.Tests/Architecture`) leggono i `.csproj`: un riferimento fra progetti non
|
||||||
|
previsto da SPEC §3 o un pacchetto fuori allowlist li fa fallire, oltre a far fallire `check-packages.sh`.
|
||||||
|
|
||||||
## 2. Ripresa di una sessione
|
## 2. Ripresa di una sessione
|
||||||
|
|
||||||
@@ -108,9 +153,26 @@ La wiki si pubblica nel wiki Gitea da `wiki.yml` (push su `main` che tocca `docs
|
|||||||
| `.gitea/workflows/release.yml` | tag `v*`; manuale | immagine, smoke test `/health/live`, push nel registro Gitea, release con note dal `CHANGELOG.md` |
|
| `.gitea/workflows/release.yml` | tag `v*`; manuale | immagine, smoke test `/health/live`, push nel registro Gitea, release con note dal `CHANGELOG.md` |
|
||||||
| `.gitea/workflows/wiki.yml` | push su `main` che tocca `docs/wiki/**` | sincronizza il wiki Gitea |
|
| `.gitea/workflows/wiki.yml` | push su `main` che tocca `docs/wiki/**` | sincronizza il wiki Gitea |
|
||||||
|
|
||||||
Segreti e variabili: `REGISTRY_TOKEN` (segreto di organizzazione `BalboSoft`, permesso `write:package`, già presente);
|
`ci.yml` costruisce e prova anche l'immagine (job *Docker image*: `/health/live`, utente `PUID`/`PGID`, `pg_dump`)
|
||||||
il token automatico del job per checkout e wiki. Il runner è condiviso con altri progetti: niente matrici superflue,
|
su PR, push e avvio manuale; sui tag lo fa `release.yml`. Un controllo YAML (Ruby) valida workflow e compose.
|
||||||
`concurrency` con cancellazione dei job superati, `timeout-minutes` su ogni job.
|
|
||||||
|
| Nome | Tipo | Uso |
|
||||||
|
|---|---|---|
|
||||||
|
| `REGISTRY_TOKEN` | segreto di organizzazione (già presente) | login al registro e controllo delle versioni già pubblicate; permesso pacchetti lettura e scrittura |
|
||||||
|
| `REGISTRY_USER` | variabile (facoltativa) | utente del login al registro; predefinito: chi ha spinto il tag (`github.actor`), che deve essere il proprietario del token |
|
||||||
|
| `REGISTRY`, `PUBLIC_URL` | variabili (facoltative) | host del registro e indirizzo pubblico di Gitea; predefiniti `gitea.encke-hake.ts.net` |
|
||||||
|
| `WIKI_TOKEN` | segreto (facoltativo) | solo se il token automatico del job non può scrivere nel wiki |
|
||||||
|
| token automatico | del job | checkout, archivio per il controllo YAML, release Gitea, wiki |
|
||||||
|
|
||||||
|
Il runner (`act_runner` in modalità Docker, etichetta `ubuntu-latest`) deve vedere il daemon Docker dell'host: i job
|
||||||
|
senza `container:` usano la CLI `docker` dell'immagine del runner, come in Chronos. Il runner è condiviso con altri
|
||||||
|
progetti: niente matrici superflue (solo PostgreSQL 16/17 sui tag), `concurrency` con cancellazione dei job superati,
|
||||||
|
`timeout-minutes` su ogni job. Ciò che un job annullato lascia sull'host (container, reti, immagini con l'etichetta
|
||||||
|
`khaemhat-ci.job`) lo rimuove il job successivo.
|
||||||
|
|
||||||
|
**Rilascio** (ADR 0015): `CHANGELOG.md` con la sezione `## [X.Y.Z] - data`, commit su `main`, poi
|
||||||
|
`git tag -a vX.Y.Z -m "Khaemhat X.Y.Z" && git push origin vX.Y.Z`. Tag git `vX.Y.Z`, immagine `X.Y.Z` (più `latest`
|
||||||
|
se non è una pre-release). Se si è pubblicato con `publish-image.sh`, il push del tag crea solo la release.
|
||||||
|
|
||||||
## 10. Chiusura di una milestone
|
## 10. Chiusura di una milestone
|
||||||
|
|
||||||
@@ -122,6 +184,8 @@ L'issue *Chiusura milestone* verifica la **Definition of Done** (SPEC §20):
|
|||||||
- [ ] log per sezione dei nuovi moduli
|
- [ ] log per sezione dei nuovi moduli
|
||||||
- [ ] wiki delle funzioni consegnate *completa*; `docs/*.md` aggiornati; `CHANGELOG.md`
|
- [ ] wiki delle funzioni consegnate *completa*; `docs/*.md` aggiornati; `CHANGELOG.md`
|
||||||
- [ ] `docs/STATUS.md` aggiornato con il punto di ripresa
|
- [ ] `docs/STATUS.md` aggiornato con il punto di ripresa
|
||||||
|
- [ ] versione nei file di `deploy/` (`KHAEMHAT_VERSION` dei compose e di `.env.example`, `<Repository>` del template
|
||||||
|
Unraid); icona versionata con `scripts/build.sh --icon` se cambia `major.minor` dalla 1.0 in poi (ADR 0016)
|
||||||
- [ ] commit, tag `vX.Y.Z`, immagine `gitea.encke-hake.ts.net/balbosoft/khaemhat:X.Y.Z`, release Gitea
|
- [ ] commit, tag `vX.Y.Z`, immagine `gitea.encke-hake.ts.net/balbosoft/khaemhat:X.Y.Z`, release Gitea
|
||||||
- [ ] l'immagine si costruisce in locale e la demo SQLite parte da zero
|
- [ ] l'immagine si costruisce in locale e la demo SQLite parte da zero
|
||||||
- [ ] le issue della milestone successiva passano in *Da fare*
|
- [ ] le issue della milestone successiva passano in *Da fare*
|
||||||
|
|||||||
@@ -136,8 +136,8 @@ programmata passa da un controllo esplicito.
|
|||||||
|
|
||||||
| Aspetto | Regola |
|
| Aspetto | Regola |
|
||||||
|---|---|
|
|---|---|
|
||||||
| Autenticazione | cookie ASP.NET Core con `CookieSessionAuthenticationHandler`; nessun ASP.NET Identity/EF |
|
| Autenticazione | schema `KhaemhatSession` scritto in casa (`SessionAuthenticationHandler`, ADR 0019); nessun ASP.NET Identity/EF |
|
||||||
| Attributi del cookie | `HttpOnly; Secure; SameSite=Lax` |
|
| 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`) |
|
| 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 |
|
| 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) |
|
| 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) |
|
| Antiforgery | sui form statici (login, cambio password, recupero) |
|
||||||
| Cookie ammessi | sessione e tema prima del login (SPEC §1.5); nessun cookie di profilazione |
|
| 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
|
**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. Rigenerare l'identificatore dopo il login e dopo il
|
database non consente di impersonare le sessioni attive. L'identificatore viene **rigenerato a ogni passaggio di
|
||||||
passaggio TOTP (prevenzione della session fixation).
|
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
|
- `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
|
string delle aziende (`sys_companies`), password SMTP/PEC/S3/WebDAV, token degli intermediari SDI, credenziali dei
|
||||||
canali e-commerce.
|
canali e-commerce.
|
||||||
- La chiave AES è **derivata** da `KHAEMHAT_SECRET_KEY`. Proposta: HKDF-SHA256 (in-box, `HKDF`) con etichette di
|
- La chiave AES è **derivata** da `KHAEMHAT_SECRET_KEY` con HKDF-SHA256 (in-box, `HKDF`) ed etichetta di contesto
|
||||||
contesto distinte per uso (`secrets`, `backup`, `totp`), così una chiave non viene riusata fra domini.
|
`khaemhat/secrets/aes-256-gcm/v1`; altri usi (backup, TOTP) avranno etichette proprie, così una chiave non viene
|
||||||
- Proposta di formato del testo cifrato: `v1` (versione/identificativo chiave) ‖ nonce 12 byte casuale ‖
|
riusata fra domini. L'identificativo della chiave è una seconda derivazione HKDF di 4 byte (8 cifre esadecimali):
|
||||||
ciphertext ‖ tag 16 byte, in base64. Il nonce non si riusa mai con la stessa chiave. Come dato associato (AAD)
|
identifica la chiave senza rivelarla.
|
||||||
usare tabella+colonna+id, così un segreto copiato in un'altra riga non si decifra.
|
- **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
|
- 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).
|
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
|
- Le varianti `_FILE` (Docker secrets) valgono per tutte le variabili sensibili, `KHAEMHAT_SECRET_KEY` compresa
|
||||||
super utente; proposta: estenderle a `KHAEMHAT_SECRET_KEY` e alle altre variabili sensibili.
|
(ADR 0014); impostare sia la variabile sia la sua `_FILE` è un errore di avvio.
|
||||||
|
|
||||||
### 7.2 Rotazione (`SecretRotationService`, `SecretRotation`)
|
### 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`.
|
3. L'operatore sostituisce `KHAEMHAT_SECRET_KEY` con la nuova e rimuove `KHAEMHAT_SECRET_KEY_NEW`.
|
||||||
4. Evento in `sys_security_audit`.
|
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
|
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).
|
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**
|
- 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
|
(`sys_data_protection_keys`) tramite `DataProtectionDbXmlRepository`: nessun file su disco, cookie validi dopo un
|
||||||
riavvio o un nuovo container.
|
riavvio o un nuovo container.
|
||||||
- Proposta: cifrare l'XML delle chiavi a riposo con un `IXmlEncryptor` basato su `SecretProtector`, così la sola
|
- **Implementato in M2** (`DataProtectionKeyStore`, `SecretKeyXmlEncryptor`): l'XML delle chiavi è cifrato a riposo
|
||||||
lettura del database di sistema non consente di falsificare cookie.
|
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 |
|
| 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` |
|
| `X-Frame-Options` | `DENY` |
|
||||||
| `Referrer-Policy` | proposta: `strict-origin-when-cross-origin` (o `no-referrer`) |
|
| `Referrer-Policy` | `same-origin` |
|
||||||
| `X-Content-Type-Options` | proposta: `nosniff` |
|
| `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 |
|
| `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
|
- 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.
|
- 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
|
- 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).
|
(eccezione: l'anteprima XML formattata, che va resa come testo).
|
||||||
|
|||||||
@@ -2,21 +2,54 @@
|
|||||||
|
|
||||||
> Punto di ripresa per ogni sessione. Aggiornare a fine sessione.
|
> Punto di ripresa per ogni sessione. Aggiornare a fine sessione.
|
||||||
|
|
||||||
**Ultimo aggiornamento:** 2026-11-10
|
**Ultimo aggiornamento:** 2026-11-11
|
||||||
**Milestone corrente:** nessuna — documentazione e pianificazione completate, **sviluppo non ancora avviato**
|
**Milestone corrente:** M3 — Framework UI, completa nel ramo `feat/25-interfaccia` e in attesa del merge in `main`
|
||||||
**Prossimo passo:** attendere il via del titolare (emendamento E5 di `CLAUDE.md`), poi M0 — Bootstrap, partendo
|
(pull request di chiusura, issue #36). Dopo il merge: tag `v0.3.0`, immagine e release.
|
||||||
dall'issue #1 *M0 · Soluzione, progetti e regole di build*
|
**Prossimo passo:** M4 — Tabelle, anagrafiche, articoli (issue #37-#46). #35 (PNG ad alta risoluzione) resta aperta
|
||||||
(colonna *Da fare* del progetto *Khaemhat 1.0 — Sviluppo*).
|
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
|
## Fatto
|
||||||
|
|
||||||
- Specifica normativa in `docs/SPEC.md`; `CLAUDE.md` con emendamenti E1-E6.
|
- 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).
|
- 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).
|
- 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`,
|
- Documentazione tecnica: `ARCHITECTURE.md`, `DATA-MODEL.md` (provvisorio, sarà generato), `MODULES.md`, `API.md`,
|
||||||
`MCP.md`, `DEPLOY.md`, `SECURITY.md`, `DEVELOPMENT.md`.
|
`MCP.md`, `DEPLOY.md`, `SECURITY.md`, `DEVELOPMENT.md`.
|
||||||
- Wiki completa in bozza in `docs/wiki/`, pubblicata nel wiki Gitea.
|
- Wiki completa in bozza in `docs/wiki/`, pubblicata nel wiki Gitea.
|
||||||
|
- **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 (completa, `v0.3.0` dopo il merge):** 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)
|
- 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,
|
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,
|
M4 #37-#46, M5 #47-#54, M6 #55-#61, M7 #62-#68, M8 #69-#73, M9 #74-#81, M10 #82-#87, M11 #88-#91,
|
||||||
@@ -24,11 +57,17 @@ dall'issue #1 *M0 · Soluzione, progetti e regole di build*
|
|||||||
|
|
||||||
## Ambiente verificato
|
## Ambiente verificato
|
||||||
|
|
||||||
Da compilare all'inizio di M0: versioni di `dotnet`, `docker`, `git`; runner Gitea Actions disponibile.
|
Rilevato il 2026-11-11 sulla macchina di sviluppo (Windows 11, Git Bash per gli script):
|
||||||
|
|
||||||
|
| Strumento | Versione |
|
||||||
|
|---|---|
|
||||||
|
| .NET SDK | 10.0.403 (`global.json`: 10.0.100, `rollForward: latestFeature`) |
|
||||||
|
| Docker | 29.1.3 (Docker Desktop, daemon da avviare a mano) |
|
||||||
|
| Git | 2.54 |
|
||||||
|
| Runner Gitea Actions | `act_runner` in modalità Docker, etichetta `ubuntu-latest` (condiviso con Chronos) |
|
||||||
|
|
||||||
## In attesa del titolare
|
## In attesa del titolare
|
||||||
|
|
||||||
- Via allo sviluppo.
|
|
||||||
- PNG ad alta risoluzione delle 66 schermate disponibili solo come miniatura (issue #35, non bloccante).
|
- PNG ad alta risoluzione delle 66 schermate disponibili solo come miniatura (issue #35, non bloccante).
|
||||||
- Scelta degli intermediari SDI e accreditamento SdICoop (issue #78, non bloccante).
|
- Scelta degli intermediari SDI e accreditamento SdICoop (issue #78, non bloccante).
|
||||||
- Prova del template su Unraid (issue #106).
|
- Prova del template su Unraid (issue #106).
|
||||||
@@ -43,15 +82,15 @@ Emersi durante la stesura della documentazione. Si decidono con un ADR quando si
|
|||||||
|
|
||||||
### Installazione, aggiornamento, backup (dalla stesura di DEPLOY e wiki installazione)
|
### Installazione, aggiornamento, backup (dalla stesura di DEPLOY e wiki installazione)
|
||||||
|
|
||||||
1. `scripts/restore-system.sh` è l'unico modo di ripristinare il DB di sistema (§13), ma gli script non sono distribuiti (ADR 0010): oggi la wiki dice di scaricarlo dal repository. Valutare di includerlo nell'immagine (`/app/scripts/`).
|
1. `scripts/restore-system.sh` è l'unico modo di ripristinare il DB di sistema (§13), ma gli script non sono distribuiti (ADR 0010): oggi la wiki dice di scaricarlo dal repository. Valutare di includerlo nell'immagine (`/app/scripts/`). **Deciso in M0: ADR 0017.**
|
||||||
2. Backup cifrati con `KHAEMHAT_SECRET_KEY`: manca uno strumento di decifratura fuori dall'app e non è definito cosa succede ai backup vecchi dopo la rotazione della chiave (oggi: conservare la chiave vecchia per tutta la retention).
|
2. Backup cifrati con `KHAEMHAT_SECRET_KEY`: manca uno strumento di decifratura fuori dall'app e non è definito cosa succede ai backup vecchi dopo la rotazione della chiave (oggi: conservare la chiave vecchia per tutta la retention).
|
||||||
3. `PUID`/`PGID` e utente non root (§16.1): proposta di avviare come root e scendere di privilegi con `setpriv` nell'entrypoint; da decidere con ADR in M0.
|
3. `PUID`/`PGID` e utente non root (§16.1): proposta di avviare come root e scendere di privilegi con `setpriv` nell'entrypoint; da decidere con ADR in M0. **Deciso in M0: ADR 0013.**
|
||||||
4. Varianti `_FILE` definite solo per `KHAEMHAT_SYSTEM_DB` e `KHAEMHAT_SUPERUSER_*`: proposta di estenderle a tutte le variabili sensibili (incluso `KHAEMHAT_SECRET_KEY`).
|
4. Varianti `_FILE` definite solo per `KHAEMHAT_SYSTEM_DB` e `KHAEMHAT_SUPERUSER_*`: proposta di estenderle a tutte le variabili sensibili (incluso `KHAEMHAT_SECRET_KEY`). **Deciso in M0: ADR 0014.**
|
||||||
5. Salute: la specifica ha `/health/live` e `/health`; `/health/ready` e le metriche sono da definire.
|
5. Salute: la specifica ha `/health/live` e `/health`; `/health/ready` e le metriche sono da definire. **Deciso in M0: ADR 0012.**
|
||||||
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.
|
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`).
|
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.
|
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).
|
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.
|
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,32 @@
|
|||||||
|
# ADR 0012 - Endpoint di salute
|
||||||
|
|
||||||
|
- **Stato:** accettata
|
||||||
|
- **Data:** 2026-11-11
|
||||||
|
- **Modifica:** SPEC §16.1, §20 (M0); chiude il punto aperto 5 di `docs/STATUS.md` (issue #114)
|
||||||
|
|
||||||
|
## Contesto
|
||||||
|
|
||||||
|
SPEC nomina `/health/live` (usato da `HEALTHCHECK`, dal compose e dal template Unraid) e un endpoint `/health` di
|
||||||
|
base in M0, ma non definisce la readiness né il contenuto delle risposte. Un controllo di liveness che dipende dal
|
||||||
|
database fa riavviare il container quando il database è solo lento.
|
||||||
|
|
||||||
|
## Decisione
|
||||||
|
|
||||||
|
| Endpoint | Risposta | Significato |
|
||||||
|
|---|---|---|
|
||||||
|
| `GET /health/live` | `200 text/plain "live"` | il processo risponde. Non tocca database, cache né file. È l'unico usato da `HEALTHCHECK` e dal compose |
|
||||||
|
| `GET /health/ready` | `200 "ready"` oppure `503 "starting"` | l'istanza può servire richieste: database di sistema raggiungibile, migrazioni di sistema applicate, bootstrap concluso. In M0 non ci sono dipendenze e risponde sempre `200`; i controlli si aggiungono in M1-M2 |
|
||||||
|
| `GET /health` | `200 application/json` `{status, live, ready, version, revision}` | riepilogo per l'amministratore e per la pagina *Stato sistema*; `status` è `ok` o `starting` |
|
||||||
|
|
||||||
|
Regole:
|
||||||
|
|
||||||
|
- risposte **senza autenticazione** e **senza dati sensibili**: niente versioni dei componenti, connection string,
|
||||||
|
nomi di aziende o percorsi. La versione del prodotto è pubblica (compare anche nella pagina di accesso);
|
||||||
|
- la modalità manutenzione di un'azienda non cambia la salute dell'istanza;
|
||||||
|
- le metriche (formato e percorso) si decidono in M2 con un ADR separato.
|
||||||
|
|
||||||
|
## Conseguenze
|
||||||
|
|
||||||
|
- `HealthEndpoints` in `Khaemhat.Web/Hosting` mappa i tre percorsi; i test web li chiamano su un host reale.
|
||||||
|
- In M1-M2 la readiness legge lo stato di `StartupOrchestrator`; un orchestratore esterno (Kubernetes o simili)
|
||||||
|
può usare `/health/ready` senza modifiche all'immagine.
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
# ADR 0013 - Utente non root con `PUID`/`PGID`
|
||||||
|
|
||||||
|
- **Stato:** accettata
|
||||||
|
- **Data:** 2026-11-11
|
||||||
|
- **Modifica:** SPEC §16.1, §16.4; chiude il punto aperto 3 di `docs/STATUS.md` (issue #114)
|
||||||
|
|
||||||
|
## Contesto
|
||||||
|
|
||||||
|
SPEC chiede un utente `app` non root e che i file in `/data` appartengano a `PUID`/`PGID` (99/100 su Unraid). Le
|
||||||
|
immagini `mcr.microsoft.com/dotnet/aspnet:10.0` hanno già un utente `app` (UID 1654). Le alternative erano: avviare
|
||||||
|
come root e cedere i privilegi nell'entrypoint, oppure avviare già come `app` e lasciare all'host la proprietà di
|
||||||
|
`/data` (rendendo inutili `PUID`/`PGID`).
|
||||||
|
|
||||||
|
## Decisione
|
||||||
|
|
||||||
|
- Il container **parte come root** solo per la preparazione; `docker/entrypoint.sh`:
|
||||||
|
1. legge `PUID`/`PGID` (predefiniti `1654`, l'utente `app` dell'immagine; i compose per Unraid passano `99`/`100`);
|
||||||
|
2. allinea UID e GID di `app` con `usermod`/`groupmod` se diversi;
|
||||||
|
3. crea `/data` se manca ed esegue `chown` **solo se** il proprietario della radice di `/data` non è già
|
||||||
|
`PUID:PGID` (niente `chown -R` a ogni avvio su volumi grandi);
|
||||||
|
4. avvia l'applicazione con `setpriv --reuid --regid --init-groups` (util-linux, già nell'immagine base): il
|
||||||
|
processo .NET **non gira mai come root**.
|
||||||
|
- Se il container è avviato già non root (`user:` nel compose, `--user`), l'entrypoint salta i passi 2-3 e avvia
|
||||||
|
direttamente l'applicazione: anche questa configurazione è supportata.
|
||||||
|
- `PUID=0` o `PGID=0` sono rifiutati con un messaggio esplicito.
|
||||||
|
|
||||||
|
## Conseguenze
|
||||||
|
|
||||||
|
- Funziona alla lettera con il template Unraid (variabili `PUID`/`PGID`) e con qualunque host Docker.
|
||||||
|
- Nessun pacchetto aggiuntivo (`setpriv`, `usermod`, `groupmod` sono nella base Debian dell'immagine).
|
||||||
|
- L'entrypoint è l'unico codice che gira come root; resta corto e senza logica applicativa (migrazioni e bootstrap
|
||||||
|
stanno nel codice .NET).
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
# ADR 0014 - Varianti `_FILE` delle variabili sensibili
|
||||||
|
|
||||||
|
- **Stato:** accettata
|
||||||
|
- **Data:** 2026-11-11
|
||||||
|
- **Modifica:** SPEC §6; chiude il punto aperto 4 di `docs/STATUS.md` (issue #114)
|
||||||
|
|
||||||
|
## Contesto
|
||||||
|
|
||||||
|
SPEC prevede la variante `_FILE` (Docker secrets) solo per `KHAEMHAT_SYSTEM_DB` e `KHAEMHAT_SUPERUSER_*`. Altre
|
||||||
|
variabili contengono segreti altrettanto delicati, a partire da `KHAEMHAT_SECRET_KEY`.
|
||||||
|
|
||||||
|
## Decisione
|
||||||
|
|
||||||
|
- Ammettono `_FILE` tutte le variabili sensibili: `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`.
|
||||||
|
- Una sola regola, in `EnvironmentConfigurationReader` (M1-M2): se esiste `X_FILE`, il valore di `X` è il contenuto
|
||||||
|
del file senza il fine riga finale; `X` e `X_FILE` impostati insieme sono un **errore di configurazione** che ferma
|
||||||
|
l'avvio con un messaggio esplicito; un file illeggibile è un errore.
|
||||||
|
- La risoluzione la fa **l'applicazione**, non l'entrypoint: i segreti non vengono esportati nell'ambiente dei
|
||||||
|
processi figli. L'entrypoint legge soltanto `KHAEMHAT_SYSTEM_DB` / `KHAEMHAT_SYSTEM_DB_FILE` per attendere il
|
||||||
|
database (ne usa host e porta, mai la password).
|
||||||
|
|
||||||
|
## Conseguenze
|
||||||
|
|
||||||
|
- La wiki *Installazione-Docker* e `docs/DEPLOY.md` elencano le variabili con `_FILE` secondo questo ADR.
|
||||||
|
- I test di `KhaemhatOptions` coprono: valore diretto, valore da file, entrambi (errore), file mancante (errore).
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
# ADR 0015 - Tag, versioni e pubblicazione dell'immagine
|
||||||
|
|
||||||
|
- **Stato:** accettata
|
||||||
|
- **Data:** 2026-11-11
|
||||||
|
- **Modifica:** SPEC §16.3, §16.5, Appendice D (con ADR 0009); chiude i punti aperti 6 e 7 di `docs/STATUS.md`
|
||||||
|
(issue #114)
|
||||||
|
|
||||||
|
## Contesto
|
||||||
|
|
||||||
|
Appendice D fa creare il tag git a `publish-image.sh`; con ADR 0009 `release.yml` parte sui tag `v*` e costruisce a
|
||||||
|
sua volta l'immagine: la stessa versione verrebbe costruita due volte. Il formato dei tag non era fissato.
|
||||||
|
|
||||||
|
## Decisione
|
||||||
|
|
||||||
|
- **Formato:** tag git `vX.Y.Z` (annotato, creato alla chiusura della milestone, E6); tag immagine `X.Y.Z` **senza
|
||||||
|
`v`**, più `latest` come comodità (mai in produzione). Versioni di prova: `vX.Y.Z-rc.N` → immagine `X.Y.Z-rc.N`,
|
||||||
|
senza `latest`.
|
||||||
|
- **Percorso normale:** push del tag → `release.yml` sul runner Gitea: build, smoke test di `/health/live`, push nel
|
||||||
|
registro pacchetti, release Gitea con le note dal `CHANGELOG.md`.
|
||||||
|
- **Percorso alternativo:** `scripts/publish-image.sh vX.Y.Z` costruisce e pubblica dalla macchina di sviluppo e
|
||||||
|
**non crea tag** git. Se in seguito si spinge il tag, `release.yml` vede che `X.Y.Z` è già nel registro
|
||||||
|
(`GET /api/v1/packages/<owner>/container/khaemhat/<X.Y.Z>` → `200`), salta build e push e crea solo la release.
|
||||||
|
- **Versione nel binario:** `/p:Version=X.Y.Z /p:SourceRevisionId=<sha>`; nelle build di sviluppo
|
||||||
|
`Directory.Build.targets` calcola `X.Y.Z-dev` dall'ultimo tag e lo SHA corrente.
|
||||||
|
|
||||||
|
## Conseguenze
|
||||||
|
|
||||||
|
- Ogni versione si costruisce una volta sola, qualunque sia il percorso.
|
||||||
|
- Il controllo aggiornamenti (§12.8, `GiteaPackagesClient`) confronta versioni SemVer senza `v`.
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
# ADR 0016 - Icona versionata generata sulla macchina di sviluppo
|
||||||
|
|
||||||
|
- **Stato:** accettata
|
||||||
|
- **Data:** 2026-11-11
|
||||||
|
- **Modifica:** SPEC §16.6 (con ADR 0009); chiude il punto aperto 8 di `docs/STATUS.md` (issue #114)
|
||||||
|
|
||||||
|
## Contesto
|
||||||
|
|
||||||
|
L'etichetta `net.unraid.docker.icon` e il template Unraid puntano a un PNG raggiungibile senza autenticazione (URL
|
||||||
|
raw del repository pubblico, ADR 0009). `scripts/build.sh` genera la variante SVG `icon-v<major.minor>.svg` con una
|
||||||
|
sostituzione di stringa, ma per il PNG serve un rasterizzatore, che l'applicazione non contiene né deve contenere
|
||||||
|
(SPEC §1.2).
|
||||||
|
|
||||||
|
## Decisione
|
||||||
|
|
||||||
|
- `scripts/build.sh --icon` genera `assets/icon-v<major.minor>.svg` dal modello `assets/icon-v1.0.svg` e, se sulla
|
||||||
|
macchina c'è un rasterizzatore, i PNG 128/256/512. Strumenti accettati, in ordine: `rsvg-convert` (librsvg),
|
||||||
|
`inkscape`, `magick` (ImageMagick). Senza nessuno dei tre lo script genera solo l'SVG e lo dice.
|
||||||
|
- I file generati si **committano su `main` prima** del tag che li usa.
|
||||||
|
- Al build dell'immagine (`release.yml`, `publish-image.sh`) l'URL dell'icona è
|
||||||
|
`.../raw/branch/main/assets/icon-v<major.minor>-256.png` se il file esiste nel repository, altrimenti
|
||||||
|
`.../assets/icon-256.png`. Le versioni `0.x` usano `icon-256.png`: la fascia "v 0.x" non serve prima della 1.0.
|
||||||
|
|
||||||
|
## Conseguenze
|
||||||
|
|
||||||
|
- Nessuna dipendenza nell'immagine né nella CI per la grafica.
|
||||||
|
- La checklist di chiusura milestone (`docs/DEVELOPMENT.md`) include la generazione dell'icona quando cambia
|
||||||
|
`major.minor`.
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
# ADR 0017 - `restore-system.sh` incluso nell'immagine
|
||||||
|
|
||||||
|
- **Stato:** accettata
|
||||||
|
- **Data:** 2026-11-11
|
||||||
|
- **Modifica:** SPEC §13, §16.1 (con ADR 0010); chiude il punto aperto 1 di `docs/STATUS.md` (issue #114)
|
||||||
|
|
||||||
|
## Contesto
|
||||||
|
|
||||||
|
Il database di sistema si ripristina solo da riga di comando, con l'istanza ferma (`scripts/restore-system.sh`,
|
||||||
|
SPEC §13). Con ADR 0010 l'unico artefatto distribuito è l'immagine: chi installa non ha il repository, e scaricare
|
||||||
|
uno script a parte al momento del bisogno è fragile (versione diversa da quella installata).
|
||||||
|
|
||||||
|
## Decisione
|
||||||
|
|
||||||
|
- L'immagine contiene `/app/scripts/restore-system.sh`, copiato dal repository alla stessa versione dell'app.
|
||||||
|
- Si usa con un container temporaneo sullo stesso volume e sulla stessa rete, con l'istanza ferma:
|
||||||
|
`docker compose run --rm --entrypoint /app/scripts/restore-system.sh khaemhat <file-di-backup>`.
|
||||||
|
- Lo script usa gli strumenti già presenti nell'immagine (`pg_restore` di `postgresql-client-17`, `curl`) e la
|
||||||
|
configurazione del container (`KHAEMHAT_SYSTEM_DB`, `KHAEMHAT_SECRET_KEY`). La logica completa arriva in M12; in
|
||||||
|
M0 è uno stub che spiega l'uso ed esce con errore.
|
||||||
|
|
||||||
|
## Conseguenze
|
||||||
|
|
||||||
|
- La wiki *Backup-e-ripristino* e *Aggiornamento* indicano il comando con `docker compose run`, non il download.
|
||||||
|
- Nessun altro script di sviluppo entra nell'immagine.
|
||||||
@@ -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.
|
||||||
@@ -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.
|
||||||
@@ -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.
|
||||||
@@ -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`.
|
||||||
@@ -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à.
|
||||||
@@ -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).
|
||||||
@@ -109,7 +109,7 @@ che non conosce. Il rollback dipende quindi dalle migrazioni:
|
|||||||
**Caso 2 — la nuova versione ha applicato migrazioni.**
|
**Caso 2 — la nuova versione ha applicato migrazioni.**
|
||||||
|
|
||||||
1. Ferma l'applicazione: `docker compose stop khaemhat`.
|
1. Ferma l'applicazione: `docker compose stop khaemhat`.
|
||||||
2. Ripristina il **database di sistema** dal backup fatto prima dell'aggiornamento con `scripts/restore-system.sh`
|
2. Ripristina il **database di sistema** dal backup fatto prima dell'aggiornamento con `restore-system.sh` incluso nell'immagine
|
||||||
(vedi [Backup e ripristino](Backup-e-ripristino#ripristino-del-database-di-sistema)).
|
(vedi [Backup e ripristino](Backup-e-ripristino#ripristino-del-database-di-sistema)).
|
||||||
3. Ripristina i **database delle aziende** migrate, dagli stessi backup (con la procedura manuale `pg_restore`
|
3. Ripristina i **database delle aziende** migrate, dagli stessi backup (con la procedura manuale `pg_restore`
|
||||||
descritta in [Backup e ripristino](Backup-e-ripristino#procedura-manuale-equivalente), perché l'applicazione è
|
descritta in [Backup e ripristino](Backup-e-ripristino#procedura-manuale-equivalente), perché l'applicazione è
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
# Allegati e file
|
# Allegati e file
|
||||||
|
|
||||||
> **Stato:** bozza · **Ultima revisione:** 2026-11-10 · **Versione software:** non ancora rilasciata (milestone M3, completata in M5)
|
> **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.delete`, permessi di lettura del documento · **Specifica:** SPEC §9.4
|
> **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
|
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
|
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)**.
|
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**.
|
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**.
|
||||||
|
|
||||||

|

|
||||||
*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).*
|
*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 — 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
|
## Regole di base
|
||||||
|
|
||||||
- Un allegato appartiene **a un solo documento** (o a una sola anagrafica). Non esistono allegati "sciolti": se lo
|
- 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 |
|
| occhio | **Anteprima** in app |
|
||||||
| freccia in giù | **Scarica** |
|
| freccia in giù | **Scarica** |
|
||||||
| busta | **Invia** per e-mail |
|
| busta | **Invia** per e-mail (con le vendite) |
|
||||||
| frecce circolari | **Rigenera**: crea una nuova versione del file generato |
|
| frecce circolari | **Rigenera** (nella sezione *Genera file*): crea una nuova versione del file generato |
|
||||||
| cestino | **Elimina** (solo file non bloccati e con permesso) |
|
| lucchetto | **Blocca**: da quel momento il file non si può più eliminare; accanto al nome indica un file bloccato |
|
||||||
| lucchetto | il 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:
|
In fondo all'elenco:
|
||||||
|
|
||||||
@@ -79,19 +89,41 @@ Il pannello apre in app l'anteprima di:
|
|||||||
|
|
||||||
| Formato | Come si vede |
|
| Formato | Come si vede |
|
||||||
|---|---|
|
|---|---|
|
||||||
| PDF | visualizzatore integrato |
|
| PDF | visualizzatore PDF del browser, dentro la finestra di anteprima |
|
||||||
| Immagini | a dimensione piena con zoom |
|
| Immagini (JPEG, PNG, GIF, WebP) | adattate alla finestra |
|
||||||
| XML | testo formattato e indentato |
|
| XML, testo | testo così com'è |
|
||||||
| CSV, XLSX | griglia |
|
| 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 — 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
|
||||||
|
|
||||||
|

|
||||||
|
*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 — l'anteprima di stampa del documento di prova, con Stampa, Apri PDF, Scarica PDF, Salva come allegato e l'ingrandimento.*
|
||||||
|
|
||||||
## Cestino
|
## Cestino
|
||||||
|
|
||||||
Quando un documento viene cancellato, i suoi allegati non spariscono subito: restano nel **cestino dell'azienda per
|
Quando un allegato viene spostato nel cestino, o quando viene cancellato il suo documento, il file non sparisce
|
||||||
30 giorni** e possono essere recuperati in quel periodo; poi vengono eliminati definitivamente. La maschera di
|
subito: resta nel **cestino dell'azienda per 30 giorni** e poi viene eliminato definitivamente da un'attività
|
||||||
consultazione del cestino sarà definita in sviluppo.
|
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
|
## Limiti e archiviazione
|
||||||
|
|
||||||
@@ -119,8 +151,10 @@ consultazione del cestino sarà definita in sviluppo.
|
|||||||
|
|
||||||
## Permessi e licenza
|
## Permessi e licenza
|
||||||
|
|
||||||
Gli allegati sono nel modulo **CORE**. Chi può leggere un documento ne vede gli allegati; caricare richiede il
|
Gli allegati sono nel modulo **CORE**. Vedere e scaricare richiede `attachments.read`; caricare, generare e bloccare
|
||||||
permesso di modifica del documento; cancellare richiede `attachments.delete`. Gli allegati sono raggiungibili anche
|
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)).
|
dalle API (download e caricamento su un documento, modulo API; vedi [API e MCP](API-e-MCP)).
|
||||||
|
|
||||||
## Domande frequenti
|
## Domande frequenti
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
# Architettura
|
# Architettura
|
||||||
|
|
||||||
> **Stato:** bozza · **Ultima revisione:** 2026-11-10 · **Versione software:** non ancora rilasciata (milestone M0-M13)
|
> **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 0009-0011
|
> **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
|
Come è fatto Khaemhat "dentro", spiegato senza entrare nel codice. Chi sviluppa trova il documento tecnico completo
|
||||||
(regole di dipendenza, contratti, elenco delle classi) in
|
(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
|
lavora solo nella sua azienda; gli amministratori scelgono l'azienda dalla barra superiore. Gestione in
|
||||||
[Istanza-e-database](Istanza-e-database).
|
[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.
|
||||||
|
|
||||||

|

|
||||||
*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).*
|
*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).*
|
||||||
|
|
||||||
|
|||||||
@@ -1,8 +1,13 @@
|
|||||||
# Attività programmate
|
# 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
|
> **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
|
## A cosa serve
|
||||||
|
|
||||||
Le **attività programmate** fanno lavorare Khaemhat da solo a orari stabiliti: backup notturni, fatturazione
|
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
|
## 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
|
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,
|
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
|
coda delle e-mail, verifica delle giacenze, backup. Le attività di sistema predefinite sono create con le tabelle di
|
||||||
|
|||||||
@@ -183,16 +183,19 @@ Khaemhat esegue un backup preventivo anche:
|
|||||||
## Ripristino del database di sistema
|
## Ripristino del database di sistema
|
||||||
|
|
||||||
Il database di sistema non si ripristina dall'interfaccia (l'interfaccia stessa dipende da lui). Si usa lo script
|
Il database di sistema non si ripristina dall'interfaccia (l'interfaccia stessa dipende da lui). Si usa lo script
|
||||||
`scripts/restore-system.sh` del repository, **con l'istanza ferma**:
|
`restore-system.sh`, incluso nell'immagine in `/app/scripts/`, **con l'istanza ferma**:
|
||||||
|
|
||||||
1. Ferma l'applicazione: `docker compose stop khaemhat` (PostgreSQL resta acceso).
|
1. Ferma l'applicazione: `docker compose stop khaemhat` (PostgreSQL resta acceso).
|
||||||
2. Esegui lo script indicando il file di backup del database di sistema. I parametri esatti sono documentati
|
2. Esegui lo script in un container temporaneo, sullo stesso volume e sulla stessa rete, indicando il file di
|
||||||
nell'intestazione dello script, che sarà scritto nella milestone M12.
|
backup del database di sistema:
|
||||||
|
```bash
|
||||||
|
docker compose run --rm --entrypoint /app/scripts/restore-system.sh khaemhat /data/backups/<file-di-backup>
|
||||||
|
```
|
||||||
|
Lo script completo arriva con la milestone M12; fino ad allora spiega l'uso ed esce senza fare nulla.
|
||||||
3. Riavvia: `docker compose start khaemhat`. All'avvio vengono applicate le eventuali migrazioni mancanti.
|
3. Riavvia: `docker compose start khaemhat`. All'avvio vengono applicate le eventuali migrazioni mancanti.
|
||||||
4. Accedi come super utente e controlla **Stato sistema** e l'elenco delle aziende.
|
4. Accedi come super utente e controlla **Stato sistema** e l'elenco delle aziende.
|
||||||
|
|
||||||
Lo script è uno strumento del repository e non è incluso nell'immagine: scaricalo da
|
Lo script ha sempre la stessa versione dell'applicazione installata, quindi non va scaricato a parte (ADR 0017).
|
||||||
[`scripts/`](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/src/branch/main/scripts) sul server che esegue Docker.
|
|
||||||
|
|
||||||
## Procedura manuale equivalente
|
## Procedura manuale equivalente
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
# Changelog
|
# Changelog
|
||||||
|
|
||||||
> **Stato:** bozza · **Ultima revisione:** 2026-11-10
|
> **Stato:** completa per 0.3.0 · **Ultima revisione:** 2026-11-11
|
||||||
|
|
||||||
Le novità di ogni versione sono nel file
|
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
|
[`CHANGELOG.md`](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/src/branch/main/CHANGELOG.md) del repository
|
||||||
@@ -11,10 +11,14 @@ Le novità di ogni versione sono nel file
|
|||||||
|
|
||||||
| Versione | Data | Contenuto |
|
| Versione | Data | Contenuto |
|
||||||
|---|---|---|
|
|---|---|---|
|
||||||
| *non rilasciata* | 2026-11-10 | Documentazione, specifica, mockup, wiki e pianificazione su Gitea. Nessun software ancora. |
|
| 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
|
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
|
## Pagine correlate
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
# Dashboard
|
# 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
|
> **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 è
|
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*.
|
|||||||

|

|
||||||
*Mockup 004 — dashboard con saluto e data, KPI, Da fare oggi, Fatto oggi, Scadenze prossimi 30 giorni, Da evadere, Fatturato 12 mesi (anteprima ridotta).*
|
*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 — la dashboard predefinita di un super utente. Indicatori, Da evadere e Fatturato 12 mesi si accendono quando arrivano i dati (vendite, M5).*
|
||||||
|
|
||||||

|

|
||||||
*Mockup 005 — la stessa dashboard in tema scuro (anteprima ridotta).*
|
*Mockup 005 — la stessa dashboard in tema scuro (anteprima ridotta).*
|
||||||
|
|
||||||
|

|
||||||
|
*Khaemhat 0.3.0 — la stessa dashboard in tema scuro.*
|
||||||
|
|
||||||

|

|
||||||
*Mockup 006 — modalità Personalizza: widget con bordo tratteggiato e pannello laterale con pagina iniziale ed elenco dei widget attivabili (anteprima ridotta).*
|
*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: 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
|
## 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 |
|
| 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 | |
|
| **Sottoscorta** | articoli sotto la scorta minima | |
|
||||||
| **Pipeline CRM** | valore delle opportunità per fase | richiede il modulo CRM |
|
| **Pipeline CRM** | valore delle opportunità per fase | richiede il modulo CRM |
|
||||||
| **Ultimi documenti** | ultimi documenti aperti o creati | |
|
| **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
|
Ogni widget ha in alto a destra le sue azioni: il numero di righe nelle liste, la matita delle **Scorciatoie** (scegli
|
||||||
completo). I dati rispettano i permessi: un utente che non vede costi e margini non li trova nemmeno nei widget.
|
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
|
## Come si personalizza
|
||||||
|
|
||||||
1. Premi **Personalizza** in alto a destra. I widget si contornano con un bordo tratteggiato e si apre il pannello
|
1. Premi **Personalizza** in alto a destra. I widget si contornano con un bordo tratteggiato e si apre il pannello
|
||||||
laterale **Personalizza dashboard**.
|
laterale **Personalizza dashboard**; la pagina resta utilizzabile e, sugli schermi larghi almeno 1280 px, si
|
||||||
2. Nel pannello, sezione **Widget (trascina per ordinare)**, attiva o disattiva ciascun widget con l'interruttore e
|
stringe per lasciare spazio al pannello.
|
||||||
trascinalo per cambiarne l'ordine.
|
2. Nel pannello, sezione **Widget**, accendi o spegni ciascun widget con l'interruttore; per quelli accesi scegli la
|
||||||
3. Sulla griglia trascina i widget per spostarli e ridimensionali (3, 4, 6, 8 o 12 colonne).
|
larghezza (*Un quarto*, *Un terzo*, *Metà*, *Due terzi*, *Tutta la riga*) e spostali con le frecce. Un widget
|
||||||
4. Imposta, se vuoi, il periodo dei KPI.
|
acceso si aggiunge in fondo.
|
||||||
5. Chiudi il pannello: la disposizione è salvata.
|
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
|
## Pagina iniziale e dashboard disattivabile
|
||||||
|
|
||||||
La dashboard si può **spegnere**. Nel pannello *Personalizza* (sezione **Pagina iniziale**) o in
|
La dashboard si può **spegnere**. Nel pannello *Personalizza* (sezione **Pagina iniziale**) o in
|
||||||
[Il mio profilo → Pagina iniziale](Preferenze-utente) scegli:
|
[Il mio profilo → Pagina iniziale](Preferenze-utente) scegli:
|
||||||
|
|
||||||
- **All'accesso apri**: *Dashboard*, oppure l'*ultima scheda aperta*, un *radar* (ad esempio *Clienti*), la *prima
|
- **Pagina da aprire**: *La pagina iniziale* (la dashboard), l'*ultima scheda aperta* o una delle pagine che puoi
|
||||||
nota*, l'*agenda CRM*…
|
aprire (ad esempio *Clienti*).
|
||||||
- **Mostra la dashboard**: se disattivato, la voce *Home* non mostra più i widget e all'accesso si apre la pagina
|
- **Mostra la dashboard**: se disattivato, la voce *Home* non mostra più i widget e all'accesso si apre la pagina
|
||||||
scelta.
|
scelta.
|
||||||
|
|
||||||
## Layout per ruolo
|
## Layout per ruolo
|
||||||
|
|
||||||
Gli amministratori possono definire un **layout predefinito per ruolo** (ad esempio un layout per *Vendite*, uno per
|
Chi ha il permesso **Modificare le impostazioni dell'azienda** (`company.settings.write`, ad esempio il ruolo
|
||||||
*Contabilità*): un nuovo utente parte dal layout del proprio ruolo e può poi modificarlo per sé. La maschera di
|
*Amministrazione*) trova in fondo al pannello la sezione **Predefinito per ruolo**: sceglie un ruolo e preme **Usa
|
||||||
gestione dei layout per ruolo sarà definita in sviluppo (vedi [Utenti e permessi](Utenti-e-permessi)).
|
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
|
## 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
|
- **Un widget non compare nell'elenco.** Il modulo relativo (ad esempio CRM) non è licenziato o non hai il permesso
|
||||||
di vederne i dati.
|
di vederne i dati.
|
||||||
- **Voglio tornare alla disposizione iniziale.** Un comando per ripristinare il layout del ruolo non è ancora
|
- **Voglio tornare alla disposizione iniziale.** *Personalizza* → **Ripristina**: torna il predefinito del tuo ruolo
|
||||||
definito nella specifica; sarà deciso in sviluppo e documentato qui. Nel frattempo riattiva o riordina i widget
|
o quello di Khaemhat.
|
||||||
da *Personalizza*.
|
- **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
|
- **"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.
|
pertinenti, chiedi all'amministratore di verificare il tuo ruolo.
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
# Design UI
|
# 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
|
> **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
|
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
|
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/`
|
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 — i mattoni di 020 e 021 dal vero: toolbar a icone, intestazione documento, schede interne, griglia delle righe.*
|
||||||
|
|
||||||
|

|
||||||
|
*Khaemhat 0.3.0 — la dashboard con tema scuro e accento Nilo.*
|
||||||
|
|
||||||
## Token di design
|
## 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
|
`AccentColor`, `Density`, `MenuState`). `ThemeService` e `MenuStateService` applicano gli attributi senza ricaricare
|
||||||
la pagina.
|
la pagina.
|
||||||
|
|
||||||
`mockup.css` **non contiene ancora i valori del tema alto contrasto**: vanno definiti in `tokens.css` rispettando il
|
`mockup.css` non contiene i valori del tema **alto contrasto**: sono definiti in `tokens.css` con gli stessi nomi di
|
||||||
contrasto AAA, con gli stessi nomi di token, e documentati in questa pagina.
|
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*`
|
## 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,
|
server, virtualizzazione, selezione multipla, editing inline, riga dei totali, layout colonne salvato, export,
|
||||||
evidenziazioni, menu di riga.
|
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
|
## Shell
|
||||||
|
|
||||||
- Griglia: barra superiore 46 px, area centrale, barra di stato 24 px; menu 228 px (60 px compresso).
|
- 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
|
- **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
|
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.
|
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.
|
- **Barra di stato**: testo 11.5 px, pallino `--kh-ok` per la connessione.
|
||||||
|
|
||||||
Dettagli d'uso in [Interfaccia e scorciatoie](Interfaccia-e-scorciatoie).
|
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.
|
**nessun font scaricato**, nessuna CDN.
|
||||||
- **Focus sempre visibile**, etichette collegate ai campi (`<label for>`), contrasto **AA** (AAA nel tema alto
|
- **Focus sempre visibile**, etichette collegate ai campi (`<label for>`), contrasto **AA** (AAA nel tema alto
|
||||||
contrasto), tutto operabile da tastiera.
|
contrasto), tutto operabile da tastiera.
|
||||||
- Desktop-first, usabile da tablet a partire da **768 px**.
|
- 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)).
|
||||||
- **Testi**: nessun testo hard-coded nei componenti (verificato da un test di architettura); `ITexts` risolve chiavi
|
- **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.
|
||||||
come `Sales.Invoice.Title` da `Resources/it-IT/*.json`.
|
- **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
|
- **Formati**: `CultureInfo("it-IT")` per numeri, importi e date; date memorizzate in UTC e mostrate nel fuso
|
||||||
`Europe/Rome`.
|
`Europe/Rome`.
|
||||||
|
|
||||||
## Stampa
|
## Stampa
|
||||||
|
|
||||||
Le stampe e i PDF sono **sempre in tema chiaro** (`print.css`), indipendentemente dal tema dell'utente. L'anteprima
|
Le stampe e i PDF sono **sempre in tema chiaro** (`print.css`), indipendentemente dal tema dell'utente. L'anteprima di
|
||||||
usa `.paper` (pagina bianca larga 794 px, cioè un A4 a 96 dpi, margini 40/44 px, tabelle con intestazione in
|
stampa (`KhPrintPreview`, mockup 025) mostra il documento come foglio `.kh-sheet` largo 210 mm e alto almeno 297 mm,
|
||||||
maiuscoletto e bordo inferiore marcato).
|
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 — l'anteprima di stampa del documento di prova.*
|
||||||
|
|
||||||
## Regola di aggiornamento
|
## Regola di aggiornamento
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
# Khaemhat
|
# Khaemhat
|
||||||
|
|
||||||
> **Stato:** bozza · **Ultima revisione:** 2026-11-10 · **Versione software:** non ancora rilasciata (sviluppo da avviare)
|
> **Stato:** bozza · **Ultima revisione:** 2026-11-10 · **Versione software:** 0.0.1 (M0, pagina "in costruzione"; sviluppo in corso)
|
||||||
|
|
||||||

|

|
||||||
|
|
||||||
|
|||||||
@@ -65,13 +65,14 @@ Regole pratiche:
|
|||||||
|
|
||||||
### Il file compose
|
### Il file compose
|
||||||
|
|
||||||
Il file definitivo è `deploy/docker-compose.yml` nel repository (sarà creato nella milestone M0). La struttura
|
Il file è [`deploy/docker-compose.yml`](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/src/branch/main/deploy/docker-compose.yml)
|
||||||
prevista è questa: applicazione, `postgres:17` e `redis:7` attivabile con un profilo.
|
nel repository: applicazione, `postgres:17` e `redis:7` attivabile con un profilo. La versione dell'immagine si
|
||||||
|
sceglie con `KHAEMHAT_VERSION` nel `.env`. In sintesi:
|
||||||
|
|
||||||
```yaml
|
```yaml
|
||||||
services:
|
services:
|
||||||
khaemhat:
|
khaemhat:
|
||||||
image: gitea.encke-hake.ts.net/balbosoft/khaemhat:1.0.0
|
image: gitea.encke-hake.ts.net/balbosoft/khaemhat:${KHAEMHAT_VERSION:-0.0.1}
|
||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
depends_on:
|
depends_on:
|
||||||
khaemhat-db: { condition: service_healthy }
|
khaemhat-db: { condition: service_healthy }
|
||||||
@@ -128,12 +129,12 @@ Note:
|
|||||||
## Demo autonoma con SQLite
|
## Demo autonoma con SQLite
|
||||||
|
|
||||||
Per provare Khaemhat senza PostgreSQL esiste `deploy/docker-compose.sqlite.yml`: un solo container, database di
|
Per provare Khaemhat senza PostgreSQL esiste `deploy/docker-compose.sqlite.yml`: un solo container, database di
|
||||||
sistema e aziende come file SQLite nel volume `/data`, dati di esempio caricati al primo avvio. Struttura prevista:
|
sistema e aziende come file SQLite nel volume `/data`, dati di esempio caricati al primo avvio. In sintesi:
|
||||||
|
|
||||||
```yaml
|
```yaml
|
||||||
services:
|
services:
|
||||||
khaemhat:
|
khaemhat:
|
||||||
image: gitea.encke-hake.ts.net/balbosoft/khaemhat:1.0.0
|
image: gitea.encke-hake.ts.net/balbosoft/khaemhat:${KHAEMHAT_VERSION:-0.0.1}
|
||||||
ports: ["8080:8080"]
|
ports: ["8080:8080"]
|
||||||
environment:
|
environment:
|
||||||
KHAEMHAT_SYSTEM_DB: sqlite:///data/system.db
|
KHAEMHAT_SYSTEM_DB: sqlite:///data/system.db
|
||||||
@@ -188,8 +189,9 @@ obbligatoria, termina con un messaggio che indica quale.
|
|||||||
| `KHAEMHAT_SEED_DEMO` | no | `false` | dati di esempio, solo su database vuoto |
|
| `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_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_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 |
|
| `TZ` | no | `Europe/Rome` | fuso orario |
|
||||||
| `PUID` / `PGID` | no | `99` / `100` | utente e gruppo proprietari dei file in `/data` |
|
| `PUID` / `PGID` | no | `1654` / `1654` (Unraid: `99` / `100`) | utente e gruppo proprietari dei file in `/data`; l'applicazione non gira mai come root |
|
||||||
|
|
||||||
Le variabili del super utente e della prima azienda sono lette solo al primo avvio (quando le tabelle
|
Le variabili del super utente e della prima azienda sono lette solo al primo avvio (quando le tabelle
|
||||||
corrispondenti sono vuote): cambiarle dopo non ha effetto. `KHAEMHAT_TEST_PG` e `KHAEMHAT_TEST_REDIS` servono solo
|
corrispondenti sono vuote): cambiarle dopo non ha effetto. `KHAEMHAT_TEST_PG` e `KHAEMHAT_TEST_REDIS` servono solo
|
||||||
@@ -198,8 +200,11 @@ ai test automatici e non vanno impostate in un'installazione.
|
|||||||
## Docker secrets
|
## Docker secrets
|
||||||
|
|
||||||
Per non scrivere le password in chiaro nel file compose, le variabili sensibili ammettono la variante `_FILE`: invece
|
Per non scrivere le password in chiaro nel file compose, le variabili sensibili ammettono la variante `_FILE`: invece
|
||||||
del valore contengono il percorso di un file da cui leggerlo. La specifica la prevede per `KHAEMHAT_SYSTEM_DB` e per
|
del valore contengono il percorso di un file da cui leggerlo. La accettano tutte le variabili sensibili: `KHAEMHAT_SYSTEM_DB`,
|
||||||
le variabili `KHAEMHAT_SUPERUSER_*`; l'elenco completo delle variabili che la accettano sarà fissato in sviluppo.
|
`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`. Il valore è il contenuto del file senza il fine riga finale;
|
||||||
|
impostare insieme `X` e `X_FILE` è un errore che ferma l'avvio.
|
||||||
|
|
||||||
```yaml
|
```yaml
|
||||||
services:
|
services:
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
# Interfaccia e scorciatoie
|
# 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)
|
> **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,
|
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.
|
|||||||

|

|
||||||
*Mockup 013 — la finestra con il menu laterale compresso: barra superiore, sottomenu Anagrafiche a comparsa, schede aperte, radar dei clienti e barra di stato.*
|
*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 con il menu espanso: barra superiore, menu, scheda Home con la dashboard predefinita e barra di stato.*
|
||||||
|
|
||||||
| Zona | Dove | Contenuto |
|
| Zona | Dove | Contenuto |
|
||||||
|---|---|---|
|
|---|---|---|
|
||||||
| Barra superiore | in alto, scura | marchio e versione, azienda, ricerca globale, nuovo, recenti, notifiche, tema, aiuto, utente |
|
| 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
|
**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).
|
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.
|
||||||
|
|
||||||

|

|
||||||
*Mockup 007 — dashboard con il menu compresso a sole icone e accento Turchese (anteprima ridotta).*
|
*Mockup 007 — dashboard con il menu compresso a sole icone e accento Turchese (anteprima ridotta).*
|
||||||
|
|
||||||
|

|
||||||
|
*Khaemhat 0.3.0 — lo stesso menu compresso a sole icone; la freccia in basso lo riapre.*
|
||||||
|
|
||||||
## Area a schede
|
## Area a schede
|
||||||
|
|
||||||
Ogni maschera aperta (un radar, un documento, una scheda anagrafica, una procedura) diventa una **scheda** in alto.
|
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.
|
- Un **pallino arancione** accanto al titolo indica modifiche non salvate.
|
||||||
- Chiudendo una scheda con modifiche non salvate Khaemhat chiede conferma.
|
- 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
|
- Si possono tenere aperte al massimo **12 schede**. Aprendone una tredicesima si chiude da sola quella usata meno di
|
||||||
sviluppo.
|
recente fra quelle **senza modifiche**; se tutte hanno modifiche da salvare, Khaemhat lo dice e non apre la nuova.
|
||||||
- `Ctrl+W` chiude la scheda attiva, `Ctrl+Tab` passa alla successiva; il pulsante `+` apre una nuova scheda.
|
- 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 — la Home su un telefono largo 390 px.*
|
||||||
|
|
||||||
## Barra di stato
|
## Barra di stato
|
||||||
|
|
||||||
@@ -91,6 +114,13 @@ e la **versione** del software con il commit (es. `v1.0.0 (a3f9c1e)`).
|
|||||||

|

|
||||||
*Mockup 009 — ricerca "rossi": risultati raggruppati per clienti, articoli, documenti, contabilità e azioni (anteprima ridotta).*
|
*Mockup 009 — ricerca "rossi": risultati raggruppati per clienti, articoli, documenti, contabilità e azioni (anteprima ridotta).*
|
||||||
|
|
||||||
|

|
||||||
|
*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
|
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
|
tipo: **clienti e fornitori**, **articoli**, **documenti**, **registrazioni e conti** contabili, **azioni** (ad
|
||||||
esempio *Nuova fattura per Rossi Impianti*, *Registra incasso*, *Scheda cliente a 360°*).
|
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` |
|
| `@` | persone (contatti, utenti) | `@ verdi` |
|
||||||
|
|
||||||
Con le frecce `↑` `↓` ti sposti tra i risultati, con `Invio` apri quello evidenziato; il piede della finestra ricorda
|
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
|
## Notifiche
|
||||||
|
|
||||||

|

|
||||||
*Mockup 010 — pannello laterale delle notifiche con filtri e azioni (anteprima ridotta).*
|
*Mockup 010 — pannello laterale delle notifiche con filtri e azioni (anteprima ridotta).*
|
||||||
|
|
||||||
|

|
||||||
|
*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à
|
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
|
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
|
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.
|
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**
|
In alto i filtri **Tutte** e **Non lette**, con il numero di voci; in basso **Segna tutte come lette**. Ogni voce ha
|
||||||
(che porta alla scheda *Notifiche* di [Il mio profilo](Preferenze-utente), dove si attiva anche il riepilogo via
|
il segno di spunta per segnarla come letta; il clic sul titolo la segna e apre la maschera collegata. Il numero
|
||||||
e-mail).
|
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)
|
## Aiuto in app (F1)
|
||||||
|
|
||||||

|

|
||||||
*Mockup 011 — l'aiuto della maschera Fatture: indice delle pagine a sinistra, pagina wiki con stato e revisione a destra.*
|
*Mockup 011 — l'aiuto della maschera Fatture: indice delle pagine a sinistra, pagina wiki con stato e revisione a destra.*
|
||||||
|
|
||||||
|

|
||||||
|
*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
|
`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
|
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
|
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
|
L'aiuto è una **copia della wiki contenuta nell'immagine Docker**, all'indirizzo `/aiuto` dell'istanza (`/help` porta
|
||||||
wiki all'indirizzo `/help` della propria istanza.
|
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
|
## Toolbar a icone
|
||||||
|
|
||||||

|

|
||||||
*Mockup 020 — fattura di vendita: toolbar a icone con il suggerimento "Salva Ctrl+S", azioni contestuali, intestazione documento e righe (anteprima ridotta).*
|
*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 — 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
|
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)).
|
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**.
|
(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**:
|
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.
|
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 — la scheda Storico del documento di prova (modifiche di esempio).*
|
||||||
|
|
||||||
## Radar
|
## Radar
|
||||||
|
|
||||||
@@ -239,13 +292,18 @@ azioni di riga. Gli sconti accettano la forma a cascata (`5+2`).
|
|||||||
|
|
||||||
| Digiti | Ottieni |
|
| Digiti | Ottieni |
|
||||||
|---|---|
|
|---|---|
|
||||||
| `T` | la data di oggi |
|
| `T` oppure `O` | la data di oggi |
|
||||||
| `F` | la fine del mese (il riferimento esatto, data del campo o mese corrente, sarà fissato in sviluppo) |
|
| `F` | la fine del mese della data già nel campo (del mese corrente se il campo è vuoto) |
|
||||||
| `+` / `-` | un giorno avanti / indietro |
|
| `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
|
**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
|
**calcolo** che inizia con `=`, ad esempio `=10*3` diventa `30`: valgono le quattro operazioni, le parentesi e il
|
||||||
sviluppo e documentate qui.
|
segno meno davanti a un numero, sempre con la virgola per i decimali (`=(12,5+3)*2` diventa `31`).
|
||||||
|
|
||||||
## Tabella completa delle scorciatoie
|
## Tabella completa delle scorciatoie
|
||||||
|
|
||||||
@@ -254,9 +312,10 @@ sviluppo e documentate qui.
|
|||||||
| `Ctrl+K` | ricerca globale | ovunque |
|
| `Ctrl+K` | ricerca globale | ovunque |
|
||||||
| `F1` | aiuto della maschera corrente | ovunque |
|
| `F1` | aiuto della maschera corrente | ovunque |
|
||||||
| `Ctrl+B` | comprime / espande il menu laterale | ovunque |
|
| `Ctrl+B` | comprime / espande il menu laterale | ovunque |
|
||||||
| `Ctrl+W` | chiude la scheda attiva | ovunque |
|
| `Ctrl+W` o `Alt+W` | chiude la scheda attiva | ovunque |
|
||||||
| `Ctrl+Tab` | passa alla scheda successiva | ovunque |
|
| `Ctrl+Tab` o `Alt+PagGiù` | passa alla scheda successiva | ovunque |
|
||||||
| `Ctrl+N` | nuovo record / documento | maschere e radar |
|
| `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 |
|
| `Ctrl+S` | salva | maschere |
|
||||||
| `Esc` | annulla le modifiche / chiude la finestra aperta | maschere, finestre |
|
| `Esc` | annulla le modifiche / chiude la finestra aperta | maschere, finestre |
|
||||||
| `Ctrl+Canc` | elimina il record (se ammesso) | maschere |
|
| `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 |
|
| `Tab` | cella o filtro successivo | griglia righe, finestra F4 |
|
||||||
| `Spazio` | seleziona la riga | radar |
|
| `Spazio` | seleziona la riga | radar |
|
||||||
| `Ctrl+D` | quadra la registrazione | prima nota (vedi [Contabilità](Contabilita)) |
|
| `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 |
|
| `=` | calcolo inline (`=10*3`) | campi numerici |
|
||||||
|
|
||||||
Le scorciatoie personali si potranno adattare nelle preferenze utente (§11.12 della specifica); l'interfaccia di
|
L'elenco è anche in **Il mio profilo → Scorciatoie** ([Preferenze utente](Preferenze-utente)). Le varianti con `Alt`
|
||||||
personalizzazione sarà definita in sviluppo.
|
esistono perché i browser non passano alla pagina `Ctrl+W`, `Ctrl+Tab` e `Ctrl+N` (ADR 0020).
|
||||||
|
|
||||||
## Permessi e licenza
|
## Permessi e licenza
|
||||||
|
|
||||||
@@ -289,6 +348,7 @@ un permesso negato.
|
|||||||
amministratore.
|
amministratore.
|
||||||
- **Ho chiuso una scheda per sbaglio.** Se c'erano modifiche non salvate Khaemhat ti ha chiesto conferma; il
|
- **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`.
|
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
|
- **Il menu si è compresso da solo.** Sotto i 1100 px di larghezza il menu parte compresso; allarga la finestra o
|
||||||
premi `Ctrl+B`.
|
premi `Ctrl+B`.
|
||||||
|
|
||||||
|
|||||||
@@ -1,8 +1,13 @@
|
|||||||
# Istanza e database
|
# 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
|
> **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
|
## A cosa serve
|
||||||
|
|
||||||
Un'installazione di Khaemhat (una **istanza**, cioè un container) può servire più aziende. Ogni azienda ha il
|
Un'installazione di Khaemhat (una **istanza**, cioè un container) può servire più aziende. Ogni azienda ha il
|
||||||
|
|||||||
@@ -1,8 +1,13 @@
|
|||||||
# Licenze e moduli
|
# 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
|
> **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
|
## A cosa serve
|
||||||
|
|
||||||
Khaemhat è diviso in **moduli** attivabili con licenza. La pagina **Licenze e moduli** mostra la licenza
|
Khaemhat è diviso in **moduli** attivabili con licenza. La pagina **Licenze e moduli** mostra la licenza
|
||||||
|
|||||||
@@ -1,8 +1,13 @@
|
|||||||
# Log
|
# 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
|
> **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
|
## A cosa serve
|
||||||
|
|
||||||
Il **log applicativo** registra ciò che succede in Khaemhat: accessi, documenti emessi, invii SDI, backup,
|
Il **log applicativo** registra ciò che succede in Khaemhat: accessi, documenti emessi, invii SDI, backup,
|
||||||
|
|||||||
@@ -1,12 +1,13 @@
|
|||||||
# Modello dati
|
# 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
|
> **Specifica:** SPEC §5, §11, §13, §14
|
||||||
|
|
||||||
Come Khaemhat organizza i dati, in sintesi. L'elenco completo di tabelle e colonne è in
|
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 è
|
[docs/DATA-MODEL.md](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/src/branch/main/docs/DATA-MODEL.md). La sua
|
||||||
la versione **pianificata**; dalla milestone M1 sarà generato automaticamente dal codice, quindi sempre allineato al
|
sezione *Schema attuale* è **generata automaticamente** dalle migrazioni del programma, quindi è sempre allineata a
|
||||||
programma.
|
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
|
## 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
|
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
|
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
|
manutenzione per il tempo necessario. Ogni migrazione è applicata
|
||||||
di ogni aggiornamento conviene un backup ([Aggiornamento](Aggiornamento), [Backup-e-ripristino](Backup-e-ripristino)).
|
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
|
## Pagine correlate
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
# Preferenze utente (Il mio profilo)
|
# 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)
|
> **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
|
**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
|
## Dove si trova
|
||||||
|
|
||||||
Menu utente in alto a destra (iniziali e nome) → **Il mio profilo**. Il percorso mostrato nella maschera è
|
Menu utente in alto a destra (iniziali e nome) → **Il mio profilo**, **Aspetto e colori** o **Sessioni attive**;
|
||||||
*Utente → Preferenze*.
|
oppure `Ctrl+K` e il comando corrispondente. L'indirizzo è `/profilo`, con `?scheda=aspetto`, `pagina-iniziale`,
|
||||||
|
`sessioni` o `scorciatoie` per aprire direttamente una scheda.
|
||||||
|
|
||||||

|

|
||||||
*Mockup 008 — scheda Aspetto con tema Scuro (notturno) e accento Ocra selezionati; a destra l'anteprima dal vivo.*
|
*Mockup 008 — scheda Aspetto con tema Scuro (notturno) e accento Ocra selezionati; a destra l'anteprima dal vivo.*
|
||||||
|
|
||||||
|

|
||||||
|
*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
|
## Schede della maschera
|
||||||
|
|
||||||
| Scheda | Contenuto |
|
| Scheda | Contenuto | Disponibile |
|
||||||
|---|---|
|
|---|---|---|
|
||||||
| **Aspetto** | tema, colore di accento, densità, dimensione testo, menu laterale, suggerimenti, animazioni |
|
| **Aspetto** | tema, colore di accento, densità, dimensione testo, menu laterale, suggerimenti, animazioni | 0.3.0 |
|
||||||
| **Dati personali** | nome, e-mail e altri dati del tuo utente |
|
| **Pagina iniziale** | cosa aprire all'accesso, dashboard sì/no | 0.3.0 |
|
||||||
| **Password e 2FA** | cambio password, attivazione della verifica in due passaggi |
|
| **Sessioni** | dispositivi collegati con il tuo utente, chiusura | 0.3.0 |
|
||||||
| **Sessioni** | dispositivi collegati con il tuo utente (il numero accanto al titolo indica quante sono) |
|
| **Scorciatoie** | l'elenco delle scorciatoie da tastiera | 0.3.0 |
|
||||||
| **Pagina iniziale** | cosa aprire all'accesso, dashboard sì/no |
|
| **Dati personali** | nome, e-mail e altri dati del tuo utente | 0.3.0 |
|
||||||
| **Layout salvati** | filtri e disposizioni di colonne memorizzati nei radar e nelle griglie |
|
| **Password e 2FA** | cambio password, attivazione della verifica in due passaggi | 0.3.0 |
|
||||||
| **Notifiche** | quali notifiche ricevere e il riepilogo via e-mail |
|
| **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
|
## Aspetto
|
||||||
|
|
||||||
@@ -35,12 +42,13 @@ In alto a destra: **Ripristina** (torna ai valori predefiniti) e **Salva**.
|
|||||||
|
|
||||||
| Tema | Descrizione |
|
| 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 |
|
| **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) |
|
| **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.
|
chiaro**, qualunque sia il tema scelto.
|
||||||
|
|
||||||
Il cambio tema rapido (sole/luna) nella barra superiore passa tra chiaro e scuro senza aprire il profilo.
|
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 |
|
| 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 |
|
| **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 |
|
| **Dimensione testo** | *100%* (13 px, predefinita), *110%*, *120%* |
|
||||||
| **Menu laterale** | *Espanso (ricorda l'ultimo stato)* o compresso all'avvio |
|
| **Menu laterale** | *Automatico* (compresso sotto i 1100 px, poi ricorda l'ultimo stato), *Espanso*, *Compresso* |
|
||||||
| **Carattere numerico tabellare** | cifre di larghezza fissa negli importi, così le colonne restano allineate |
|
| **Numeri tabellari** | cifre di larghezza fissa negli importi, così le colonne restano allineate (attivo) |
|
||||||
|
|
||||||
Interruttori:
|
Interruttori:
|
||||||
|
|
||||||
@@ -78,8 +86,8 @@ Interruttori:
|
|||||||
- **Evidenzia riga sotto il cursore nelle griglie**.
|
- **Evidenzia riga sotto il cursore nelle griglie**.
|
||||||
- **Animazioni ridotte** — riduce transizioni e movimenti.
|
- **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
|
Al posto del riquadro **Anteprima** del mockup, l'anteprima è la pagina stessa: ogni scelta si applica subito a
|
||||||
i badge di stato (*Bozza*, *Confermato*, *Emessa*, *Attenzione*, *Scartata*).
|
tutta l'interfaccia.
|
||||||
|
|
||||||
## Dati personali
|
## Dati personali
|
||||||
|
|
||||||
@@ -99,34 +107,39 @@ non si cambiano da qui: li assegna un amministratore ([Utenti e permessi](Utenti
|
|||||||
|
|
||||||
## Sessioni
|
## Sessioni
|
||||||
|
|
||||||
Elenco delle sessioni aperte con il tuo utente: dispositivo, indirizzo IP, data di inizio e ultima attività. Puoi
|
Elenco delle sessioni aperte con il tuo utente: dispositivo (browser e sistema), indirizzo IP, azienda, data di
|
||||||
**chiudere** (revocare) una sessione che non riconosci. Un accesso da un **nuovo dispositivo** genera una notifica
|
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
|
di sicurezza. Le sessioni scadono dopo un periodo di inattività (scadenza scorrevole) e contano nel numero di utenti
|
||||||
contemporanei previsto dalla licenza.
|
contemporanei previsto dalla licenza.
|
||||||
|
|
||||||
## Pagina iniziale
|
## Pagina iniziale
|
||||||
|
|
||||||
- **All'accesso apri**: *Dashboard*, *ultima scheda aperta*, un *radar* (ad esempio Clienti), la *prima nota*,
|
- **All'accesso apri**: *la pagina iniziale*, *le schede aperte l'ultima volta* (si riapre quella attiva), oppure
|
||||||
l'*agenda*…
|
*una pagina a scelta* fra quelle del menu che puoi aprire.
|
||||||
- **Mostra la dashboard**: sì/no. Vedi [Dashboard](Dashboard).
|
- **Mostra la dashboard**: sì/no. Vedi [Dashboard](Dashboard).
|
||||||
|
|
||||||
## Layout salvati
|
## Layout salvati
|
||||||
|
|
||||||
Qui trovi i **filtri salvati** (stella nei radar) e le **disposizioni delle colonne** delle griglie che hai
|
La scheda raccoglierà i **filtri salvati** (stella nei radar) e le **disposizioni delle colonne** delle griglie che
|
||||||
memorizzato, con la possibilità di eliminarli (le altre operazioni, come rinomina o scelta del predefinito, saranno
|
hai memorizzato, con la possibilità di eliminarli. **In questa versione** filtri e colonne si salvano e si eliminano
|
||||||
definite in sviluppo). Il numero accanto al titolo della scheda indica quanti sono.
|
direttamente dal radar e dalla griglia; la scheda nel profilo arriva con le prime maschere che li usano davvero
|
||||||
|
(anagrafiche, M4).
|
||||||
|
|
||||||
## Notifiche
|
## Notifiche
|
||||||
|
|
||||||
Scegli quali notifiche ricevere in app (documenti, SDI, scadenze, magazzino, sicurezza, attività programmate…) e se
|
La scheda permetterà di scegliere quali notifiche ricevere in app (documenti, SDI, scadenze, magazzino, sicurezza,
|
||||||
ricevere anche un **riepilogo via e-mail** (digest). L'elenco preciso delle categorie e quali di esse siano
|
attività programmate…) e se ricevere anche un **riepilogo via e-mail** (digest). **In questa versione** arrivano
|
||||||
obbligatorie saranno definiti in sviluppo. Vedi anche
|
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).
|
[Interfaccia e scorciatoie](Interfaccia-e-scorciatoie) (pannello notifiche).
|
||||||
|
|
||||||
## Dove sono salvate le preferenze
|
## Dove sono salvate le preferenze
|
||||||
|
|
||||||
Le preferenze sono salvate **nel database dell'azienda** e valgono su ogni dispositivo da cui accedi. Le preferenze
|
Le preferenze sono salvate **nel database**, non nel browser, e valgono su ogni dispositivo da cui accedi: per gli
|
||||||
esistono su tre livelli:
|
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 |
|
| Livello | Esempi | Chi le cambia |
|
||||||
|---|---|---|
|
|---|---|---|
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
# Primi passi
|
# 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
|
> **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
|
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,
|
*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).*
|
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`).
|
2. In **Nome utente** scrivi il nome del super utente (`KHAEMHAT_SUPERUSER`, predefinito `root`).
|
||||||
3. In **Password** scrivi la password iniziale (`KHAEMHAT_SUPERUSER_PASSWORD`).
|
3. In **Password** scrivi la password iniziale (`KHAEMHAT_SUPERUSER_PASSWORD`).
|
||||||
4. Spunta **Ricordami su questo dispositivo** solo su un computer personale.
|
4. Spunta **Ricordami su questo dispositivo** solo su un computer personale.
|
||||||
5. Premi **Accedi**.
|
5. Premi **Accedi**.
|
||||||
|
|
||||||
Il riquadro giallo in fondo al modulo ricorda che l'istanza è in **modalità Trial** finché non attivi una licenza
|
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
|
(passo 6). Il collegamento **Password dimenticata?** invia un link monouso all'indirizzo e-mail registrato; arriva con
|
||||||
solo dopo aver configurato la posta (SMTP) in **Amministrazione → Impostazioni**.
|
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
|
## 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
|
*Mockup 003 — cambio password al primo accesso, con indicatore di robustezza e avviso che la password del container
|
||||||
viene disattivata (anteprima ridotta).*
|
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**
|
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.
|
(minuscole, maiuscole, numeri, simboli), non deve contenere il nome utente e non ammette nessuna delle ultime 5
|
||||||
3. Ripetila in **Conferma nuova password** e controlla la barra **Robustezza**.
|
password usate.
|
||||||
4. Premi **Imposta password e continua**.
|
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
|
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.
|
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
|
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,
|
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à
|
RFC 6238). La schermata **Configura la verifica in due passaggi** non è tra i mockup (ADR 0019): mostra la chiave
|
||||||
definito in sviluppo.
|
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.
|
1. Apri l'app di autenticazione (Google Authenticator, Microsoft Authenticator, Aegis, 2FAS…) e aggiungi un nuovo
|
||||||
2. Scrivi in Khaemhat il codice a 6 cifre generato dall'app per confermare il collegamento.
|
account scrivendo la chiave mostrata da Khaemhat, oppure tocca **Apri nell'app di autenticazione** dal telefono.
|
||||||
3. Conserva in un luogo sicuro le eventuali informazioni di recupero proposte.
|
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**.
|
||||||
|
|
||||||

|

|
||||||
|
|
||||||
@@ -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
|
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.
|
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
|
> **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
|
## Passo 5 — Creare un amministratore
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
# Roadmap
|
# 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
|
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*.
|
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
|
[progetti](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/projects) *Khaemhat 1.0 — Sviluppo* e
|
||||||
*Khaemhat 1.1+ — Fase 2*.
|
*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 |
|
| # | 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 |
|
| 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 |
|
||||||
@@ -30,8 +32,8 @@ Il lavoro di dettaglio è nelle issue di Gitea, raggruppate per
|
|||||||
|
|
||||||
## Stato attuale
|
## Stato attuale
|
||||||
|
|
||||||
La documentazione e la pianificazione sono pronte (2026-11-10). Lo sviluppo parte dalla milestone M0 dopo il via
|
Sviluppo avviato il 2026-11-11. M0 consegna la versione 0.0.1 (struttura, immagine Docker, CI); poi si prosegue
|
||||||
del titolare del progetto. Lo stato aggiornato è in
|
milestone dopo milestone, a partire da M1 — Fondamenta dati. Lo stato aggiornato è in
|
||||||
[`docs/STATUS.md`](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/src/branch/main/docs/STATUS.md).
|
[`docs/STATUS.md`](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/src/branch/main/docs/STATUS.md).
|
||||||
|
|
||||||
## Pagine correlate
|
## Pagine correlate
|
||||||
|
|||||||
@@ -1,8 +1,14 @@
|
|||||||
# Utenti e permessi
|
# 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
|
> **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
|
## A cosa serve
|
||||||
|
|
||||||
Queste due pagine stabiliscono **chi entra** in Khaemhat e **cosa può fare**:
|
Queste due pagine stabiliscono **chi entra** in Khaemhat e **cosa può fare**:
|
||||||
|
|||||||
|
After Width: | Height: | Size: 122 KiB |
|
After Width: | Height: | Size: 119 KiB |
|
After Width: | Height: | Size: 84 KiB |
|
After Width: | Height: | Size: 159 KiB |
|
After Width: | Height: | Size: 93 KiB |
|
After Width: | Height: | Size: 89 KiB |
|
After Width: | Height: | Size: 215 KiB |
|
After Width: | Height: | Size: 89 KiB |
|
After Width: | Height: | Size: 74 KiB |
|
After Width: | Height: | Size: 54 KiB |
|
After Width: | Height: | Size: 98 KiB |
|
After Width: | Height: | Size: 101 KiB |
|
After Width: | Height: | Size: 99 KiB |
|
After Width: | Height: | Size: 93 KiB |
@@ -0,0 +1,7 @@
|
|||||||
|
{
|
||||||
|
"sdk": {
|
||||||
|
"version": "10.0.100",
|
||||||
|
"rollForward": "latestFeature",
|
||||||
|
"allowPrerelease": false
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,64 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# Builds the solution with warnings as errors (SPEC §19).
|
||||||
|
# scripts/build.sh [-c Debug|Release] build
|
||||||
|
# scripts/build.sh --icon [X.Y] also generate the versioned icon (ADR 0016); X.Y from the last tag
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
|
||||||
|
cd "$root"
|
||||||
|
|
||||||
|
configuration=Release
|
||||||
|
icon=""
|
||||||
|
while (( $# > 0 )); do
|
||||||
|
case "$1" in
|
||||||
|
-c | --configuration) configuration="${2:?manca la configurazione}"; shift 2 ;;
|
||||||
|
--icon)
|
||||||
|
if [[ "${2:-}" =~ ^[0-9]+\.[0-9]+$ ]]; then icon="$2"; shift 2; else icon="auto"; shift; fi ;;
|
||||||
|
-h | --help) sed -n '2,5p' "$0"; exit 0 ;;
|
||||||
|
*) echo "argomento sconosciuto: $1" >&2; exit 2 ;;
|
||||||
|
esac
|
||||||
|
done
|
||||||
|
|
||||||
|
# Generates assets/icon-v<X.Y>.svg from the template by string replacement, then the PNGs if a rasterizer exists.
|
||||||
|
generate_icon() {
|
||||||
|
local version="$1" svg png size tool=""
|
||||||
|
if [[ "$version" == "auto" ]]; then
|
||||||
|
version="$(git describe --tags --match 'v[0-9]*' --abbrev=0 2>/dev/null || true)"
|
||||||
|
[[ -n "$version" ]] || { echo "nessun tag vX.Y.Z: indica la versione, es. --icon 1.0" >&2; exit 2; }
|
||||||
|
version="${version#v}"
|
||||||
|
version="${version%.*}"
|
||||||
|
fi
|
||||||
|
|
||||||
|
svg="assets/icon-v${version}.svg"
|
||||||
|
if [[ "$version" != "1.0" ]]; then
|
||||||
|
sed "s/v 1\.0/v ${version}/" assets/icon-v1.0.svg > "$svg"
|
||||||
|
grep -q "v ${version}" "$svg" || { echo "il modello assets/icon-v1.0.svg non contiene il testo 'v 1.0'" >&2; exit 1; }
|
||||||
|
fi
|
||||||
|
echo "icona: $svg"
|
||||||
|
|
||||||
|
for candidate in rsvg-convert inkscape magick; do
|
||||||
|
if command -v "$candidate" > /dev/null 2>&1; then tool="$candidate"; break; fi
|
||||||
|
done
|
||||||
|
if [[ -z "$tool" ]]; then
|
||||||
|
echo "nessun rasterizzatore (rsvg-convert, inkscape, magick): genera i PNG su una macchina che ne ha uno (ADR 0016)." >&2
|
||||||
|
return 0
|
||||||
|
fi
|
||||||
|
|
||||||
|
for size in 128 256 512; do
|
||||||
|
png="assets/icon-v${version}-${size}.png"
|
||||||
|
case "$tool" in
|
||||||
|
rsvg-convert) rsvg-convert -w "$size" -h "$size" -o "$png" "$svg" ;;
|
||||||
|
inkscape) inkscape "$svg" --export-type=png --export-filename="$png" -w "$size" -h "$size" > /dev/null ;;
|
||||||
|
magick) magick -background none -density 384 "$svg" -resize "${size}x${size}" "$png" ;;
|
||||||
|
esac
|
||||||
|
echo "icona: $png ($tool)"
|
||||||
|
done
|
||||||
|
echo "Committa i file generati su main prima del tag che li usa (ADR 0016)."
|
||||||
|
}
|
||||||
|
|
||||||
|
bash scripts/check-packages.sh
|
||||||
|
dotnet build Khaemhat.sln -c "$configuration" -warnaserror
|
||||||
|
|
||||||
|
if [[ -n "$icon" ]]; then
|
||||||
|
generate_icon "$icon"
|
||||||
|
fi
|
||||||
@@ -0,0 +1,60 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# Package allowlist (SPEC §1.2, ADR 0002). Fails when an MSBuild file references a package that is not allowed, or an
|
||||||
|
# allowed package outside its project. The architecture tests check the same rules; this script runs before any build
|
||||||
|
# (Dockerfile, CI) so a forbidden package never gets restored.
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
|
||||||
|
cd "$root"
|
||||||
|
|
||||||
|
# package -> where it may be referenced (a project file name, or "tests/" for any test project)
|
||||||
|
allowed_in() {
|
||||||
|
case "$1" in
|
||||||
|
Npgsql) echo "src/Khaemhat.Data.PostgreSql/Khaemhat.Data.PostgreSql.csproj" ;;
|
||||||
|
Microsoft.Data.Sqlite) echo "src/Khaemhat.Data.Sqlite/Khaemhat.Data.Sqlite.csproj" ;;
|
||||||
|
Microsoft.NET.Test.Sdk | MSTest) echo "tests/" ;;
|
||||||
|
*) echo "" ;;
|
||||||
|
esac
|
||||||
|
}
|
||||||
|
|
||||||
|
# Prints "<file> <package>" for each element of the given kind (PackageReference, PackageVersion).
|
||||||
|
references() {
|
||||||
|
local element="$1" file
|
||||||
|
while IFS= read -r file; do
|
||||||
|
file="${file#./}"
|
||||||
|
grep -oE "<${element}[[:space:]]+(Include|Update)=\"[^\"]+\"" "$file" \
|
||||||
|
| sed -E 's/.*="([^"]+)"/\1/' \
|
||||||
|
| while IFS= read -r package; do printf '%s %s\n' "$file" "$package"; done || true
|
||||||
|
done < <(find . \( -name bin -o -name obj -o -name .git -o -name .claude -o -name out \) -prune -o \
|
||||||
|
-type f \( -name '*.csproj' -o -name '*.props' -o -name '*.targets' \) -print | sort)
|
||||||
|
}
|
||||||
|
|
||||||
|
errors=0
|
||||||
|
checked=0
|
||||||
|
while read -r file package; do
|
||||||
|
checked=$((checked + 1))
|
||||||
|
where="$(allowed_in "$package")"
|
||||||
|
if [[ -z "$where" ]]; then
|
||||||
|
echo "ERRORE: $file: il pacchetto $package non è nell'allowlist (SPEC §1.2)." >&2
|
||||||
|
errors=$((errors + 1))
|
||||||
|
elif [[ "$where" == "tests/" && "$file" != tests/* ]]; then
|
||||||
|
echo "ERRORE: $file: $package è ammesso solo nei progetti di test." >&2
|
||||||
|
errors=$((errors + 1))
|
||||||
|
elif [[ "$where" != "tests/" && "$file" != "$where" ]]; then
|
||||||
|
echo "ERRORE: $file: $package è ammesso solo in $where." >&2
|
||||||
|
errors=$((errors + 1))
|
||||||
|
fi
|
||||||
|
done < <(references PackageReference)
|
||||||
|
|
||||||
|
while read -r file package; do
|
||||||
|
if [[ -z "$(allowed_in "$package")" ]]; then
|
||||||
|
echo "ERRORE: $file: versione centrale per $package, che non è nell'allowlist." >&2
|
||||||
|
errors=$((errors + 1))
|
||||||
|
fi
|
||||||
|
done < <(references PackageVersion)
|
||||||
|
|
||||||
|
if (( errors > 0 )); then
|
||||||
|
echo "check-packages: $errors violazioni." >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
echo "check-packages: OK ($checked riferimenti a pacchetti, tutti ammessi)."
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# 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
|
||||||
|
|
||||||
|
root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
|
||||||
|
cd "$root"
|
||||||
|
|
||||||
|
dotnet run --project tools/Khaemhat.DataModelTool -c Release -- "$@" docs/DATA-MODEL.md
|
||||||
@@ -0,0 +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> <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
|
||||||
|
|
||||||
|
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,70 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# Builds the image on this machine and pushes it to the Gitea package registry (ADR 0009, ADR 0015). The normal path
|
||||||
|
# is release.yml on a vX.Y.Z tag; use this when the runner is not available. It does NOT create git tags: pushing the
|
||||||
|
# tag later makes release.yml find the version in the registry and only create the release.
|
||||||
|
#
|
||||||
|
# scripts/publish-image.sh vX.Y.Z [--arm64] [--force]
|
||||||
|
#
|
||||||
|
# Environment: GITEA_TOKEN (required, scope write:package), GITEA_URL (https://gitea.encke-hake.ts.net),
|
||||||
|
# GITEA_OWNER (BalboSoft), GITEA_USER (login of the token owner; defaults to GITEA_OWNER).
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
|
||||||
|
cd "$root"
|
||||||
|
|
||||||
|
tag="${1:-}"
|
||||||
|
[[ "$tag" =~ ^v[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.]+)?$ ]] || { echo "uso: publish-image.sh vX.Y.Z [--arm64] [--force]" >&2; exit 2; }
|
||||||
|
shift
|
||||||
|
platforms="linux/amd64"
|
||||||
|
force=false
|
||||||
|
for arg in "$@"; do
|
||||||
|
case "$arg" in
|
||||||
|
--arm64) platforms="linux/amd64,linux/arm64" ;;
|
||||||
|
--force) force=true ;;
|
||||||
|
*) echo "argomento sconosciuto: $arg" >&2; exit 2 ;;
|
||||||
|
esac
|
||||||
|
done
|
||||||
|
|
||||||
|
gitea_url="${GITEA_URL:-https://gitea.encke-hake.ts.net}"
|
||||||
|
gitea_url="${gitea_url%/}"
|
||||||
|
registry="${gitea_url#https://}"
|
||||||
|
registry="${registry#http://}"
|
||||||
|
owner="${GITEA_OWNER:-BalboSoft}"
|
||||||
|
owner_lc="$(printf '%s' "$owner" | tr '[:upper:]' '[:lower:]')"
|
||||||
|
image="$registry/$owner_lc/khaemhat"
|
||||||
|
version="${tag#v}"
|
||||||
|
sha="$(git rev-parse --short HEAD)"
|
||||||
|
token="${GITEA_TOKEN:?imposta GITEA_TOKEN (permesso write:package)}"
|
||||||
|
|
||||||
|
if [[ -n "$(git status --porcelain)" ]]; then
|
||||||
|
echo "ATTENZIONE: ci sono modifiche non committate; l'immagine riporterà lo SHA $sha." >&2
|
||||||
|
fi
|
||||||
|
|
||||||
|
status="$(curl -s -o /dev/null -w '%{http_code}' -H "Authorization: token $token" \
|
||||||
|
"$gitea_url/api/v1/packages/$owner/container/khaemhat/$version")"
|
||||||
|
if [[ "$status" == "200" && "$force" != true ]]; then
|
||||||
|
echo "La versione $version è già nel registro: niente da fare (usa --force per sovrascriverla)." >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Versioned icon for Unraid if committed, otherwise the plain one (ADR 0016).
|
||||||
|
major_minor="${version%%-*}"
|
||||||
|
major_minor="${major_minor%.*}"
|
||||||
|
icon_url="$gitea_url/$owner/Khaemhat/raw/branch/main/assets/icon-256.png"
|
||||||
|
if git cat-file -e "origin/main:assets/icon-v${major_minor}-256.png" 2>/dev/null; then
|
||||||
|
icon_url="$gitea_url/$owner/Khaemhat/raw/branch/main/assets/icon-v${major_minor}-256.png"
|
||||||
|
fi
|
||||||
|
|
||||||
|
tags=(-t "$image:$version")
|
||||||
|
[[ "$version" == *-* ]] || tags+=(-t "$image:latest")
|
||||||
|
|
||||||
|
printf '%s' "$token" | docker login "$registry" -u "${GITEA_USER:-$owner}" --password-stdin
|
||||||
|
docker buildx build --platform "$platforms" -f docker/Dockerfile \
|
||||||
|
--build-arg VERSION="$version" \
|
||||||
|
--build-arg GIT_SHA="$sha" \
|
||||||
|
--build-arg CREATED="$(date -u +%Y-%m-%dT%H:%M:%SZ)" \
|
||||||
|
--build-arg SOURCE_URL="$gitea_url/$owner/Khaemhat" \
|
||||||
|
--build-arg ICON_URL="$icon_url" \
|
||||||
|
"${tags[@]}" --push .
|
||||||
|
|
||||||
|
echo "Pubblicata $image:$version ($platforms)."
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# Publishes docs/wiki/ to the Gitea wiki (Khaemhat.wiki.git), the same job as .gitea/workflows/wiki.yml.
|
||||||
|
# The wiki becomes an exact copy of docs/wiki/: pages removed here are removed there.
|
||||||
|
#
|
||||||
|
# Environment: GITEA_URL (https://gitea.encke-hake.ts.net), GITEA_OWNER (BalboSoft); GITEA_TOKEN is optional (without
|
||||||
|
# it git uses the credentials already configured on this machine). WIKI_REMOTE overrides the whole URL.
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
|
||||||
|
cd "$root"
|
||||||
|
|
||||||
|
gitea_url="${GITEA_URL:-https://gitea.encke-hake.ts.net}"
|
||||||
|
remote="${WIKI_REMOTE:-${gitea_url%/}/${GITEA_OWNER:-BalboSoft}/Khaemhat.wiki.git}"
|
||||||
|
sha="$(git rev-parse --short HEAD)"
|
||||||
|
|
||||||
|
auth=()
|
||||||
|
if [[ -n "${GITEA_TOKEN:-}" ]]; then
|
||||||
|
auth=(-c "http.extraheader=Authorization: basic $(printf 'x-access-token:%s' "$GITEA_TOKEN" | base64 -w0)")
|
||||||
|
fi
|
||||||
|
|
||||||
|
work="$(mktemp -d)"
|
||||||
|
trap 'rm -rf "$work"' EXIT
|
||||||
|
|
||||||
|
git "${auth[@]}" clone -q --depth 1 "$remote" "$work/wiki"
|
||||||
|
find "$work/wiki" -mindepth 1 -maxdepth 1 ! -name .git -exec rm -rf {} +
|
||||||
|
cp -R docs/wiki/. "$work/wiki/"
|
||||||
|
|
||||||
|
cd "$work/wiki"
|
||||||
|
git add -A
|
||||||
|
if git diff --cached --quiet; then
|
||||||
|
echo "Wiki già allineata a docs/wiki ($sha)."
|
||||||
|
exit 0
|
||||||
|
fi
|
||||||
|
git -c user.name="${GIT_AUTHOR_NAME:-Khaemhat wiki}" -c user.email="${GIT_AUTHOR_EMAIL:-wiki@khaemhat.invalid}" \
|
||||||
|
commit -q -m "docs(wiki): sync from $sha"
|
||||||
|
git "${auth[@]}" push -q origin HEAD
|
||||||
|
echo "Wiki pubblicata da docs/wiki ($sha): $(git diff --stat HEAD~1 | tail -n 1)"
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# Restores the system database from a backup with the instance stopped (SPEC §13, ADR 0017). Shipped in the image as /app/scripts/restore-system.sh.
|
||||||
|
# docker compose run --rm --entrypoint /app/scripts/restore-system.sh khaemhat <file-di-backup>
|
||||||
|
# Stub: completed in milestone M12 (SPEC §20). Until then it explains what it will do and exits with an error.
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
echo "restore-system.sh: non ancora disponibile, arriva con la milestone M12." >&2
|
||||||
|
echo "Uso previsto: docker compose run --rm --entrypoint /app/scripts/restore-system.sh khaemhat <file-di-backup>" >&2
|
||||||
|
exit 1
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# Starts Khaemhat locally on http://localhost:5080 with SQLite in .data/dev (ignored by git).
|
||||||
|
# Any KHAEMHAT_* variable already set in the shell wins over the defaults below.
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
|
||||||
|
cd "$root"
|
||||||
|
|
||||||
|
data_dir="$root/.data/dev"
|
||||||
|
mkdir -p "$data_dir"
|
||||||
|
|
||||||
|
export ASPNETCORE_ENVIRONMENT="${ASPNETCORE_ENVIRONMENT:-Development}"
|
||||||
|
export KHAEMHAT_DATA_DIR="${KHAEMHAT_DATA_DIR:-$data_dir}"
|
||||||
|
export KHAEMHAT_SYSTEM_DB="${KHAEMHAT_SYSTEM_DB:-sqlite://$data_dir/system.db}"
|
||||||
|
# Development-only key: never use it outside this script.
|
||||||
|
export KHAEMHAT_SECRET_KEY="${KHAEMHAT_SECRET_KEY:-a2hhZW1oYXQtZGV2ZWxvcG1lbnQtb25seS1ub3QtYS1zZWNyZXQ=}"
|
||||||
|
export KHAEMHAT_SUPERUSER="${KHAEMHAT_SUPERUSER:-root}"
|
||||||
|
export KHAEMHAT_SUPERUSER_PASSWORD="${KHAEMHAT_SUPERUSER_PASSWORD:-Khaemhat-dev-1}"
|
||||||
|
export KHAEMHAT_COMPANY_CODE="${KHAEMHAT_COMPANY_CODE:-DEMO}"
|
||||||
|
export KHAEMHAT_COMPANY_NAME="${KHAEMHAT_COMPANY_NAME:-Khaemhat Demo S.r.l.}"
|
||||||
|
export KHAEMHAT_LICENSE_MODE="${KHAEMHAT_LICENSE_MODE:-test}"
|
||||||
|
export KHAEMHAT_SEED_DEMO="${KHAEMHAT_SEED_DEMO:-true}"
|
||||||
|
|
||||||
|
echo "Khaemhat in sviluppo: http://localhost:5080 (dati in $KHAEMHAT_DATA_DIR)"
|
||||||
|
exec dotnet run --project src/Khaemhat.Web -- --urls http://localhost:5080 "$@"
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# Loads base tables and demo data into a company database (SPEC §15).
|
||||||
|
# scripts/seed.sh --base | --demo [--scale N] [--company CODE]
|
||||||
|
# Stub: completed in milestone M4 (SPEC §20). Until then it explains what it will do and exits with an error.
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
echo "seed.sh: non ancora disponibile, arriva con la milestone M4." >&2
|
||||||
|
echo "Uso previsto: scripts/seed.sh --base | --demo [--scale N] [--company CODE]" >&2
|
||||||
|
exit 1
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# Runs every test (SPEC §20). SQLite always; PostgreSQL when KHAEMHAT_TEST_PG is set
|
||||||
|
# (e.g. postgres://khaemhat:secret@localhost:5432/postgres); Redis when KHAEMHAT_TEST_REDIS is set.
|
||||||
|
# Extra arguments go to "dotnet test", e.g. scripts/test.sh --filter FullyQualifiedName~Health
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
|
||||||
|
cd "$root"
|
||||||
|
|
||||||
|
export KHAEMHAT_LICENSE_MODE=test
|
||||||
|
echo "PostgreSQL: ${KHAEMHAT_TEST_PG:+attivo}${KHAEMHAT_TEST_PG:-non configurato (KHAEMHAT_TEST_PG), test saltati}"
|
||||||
|
echo "Redis: ${KHAEMHAT_TEST_REDIS:+attivo}${KHAEMHAT_TEST_REDIS:-non configurato (KHAEMHAT_TEST_REDIS), test saltati}"
|
||||||
|
|
||||||
|
bash scripts/check-packages.sh
|
||||||
|
dotnet test Khaemhat.sln -c Release "$@"
|
||||||
@@ -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.");
|
||||||
|
}
|
||||||
|
}
|
||||||