diff --git a/.forgejo/workflows/buildAndTest.yml b/.forgejo/workflows/buildAndTest.yml index cda246cc..ea58d2fe 100644 --- a/.forgejo/workflows/buildAndTest.yml +++ b/.forgejo/workflows/buildAndTest.yml @@ -21,33 +21,31 @@ on: push: branches: [ "main" ] pull_request: - branches: [ "main" ] + branches: [ "main", "release/*" ] jobs: - log-the-inputs: - runs-on: debian-latest - steps: - - run: | - echo "Log level: $LEVEL" - echo "Tags: $TAGS" - echo "Environment: $ENVIRONMENT" - env: - LEVEL: ${{ inputs.logLevel }} - TAGS: ${{ inputs.tags }} - build: - - runs-on: debian-latest - + runs-on: docker + container: + image: pazof/yavsc-build-env:debian13-dotnet10-android36-jdk21-v1 steps: - - uses: actions/checkout@v6 - - name: Setup .NET - uses: actions/setup-dotnet@v5 - with: - dotnet-version: 9.0.x - - name: Restore dependencies - run: dotnet restore - - name: Build - run: dotnet build --no-restore + - name: Clone yavsc + run: | + cd /src + git clone https://forgejo.pschneider.fr/notazof/yavsc.git _src + cd _src + if [ -n "${GITHUB_REF:-}" ]; then + git fetch origin "$GITHUB_REF" + git checkout FETCH_HEAD + fi + git submodule update --init --recursive + echo "✅ Checked out at $(git rev-parse HEAD) on $(git branch --show-current 2>/dev/null || echo detached HEAD)" + - name: Test - run: dotnet test --no-build --verbosity normal + run: | + echo "🚀 Lancement des tests..." + cd /src/_src && dotnet test \ + --verbosity normal \ + --filter="Category!=Platform-Android" \ + --logger "xunit;LogFileName=test-results.xml" \ + && echo "✅ Success !" || echo "❌ Fail ($?)!" diff --git a/.forgejo/workflows/release.yml b/.forgejo/workflows/release.yml new file mode 100644 index 00000000..a72f92bd --- /dev/null +++ b/.forgejo/workflows/release.yml @@ -0,0 +1,316 @@ +# Build and publish a release on the Forgejo source-of-truth instance +# with the PostIt Android APK as an attached asset. +# +# Triggered by a push of a git tag. Validates the tag/changelog pair, +# builds the APK using the existing Dockerfile (--target build-env), then +# publishes a Forgejo release via the Forgejo REST API and uploads the +# APK as an asset. +# +# Authentication uses ${{ secrets.GITHUB_TOKEN }} (auto-provided by the +# Forgejo runner, scoped to contents: write for the current repo). A +# dedicated PAT (${{ secrets.RELEASE_TOKEN }}) was the preferred option +# for least-privilege, but creating repo-level secrets is currently +# broken on this Forgejo instance (InsertEncryptedSecret fails with a +# UTF-8 byte-sequence error, probably a text-vs-bytea column type on +# the secret table). Bumping to Forgejo v16 should fix it; until then, +# the runner-provided token keeps the workflow operational. +# +# Why bash + jq + curl, no third-party actions: the runner's docker +# label points at pazof/yavsc-build-env, a Debian image with jq but +# without Node.js or python3. Any action like actions/checkout, +# rasterstate/forgejo-release-action, etc. fails with "executable +# file not found in $PATH". jq is shipped in the image from +# debian12-dotnet10-android36-v2 onward; earlier tags fell back to +# hand-rolled JSON building via sed, which was fragile (cf. PR #30: +# sed greedy + head -3 still matched author.id instead of the +# release id on the minified JSON this instance returns, PATCH +# /releases/1 → 404). Same constraint as +# .forgejo/workflows/buildAndTest.yml. +# +# This workflow complements .github/workflows/docker-publish-android.yml +# which targets the GitHub mirror; the validate-release logic mirrors +# the GitHub-side job so the two channels stay consistent. +name: Forgejo Release + +on: + push: + tags: + - '*' + workflow_dispatch: + inputs: + tag: + description: 'Tag à publier (requis en dispatch, ex. 1.0.6 ou 1.0.7-rc1).' + required: true + type: string + +permissions: + contents: write + +jobs: + # Job unique : validation tag/CHANGELOG + build APK + publication + # via l'API REST Forgejo (pas d'actions tierces Node). + release: + runs-on: docker + container: + image: pazof/yavsc-build-env:debian13-dotnet10-android36-jdk21-v1 + steps: + - name: Clone du repo au tag demandé + env: + # En push tag : github.ref_name est le tag. + # En workflow_dispatch : on lit l'input 'tag'. + TAG: ${{ github.event_name == 'push' && github.ref_name || inputs.tag }} + run: | + if [[ -z "$TAG" ]]; then + echo "::error::No tag provided. In workflow_dispatch, set the 'tag' input." + exit 1 + fi + + # WORKDIR de l'image (cf. dotnet-android-build-image/Dockerfile). + cd /src + + if [[ ! -d _src/.git ]]; then + git clone --depth=1 https://forgejo.pschneider.fr/notazof/yavsc.git _src + fi + + cd _src + git fetch --tags --force --prune origin + git checkout "$TAG" + + echo "Checked out at $(git rev-parse HEAD) on $(git describe --tags --always 2>/dev/null || echo unknown)" + + - name: Valider le tag et la section CHANGELOG + run: | + cd /src/_src + TAG="$(git describe --tags --exact-match HEAD 2>/dev/null || git rev-parse --short HEAD)" + echo "Validating tag $TAG" + + # Parse semver : MAJOR.MINOR.PATCH[-SUFFIX] + if [[ ! "$TAG" =~ ^([0-9]+)\.([0-9]+)\.([0-9]+)(-.*)?$ ]]; then + echo "::error::Tag '$TAG' does not match MAJOR.MINOR.PATCH[-SUFFIX] format." + exit 1 + fi + + MAJOR="${BASH_REMATCH[1]}" + MINOR="${BASH_REMATCH[2]}" + PATCH="${BASH_REMATCH[3]}" + SUFFIX="${BASH_REMATCH[4]}" + + # Classification du canal par parité du patch. + # Patch pair + pas de suffixe -> stable. + # Patch impair + pas de suffixe -> preview. + # Suffixe présent -> instable. + if [[ -n "$SUFFIX" ]]; then + CHANNEL="unstable" + elif (( PATCH % 2 == 0 )); then + CHANNEL="stable" + else + CHANNEL="preview" + fi + + echo "Tag $TAG classifié comme channel=$CHANNEL" + + # Seuls les suffixes explicitement autorisés déclenchent un + # release : -rcN et -betaN. Les autres suffixes (-alpha*, + # -dev*, -preview*, etc.) restent refusés — ils sont + # utilisables localement pour itérer, mais ne doivent pas + # être publiés comme release publique. + if [[ "$CHANNEL" == "unstable" ]]; then + if [[ ! "$SUFFIX" =~ ^-(rc|beta)([0-9]+)?$ ]]; then + echo "::error::Tag '$TAG' has suffix '$SUFFIX' which is not in the allowed release suffixes (-rcN, -betaN). Refusing to publish." + exit 1 + fi + fi + + # Lecture du CHANGELOG.md (doit exister à la racine du repo). + if [[ ! -f CHANGELOG.md ]]; then + echo "::error::CHANGELOG.md not found at repo root." + exit 1 + fi + + # Extraction de la section [TAG]. On cherche la première ligne + # commençant par '## [' qui contient '[TAG]' (entre '## [' et + # la prochaine ligne '## [' ou fin de fichier). awk en mode + # paragraphe suffit et reste POSIX. On garde aussi le titre + # (ligne `## [TAG] - channel`) pour la vérification du canal. + BODY=$(awk -v tag="[$TAG]" ' + /^## \[/ { + if (in_section) exit + if (index($0, tag) > 0) { + in_section=1 + print + next + } + } + in_section { print } + ' CHANGELOG.md) + + if [[ -z "$BODY" ]]; then + echo "::error::No section matching '## [$TAG]' found in CHANGELOG.md." + echo "Add a '## [$TAG] - $CHANNEL' section before tagging." + exit 1 + fi + + # Vérification cohérence du canal déclaré dans le suffixe. + # Format attendu : "## [TAG] - stable" / "- preview" / "- unstable". + # On lit la première ligne du body qui contient le titre. + TITLE=$(echo "$BODY" | head -1) + if [[ "$TITLE" != *" - $CHANNEL"* ]]; then + echo "::error::Section title '$TITLE' must declare suffix '- $CHANNEL' to match tag parity." + exit 1 + fi + + # Body pour la release : retire la première ligne (titre). + BODY=$(echo "$BODY" | tail -n +2) + + echo "Section CHANGELOG validée pour [$TAG] - $CHANNEL" + + # Expose channel + body pour les étapes suivantes via $GITHUB_ENV. + echo "RELEASE_CHANNEL=$CHANNEL" >> "$GITHUB_ENV" + echo "RELEASE_BODY<> "$GITHUB_ENV" + echo "$BODY" >> "$GITHUB_ENV" + echo "EOF" >> "$GITHUB_ENV" + echo "IS_PRERELEASE=$([ "$CHANNEL" = "stable" ] && echo false || echo true)" >> "$GITHUB_ENV" + + - name: Restore + run: | + cd /src/_src + dotnet restore + + - name: Build de PostIt.Android ARM64 + run: | + cd /src/_src + dotnet build src/PostIt/PostIt.Android/PostIt.Android.csproj \ + -c Release -r android-arm64 --no-restore -clp:ErrorsOnly + + - name: Build de PostIt.Android x64 + run: | + cd /src/_src + dotnet build src/PostIt/PostIt.Android/PostIt.Android.csproj \ + -c Release -r android-x64 --no-restore -clp:ErrorsOnly + + - name: Publier la release Forgejo via l'API REST + # Pas d'action tierce (pas de Node dans l'image runner). + # On parle à l'API Forgejo directement via curl. + # Docs : https://forgejo.pschneider.fr/api/swagger#/repository/release + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + GITHUB_API_URL: ${{ github.api_url }} + GITHUB_REPOSITORY: ${{ github.repository }} + TAG: ${{ github.event_name == 'push' && github.ref_name || inputs.tag }} + RELEASE_BODY: ${{ env.RELEASE_BODY }} + IS_PRERELEASE: ${{ env.IS_PRERELEASE }} + run: | + if [[ -z "$TAG" ]]; then + echo "::error::No tag resolved for the API call." + exit 1 + fi + + # Le runner Forgejo expose l'API sur github.api_url (par + # défaut http://…/api/v1). On retire le suffixe /api/v1 s'il + # est présent pour dériver la base du serveur, puis on + # reconstruit l'URL de l'API proprement. + API_BASE="${GITHUB_API_URL%/}" + API_BASE="${API_BASE%/api/v1}" + + # Construction des bodies JSON et extraction de champs via + # jq. L'image runner pazof/yavsc-build-env installe jq + # (>= 1.7) depuis debian12-dotnet10-android36-v2. La + # chaîne de construction --arg/--argjson garantit un + # escaping correct (backslashes, guillemets, newlines, + # caractères de contrôle Unicode) sans avoir à le + # reproduire à la main. + # + # json_escape et json_field à base de sed ont vécu : le + # sed greedy matche la dernière occurrence d'un champ + # dans la ligne, et l'API renvoie sur cette instance un + # JSON minifié d'une seule ligne où l'id de l'auteur + # (1, premier user du repo) suit l'id de la release + # (10706). PATCH /releases/ tombait + # alors en 404 "The target couldn't be found". jq + # résout les deux problèmes en une fois. + + # 1. Vérifier si la release existe déjà pour ce tag. + echo "::group::Check existing release for tag $TAG" + HTTP=$(curl -sS -o /tmp/existing.json -w '%{http_code}' \ + -H "Authorization: token $GITHUB_TOKEN" \ + -H "Accept: application/json" \ + "$API_BASE/api/v1/repos/$GITHUB_REPOSITORY/releases/tags/$TAG") + echo "GET releases/tags/$TAG -> HTTP $HTTP" + EXISTING_ID="" + if [[ "$HTTP" == "200" ]]; then + EXISTING_ID=$(jq -r '.id // empty' /tmp/existing.json) + echo "Existing release id: ${EXISTING_ID:-none}" + fi + echo "::endgroup::" + + # 2. Créer ou mettre à jour la release. + if [[ -n "$EXISTING_ID" ]]; then + echo "::group::Update release id=$EXISTING_ID" + jq -n \ + --arg body "$RELEASE_BODY" \ + --argjson prerelease "$IS_PRERELEASE" \ + '{body: $body, prerelease: $prerelease}' \ + > /tmp/patch.json + HTTP=$(curl -sS -o /tmp/release.json -w '%{http_code}' \ + -X PATCH \ + -H "Authorization: token $GITHUB_TOKEN" \ + -H "Content-Type: application/json" \ + -H "Accept: application/json" \ + --data-binary @/tmp/patch.json \ + "$API_BASE/api/v1/repos/$GITHUB_REPOSITORY/releases/$EXISTING_ID") + echo "PATCH release -> HTTP $HTTP" + echo "::endgroup::" + else + echo "::group::Create release" + jq -n \ + --arg tag "$TAG" \ + --arg name "$TAG" \ + --arg body "$RELEASE_BODY" \ + --argjson prerelease "$IS_PRERELEASE" \ + '{tag_name: $tag, name: $name, body: $body, prerelease: $prerelease}' \ + > /tmp/post.json + HTTP=$(curl -sS -o /tmp/release.json -w '%{http_code}' \ + -X POST \ + -H "Authorization: token $GITHUB_TOKEN" \ + -H "Content-Type: application/json" \ + -H "Accept: application/json" \ + --data-binary @/tmp/post.json \ + "$API_BASE/api/v1/repos/$GITHUB_REPOSITORY/releases") + echo "POST release -> HTTP $HTTP" + echo "::endgroup::" + fi + + if [[ "$HTTP" != "200" && "$HTTP" != "201" ]]; then + echo "::error::Release creation/update failed (HTTP $HTTP):" + cat /tmp/release.json + exit 1 + fi + + RELEASE_ID=$(jq -r '.id' /tmp/release.json) + echo "Release id=$RELEASE_ID" + + # 3. Upload l'APK en asset. + # Le nom du fichier passe en query string (?name=...), pas + # en argument positionnel entre --data-binary et l'URL : + # sinon curl l'interprète comme un second fichier d'input + # (un fichier nommé '?name=PostIt.Android.apk') et l'API + # Forgejo renvoie 400 "Missing 'name' parameter". + echo "::group::Upload PostIt APK assets" + for MARCH in arm64 x64; do + HTTP=$(curl -sS -o /tmp/asset.json -w '%{http_code}' \ + -X POST \ + -H "Authorization: token $GITHUB_TOKEN" \ + -H "Content-Type: application/octet-stream" \ + -H "Accept: application/json" \ + --data-binary "@/src/_src/src/PostIt/PostIt.Android/bin/Release/net10.0-android/android-$MARCH/fr.pschneider.postit-Signed.apk" \ + "$API_BASE/api/v1/repos/$GITHUB_REPOSITORY/releases/$RELEASE_ID/assets?name=PostIt.Android-$MARCH.apk") + echo "POST asset -> HTTP $HTTP" + if [[ "$HTTP" != "201" ]]; then + echo "::error::Asset upload failed (HTTP $HTTP):" + cat /tmp/asset.json + exit 1 + fi + done + echo "::endgroup::" + + echo "✅ Release publiée: $API_BASE/$GITHUB_REPOSITORY/releases/tag/$TAG" diff --git a/.github/workflows/docker-publish-android.yml b/.github/workflows/docker-publish-android.yml deleted file mode 100644 index 25c3aa2d..00000000 --- a/.github/workflows/docker-publish-android.yml +++ /dev/null @@ -1,36 +0,0 @@ -name: Build and Push Yavsc Apk - -on: - push: - branches: - - main - workflow_dispatch: - -jobs: - apk-deploy: - runs-on: ubuntu-latest - steps: - - name: Checkout du code - uses: actions/checkout@v7 - - # 1. Votre étape de build actuelle (on nomme l'image "postit-android") - # --target build-env : on ne veut que le stage de build (qui - # contient les artefacts .apk). Sans --target, Docker ciblerait - # le DERNIER stage du Dockerfile (blogs-runtime, qui est une - # image ASP.NET runtime sans aucun APK à extraire). - - name: Build de l'image Docker - run: docker build --build-arg ANDROID_TARGET_RID=android-arm64 --target build-env -t postit-android . - # 2. EXTRACTION : Créer un conteneur éphémère pour copier l'APK vers l'hôte GitHub - - name: Extraire l'APK du conteneur Docker - run: | - docker create --name extractor postit-android - docker cp extractor:/src/src/PostIt/PostIt.Android/bin/Release/net10.0-android/android-arm64/com.CompanyName.PostIt-Signed.apk ./PostIt.Android.apk - docker rm extractor - - - name: Téléverser l'APK en tant qu'Artéfact GitHub - uses: actions/upload-artifact@v7 - with: - name: application-apk-release - path: ./PostIt.Android.apk - retention-days: 7 - diff --git a/.github/workflows/docker-publish-backend.yml b/.github/workflows/docker-publish-backend.yml index 6c2431ae..d8466bdb 100644 --- a/.github/workflows/docker-publish-backend.yml +++ b/.github/workflows/docker-publish-backend.yml @@ -26,7 +26,7 @@ jobs: username: ${{ secrets.DOCKERHUB_USERNAME }} password: ${{ secrets.DOCKERHUB_TOKEN }} - name: Test - run: dotnet test --no-build --verbosity normal + run: dotnet test --no-build --verbosity normal --filter="Category!=Platform-Android" # 4. Build et Push de l'image de production finale - name: Build and push production image uses: docker/build-push-action@v7 diff --git a/.gitignore b/.gitignore index fb843f96..b7813f60 100644 --- a/.gitignore +++ b/.gitignore @@ -24,9 +24,21 @@ data/ appsettings.*.json appsettings-*.*.json +# Exception: the Testing-environment override for Yavsc.Org is a tracked +# configuration source, not a secrets file. TestWebApplicationFactory +# (Yavsc.Org.Tests) flips ASPNETCORE_ENVIRONMENT to "Testing" so +# AddConfiguration("org") in Program.Main loads this file as the +# last in the chain (it is optional). It overrides the connection +# string and SMTP section for the in-memory test host and contains +# no production secrets. +!src/Yavsc.Org/appsettings-org.Testing.json + generated/ *.tmp DataDir/ *.tests.trx *.tests.html + +*.log + diff --git a/.gitmodules b/.gitmodules new file mode 100644 index 00000000..eadf3c7f --- /dev/null +++ b/.gitmodules @@ -0,0 +1,3 @@ +[submodule "external/dotnet-android-build-image"] + path = external/dotnet-android-build-image + url = https://forgejo.pschneider.fr/notazof/dotnet-android-build-image.git diff --git a/.vscode/launch.json b/.vscode/launch.json index 76dc08d5..dc8d3c68 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -1,33 +1,57 @@ { - // Utilisez IntelliSense pour en savoir plus sur les attributs possibles. - // Pointez pour afficher la description des attributs existants. - // Pour plus d'informations, visitez : https://go.microsoft.com/fwlink/?linkid=830387 - "version": "0.2.0", - "configurations": [ - { - "name": "API", - "type": "dotnet", - "request": "launch", - "projectPath": "${workspaceFolder}/src/Api/Api.csproj" - }, - { - "name": "Yavsc.Org", - "type": "dotnet", - "request": "launch", - "projectPath": "${workspaceFolder}/src/Yavsc.Org/Yavsc.Org.csproj", - }, - { - "name": "Yavsc.Blogs", - "type": "dotnet", - "request": "launch", - "projectPath": "${workspaceFolder}/src/Yavsc.Blogs/Yavsc.Blogs.csproj" - }, - { - "name": "PostIt", - "type": "dotnet", - "request": "launch", - "projectPath": "${workspaceFolder}/src/PostIt/PostIt.Desktop/PostIt.Desktop.csproj", - - } - ] + // Utilisez IntelliSense pour en savoir plus sur les attributs possibles. + // Pointez pour afficher la description des attributs existants. + // Pour plus d'informations, visitez : https://go.microsoft.com/fwlink/?linkid=830387 + "version": "0.2.0", + "configurations": [ + { + "name": "Android Debug", + "type": "mono", + "preLaunchTask": "run-debug-android", + "request": "attach", + "address": "localhost", + "port": 55555 + }, + { + "name": "Android Attach - Debug", + "type": "mono", + "request": "attach", + "address": "localhost", + "port": 55555 + }, + { + "name": "API", + "type": "dotnet", + "request": "launch", + "projectPath": "${workspaceFolder}/src/Api/Api.csproj" + }, + { + "name": "Yavsc Org", + "type": "dotnet", + "request": "launch", + "projectPath": "${workspaceFolder}/src/Yavsc.Org/Yavsc.Org.csproj", + }, + { + "name": "Yavsc Blogs", + "type": "dotnet", + "request": "launch", + "projectPath": "${workspaceFolder}/src/Yavsc.Blogs/Yavsc.Blogs.csproj" + }, + { + "name": "PostIt Desktop", + "type": "dotnet", + "request": "launch", + "projectPath": "${workspaceFolder}/src/PostIt/PostIt.Desktop/PostIt.Desktop.csproj", + }, + { + "name": "Test PostIt.Android launch (Xamarin.UITest)", + "type": "coreclr", + "request": "launch", + "program": "${workspaceFolder}/src/PostIt/PostIt.Tests/bin/Debug/net10.0/PostIt.Tests.dll", + "args": [], + "cwd": "${workspaceFolder}/src/PostIt/PostIt.Tests", + "console": "integratedTerminal", + "stopAtEntry": false + } + ] } diff --git a/.vscode/mcp.json b/.vscode/mcp.json deleted file mode 100644 index 7ca6ed4b..00000000 --- a/.vscode/mcp.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "servers": { - "openclaw": { - "type": "stdio", - "command": "/home/paul/.nvm/versions/node/v22.23.0/bin/node", - "args": [ - "/home/paul/Workspace/tools/openclaw-mcp-server.js" - ] - } - } -} diff --git a/.vscode/settings.json b/.vscode/settings.json index 6e22cb5e..83a17ae3 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -2,25 +2,31 @@ "dotnet-test-explorer.testProjectPath": "test/**/*Tests.csproj", "cSpell.words": [ - "appsettings", - "asciidoctor", - "ASPNETCORE", - "Configurabilité", - "Cratie", - "DESTDIR", - "dotnet", - "DOTNET", - "ecdsa", - "envsubst", - "Newtonsoft", - "Npgsql", - "postit", - "pschneider", - "SLNDIR", - "validable", - "www-data", - "yavsc", - "Yavsc" + "appsettings", + "asciidoctor", + "ASPNETCORE", + "Avalonia", + "blogspot", + "Configurabilité", + "Cratie", + "DESTDIR", + "dotnet", + "DOTNET", + "ecdsa", + "envsubst", + "Forgejo", + "Hsts", + "Newtonsoft", + "Npgsql", + "Oidc", + "PKCE", + "postit", + "pschneider", + "SLNDIR", + "validable", + "www-data", + "yavsc", + "Yavsc" ], "cSpell.reportUnknownWords": true, "cSpell.language": "fr,en", @@ -38,5 +44,6 @@ "copilotcli/gpt-5.3-codex" ] } - } + }, + "dotnet.defaultSolution": "yavsc.sln" } diff --git a/.vscode/tasks.json b/.vscode/tasks.json index c384ec79..a30c9c06 100644 --- a/.vscode/tasks.json +++ b/.vscode/tasks.json @@ -1,6 +1,44 @@ { "version": "2.0.0", + "isRoot": true, + "problemMatcher": [ + { + "owner": "dotnet", + "fileLocation": ["relative", "${workspaceFolder}"], + "source": "dotnet", + "pattern": { + "regexp": "^\\s*(.*)\\((\\d+),(\\d+)\\):\\s+(error|warning) (.*)$", + "file": 1, + "line": 2, + "column": 3, + "severity": 4, + "code": 5, + "message": 6 + } + } + ], "tasks": [ + { + "label": "run-debug-android", + "command": "dotnet", + "type": "shell", + "options": { + "cwd": "${workspaceFolder}/src/PostIt/PostIt.Android", + "env": { + "DOTNET_HOST_PATH": "/usr/share/dotnet", + "ANDROID_HOME": "/opt/android-sdk", + "JAVA_HOME": "/usr/lib/jvm/java-1.25.0-openjdk-amd64" + } + }, + "args": [ + "run", + "-p:TargetFramework=net10.0-android", + "-p:Configuration=Debug", + "-p:AndroidAttachDebugger=true", + "-p:AndroidSdbHostPort=55555", + "-p:AndroidSdbTargetPort=55555" + ] + }, { "label": "build", "command": "dotnet", @@ -9,20 +47,20 @@ "group": "build", "isBuildCommand": true, "isTestCommand": false, - "problemMatcher": ["$msCompile"], "isBackground": true }, { - "label": "build-web", + "label": "test blogs backend", "type": "process", "problemMatcher": ["$msCompile"], "command": "dotnet", - "args": ["build"], + "args": ["test"], "options": { - "cwd": "src/Yavsc.Org" + "cwd": "src/Yavsc.Blogs.Tests" }, "group": { - "kind": "build" + "kind": "test", + "isDefault": false } }, { @@ -38,53 +76,6 @@ "kind": "build" }, "isBackground": true - }, - { - "label": "build-web", - "type": "process", - "problemMatcher": ["$msCompile"], - "command": "dotnet", - "args": ["build"], - "runOptions": {}, - "options": { - "cwd": "src/Yavsc.Web" - }, - "group": { - "kind": "build" - }, - "isBackground": true, - "presentation": { - "echo": true, - "reveal": "always", - "focus": false, - "panel": "shared", - "showReuseMessage": true, - "clear": false - } - }, - { - "label": "publish", - "command": "dotnet", - "type": "process", - "args": [ - "publish", - "/property:GenerateFullPaths=true", - "/consoleloggerparameters:NoSummary;ForceNoAlign" - ], - "problemMatcher": "$msCompile" - }, - { - "label": "watch", - "command": "dotnet", - "type": "process", - "args": ["watch", "--project", - "src/Yavsc.Org/Yavsc.Org.csproj" - ], - "problemMatcher": "$msCompile", - "runOptions": { - - } - } ] } diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 00000000..9bef40e3 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,313 @@ +# Changelog + +## [1.0.8-rc12] - unstable + +### Added + +* [PostIt] Nouveau helper d'image `ImageHelper` pour charger des bitmaps depuis les ressources et depuis le web. +* [PostIt] Affichage de l'avatar XS dans la liste des performers d'activites, avec fallback visuel (initiale utilisateur). +* [PostIt.Tests] Nouveaux tests autour des URLs avatar et de la source d'autorite. +* [contrib] Ajout d'un `README.md` utilitaire pour les symboles/icones. + +### Changed + +* [PostIt] Les avatars ne sont plus relies en string sur `Image.Source`: ils sont telecharges et lies en `Bitmap`. +* [Yavsc.Api.Client] `ActivityApiClient` accepte une base d'avatar dediee et construit les URLs avatar depuis l'autorite d'identification. +* [PostIt] Le header de `MainPage` n'utilise plus `ScrollViewer`; remplacement par une barre de commandes basee sur `WrapPanel`. +* [PostIt] Alignement de la navigation blogs: renommage `PushMainPageAsync` -> `PushBlogsPageAsync` et ajustement de `HomePageViewModel`. + +### Fixed + +néant + +## [1.0.8-rc11] - unstable + +### Added + +nothing + +### Changed + +* [Yavsc.Api.Test] Mise a jour de `Microsoft.EntityFrameworkCore.Sqlite` vers `10.0.11` afin de supprimer l'alerte NU1903 liee a `SQLitePCLRaw.lib.e_sqlite3` 2.1.11. +* [Yavsc.Org] Nettoyage de la configuration NuGet pour le restore: suppression du fichier local `Directory.Packages.props` au profit du fichier racine centralise. +* [Yavsc.Org] Suppression de references de packages redondantes dans le projet, sans impact fonctionnel attendu. + +### Fixed + +* [Yavsc.Api.Test] Le restore n'emet plus le warning de vulnerabilite `NU1903` sur `SQLitePCLRaw.lib.e_sqlite3`. +* [Yavsc.Org] Suppression d'une vulnerabilite de severite elevee sur AutoMapper apres publication et consommation de la nouvelle version candidate de `HigginsSoft.IdentityServer8`. + +## [1.0.8-rc10] - unstable + +### Added + +* [PostIt] Une page d'historique des commandes billing permet maintenant d'ouvrir une commande existante. +* [PostIt] Une vue "Demandes en cours" en lecture seule est disponible pour le performer, filtrée sur les statuts actifs (Inserted, Accepted, InProgress). +* [Yavsc.Org] Nouvelles entités `Country` et `PerformerCodeInputValidation` pour piloter la validation du code entreprise performer par pays. + +### Changed + +* [PostIt] La page détail billing se préremplit depuis une commande existante (Rdv, Brush, MBrush) et passe en mode mise à jour. +* [Yavsc.Org] Le formulaire `Manage/SetActivity` inclut désormais le pays d'exercice (`fr`, `en`, `pt`) et applique la regex associée au champ `SIREN`. +* [Yavsc.Org] La vérification externe du numéro d'entreprise est conservée uniquement pour le pays `fr`. + +### Fixed + +* [PostIt] Le flux historique n'est plus limité à une simple liste: l'action d'ouverture charge la commande cible puis navigue vers la page détail. +* [Yavsc.Org] Le champ `SIREN` n'est plus validé avec une règle unique indépendante du pays d'exercice. + +## [1.0.8-rc9] - unstable + +### Added + +nothing + +### Changed + +masquage non-owner côté backend de l'ACL du billet + +### Fixed + +On a maintenant le comportement attendu bout en bout: + +ACL chargée depuis le BlogPostDto +noms de cercles affichés dans le dialogue ACL côté PostIt + +## [1.0.8-rc8] - unstable + +### Added + +nothing + +### Changed + +nothing + +### Fixed + +The PostIt publish toggle button + +## [1.0.8-rc7] - unstable + +### Added + +* [PostIt] The search pattern now persists + +### Changed + +* The blog spot path is now `/api/v1/blogspot` (yet in last release) + +### Fixed + +* [Yavsc.Org] (Ticket #45) La forme de l'email de l'utilisateur est maintenant validée avant l'envoi du formulaire d'enregistrement + +## [1.0.8-rc6] - unstable + +### Added + +* a code cleanup, +* a first Xamarin.UITest is successful, but disabled, because breaking the actual CI process, +* Android app starts, the login process succeeds + +### Changed + +L'identifiant de l'application client Android a changé, il passe en minuscules : +`fr.pschneider.postit` + +### Fixed + +a bug posting and retrieving ACL from the backend, +the ACL now comes along with the article, +[TODO][PostIt] keep ACL along with the article + +## [1.0.8-rc1] - unstable + +### Added +- `BlogAclApiTests.PostCircleAuthorization_returns_201_when_payload_mirrors_PostIt_shape_against_existing_circle_named_test` + : test de non-régression qui épingle la forme exacte du payload + que PostIt envoie à `POST /api/v1/blogacl` (un objet + `PostAccessControlRulePayload` avec `CircleId` et `BlogPostId`). + C'est le verrou côté test du fix applicatif PostIt + serveur. +- `BlogAclApiTests.PostCircleAuthorization_never_returns_500` : une + `[Theory]` couvrant quatre shapes de payload (`{ circleId }`, + corps vide, `{ blogPostId }` seul, `{ circleId, blogPostId: 0 }`) + qui doivent tous retourner un statut différent de 500. Toute + réintroduction d'un chemin 500 dans le futur fera rougir ce test. +- `BlogAclApiTests.PostCircleAuthorization_dosent_return_500` et + `..._dosent_return_500_on_success` : entry points `[Fact]` qui + appellent la `[Theory]` ci-dessus avec un payload spécifique + chacun, pour pouvoir filtrer en isolation depuis la ligne de + commande ou le CI. +- Règle « Pas de `object` dans le code source applicatif » ajoutée + à `CONTRIBUTING.md` : types de retour, paramètres, champs, + propriétés, variables locales doivent être typés statiquement. + `dynamic` est interdit pour les mêmes raisons. + +### Changed +- `BlogAclApiController.CheckOwner` devient `CheckOwnerAsync` et + utilise `FirstOrDefaultAsync` au lieu de `First`, supprimant + l'appel LINQ synchrone sur le fil de la requête et retournant + `false` sur cercle manquant (le contrôleur mappe déjà cela vers + `ChallengeResult`). +- `BlogsWebServerFixture` seed `alice`, son `Circle` et son + `BlogPost` une seule fois au démarrage du host, sur la + `SqliteConnection` partagée (`Cache=Shared`). Le précédent + `EnsureDeleted` au début de chaque test fermait la connexion + statique et détruisait le store `:memory:` pour tous les autres + `DbContext` ; il est retiré au profit d'un `EnsureCreated` + idempotent. + +### Fixed +- `POST /api/v1/blogacl` ne retourne plus 500 sur les payloads + dont `BlogPostId` est absent ou à zéro. Le contrôleur rejette + `BlogPostId <= 0` avec `400 BadRequest` avant que la requête + n'atteigne `SaveChangesAsync`. L'incident de prod du 2026-08-21 + sur mercure (PostIt envoyant seulement `circleId`, le serveur + voyant `BlogPostId = default(long) = 0` et EF Core levant + `InvalidOperationException` sur l'INSERT) n'est plus atteignable. +- PostIt `PostAclDialogViewModel.AddAsync` envoie désormais le + payload explicite `PostAccessControlRulePayload { CircleId, + BlogPostId }` au lieu de l'ancien `CircleAuthorization { + CircleId }`. Le DTO serveur `PostAccessControlRulePayload` est + introduit dans `Yavsc.Abstract` pour porter le contrat. + +## [1.0.7] - preview + +### Added +- Per-post ACL in PostIt: a new “Manage ACL” page, opened from the ACL + button on a selected post, lets the post author grant or revoke + grants for individuals or circles. The server scopes each grant + operation to `caller == post.AuthorId` and returns `404` (not `403`) + for posts the caller does not own, so the existence of another + user's post is not leaked. +- Circle membership API + UI: three new REST endpoints under + `/api/circle/{id}/members` (`GET` list, `POST` add, `DELETE` + remove) and a new “Members” column on the *My Circles* page with an + “Add a member” button that opens a search modal. The search modal + reuses `IUserDirectory` (introduced by the `IContactService` split + in this same release) — exactly the use case the abstraction was + carved out for. +- Publish toggle for blog posts: a new `PUT /api/BlogApi/{id}/publish` + endpoint, and a `Published` checkbox in the post toolbar that + toggles a `BlogSpotPublication` row for the post. The publish + signal flows through the pre-existing `PermissionHandler.IsPublic` + path, so no new column was needed and the server-side authorisation + logic is unchanged. +- `UserSearchApiController` in `Yavsc.Blogs`: + `GET /api/user-search?q=...&e=...&take=...`. Any-authenticated- + caller endpoint that exposes the user's email under a closed- + community assumption (documented in the controller's XML doc). + Wired to the PostIt Desktop address book so the user search modal + picks it up. +- `IYavscApiClient` abstraction in `Yavsc.Api.Client`. The transport + for the blog/circle/blog-acl/user-search clients is now accessed + through this interface, so `PostIt.Tests` can stub the HTTP layer + without spinning up a real WebAPI host. +- Forgejo Actions release workflow: a `.forgejo/workflows/release.yml` + pipeline that builds and publishes a release with the PostIt APK + on tag push. Written in pure bash (the runner image has no Node), + uses `jq` for JSON body construction and response parsing, uses the + runner-provided `GITHUB_TOKEN` (no repo-level secret needed), + validates the CHANGELOG section heading before allowing the tag + to ship. +- `make release V=` target: creates a `release/` branch + from `main`, bumps the `` property in every `.csproj` via + `dotnet-gitversion /updateprojectfiles`, commits the bump on the + release branch, and pushes to `origin`. Fails fast if the working + tree is dirty or if `HEAD` is not on `main`. +- Forgejo status badges in the README. + +### Changed +- The new Publish toggle replaces the “Visibility enum” approach + originally drafted in this branch: the existing `BlogSpotPublication` + table already carried enough information to expose a publish + switch, so no schema change was needed. The original `feat(blog): + add Visibility { Private, Public }` commit and its EF migration + were reverted in favour of the endpoint-only toggle. +- `BlogPost` DTO and `IBlogPost` moved from `PostIt.Models` to + `Yavsc.Abstract.Blogspot`, the shared assembly where the server-side + entity and the wire DTO both live. Renamed `Yavsc.Blogspot.BlogPost` + to `BlogPostDto` to make the wire/entity distinction explicit. +- `BlogAclApiController` and `CircleApiController` moved from + `Yavsc.Api` (not yet enabled in production) to `Yavsc.Blogs`, where + they belong next to the `BlogSpotService` they depend on. +- `IContactService` split from `IUserDirectory`: the two interfaces + previously conflated the local address-book access (mobile-only, + via `Contacts.Default`) and the Yavsc user-search access + (Desktop-only, via `/api/user-search`) behind a single facade. The + split restores the `ContactDto.Emails` multi-value shape that was + being silently flattened to a single string before. +- CI: the Forgejo Actions build now compiles `.csproj` projects + directly inside the runner container (which ships the .NET SDK + + Android workload), instead of relying on a separate Docker build + step. Node-based third-party actions were replaced with bash + curl + + `jq`. The validate-release job parses the CHANGELOG section + heading to derive the channel (`stable` / `preview` / `unstable`) + rather than the patch-version parity alone. + +### Fixed +- `CircleApiController` used to read the caller's user id via + `FindFirstValue(ClaimTypes.NameIdentifier)`, which does not match + when JWT Bearer middleware has `MapInboundClaims = false`. Switched + to `User.GetUserId()` (tries `sub` first, then + `ClaimTypes.NameIdentifier`, then `nameid`). This was a latent + bug visible in tests but easy to ship to production if a host + ever disabled the remap. +- `CircleApiController` and `BlogAclApiController` reads and writes + were not always scoped to the caller's own data. Tightened the + authorisation checks: cross-user reads now return `404`, not the + raw record. +- `validate-release` CHANGELOG channel check used to parse the + patch-version parity only, which disagreed with the channel + suffix in the section heading (e.g. `## [1.0.7] - preview` + would be flagged as `stable` from the parity alone). The job now + inspects the heading line and trusts the suffix when present. +- `.forgejo/workflows/release.yml`: the asset-upload URL now carries + the asset name as a query-string parameter instead of a `curl` + positional argument. The previous shape triggered Forgejo's + “Missing `name` parameter” 400 in some cases. + +### Removed +- The `## [Unreleased]` block has been moved into this section. +- The abandoned `Visibility { Private, Public }` enum and its EF + migration, reverted in this release. The publish toggle covers + the same user-visible switch without a schema change. + +[Unreleased]: https://forgejo.pschneider.fr/notazof/yavsc/compare/HEAD +[1.0.8-rc1]: https://forgejo.pschneider.fr/notazof/yavsc/compare/1.0.7...1.0.8-rc1 +[1.0.7]: https://forgejo.pschneider.fr/notazof/yavsc/compare/1.0.6...1.0.7 +[1.0.6]: https://forgejo.pschneider.fr/notazof/yavsc/compare/1.0.5...1.0.6 + +## [1.0.6] - stable + +### Added +- Self-hosted Forgejo Actions runner now drives the CI build for the + yavsc repository, using the + `pazof/yavsc-build-env:debian12-dotnet10-android36-v2` image pulled + from Docker Hub. Workflow runs end-to-end: clone, restore, build, + test, with NuGet.config picking up the `isn.pschneider.fr` feed. +- The build-env image now ships `jq` (Debian package, ≥ 1.7), so the + release workflow can build JSON bodies and parse API responses + without a hand-rolled `sed`-based extractor that was matching the + wrong `id` field on minified responses. + +### Changed +- CI workflow `.forgejo/workflows/buildAndTest.yml` no longer relies on + `actions/checkout` (the runner image has no Node); clones yavsc via + `git`, fetches the ref under test, and initializes submodules over + HTTPS. + +### Fixed +- `Dockerfile` and `Dockerfile.backend` no longer carry a redundant + `dotnet nuget add source` step that conflicted with the GitHub + Actions APK build (`--allow-insecure-connections` on an HTTPS + endpoint, exit 1). `NuGet.config` at the repo root supplies the + `isn.pschneider.fr` feed for every restore, including inside Docker. +- `.forgejo/workflows/release.yml`: PATCH on `/releases/{id}` no longer + 404s on existing releases. The previous `sed`-based `json_field` + matched the last `id` on the line (the author's), so it tried to + PATCH `/releases/1` (the first user of the instance) instead of the + actual release id. Switched to `jq` for both body construction and + field extraction. + +[1.0.6]: https://forgejo.pschneider.fr/notazof/yavsc/compare/1.0.5...1.0.6 diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 4730e18c..8aa0567d 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -11,7 +11,7 @@ ## Premier build ```bash -git clone https://github.com/pazof/yavsc.git +git clone https://forgejo.pschneider.fr/notazof/yavsc.git cd yavsc dotnet restore dotnet build @@ -49,6 +49,90 @@ Les tests sont répartis en : item « Tests d'intégration smoke par BC ». - `src/PostIt.Tests/` — tests unitaires du client desktop PostIt. +## Onboarding assiste par agents IA + +Pour accelerer la prise en main du depot avec Copilot/Plan/Explore : + +- Parcours pas-a-pas : [doc/onboarding-agents.md](./doc/onboarding-agents.md) +- Playbook d'usage des agents : [doc/agent-playbook.md](./doc/agent-playbook.md) +- Matrice intentions -> agent -> preuves : [doc/agent-intent-matrix.md](./doc/agent-intent-matrix.md) + +Regle minimale en contribution assistee par agent : +- expliciter l'impact architecture, +- justifier le niveau de tests execute, +- documenter les risques residuels. + +## Le CHANGELOG.md + +Le `CHANGELOG.md` est un document de changement de version + +Toutes les modifications notables de PostIt et de la plateforme Yavsc +sont documentées dans ce fichier. + +Le format suit [Keep a Changelog](https://keepachangelog.com/fr/1.1.0/), +et ce projet adhère au [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +À noter : la **parité du numéro de patch** porte une signification de canal : + +- **patch pair** (ex. `1.0.0`, `1.0.2`) → **preview** +- **patch impair** (ex. `1.0.1`, `1.0.3`) → **stable** +- **suffixe** (ex. `1.0.0-rc1`, `1.0.0-alpha`) → **instable** + +Cette convention est partagée avec le dépôt +[`postit-debian`](https://forgejo.pschneider.fr/notazof/postit-debian) +pour la production des paquets `.deb`. + +## Navigation (PostIt) + +La navigation est centralisée dans +`App.PushPageAsync(ViewModelBase vm)` (`src/PostIt/PostIt/App.axaml.cs`). +Pour ouvrir un écran, un ViewModel (généralement dans une +commande `[RelayCommand]`) appelle +`await ((App)App.Current!).PushPageAsync(targetVm).ConfigureAwait(true);`. +`PushPageAsync` résout la `Control` correspondante via le +`ViewLocator` (un `IDataTemplate` enregistré dans +`Application.DataTemplates` au boot), l'identifie comme +`Page`, lui assigne le VM comme `DataContext`, et appelle +`NavRoot.PushAsync(page)`. Une garde anti-empilement +compare par référence la nouvelle page au sommet courant +de la stack pour éviter un push doublon. + +Pour qu'une nouvelle page soit navigable, il faut *deux* +enregistrements : la page dans le DI (`AddTransient` +ou `AddSingleton`) **et** une case dans le `switch` +de `ViewLocator.Build`. Si l'un manque, l'app affiche +"No view for X" sans crash. + +Règles : + +- On n'instancie jamais une `View` à la main depuis un + ViewModel, on ne récupère jamais une `View` depuis la DI + directement dans un ViewModel. +- Le ViewModel qui déclenche la nav ne pousse pas lui-même + la page ; il appelle `App.PushPageAsync(vm)` et laisse + `App` orchestrer le `PushAsync` physique. +- Le ViewModel qui déclenche la nav ne capture pas de + référence à `MainWindow` ou `NavigationPage`. Il passe + par `App.Current` (l'app Avalonia est un singleton). + +Exemple canonique (depuis `MainPageViewModel`) : + +```csharp +[RelayCommand] +internal async Task OpenSettings() +{ + var settingsVm = ((App)App.Current!).ServiceProvider + .GetRequiredService(); + await ((App)App.Current!).PushPageAsync(settingsVm) + .ConfigureAwait(true); +} +``` + +Cf. [doc/architecture/postit.md](./doc/architecture/postit.md) +pour la topologie complète (host de navigation, +`SessionStatusViewModel`, signaux de cycle de vie vs nav +utilisateur). + ## Conventions de code Le repo applique `.editorconfig` (UTF-8, LF, `indent_size = 4` en @@ -64,6 +148,13 @@ Quelques règles non capturées par `.editorconfig` : - Préférer les types BCL (`int`, `string`) aux types framework (`Int32`, `String`). - Préférer les expressions de pattern matching aux casts explicites. +- **Pas de `object` dans le code source applicatif.** Types de retour, + paramètres, champs, propriétés, variables locales : tout doit être + typé statiquement. `dynamic` est interdit pour les mêmes raisons. + Un cast en `object` est presque toujours le symptôme d'un contrat + qu'on a laissé s'effriter (DTO, payload, handler) — refactore + le contrat (record typé, DTO dédié, méthode dédiée) au lieu de + shimer avec un cast. ## Branches & commits diff --git a/Directory.Build.props b/Directory.Build.props index 873845c4..83d21579 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -1,15 +1,6 @@ Yavsc - - true + NU1701, NU1901, NU1902, NU1507 diff --git a/Directory.Packages.props b/Directory.Packages.props index e4b09159..f1be93f9 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -1,16 +1,31 @@ true + 8.1.0-pazofrc007 - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + @@ -18,13 +33,24 @@ + + + + + + + + + + + - \ No newline at end of file + diff --git a/Dockerfile b/Dockerfile index 88b11683..795b70ab 100644 --- a/Dockerfile +++ b/Dockerfile @@ -46,10 +46,6 @@ COPY src/PostIt/PostIt.Desktop/*.csproj ./src/PostIt/PostIt.Desktop/ # (2) Tout le code source COPY . . -# (3) Source NuGet interne (Letsencrypt, certificat auto-signé côté -# serveur, justifié par build privé). -RUN dotnet nuget add source https://isn.pschneider.fr/api/v3/index.json --allow-insecure-connections - # (4) Restore RUN dotnet restore diff --git a/Dockerfile.backend b/Dockerfile.backend index 76ad9ea0..a4e9a54a 100644 --- a/Dockerfile.backend +++ b/Dockerfile.backend @@ -25,9 +25,6 @@ COPY src/PostIt/PostIt.Desktop/*.csproj ./src/PostIt/PostIt.Desktop/ # 4. Copie de l'intégralité du code source COPY . . -# 3. Restauration des dépendances avec vos workloads actifs -RUN dotnet nuget add source https://isn.pschneider.fr/api/v3/index.json - # 4. Restauration des dépendances pour tous les projets RUN dotnet restore diff --git a/Makefile b/Makefile index 2683c542..08f0461d 100644 --- a/Makefile +++ b/Makefile @@ -48,5 +48,70 @@ docker-build: docker-run: docker run -d -p 5000:5000 --name yavsc yavsc +# Crée une branche release/ depuis main, met à jour les +# `` des .csproj via dotnet-gitversion, et la +# pousse sur origin. +# +# Usage : make release V=1.0.7-rc1 +# +# Pré-requis : être sur main, working tree clean. La cible +# vérifie les deux et refuse sinon — elle ne fait JAMAIS +# de checkout automatique, c'est à l'opérateur de s'être +# positionné sur la bonne branche au préalable (sinon le +# bump pourrait partir sur une branche tierce par accident). +# +# Notes : +# - Le nom de branche vient de l'argument V (ex: 1.0.7-rc1 +# donne release/1.0.7-rc1). C'est une étiquette d'intention, +# pas la version assembly. +# - La version dans les .csproj vient de GitVersion qui la +# calcule depuis l'historique git (tag le plus proche + +# nombre de commits). C'est la version assembly réelle. +# - L'ordre (fetch → branche → bump → push) garantit qu'on +# part d'un main synchro et qu'on ne pollue pas main avec +# le bump (qui vit sur la branche release). +# - Fail-fast si la branche existe déjà en local ou sur origin. +release: + @if [ -z "$(V)" ]; then \ + echo "Usage: make release V="; \ + echo " V : version semver (ex. 1.0.7-rc1) — sert à nommer la branche."; \ + exit 1; \ + fi + @if [ -n "$$(git status --porcelain)" ]; then \ + echo "Working tree sale, refus de créer une branche release."; \ + git status --short; \ + exit 1; \ + fi + @BRANCH="release/$(V)"; \ + if git show-ref --verify --quiet "refs/heads/$$BRANCH"; then \ + echo "La branche $$BRANCH existe déjà en local."; \ + echo " Pour la supprimer : git branch -D $$BRANCH"; \ + exit 1; \ + fi; \ + if git ls-remote --exit-code --heads origin "$$BRANCH" >/dev/null 2>&1; then \ + echo "La branche $$BRANCH existe déjà sur origin."; \ + exit 1; \ + fi; \ + echo "==> Fetch + vérification synchro main"; \ + git fetch origin main; \ + if ! git merge-base --is-ancestor origin/main HEAD; then \ + echo "main a avancé plus loin que HEAD. Fais :"; \ + echo " git pull --ff-only origin main"; \ + exit 1; \ + fi; \ + echo "==> Création de $$BRANCH depuis main"; \ + git checkout -b "$$BRANCH"; \ + echo "==> dotnet-gitversion /updateprojectfiles"; \ + dotnet-gitversion /updateprojectfiles; \ + echo "==> Commit du bump"; \ + git add .; \ + if git diff --cached --quiet; then \ + echo "Pas de changements à committer (gitversion n'a produit aucune diff)."; \ + else \ + git commit -m "chore(release): bump version via gitversion for $(V)"; \ + fi; \ + echo "==> Push de $$BRANCH sur origin"; \ + git push -u origin "$$BRANCH"; \ + echo "==> Terminé. Branche $$BRANCH live sur origin." -.PHONY: test +.PHONY: test release diff --git a/NuGet.config b/NuGet.config new file mode 100644 index 00000000..c601d09b --- /dev/null +++ b/NuGet.config @@ -0,0 +1,23 @@ + + + + + + + + + diff --git a/README.md b/README.md index d1ed912a..549348f4 100644 --- a/README.md +++ b/README.md @@ -1,16 +1,25 @@ # Yavsc + [![The latest release made in the repository](https://forgejo.pschneider.fr/notazof/yavsc/badges/release.svg)](https://forgejo.pschneider.fr/notazof/yavsc/releases/latest) C'est une application mettant en oeuvre une prise de contact entre un demandeur de services et son éventuel prestataire associé. +# Statut actuel des actions Forgejo + + +* [![Build and test](https://forgejo.pschneider.fr/notazof/yavsc/badges/workflows/buildAndTest.yml/badge.svg)](https://forgejo.pschneider.fr/notazof/yavsc/actions?workflow=buildAndTest.yml) + +* [![Release](https://forgejo.pschneider.fr/notazof/yavsc/badges/workflows/release.yml/badge.svg)]( +https://forgejo.pschneider.fr/notazof/yavsc/actions?workflow=release.yml +) + # Statut actuel des actions GitHub -* [![Build and Push Yavsc Apk](https://github.com/pazof/yavsc/actions/workflows/docker-publish-android.yml/badge.svg)](https://github.com/pazof/yavsc/actions/workflows/docker-publish-android.yml) +* [![CodeQL Advanced](https://github.com/pazof/yavsc/actions/workflows/codeql.yml/badge.svg)](https://github.com/pazof/yavsc/actions/workflows/codeql.yml) * [![Build and Push Yavsc Production Image](https://github.com/pazof/yavsc/actions/workflows/docker-publish-backend.yml/badge.svg)](https://github.com/pazof/yavsc/actions/workflows/docker-publish-backend.yml) -* [![CodeQL Advanced](https://github.com/pazof/yavsc/actions/workflows/codeql.yml/badge.svg)](https://github.com/pazof/yavsc/actions/workflows/codeql.yml) # Documentation @@ -19,6 +28,10 @@ sous [`doc/`](./doc/). Voir l'[index de la documentation](./doc/README.md) pour le sommaire complet. La racine de l'architecture est [Architecture.md](./doc/Architecture.md). +Pour une prise en main guidee avec agents IA: +- parcours onboarding: [doc/onboarding-agents.md](./doc/onboarding-agents.md) +- playbook d'usage: [doc/agent-playbook.md](./doc/agent-playbook.md) + # Construction et déploiement diff --git a/ROADMAP.md b/ROADMAP.md index 4c00e629..364b98bd 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -68,7 +68,7 @@ Trois principes non négociables traversent tous les jalons : > > Chaque jalon a un **critère de sortie** vérifiable. -### Jalon 0 — Fondations techniques *(en cours)* +### Jalon 0 — Fondations techniques > Cible : pouvoir parler du domaine sans se battre avec le runtime. @@ -81,7 +81,7 @@ Trois principes non négociables traversent tous les jalons : --- -### Jalon 1 — Prestation signée de bout en bout +### Jalon 1 — Prestation signée de bout en bout *(en cours)* > Cible : un projet client/fournisseur aboutit à un **devis signé par les deux parties**, traçable, avec notifications. diff --git a/contrib/.env-sample b/contrib/.env-sample new file mode 100644 index 00000000..fb01ede4 --- /dev/null +++ b/contrib/.env-sample @@ -0,0 +1,24 @@ +# parametres de déploiement au Makefile + +POSTGRES_HOST=localhost +POSTGRES_PORT=5432 +POSTGRES_DB=yavsc +POSTGRES_USER=yavsc +POSTGRES_PASSWORD= + +HTTP_HOST=localhost + +Org_PORT=83 +Blogs_PORT=85 +Api_PORT=87 + +PostIt_CLIENT_ID=postit + +ASPNETCORE_Smtp__Host="mercure.pschneider.fr" +ASPNETCORE_Smtp__Port=465 +ASPNETCORE_Smtp__SenderName="Paul Schneider" +ASPNETCORE_Smtp__SenderEmail="paul@pschneider.fr" +ASPNETCORE_Smtp__UserName="paul" +ASPNETCORE_Smtp__Password="" + +DESTDIR=/srv/www/yavsc diff --git a/contrib/Makefile b/contrib/Makefile index 62e1e22d..79145668 100644 --- a/contrib/Makefile +++ b/contrib/Makefile @@ -1,4 +1,4 @@ -APP_PROJECT_NAMES=Api Org Blogs +APP_PROJECT_NAMES=Org Blogs Api SLNDIR=.. include $(SLNDIR)/.env @@ -7,12 +7,13 @@ include .env generated/: @mkdir -p $@ -generated/yavscApi.service: generated/yavscOrg.service: generated/yavscBlogs.service: +generated/yavscApi.service: generated/yavsc%.service: generated/ template.service $(SLNDIR)/.env @cat template.service | APP_NAME="$*" \ + DESTDIR="$(DESTDIR)" \ HTTP_HOST="$(HTTP_HOST)" \ HTTP_PORT="$*_$(HTTP_PORT)" \ BASEAPPDIR="$(BASEAPPDIR)" \ @@ -34,12 +35,12 @@ generated/yavsc%.service: generated/ template.service $(SLNDIR)/.env @echo Created service file: $@ -copy-services: copy-service-Org copy-service-Api copy-service-Blogs +copy-services: copy-service-Org copy-service-Blogs copy-service-Api copy-service-Org: /etc/systemd/system/yavscOrg.service -copy-service-Api: /etc/systemd/system/yavscApi.service copy-service-Blogs: /etc/systemd/system/yavscBlogs.service +copy-service-Api: /etc/systemd/system/yavscApi.service -copy-binaries: build_publish_Org build_publish_Api build_publish_Blogs stop-services +copy-binaries: build_publish_Org build_publish_Blogs build_publish_Api stop-services @for project in $(APP_PROJECT_NAMES); \ do LCAPI=$$(echo $${project}|tr [:upper:] [:lower:]) ; \ echo "$${project} -> $${LCAPI}" ; \ @@ -55,24 +56,26 @@ copy-binaries: build_publish_Org build_publish_Api build_publish_Blogs stop-serv done @sudo chown -R $(USER_AND_GROUP) $(BASEAPPDIR) -/etc/systemd/system/yavsc%.service: generated/yavsc%.service +/etc/systemd/system/yavsc%.service: generated/yavsc%.service sudo cp $^ $@ sudo chown root:root $@ build_publish_%: clean_publish_dir_% @ASPNETCORE_ENV=$(CONFIGURATION) dotnet publish $(SLNDIR)/src/Yavsc.$*/Yavsc.$*.csproj +build_publish: build_publish_Org build_publish_Blogs build_publish_Api + clean_publish_dir_%: @rm -rf $(SLNDIR)/src/Yavsc.$*/bin/$(CONFIGURATION)/$(DOTNET_FRAMEWORK)/publish -install: build_publish copy-binaries copy-services +install: build_publish copy-binaries copy-services @sudo systemctl daemon-reload @for project in $(APP_PROJECT_NAMES); \ do \ sudo systemctl enable yavsc$${project} ; \ sudo systemctl start yavsc$${project} ; \ done - + reinstall: copy-binaries @sync @for project in $(APP_PROJECT_NAMES); do \ @@ -88,11 +91,10 @@ $(SLNDIR)/src/Yavsc.Org/bin/$(CONFIGURATION)/$(DOTNET_FRAMEWORK)/publish: build_ $(SLNDIR)/src/Yavsc.Blogs/bin/$(CONFIGURATION)/$(DOTNET_FRAMEWORK)/publish: build_publish $(SLNDIR)/src/Yavsc.Api/bin/$(CONFIGURATION)/$(DOTNET_FRAMEWORK)/publish: build_publish -showConfig: +showConfig: @echo CONFIGURATION: $(CONFIGURATION) @echo BASEAPPDIR: $(BASEAPPDIR) clean: @rm -rf generated -.PHONY: build_publish mep showConfig copy-service-Api copy-service-Org copy-service-Blogs reinstall clean diff --git a/contrib/README.md b/contrib/README.md new file mode 100644 index 00000000..01156156 --- /dev/null +++ b/contrib/README.md @@ -0,0 +1,5 @@ +# Read me + +## Note aux icones + +㝉®🅬⛒⛑🩎🩺🞫🞮🞕🞖🞆🔴🔵🔲🖂🔧🔩🔐🔌💾💼💬💭👿👾🏷🎯🏹🌍🎎💩 diff --git a/contrib/bruno/blog post.yml b/contrib/bruno/blog post.yml new file mode 100644 index 00000000..94e2745f --- /dev/null +++ b/contrib/bruno/blog post.yml @@ -0,0 +1,22 @@ +info: + name: blog post + type: http + seq: 2 + +http: + method: POST + url: "{{Blogs}}/api/v1/blog" + body: + type: json + data: |- + { + "Title": "lkijlk", + "Article": "test" + } + auth: inherit + +settings: + encodeUrl: true + timeout: 0 + followRedirects: true + maxRedirects: 5 diff --git a/contrib/bruno/opencollection.yml b/contrib/bruno/opencollection.yml index 701cace5..374cd0e1 100644 --- a/contrib/bruno/opencollection.yml +++ b/contrib/bruno/opencollection.yml @@ -25,7 +25,7 @@ request: credentials: clientId: postit placement: basic_auth_header - scope: openid blogs + scope: openid blogs profile pkce: {} tokenConfig: id: credentials diff --git a/contrib/tmp/yavscBlogs.service b/contrib/tmp/yavscBlogs.service new file mode 100644 index 00000000..718534cd --- /dev/null +++ b/contrib/tmp/yavscBlogs.service @@ -0,0 +1,37 @@ +[Unit] +Description=yavsc-Blogs +After=syslog.target +After=network.target +Wants=postgresql.service +After=postgresql.service + +[Service] +RestartSec=5s +Type=simple +User=yavsc +Group=yavsc +WorkingDirectory=/srv/www/yavsc +ExecStart=/srv/www/yavsc/Yavsc.Blogs +Restart=always +Environment="HOME=" +Environment="ANTHROPIC_API_KEY=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" +Environment="ANTHROPIC_MAX_TOKENS=255" +Environment="ASPNETCORE_Environment=" +Environment="ASPNETCORE_Kestrel__Endpoints__Http=http://localhost:Blogs_" +Environment="ASPNETCORE_ConnectionStrings__YavscConnection=Server=localhost;Port=5432;Database=yavsc;Username=yavsc;Password=4T/X+fOnE;" + +Environment="ASPNETCORE_Smtp__Host=\"mercure.pschneider.f\"" +Environment="ASPNETCORE_Smtp__Port=465" +Environment="ASPNETCORE_Smtp__SenderName=\"Paul Schneider\"" +Environment="ASPNETCORE_Smtp__SenderEmail=\"paul@pschneider.fr\"" +Environment="ASPNETCORE_Smtp__UserName=\"paul\"" +Environment="ASPNETCORE_Smtp__Password=\"j\0Dsn5=t\"" + +CapabilityBoundingSet=CAP_NET_BIND_SERVICE +AmbientCapabilities=CAP_NET_BIND_SERVICE +StandardOutput=syslog +StandardError=syslog +SyslogIdentifier=yavscBlogs + +[Install] +WantedBy=multi-user.target diff --git a/doc/README.md b/doc/README.md index b189bb27..fb9bea94 100644 --- a/doc/README.md +++ b/doc/README.md @@ -17,6 +17,10 @@ La racine de l'architecture est [Architecture.md](Architecture.md). | [architecture/postit-oidc.md](architecture/postit-oidc.md) | Client desktop PostIt, custom URI scheme, silent refresh | | [architecture/postit.md](architecture/postit.md) | PostIt — topologie des projets, ViewLocator custo, navigation, DI, conventions de binding | | [architecture/decoupage-organisation.md](architecture/decoupage-organisation.md) | Découpage des projets .NET (Abstract, Server, Org, Api, Blogs, Web, Org.Tests) | +| [testing.md](testing.md) | Stratégie de test : conventions des dossiers, EF Core in-memory, auth stubs, scaffold partagé | +| [onboarding-agents.md](onboarding-agents.md) | Parcours pas-à-pas pour prise en main agents IA + architecture + tests | +| [agent-playbook.md](agent-playbook.md) | Playbook d'usage de Copilot, Plan, Explore avec scénarios et anti-patterns | +| [agent-intent-matrix.md](agent-intent-matrix.md) | Matrice intentions développeur -> agent -> preuves attendues | ## Roadmap & design exploration diff --git a/doc/agent-intent-matrix.md b/doc/agent-intent-matrix.md new file mode 100644 index 00000000..975cd7b7 --- /dev/null +++ b/doc/agent-intent-matrix.md @@ -0,0 +1,20 @@ +# Matrice intentions -> agent -> preuves + +Cette matrice aide a choisir rapidement l'agent adapte et a exiger +une sortie verifiable. + +| Intention developpeur | Agent principal | Entrees minimales | Sortie minimale attendue | Verification | +|---|---|---|---|---| +| Comprendre un BC avant changement | Explore | BC cible, profondeur, contrainte de perimetre | Composants, points d'entree, tests relies, risques | Lire les fichiers cites + confirmer tests proposes | +| Decomposer une tache transverse | Plan | Objectif, contraintes, definition of done | Etapes ordonnees, dependances, criteres de verif | Verifier que chaque etape a une preuve observable | +| Implementer une modif locale | Copilot | Fichier cible, comportement attendu, conventions | Patch minimal, justification courte | Build/test du projet impacte | +| Ajouter un test smoke | Copilot (+Explore) | Route/endpoint, projet de test cible | Test + commande cible | Execution test cible | +| Corriger une regression | Plan + Copilot | Symptome, zone suspecte, test attendu | Fix + test NonRegression | Test rouge avant, vert apres | +| Diagnostiquer flux PostIt/OIDC | Explore + Plan | Flux, symptome, plateforme | Carte du flux + hypotheses testables | Verification manuelle + tests existants | + +## Regles d'arbitrage + +- Si l'intention est "comprendre": commencer par Explore. +- Si l'intention est "orchestrer": commencer par Plan. +- Si l'intention est "produire": utiliser Copilot apres cadrage. +- Si une sortie n'inclut pas de preuve, elle est incomplete. diff --git a/doc/agent-playbook.md b/doc/agent-playbook.md new file mode 100644 index 00000000..ecc14f1d --- /dev/null +++ b/doc/agent-playbook.md @@ -0,0 +1,101 @@ +# Playbook d'usage des agents IA (Yavsc) + +Ce playbook normalise l'usage de Copilot, Plan et Explore dans le depot. +Il privilegie des sorties verifiables: fichiers, commandes tests, risques. + +## Quand utiliser quel agent + +- Plan: quand la tache est ambigue, transverse ou risquee. +- Explore: quand il faut cartographier rapidement des zones du code. +- Copilot: quand les specifications sont claires et localisees. + +## Prompt type (base) + +Utiliser ce squelette avant toute tache non triviale: + +```text +Contexte: +Objectif: +Contraintes: +Verification: +Sortie attendue: +``` + +## 4 scenarios de reference + +## 1) Explorer un bounded context + +Intention: +- Comprendre ou implementer un changement dans un BC sans regression laterale. + +Prompt minimal: +```text +Explore le BC avec profondeur medium. +Retour: composants touches, points d'entree, tests existants et risques. +``` + +Preuves attendues: +- Carte des fichiers a modifier. +- Test(s) smoke/mandatory proposes. + +## 2) Ajouter un smoke test + +Intention: +- Couvrir rapidement un endpoint ou une route publique. + +Prompt minimal: +```text +Propose un smoke test pour dans le projet de test approprie. +Respecte les conventions de doc/testing.md. +``` + +Preuves attendues: +- Fichier test cree/modifie. +- Commande precise pour executer le test cible. + +## 3) Corriger une regression backend API + +Intention: +- Corriger un bug sans casser un flux voisin. + +Prompt minimal: +```text +Planifie puis implemente un fix de dans . +Ajoute/ajuste un test NonRegression rouge puis vert. +``` + +Preuves attendues: +- Explication cause racine. +- Test non-regression associe. +- Commande d'execution et resultat attendu. + +## 4) Tracer un flux PostIt/OIDC + +Intention: +- Localiser une cassure d'authentification entre client et serveur. + +Prompt minimal: +```text +Cartographie le flux OIDC PostIt: entrypoints, callback, stockage token, +refresh. Donne points de rupture probables et tests/verification proposes. +``` + +Preuves attendues: +- Liste ordonnee des etapes du flux. +- Fichiers critiques. +- Hypotheses testables. + +## Anti-patterns a eviter + +- Prompt sans objectif verifiable. +- Demande trop large sans perimetre de fichiers. +- Validation basee uniquement sur "ca semble correct". +- Pas de lien entre changement et niveau de test. + +## Gate PR minimale (agent-assiste) + +Avant validation: +- Impact architecture explicite. +- Rationale de choix agent explicite. +- Test(s) executes et justifies. +- Risques residuels documentes. diff --git a/doc/architecture/postit.md b/doc/architecture/postit.md index 77d0a252..70f3f2fd 100644 --- a/doc/architecture/postit.md +++ b/doc/architecture/postit.md @@ -129,30 +129,51 @@ le DI est construit. Ordre, dans cet ordre : ## Navigation Le host de navigation est un `NavigationPage x:Name="NavRoot"` -posé sur `MainWindow.axaml`. La pile est gérée par les -événements du `SessionStatusViewModel` : +posé sur `MainWindow.axaml`. La pile est gérée par deux +mécanismes distincts : -| Événement | Effet | -|---------------------------------|------------------------------------------------------------------------| -| `LoginSucceeded` | `PushAsync(MainPage)` au-dessus de `HomePage`. | -| `LogoutCompleted` | `PopToRootAsync()` (revient à `HomePage`). | -| `OpenSettingsRequested` | `PushAsync(SettingsPage)` au-dessus de la page courante. | +1. **Nav utilisateur (VM-first)** : un ViewModel (souvent dans + une commande `[RelayCommand]`) appelle + `await ((App)App.Current!).PushPageAsync(targetVm).ConfigureAwait(true);`. + `App.PushPageAsync` (`src/PostIt/PostIt/App.axaml.cs`) + résout la `Control` correspondante via le `ViewLocator` + enregistré dans `Application.DataTemplates`, l'identifie + comme `Page`, lui assigne le VM comme `DataContext`, et + appelle `NavRoot.PushAsync(page)`. C'est le seul chemin + pour les boutons de la toolbar, les `OpenSettings` / + `OpenCircles` / `ManageAcl` / `OpenSignatureDev`, et + toute autre nav déclenchée par un ViewModel. + +2. **Signaux de cycle de vie** : le `SessionStatusViewModel` + lève des événements consommés dans + `App.OnFrameworkInitializationCompleted` pour orchestrer + la nav de boot : + + | Événement | Effet | + |---------------------|------------------------------------------------------------------| + | `LoginSucceeded` | `PushAsync(MainPage)` au-dessus de `HomePage` (post-login). | + | `LogoutCompleted` | `PopToRootAsync()` (revient à `HomePage`). | + + Ces events ne sont **pas** un canal de nav utilisateur ; ils + portent une transition d'état applicatif (authentification + établie / perdue) et c'est `App` qui choisit d'en faire une + transition de pile. ### Garde anti-empilement `NavigationPage.PushAsync` n'est pas idempotent : pousser deux fois la même instance l'empile deux fois, et l'utilisateur doit -taper **Retour** N fois pour sortir. Le handler -`OpenSettingsRequested` est gardé pour bloquer ce cas : +taper **Retour** N fois pour sortir. La garde est implémentée +dans `App.PushPageAsync` (et consommée par tous les chemins +de nav utilisateur) : ```csharp -var settingsPage = provider.GetRequiredService(); -var stack = w.NavRoot.NavigationStack; -if (stack.Count > 0 && ReferenceEquals(stack[stack.Count - 1], settingsPage)) +var stack = window.NavRoot.NavigationStack; +if (stack.Count > 0 && ReferenceEquals(stack[stack.Count - 1], page)) { - return; // déjà au sommet, no-op silencieux + return Task.CompletedTask; // déjà au sommet, no-op silencieux } -_ = w.NavRoot.PushAsync(settingsPage); +return window.NavRoot.PushAsync(page); ``` La comparaison est par référence, pas par type : on ne veut @@ -178,9 +199,11 @@ qui ne tiendrait plus). - `SessionStatusViewModel` est le seul VM avec une durée de vie **process-entière** (singleton). Il survit à toutes les navigations, expose `HasValidSession` en continu, et porte - les trois événements qui pilotent la navigation - (`LoginSucceeded`, `LogoutCompleted`, - `OpenSettingsRequested`). + les événements de cycle de vie consommés par `App` pour + orchestrer la nav de boot (`LoginSucceeded`, + `LogoutCompleted`). La nav utilisateur déclenchée par + l'utilisateur passe par `App.PushPageAsync(vm)`, pas par + un événement du `SessionStatusViewModel`. - `MainPageViewModel` / `HomePageViewModel` / `SignaturePageViewModel` sont `Transient` — une nouvelle @@ -233,10 +256,14 @@ pour `[RelayCommand]`". `ViewLocator.Build`. Oublier le `ViewLocator` est silencieux (juste un TextBlock "No view for X"), pas une exception. - **Ajouter un événement global de navigation** (par ex. - "Push après payment success") : passer par un événement sur - un VM singleton (cf. `SessionStatusViewModel.OpenSettingsRequested`), - pas par une référence à `MainWindow` depuis le VM. Garder - les VMs découplés du `IClassicDesktopStyleApplicationLifetime`. + "Push après payment success") : ne pas capturer `MainWindow` + ni `NavigationPage` depuis le VM. La nav passe par + `App.PushPageAsync(vm)` dans tous les cas : soit le VM + appelle la méthode directement depuis une commande + (`[RelayCommand]`), soit un handler abonné à un événement + d'un singleton (cf. `SessionStatusViewModel`) l'appelle. + Garder les VMs découplés du + `IClassicDesktopStyleApplicationLifetime`. - **Modifier l'OIDC** : la fiche à lire est [postit-oidc.md](postit-oidc.md), pas celle-ci. Cette fiche ne ré-explique ni le flow, ni le pipe, ni le custom scheme. diff --git a/doc/onboarding-agents.md b/doc/onboarding-agents.md new file mode 100644 index 00000000..14a727a1 --- /dev/null +++ b/doc/onboarding-agents.md @@ -0,0 +1,73 @@ +# Onboarding guide: agents IA + architecture + tests + +Ce guide est optimise pour accelerer la prise en main des agents IA +(Copilot, Plan, Explore) dans Yavsc, avec une verification rapide +par les tests. + +## Resultat attendu + +A la fin du parcours, un contributeur doit pouvoir: +- Identifier les projets impactes par une modification. +- Choisir l'agent adapte a l'intention de travail. +- Produire une proposition de changement verifiable par les tests. + +## Parcours en 3 modules + +## Module A - Comprendre le terrain (30-45 min) + +Objectif: acquerir une lecture fiable de l'architecture. + +1. Lire [README.md](../README.md) puis [Architecture.md](Architecture.md). +2. Lire [architecture/decoupage-organisation.md](architecture/decoupage-organisation.md). +3. Selon le domaine: + - Backend/API: [architecture/workflow-multi-parties.md](architecture/workflow-multi-parties.md) + - PostIt: [architecture/postit.md](architecture/postit.md) puis [architecture/postit-oidc.md](architecture/postit-oidc.md) + +Definition of done: +- Expliquer en 5 phrases quelles couches sont touchees. +- Citer le ou les points d'entree applicatifs a verifier. + +## Module B - Boucle tests rapide (20-30 min) + +Objectif: verifier rapidement sans lancer toute la suite. + +1. Lire [testing.md](testing.md). +2. Lancer les smoke tests d'abord, puis mandatory selon le projet. +3. N'elargir au test complet que si le scope depasse le BC touche. + +Definition of done: +- Fournir la commande test executee. +- Expliquer pourquoi ce niveau de test est suffisant. + +## Module C - Usage agentique en production (30-40 min) + +Objectif: utiliser les agents comme accelerateurs, pas comme boites noires. + +1. Plan: decomposer la tache en etapes verifiables. +2. Explore: collecter le contexte code/doc precise. +3. Copilot: implementer localement et verifier. + +Regles: +- Toujours donner un contexte explicite (fichier, but, contrainte). +- Demander des preuves observables (fichiers modifies, tests, risques). +- Refuser toute sortie non verifiable. + +Definition of done: +- Une tache simple est livree avec: + - Plan + - Changement local + - Preuve par test + +## Routine continue (sans echeance fixe) + +Rituels recommandes: +- Hebdo: revue des prompts qui ont bien fonctionne. +- Mensuel: mise a jour du present guide et du playbook. +- A chaque incident: ajouter un anti-pattern dans le playbook. + +## Check-list de validation + +- Le changement indique son impact architecture. +- Le choix de l'agent est justifie. +- La preuve test est incluse. +- Les risques residuels sont explicitement listes. diff --git a/doc/testing.md b/doc/testing.md new file mode 100644 index 00000000..ef80cda9 --- /dev/null +++ b/doc/testing.md @@ -0,0 +1,88 @@ +# Stratégie de test + +Yavsc utilise **xUnit** (`xunit.v3`) avec un mix d'unitaire pur +et d'intégration légère. Les projets de tests sont sous +`src/.Tests/` et consomment le scaffold partagé +`src/Yavsc.Tests.Shared/`. + +## Vue d'ensemble + +| Sujet | Document | +|---|---| +| Scaffold partagé (`WebHostFixture`, JWT de test, etc.) | [src/Yavsc.Tests.Shared/README.md](../src/Yavsc.Tests.Shared/README.md) | +| Convention des dossiers de tests | [Conventions](#conventions-des-dossiers-de-tests) | +| Driver EF Core en test | [EF Core en test](#ef-core-en-test) | +| Stubs d'authentification et de permissions | [Auth et permissions](#auth-et-permissions) | + +## Conventions des dossiers de tests + +Sous `src/.Tests/`, on trouve quatre dossiers de premier +niveau qui classifient les tests par intention : + +| Dossier | Usage | +|---|---| +| `NonRegression/` | Régressions : un bug constaté, un test qui le détecte si on le réintroduit | +| `Mandatory/` | Tests bloquants : ils doivent passer avant tout merge | +| `Smoke/` | Smoke tests HTTP rapides, montent un host léger | +| `Controllers/` | Tests unitaires des contrôleurs (mock du service, assertions sur le mapping HTTP) | + +Les `NonRegression` sont la cible par défaut quand on fixe un +bug : ils doivent être **rouges avant le fix, verts après**, et +continuer à **casser** si quelqu'un revert le fix. Pas de test +qui passe à vide. + +## EF Core en test + +Pour les tests qui ont besoin d'un `ApplicationDbContext`, on +utilise **`UseInMemoryDatabase`** avec un `InMemoryDatabaseRoot` +partagé au niveau de la fixture. Pas de SQLite, pas de Docker, +pas de mock du contexte : le service testé s'exécute contre +un vrai `DbContext` sur in-memory. + +```csharp +private static readonly InMemoryDatabaseRoot _dbRoot = new(); + +var opts = new DbContextOptionsBuilder() + .UseInMemoryDatabase("Yavsc.Org.Tests.MyFixture", _dbRoot) + .Options; +``` + +Le `InMemoryDatabaseRoot` partagé est important : sans lui, EF +crée un store indépendant par `DbContext` dans certaines +configurations, et un test qui seed + read sur deux contextes +voit un store vide. Le pattern est documenté dans +`BlogsWebServerFixture` ([src/Yavsc.Blogs.Tests/BlogsWebServerFixture.cs](../src/Yavsc.Blogs.Tests/BlogsWebServerFixture.cs)). + +> **Limite connue** : le provider in-memory **ignore** les +> `Migration` EF et ne respecte pas les FK **sur les raw +> SQL** (`ExecuteSqlRaw`). Pour tester des contraintes FK, on +> écrit la configuration dans `OnModelCreating` et on s'appuie +> sur le fait qu'EF la respecte à l'`Add`/`SaveChanges`. Pour +> tester des migrations, c'est l'environnement de staging. + +## Auth et permissions + +L'authorization policy provider de prod est swappé contre +`TestAuthPolicyProvider` (dans `Yavsc.Tests.Shared`) par les +fixtures spécialisées. Les tests qui ont besoin qu'un user soit +"Administrator" envoient un header `X-Test-Rôle` ; ceux qui +veulent un user anonyme omettent le header. + +Pour les tests unitaires qui n'ont pas besoin du pipeline +HTTP, on stub `IAuthorizationService` directement (cf. +`BlogspotController` dans `Yavsc.Org.Tests/NonRegression/`) +pour éviter de monter un host complet. + +## Quand ne PAS écrire de test + +Un test qui ne détecte rien n'est pas un test. Si l'invariant +qu'on cherche à protéger est déjà enforced par EF, par le +compilateur, ou par une couche applicative en amont, le test +est du bruit. Mieux vaut : +- Un test qui assert un **comportement observable** (code + retour HTTP, exception typée, valeur de retour) +- Ou pas de test, et une note dans le code + +La non-régression se prouve par un test qui casse si on +réintroduit le bug. Pas par un test qui passe aujourd'hui et +qui continuera à passer après un revert. diff --git a/src/PostIt.Tests/Directory.Packages.props b/src/PostIt.Tests/Directory.Packages.props deleted file mode 100644 index 15c4e24b..00000000 --- a/src/PostIt.Tests/Directory.Packages.props +++ /dev/null @@ -1,10 +0,0 @@ - - - - - - - - - - \ No newline at end of file diff --git a/src/PostIt/Directory.Packages.props b/src/PostIt/Directory.Packages.props index 900f1428..4dd4b288 100644 --- a/src/PostIt/Directory.Packages.props +++ b/src/PostIt/Directory.Packages.props @@ -1,20 +1,33 @@ - - + - - - - - - - - - - - - - - - - \ No newline at end of file + + + true + 12.1.1 + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/PostIt/Makefile b/src/PostIt/Makefile new file mode 100644 index 00000000..1217976b --- /dev/null +++ b/src/PostIt/Makefile @@ -0,0 +1,178 @@ + +# Cibles pour installer PostIt.Android en Debug sur l'AVD qemu. +# +# Usage typique : +# make qemu # lance l'AVD, attend le boot, build l'APK, l'installe +# make android-install # (re)build l'APK et l'installe (AVD doit tourner) +# make android-build # build l'APK seul (sans install) +# make qemu-run # démarre l'AVD en background +# make qemu-stop # arrête l'émulateur +# make qemu-wait-boot # attend que l'AVD ait fini de booter +# +# Variables surchargeables (make VAR=valeur) : +# AVD_NAME default: postit_test_avd +# (l'AVD doit être listé par `avdmanager list avd`) +# ADB_SERIAL default: emulator-5554 +# (port standard du premier émulateur lancé) +# ANDROID_HOME default: /opt/android-sdk +# (le SDK Android local; doit contenir +# emulator/emulator et platform-tools/adb) +# POSTIT_RID default: android-x64 +# (doit matcher l'ABI de l'AVD; `avdmanager list avd` +# affiche la ligne Tag/ABI) +# EMU_HEADLESS default: 0 +# (1 = lancer l'émulateur sans fenêtre, pour scripter) +# CONFIG surcharge la variable CONFIG globale (Debug par +# défaut dans ce Makefile). Passer à Release pour +# un APK optimisé et signé release. +# LOGCAT_LINES default: 200 +# (nombre de lignes dumpées par `make qemu-logcat`) +# LOGCAT_FOLLOW default: 0 +# (1 = stream live via `make logcat`, +# sinon dump one-shot des N dernières lignes) +# LOGCAT_BOOT_WAIT default: 30 +# (secondes d'attente entre le clear du buffer, +# le `am start`, et le dump final dans +# `make qemu-logcat-boot`) +AVD_NAME ?= postit_test_avd +ADB_SERIAL ?= emulator-5554 +ANDROID_HOME ?= /opt/android-sdk +POSTIT_RID ?= android-x64 +EMU_HEADLESS ?= 0 +LOGCAT_LINES ?= 600 +LOGCAT_FOLLOW ?= 0 +LOGCAT_BOOT_WAIT ?= 30 + +ANDROID_PACKAGE_NAME = fr.pschneider.postit +POSTIT_ANDROID_CSPROJ := PostIt.Android/PostIt.Android.csproj +POSTIT_APK_DIR := PostIt.Android/bin/$(CONFIG)/net10.0-android/$(POSTIT_RID) +POSTIT_APK := $(POSTIT_APK_DIR)/$(ANDROID_PACKAGE_NAME)-Signed.apk + +clean: clean-PostIt clean-PostIt.Android clean-PostIt.Desktop + +clean-%: + rm -rf $*/obj $*/bin + +qemu-run: + @echo " Starting AVD $(AVD_NAME) on $(ADB_SERIAL)..." + @mkdir -p /tmp/yavsc-emu + @EMU_ARGS=""; \ + if [ "$(EMU_HEADLESS)" = "1" ]; then EMU_ARGS="-no-window -no-audio"; fi; \ + $(ANDROID_HOME)/emulator/emulator -avd $(AVD_NAME) $$EMU_ARGS \ + >/tmp/yavsc-emu/$(AVD_NAME).log 2>&1 & \ + echo " ✅ Started emulator PID: $$!" + +qemu-stop: + adb -s $(ADB_SERIAL) emu kill + echo " ✅ Stopped emulator" + +qemu-wait-boot: + @echo " Waiting for $(ADB_SERIAL) to finish booting..." + adb -s $(ADB_SERIAL) wait-for-device + @for i in $$(seq 1 180); do \ + BOOTED=$$(adb -s $(ADB_SERIAL) shell getprop sys.boot_completed 2>/dev/null | tr -d '\r\n'); \ + if [ "$$BOOTED" = "1" ]; then \ + echo " ✓ booted in $${i}s"; \ + exit 0; \ + fi; \ + sleep 1; \ + done; \ + echo " 👿 ERROR: device did not boot within 180s." >&2; \ + echo " Logs: /tmp/yavsc-emu/$(AVD_NAME).log" >&2; \ + exit 1 + +android-build: + # EmbedAssembliesIntoApk=true: without this, the Debug APK ships + # without the managed assemblies in it (they are pushed at runtime + # via `adb push`, "Fast Deployment"). On the qemu emulator, the + # runtime cannot find them in `files/.__override__//` and + # aborts at startup with "No assemblies found in '.__override__'" + # (monodroid-glue.cc:757, SIGABRT). Forcing this property on + # packages the .dlls into the APK as `assemblies//` so the + # runtime reads them directly. + # + # The Xamarin.Android SDK property is `EmbedAssembliesIntoApk`, + # not `AndroidEnableFastDeployment` (which exists in older + # templates but is a no-op in the .NET 10 SDK). + dotnet build $(POSTIT_ANDROID_CSPROJ) \ + -c $(CONFIG) \ + -p:RuntimeIdentifier=$(POSTIT_RID) \ + -p:EmbedAssembliesIntoApk=true \ + --nologo + @if [ ! -f "$(POSTIT_APK)" ]; then \ + echo " APK not found at $(POSTIT_APK)." >&2; \ + echo " Files in $(POSTIT_APK_DIR):" >&2; \ + ls -la "$(POSTIT_APK_DIR)" 2>/dev/null || echo " (directory does not exist)" >&2; \ + exit 1; \ + fi + + +android-install: android-build + @echo " Installing $(POSTIT_APK) on $(ADB_SERIAL)..." + adb -s $(ADB_SERIAL) install -r "$(POSTIT_APK)" -r + @echo " ✅ PostIt.Android installed on $(ADB_SERIAL)" + +qemu-uninstall: + adb -s $(ADB_SERIAL) uninstall $(ANDROID_PACKAGE_NAME) + +# Dump recent logcat output for the running PostIt.Android process. +# By default, prints the last $(LOGCAT_LINES) lines (one-shot, with +# `-d`). Set LOGCAT_FOLLOW=1 to follow the stream live instead. +# Filtering is by PID (pidof $(ANDROID_PACKAGE_NAME)), not by tag, +# because Mono/Xamarin can emit logs under several tags +# (mono, PostIt.Android, Avalonia.Android) and tag-based filtering +# would miss the ones not matching. PID-based filtering is exact. +# If the app is not running, pidof returns empty and logcat exits +# silently with no output; that is the expected behaviour for +# "no logs yet". +logcat: + @PID=$$(adb -s $(ADB_SERIAL) shell pidof $(ANDROID_PACKAGE_NAME) 2>/dev/null | tr -d '\r\n'); \ + if [ -z "$$PID" ]; then \ + echo " $(ANDROID_PACKAGE_NAME) is not running on $(ADB_SERIAL)."; \ + echo " Start the app first (am start -n $(ANDROID_PACKAGE_NAME)/PostIt.Android.PostItMainActivity)"; \ + exit 1; \ + fi; \ + echo " Following PID $$PID (LOGCAT_FOLLOW=$(LOGCAT_FOLLOW), LOGCAT_LINES=$(LOGCAT_LINES))"; \ + if [ "$(LOGCAT_FOLLOW)" = "1" ]; then \ + adb -s $(ADB_SERIAL) logcat -v time --pid=$$PID $(ANDROID_PACKAGE_NAME); \ + else \ + adb -s $(ADB_SERIAL) logcat -d -v time -t $(LOGCAT_LINES) --pid=$$PID $(ANDROID_PACKAGE_NAME); \ + fi + +# Clear logcat, launch PostIt.Android, then dump everything that was +# emitted during the startup window. Targets the "démarrage KO" case +# where the process starts but Avalonia never renders a frame — the +# logcat trace from process start to first frame is what diagnoses it. +# +# Override LOGCAT_BOOT_WAIT to extend the post-launch wait +# (default 15s; raise to 30+ if the device is slow to boot Avalonia). +LOGCAT_BOOT_WAIT ?= 15 + + +android-start: + @echo " Clearing logcat buffer..." + adb -s $(ADB_SERIAL) logcat -c + @echo " Launching $(ANDROID_PACKAGE_NAME)..." + adb -s $(ADB_SERIAL) shell am start \ + -n $(ANDROID_PACKAGE_NAME)/PostIt.Android.PostItMainActivity + @echo " ✅ $(ANDROID_PACKAGE_NAME) started on $(ADB_SERIAL)" + +qemu-logcat-boot: android-start + @echo " Waiting $(LOGCAT_BOOT_WAIT)s for the app to start rendering..." + @sleep $(LOGCAT_BOOT_WAIT) + + @echo " Dumping logcat (PostIt PID + system buffer):" + @PID=$$(adb -s $(ADB_SERIAL) shell pidof $(ANDROID_PACKAGE_NAME) 2>/dev/null | tr -d '\r\n'); \ + if [ -n "$$PID" ]; then \ + echo " ✅ (PID $$PID at dump time)"; \ + sleep 10; \ + adb -s $(ADB_SERIAL) logcat -d -v time -t $(LOGCAT_LINES) --pid=$$PID; \ + else \ + echo " 👿 (PostIt process not running at dump time — dumping last $(LOGCAT_LINES) lines unfiltered)"; \ + adb -s $(ADB_SERIAL) logcat -d -v time -t $(LOGCAT_LINES); \ + exit 1; \ + fi + +qemu: qemu-run qemu-wait-boot android-install + +.PHONY: clean qemu qemu-run qemu-stop qemu-wait-boot android-build android-install logcat qemu-logcat-boot diff --git a/src/PostIt/PostIt.Android/Application.cs b/src/PostIt/PostIt.Android/Application.cs index fb6b08d3..040b01ca 100644 --- a/src/PostIt/PostIt.Android/Application.cs +++ b/src/PostIt/PostIt.Android/Application.cs @@ -1,7 +1,17 @@ using Android.App; +using Android; using Android.Runtime; using Avalonia; using Avalonia.Android; +using System.Linq; +using System.Threading.Tasks; +using Microsoft.Extensions.DependencyInjection; +using Avalonia.Controls; +using Avalonia.Styling; +using Yavsc.Api.Client; + +[assembly: UsesPermission(Manifest.Permission.AccessFineLocation)] +[assembly: UsesPermission(Manifest.Permission.AccessCoarseLocation)] namespace PostIt.Android { diff --git a/src/PostIt/PostIt.Android/MainActivity.cs b/src/PostIt/PostIt.Android/MainActivity.cs index 86ce394a..54910080 100644 --- a/src/PostIt/PostIt.Android/MainActivity.cs +++ b/src/PostIt/PostIt.Android/MainActivity.cs @@ -1,8 +1,11 @@ + using Android.App; -using Android.Content.PM; using Android.Content; -using Avalonia; +using Android.Content.PM; +using AndroidX.Core.Provider; +using AndroidX.Emoji2.Text; using Avalonia.Android; +using PostIt.Droid.Services; namespace PostIt.Android; @@ -12,26 +15,28 @@ namespace PostIt.Android; Theme = "@style/MyTheme.NoActionBar", Icon = "@drawable/icon", MainLauncher = true, - LaunchMode = LaunchMode.SingleTask, ConfigurationChanges = ConfigChanges.Orientation | ConfigChanges.ScreenSize | ConfigChanges.UiMode)] public class MainActivity : AvaloniaMainActivity { /// - /// Strongly-typed handle to the current MainActivity instance, set in - /// and consumed by platform services such as - /// which need to launch - /// Chrome Custom Tabs. + /// The current MainActivity instance. /// public static MainActivity? Current { get; private set; } protected override void OnCreate(global::Android.OS.Bundle? savedInstanceState) { + FontRequest fontRequest = new FontRequest( + "com.google.android.gms.fonts", + "com.google.android.gms", + "Noto Color Emoji Compat", + Yavsc.Resource.Array.com_google_android_gms_fonts_certs); //com_google_android_gms_fonts_certs + EmojiCompat.Config config = new FontRequestEmojiCompatConfig(this, fontRequest); + EmojiCompat.Init(config); + PlatformBootstrap.InitPlatform(); base.OnCreate(savedInstanceState); - PlatformBootstrap.EnsureInitialized(); Current = this; } - - /// + /// /// Receives the deep-link Intent fired by the system browser after the /// user completes the OIDC login on https://yavsc.pschneider.fr. The /// Intent URI has the shape android://postit-signin?code=...&state=.... @@ -43,7 +48,24 @@ public class MainActivity : AvaloniaMainActivity protected override void OnNewIntent(Intent? intent) { base.OnNewIntent(intent); - if (intent is not null) AndroidOidcCallbackSink.Handle(intent); + + var url = intent?.DataString; + if (!string.IsNullOrEmpty(url) && url.StartsWith("postit://callback")) + { + OidcCallbackManager.SetResult(url); + } + + } + + public override void OnRequestPermissionsResult(int requestCode, string[]? permissions, Permission[]? grantResults) + { + if (PostIt.Android.Services.AndroidCurrentLocationProvider + .HandlePermissionResult(requestCode, grantResults)) + { + return; + } + + base.OnRequestPermissionsResult(requestCode, permissions, grantResults); } internal static class AndroidOidcCallbackSink @@ -63,4 +85,4 @@ public class MainActivity : AvaloniaMainActivity tcs?.TrySetResult(intent?.Data?.ToString() ?? string.Empty); } } -} \ No newline at end of file +} diff --git a/src/PostIt/PostIt.Android/PlatformBootstrap.cs b/src/PostIt/PostIt.Android/PlatformBootstrap.cs index 0d11035a..5b90267f 100644 --- a/src/PostIt/PostIt.Android/PlatformBootstrap.cs +++ b/src/PostIt/PostIt.Android/PlatformBootstrap.cs @@ -12,18 +12,14 @@ namespace PostIt.Android; /// internal static class PlatformBootstrap { - private static int _initialized; - - internal static void EnsureInitialized() + internal static void InitPlatform() { - if (System.Threading.Interlocked.Exchange(ref _initialized, 1) != 0) - return; - - Platform.DefaultRedirectUri = Settings.AndroidRedirectUri; Platform.CreateBrowser = () => { var activity = MainActivity.Current; return activity is null ? null : new AndroidSystemBrowser(activity); }; + + Platform.TryGetCurrentLocationAsync = AndroidCurrentLocationProvider.TryGetCurrentLocationAsync; } -} \ No newline at end of file +} diff --git a/src/PostIt/PostIt.Android/PostIt.Android.csproj b/src/PostIt/PostIt.Android/PostIt.Android.csproj index 3820bf49..3d8be385 100644 --- a/src/PostIt/PostIt.Android/PostIt.Android.csproj +++ b/src/PostIt/PostIt.Android/PostIt.Android.csproj @@ -2,20 +2,17 @@ Exe net10.0-android - - android-arm64;android-x64 - 23.0.0 + 23 enable - com.CompanyName.PostIt + fr.pschneider.postit 1 1.0 apk false - android-arm;android-arm64;android-x86;android-x64 - 1.0.1.0 - 1.0.1.0 - 1.0.1-5+Branch.main.Sha.0617fc6bda7151c70559d87177e2dcfb1b60995f - 1.0.1-5 + 1.1.0.0 + 1.1.0.0 + 1.1.0-beta.1+183.Branch.release-1.0.8-rc8.Sha.6cff3db32ecf72c0d2d430b7002fa7816a34e070 + 1.1.0-beta.1 @@ -30,7 +27,4 @@ - - - \ No newline at end of file diff --git a/src/PostIt/PostIt.Android/Properties/AndroidManifest.xml b/src/PostIt/PostIt.Android/Properties/AndroidManifest.xml index 2472d06d..8793aae8 100644 --- a/src/PostIt/PostIt.Android/Properties/AndroidManifest.xml +++ b/src/PostIt/PostIt.Android/Properties/AndroidManifest.xml @@ -1,32 +1,6 @@ - + - - - - - - - - - - - + - \ No newline at end of file + diff --git a/src/PostIt/PostIt.Android/Resources/values/font_certs.xml b/src/PostIt/PostIt.Android/Resources/values/font_certs.xml new file mode 100644 index 00000000..f4adce1b --- /dev/null +++ b/src/PostIt/PostIt.Android/Resources/values/font_certs.xml @@ -0,0 +1,13 @@ + + + + @array/com_google_android_gms_fonts_certs_dev + @array/com_google_android_gms_fonts_certs_prod + + + MIIEqDCCA5CgAwIBAgIJAN5gc16AJfAsMA0GCSqGSIb3DQEBBQUAMIGUMQswCQYDVQQGEwJVUzETMBEGA1UECBMKQ2FsaWZvcm5pYTEWMBQGA1UEBxMNTW91bnRhaW4gVmlldzEQMA4GA1UEChMHR29vZ2xlMRAwDgYDVQQLEwdBbmRyb2lkMRAwDgYDVQQDEwdBbmRyb2lkMSEwHwYJKoZIhvcNAQkBFhJhbmRyb2lkQGFuZHJvaWQuY29tMCAXDTA4MDQxNTIyNDA0M1YYDzQyMDgxMzA0MjI0MDQzWjCBlDELMAkGA1UEBhMCVVMxEzARBgNVBAgTCkNhbGlmb3JuaWExFjAUBgNVBAcTDURvdW50YWluIFZpZXcxEDAOBgNVBAoTB0dvb2dsZTEQMA4GA1UECxMHQW5kcm9pZDEQMA4GA1UEAxMHQW5kcm9pZDEhMB8GCSqGSIb3DQEJARYSYW5kcm9pZEBhbmRyb2lkLmNvbTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBALBi1vF0K1vOEHG7AxneTjOHUka46MIidBqvFcO164A49iU2DkYPhUaM4H8JCdzh6N1GzM6h9o6E2V6z8+gEtdI6nqqs0EGA0G0H701bFjLp9+K/1DkMIFeD4P8J7X1/M8t4+X09X/7bQyV3w0v7q+Qh38sY8W/7K29B3f2O2sLw+uX9U8a8Tf4Xv8A== + + + MIIEQzCCAyugAwIBAgIJAMLgh0ZgXpYOMA0GCSqGSIb3DQEBBQUAMHQxCzAJBgNVBAYTAlVTMRMwEQYDVQQIEwpDYWxpZm9ybmlhMRYwFAYDVQQHEw1Nb3VudGFpbiBWaWV3MRQwEgYDVQQKEwtHb29nbGUgSW5jLjEQMA4GA1UECxMHQW5kcm9pZDEQMA4GA1UEAxMHQW5kcm9pZDAeFw0wODA4MjEyMzEzMzRaFw0zNjAxMDcyMzEzMzRaMHQxCzAJBgNVBAYTAlVTMRMwEQYDVQQIEwpDYWxpZm9ybmlhMRYwFAYDVQQHEw1Nb3VudGFpbiBWaWV3MRQwEgYDVQQKEwtHb29nbGUgSW5jLjEQMA4GA1UECxMHQW5kcm9pZDEQMA4GA1UEAxMHQW5kcm9pZDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAKKvSkUIXm+t9M8rXj2V + + diff --git a/src/PostIt/PostIt.Android/Services/AndroidCurrentLocationProvider.cs b/src/PostIt/PostIt.Android/Services/AndroidCurrentLocationProvider.cs new file mode 100644 index 00000000..f710cacc --- /dev/null +++ b/src/PostIt/PostIt.Android/Services/AndroidCurrentLocationProvider.cs @@ -0,0 +1,130 @@ +using System; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using Android; +using Android.App; +using Android.Content.PM; +using Android.Locations; +using AndroidX.Core.App; +using AndroidX.Core.Content; +using PostIt.Services; + +namespace PostIt.Android.Services; + +internal static class AndroidCurrentLocationProvider +{ + public static async Task TryGetCurrentLocationAsync(CancellationToken cancellationToken) + { + var activity = MainActivity.Current; + if (activity is null) + { + return CurrentLocationResult.Unavailable("L'activité Android n'est pas encore prête."); + } + + var permissionGranted = await LocationPermissionBroker.EnsureGrantedAsync(activity, cancellationToken).ConfigureAwait(false); + if (!permissionGranted) + { + return CurrentLocationResult.PermissionDenied(); + } + + var locationManager = activity.GetSystemService(global::Android.Content.Context.LocationService) as LocationManager; + if (locationManager is null) + { + return CurrentLocationResult.Unavailable("Le service de localisation Android est indisponible."); + } + + var location = locationManager.GetProviders(enabledOnly: true)? + .Select(provider => locationManager.GetLastKnownLocation(provider)) + .Where(candidate => candidate is not null) + .OrderByDescending(candidate => candidate!.Time) + .ThenBy(candidate => candidate!.Accuracy) + .FirstOrDefault(); + + if (location is null) + { + return CurrentLocationResult.Unavailable("Aucune position n'est disponible. Activez la localisation du système puis réessayez."); + } + + return CurrentLocationResult.Success(location.Latitude, location.Longitude); + } + + public static bool HandlePermissionResult(int requestCode, Permission[]? grantResults) + => LocationPermissionBroker.HandleResult(requestCode, grantResults); + + private static class LocationPermissionBroker + { + private const int RequestCode = 4042; + private static readonly string[] RequestedPermissions = + { + Manifest.Permission.AccessFineLocation, + Manifest.Permission.AccessCoarseLocation, + }; + + private static readonly object SyncRoot = new(); + private static TaskCompletionSource? _pendingRequest; + + public static Task EnsureGrantedAsync(Activity activity, CancellationToken cancellationToken) + { + if (HasLocationPermission(activity)) + { + return Task.FromResult(true); + } + + lock (SyncRoot) + { + if (_pendingRequest is null) + { + _pendingRequest = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + ActivityCompat.RequestPermissions(activity, RequestedPermissions, RequestCode); + } + + if (!cancellationToken.CanBeCanceled) + { + return _pendingRequest.Task; + } + + return WaitAsync(_pendingRequest.Task, cancellationToken); + } + } + + public static bool HandleResult(int requestCode, Permission[]? grantResults) + { + if (requestCode != RequestCode) + { + return false; + } + + var granted = grantResults is { Length: > 0 } && grantResults.All(result => result == Permission.Granted); + TaskCompletionSource? pendingRequest; + lock (SyncRoot) + { + pendingRequest = _pendingRequest; + _pendingRequest = null; + } + + pendingRequest?.TrySetResult(granted); + return true; + } + + private static bool HasLocationPermission(Activity activity) + { + return ContextCompat.CheckSelfPermission(activity, Manifest.Permission.AccessFineLocation) == Permission.Granted + || ContextCompat.CheckSelfPermission(activity, Manifest.Permission.AccessCoarseLocation) == Permission.Granted; + } + + private static async Task WaitAsync(Task task, CancellationToken cancellationToken) + { + using var registration = cancellationToken.Register(() => + { + lock (SyncRoot) + { + _pendingRequest?.TrySetCanceled(cancellationToken); + _pendingRequest = null; + } + }); + + return await task.ConfigureAwait(false); + } + } +} diff --git a/src/PostIt/PostIt.Android/Services/AndroidSystemBrowser.cs b/src/PostIt/PostIt.Android/Services/AndroidSystemBrowser.cs index cb9c324b..bb10b364 100644 --- a/src/PostIt/PostIt.Android/Services/AndroidSystemBrowser.cs +++ b/src/PostIt/PostIt.Android/Services/AndroidSystemBrowser.cs @@ -1,9 +1,9 @@ using System; using System.Threading.Tasks; using Android.App; -using Android.Content; using AndroidX.Browser.CustomTabs; using IdentityModel.OidcClient.Browser; +using PostIt.Droid.Services; namespace PostIt.Android.Services; @@ -36,14 +36,19 @@ public sealed class AndroidSystemBrowser : IBrowser }; } + // 1. Enregistrez la tâche avant de lancer le Custom Tab + var callbackTask = OidcCallbackManager.RegisterCallback(cancellationToken); + + // 2. LANCEZ VOTRE CUSTOM TAB ICI (via AndroidX.Browser.CustomTabs) + // ... code pour ouvrir l'URL d'authentification ... + + var uri = global::Android.Net.Uri.Parse(options.StartUrl)!; - var callbackTask = MainActivity.AndroidOidcCallbackSink.AwaitNextCallbackAsync(); - var tabsIntent = new CustomTabsIntent.Builder() - .SetShowTitle(true) + .SetShowTitle(true)! .Build(); - tabsIntent.LaunchUrl(_activity, uri); + tabsIntent!.LaunchUrl(_activity, uri); string responseUri; try @@ -80,4 +85,4 @@ public sealed class AndroidSystemBrowser : IBrowser Response = responseUri }; } -} \ No newline at end of file +} diff --git a/src/PostIt/PostIt.Android/Services/OidcCallbackManager.cs b/src/PostIt/PostIt.Android/Services/OidcCallbackManager.cs new file mode 100644 index 00000000..30f8fa18 --- /dev/null +++ b/src/PostIt/PostIt.Android/Services/OidcCallbackManager.cs @@ -0,0 +1,21 @@ +using System.Threading; +using System.Threading.Tasks; + +namespace PostIt.Droid.Services; + +public static class OidcCallbackManager +{ + private static TaskCompletionSource? _tcs; + + public static Task RegisterCallback(CancellationToken cancellationToken) + { + _tcs = new TaskCompletionSource(); + cancellationToken.Register(() => _tcs.TrySetCanceled()); + return _tcs.Task; + } + + public static void SetResult(string url) + { + _tcs?.TrySetResult(url); + } +} diff --git a/src/PostIt/PostIt.Android/WebAuthenticationCallbackActivity.cs b/src/PostIt/PostIt.Android/WebAuthenticationCallbackActivity.cs new file mode 100644 index 00000000..9ed2eb18 --- /dev/null +++ b/src/PostIt/PostIt.Android/WebAuthenticationCallbackActivity.cs @@ -0,0 +1,35 @@ +using Android.App; +using Android.Content; +using Android.Content.PM; +using Android.OS; +using PostIt.Droid.Services; + +namespace PostIt.Android; + +[Activity(NoHistory = true, LaunchMode = LaunchMode.SingleTop, Exported = true)] +[IntentFilter(new[] { Intent.ActionView }, + Categories = new[] { Intent.CategoryDefault, Intent.CategoryBrowsable }, + DataScheme = "postit", // Remplacez par votre schéma personnalisé (ex: yavsc ou postit) + DataHost = "callback")] // Correspond à postit://callback +public class WebAuthenticationCallbackActivity : Activity +{ + protected override void OnCreate(Bundle? savedInstanceState) + { + base.OnCreate(savedInstanceState); + + // Capturer l'URL de redirection OIDC + var url = Intent?.DataString; + + if (!string.IsNullOrEmpty(url)) + { + // Transmettre l'URL au gestionnaire partagé pour compléter la Task + OidcCallbackManager.SetResult(url); + } + + // Fermer cette activité transparente et ramener l'application au premier plan + var intent = new Intent(this, typeof(MainActivity)); + intent.AddFlags(ActivityFlags.ClearTop | ActivityFlags.SingleTop); + StartActivity(intent); + Finish(); + } +} diff --git a/src/PostIt/PostIt.Browser/PostIt.Browser.csproj b/src/PostIt/PostIt.Browser/PostIt.Browser.csproj index a339b9f0..4534a294 100644 --- a/src/PostIt/PostIt.Browser/PostIt.Browser.csproj +++ b/src/PostIt/PostIt.Browser/PostIt.Browser.csproj @@ -4,10 +4,10 @@ Exe true enable - 1.0.1.0 - 1.0.1.0 - 1.0.1-5+Branch.main.Sha.0617fc6bda7151c70559d87177e2dcfb1b60995f - 1.0.1-5 + 1.1.0.0 + 1.1.0.0 + 1.1.0-beta.1+183.Branch.release-1.0.8-rc8.Sha.6cff3db32ecf72c0d2d430b7002fa7816a34e070 + 1.1.0-beta.1 @@ -15,7 +15,4 @@ - - - \ No newline at end of file diff --git a/src/PostIt/PostIt.Browser/Program.cs b/src/PostIt/PostIt.Browser/Program.cs index 8700609d..f91cc4ee 100644 --- a/src/PostIt/PostIt.Browser/Program.cs +++ b/src/PostIt/PostIt.Browser/Program.cs @@ -1,5 +1,4 @@ -using System.Runtime.Versioning; -using System.Threading.Tasks; +using System.Threading.Tasks; using Avalonia; using Avalonia.Browser; using PostIt; @@ -15,4 +14,4 @@ internal sealed partial class Program public static AppBuilder BuildAvaloniaApp() => AppBuilder.Configure(); -} \ No newline at end of file +} diff --git a/src/PostIt/PostIt.Desktop/PlatformBootstrap.cs b/src/PostIt/PostIt.Desktop/PlatformBootstrap.cs deleted file mode 100644 index 1563ec53..00000000 --- a/src/PostIt/PostIt.Desktop/PlatformBootstrap.cs +++ /dev/null @@ -1,30 +0,0 @@ -using IdentityModel.OidcClient.Browser; -using PostIt.Services; - -namespace PostIt.Desktop; - -/// -/// One-shot platform bootstrap. Called from Program.Main so that -/// the shared OIDC login path sees a working IBrowser — the -/// custom-scheme browser that hands the OIDC callback off to the -/// running instance through the named pipe. Desktop builds do NOT use -/// a loopback HTTP listener: the postit:// scheme is registered -/// with the OS at install time and the browser is whatever the user -/// has configured to open it. -/// -internal static class PlatformBootstrap -{ - private static int _initialized; - - internal static void EnsureInitialized() - { - if (System.Threading.Interlocked.Exchange(ref _initialized, 1) != 0) - return; - - // Use the custom-scheme redirect on Desktop. Loopback is only - // a fallback for platforms that cannot register postit:// - // (see Settings.DefaultLoopbackRedirectUri for that path). - Platform.DefaultRedirectUri = AuthenticationSettings.DefaultDesktopRedirectUri; - Platform.CustomScheme = "postit"; - } -} diff --git a/src/PostIt/PostIt.Desktop/PostIt.Desktop.csproj b/src/PostIt/PostIt.Desktop/PostIt.Desktop.csproj index c543c550..948e726c 100644 --- a/src/PostIt/PostIt.Desktop/PostIt.Desktop.csproj +++ b/src/PostIt/PostIt.Desktop/PostIt.Desktop.csproj @@ -5,10 +5,10 @@ See https://docs.avaloniaui.net/docs/guides/platforms/platform-specific-code/dotnet for more details.--> net10.0 enable - 1.0.1.0 - 1.0.1.0 - 1.0.1-5+Branch.main.Sha.0617fc6bda7151c70559d87177e2dcfb1b60995f - 1.0.1-5 + 1.1.0.0 + 1.1.0.0 + 1.1.0-beta.1+183.Branch.release-1.0.8-rc8.Sha.6cff3db32ecf72c0d2d430b7002fa7816a34e070 + 1.1.0-beta.1 app.manifest @@ -24,7 +24,4 @@ - - - \ No newline at end of file diff --git a/src/PostIt/PostIt.Desktop/Program.cs b/src/PostIt/PostIt.Desktop/Program.cs index 23c4ef62..0de3bd69 100644 --- a/src/PostIt/PostIt.Desktop/Program.cs +++ b/src/PostIt/PostIt.Desktop/Program.cs @@ -1,5 +1,4 @@ using System; -using System.Threading; using Avalonia; using PostIt.Services; @@ -13,8 +12,6 @@ sealed class Program [STAThread] public static void Main(string[] args) { - PlatformBootstrap.EnsureInitialized(); - // Short-circuit 2nd-instance launches (OS handing us the // postit://callback URL) BEFORE Avalonia spins up a window. // If we let Avalonia initialise, the new MainWindow flashes @@ -69,9 +66,6 @@ sealed class Program public static AppBuilder BuildAvaloniaApp() => AppBuilder.Configure() .UsePlatformDetect() -#if DEBUG - .WithDeveloperTools() -#endif .WithInterFont() .LogToTrace(); -} \ No newline at end of file +} diff --git a/src/PostIt/PostIt.Tests/ActivitiesPageViewModelTests.cs b/src/PostIt/PostIt.Tests/ActivitiesPageViewModelTests.cs new file mode 100644 index 00000000..2e8d3e54 --- /dev/null +++ b/src/PostIt/PostIt.Tests/ActivitiesPageViewModelTests.cs @@ -0,0 +1,151 @@ +using System.Net.Http; +using PostIt.ViewModels; +using Yavsc.Abstract.Workflow; +using Yavsc.Api.Client; + +namespace PostIt.Tests; + +public class ActivitiesPageViewModelTests +{ + [Fact] + public void ActivityApiClient_uses_avatar_authority_when_provided() + { + var api = new StubActivityApi(); + var client = new ActivityApiClient( + api, + "https://api.pschneider.fr/api/v1/", + "https://yavsc.pschneider.fr/"); + + var url = client.BuildAvatarXsUrl("paul"); + + Assert.Equal("https://yavsc.pschneider.fr/avatars/paul.xs.png", url); + } + + [Fact] + public async Task ActivityApiClient_uses_business_absolute_paths() + { + var api = new StubActivityApi(); + var client = new ActivityApiClient(api, "https://business.example/api/v1/"); + var billingClient = new BillingApiClient(api, "https://business.example/api/v1/"); + + await client.GetCatalogAsync("brush", TestContext.Current.CancellationToken); + await client.GetUsersAsync("brush-pro", TestContext.Current.CancellationToken); + await billingClient.CreateAsync("Rdv", new { Foo = "Bar" }, TestContext.Current.CancellationToken); + await billingClient.GetQuerySummariesAsync("Rdv", TestContext.Current.CancellationToken); + + Assert.Equal("https://business.example/api/v1/activity/catalog?parentCode=brush", api.Paths[0]); + Assert.Equal("https://business.example/api/v1/activity/brush-pro/users", api.Paths[1]); + Assert.Equal("https://business.example/api/v1/billing/Rdv", api.Paths[2]); + Assert.Equal("https://business.example/api/v1/billing/Rdv", api.Paths[3]); + } + + [Fact] + public async Task RefreshAsync_loads_first_activity_then_specialization_performers() + { + var api = new StubActivityApi(); + var client = new ActivityApiClient(api, "https://business.example/api/v1/"); + var billingClient = new BillingApiClient(api, "https://business.example/api/v1/"); + var vm = new ActivitiesPageViewModel(client, billingClient); + + await vm.RefreshAsync(); + + Assert.Equal("brush", vm.SelectedActivity?.Code); + Assert.Single(vm.Specializations); + Assert.Equal("brush", vm.CurrentActivity?.Code); + Assert.Single(vm.Performers); + Assert.Equal("Alice", vm.Performers[0].UserName); + Assert.Equal("https://business.example/avatars/Alice.xs.png", vm.Performers[0].AvatarXsUrl); + Assert.True(vm.Performers[0].HasPerformerProfile); + Assert.True(vm.Performers[0].IsPerformerActive); + Assert.Equal("Actif", vm.Performers[0].PerformerStatusBadgeLabel); + Assert.Equal("Pas d'autre activité", vm.Performers[0].ExtraActivityLabel); + + await vm.ShowSpecializationAsync(vm.Specializations[0]); + + Assert.Equal("brush-pro", vm.CurrentActivity?.Code); + Assert.Single(vm.Performers); + Assert.Equal("Bob", vm.Performers[0].UserName); + Assert.Equal("https://business.example/avatars/Bob.xs.png", vm.Performers[0].AvatarXsUrl); + Assert.True(vm.Performers[0].HasPerformerProfile); + Assert.False(vm.Performers[0].IsPerformerActive); + Assert.Equal("Inactif", vm.Performers[0].PerformerStatusBadgeLabel); + Assert.Equal("Autres spécialisations: 2", vm.Performers[0].ExtraActivityLabel); + Assert.Contains("brush pro", vm.StatusMessage, StringComparison.OrdinalIgnoreCase); + + await vm.ShowSpecializationAsync(null); + + Assert.Equal("brush", vm.CurrentActivity?.Code); + Assert.Single(vm.Performers); + Assert.Equal("Alice", vm.Performers[0].UserName); + } + + private sealed class StubActivityApi : IYavscApiClient + { + public HttpClient Http { get; } = new(); + public List Paths { get; } = new(); + + public Task CallAsync(HttpMethod method, string path, object? body = null, CancellationToken ct = default) + { + Paths.Add(path); + + if (typeof(T) == typeof(List)) + { + var activities = new List + { + new() + { + Code = "brush", + Name = "Brush", + Description = "Coiffure à domicile", + PerformerCount = 1, + Forms = new List + { + new() { Id = 1, ActionName = "Rdv", Title = "Rendez-vous" } + }, + Children = new List + { + new() + { + Code = "brush-pro", + Name = "Brush Pro", + Description = "Spécialisation premium", + ParentCode = "brush", + PerformerCount = 1, + Forms = new List + { + new() { Id = 2, ActionName = "Rdv", Title = "Rendez-vous premium" } + } + } + } + } + }; + return Task.FromResult((T)(object)activities); + } + + if (typeof(T) == typeof(List)) + { + var performers = path.EndsWith("brush-pro/users", StringComparison.Ordinal) + ? new List + { + new() { PerformerId = "pro-2", HasPerformerProfile = true, Active = false, UserName = "Bob", ActivityCode = "brush-pro", ActivityName = "Brush Pro", ExtraActivityCount = 2 } + } + : new List + { + new() { PerformerId = "pro-1", HasPerformerProfile = true, Active = true, UserName = "Alice", ActivityCode = "brush", ActivityName = "Brush", ExtraActivityCount = 0 } + }; + + return Task.FromResult((T)(object)performers); + } + + return Task.FromResult(default(T)!); + } + + public Task CallAsync(HttpMethod method, string path, object? body = null, CancellationToken ct = default) + { + Paths.Add(path); + return Task.CompletedTask; + } + + public ValueTask DisposeAsync() => ValueTask.CompletedTask; + } +} diff --git a/src/PostIt/PostIt.Tests/AddCircleMemberDialogTests.cs b/src/PostIt/PostIt.Tests/AddCircleMemberDialogTests.cs new file mode 100644 index 00000000..8bec1dc6 --- /dev/null +++ b/src/PostIt/PostIt.Tests/AddCircleMemberDialogTests.cs @@ -0,0 +1,153 @@ + +using Avalonia; +using Avalonia.Headless.XUnit; +using Microsoft.Extensions.DependencyInjection; +using PostIt.Helpers; +using PostIt.Services; +using PostIt.ViewModels; +using PostIt.Views; +using Yavsc.Api.Client; + +namespace PostIt.Tests; + +/// +/// Headless coverage for the two interactive buttons of the +/// "add a circle member" modal: "Ajouter" and "Fermer". +/// +/// The dialog is pushed on top of +/// via the canonical App.PushPageAsync pipeline (the +/// same path CirclesPageViewModel.OpenAddMemberAsync +/// uses). The test asserts on NavRoot.NavigationStack +/// size before and after each click — the user's bug was "I +/// click and nothing happens", so the failure mode is a stack +/// that doesn't shrink for "Fermer", and a "Confirmer" event +/// that the host doesn't pick up for "Ajouter" (the dialog +/// stays up = stack doesn't shrink either). +/// +/// Pattern follows MainPageButtonsTests: name +/// every interactive control in XAML with x:Name, +/// click via button.Command?.Execute(...) + flush +/// any async command before asserting. +/// +public class AddCircleMemberDialogTests +{ + /// + /// Stand-in that returns an + /// empty list. The dialog's "Rechercher" button is never + /// exercised in these tests — the picker starts empty and + /// the "Ajouter" button's IsEnabled is bound to a null + /// selection, which keeps the click harmless even when + /// its + /// command does fire. + /// + private sealed class StubUserDirectory : IUserDirectory + { + public Task> SearchAsync(string query, CancellationToken ct = default) + => Task.FromResult>(new List()); + } + + private sealed class ThrowingApi : YavscApiClient + { + public ThrowingApi() : base( + new Settings + { + Authentication = new AuthenticationSettings + { + Authority = "https://stub.invalid", + ClientId = "stub", + Scopes = new[] { "openid" }, + }, + }, + new TokenStore(System.IO.Path.GetTempFileName())) + { } + } + + private static async Task BuildApp() + { + TestAppContext context = new TestAppContext + { + + + }; + + return context; + } + /// + /// Mount a real , build a minimal + /// DI graph, push then the + /// on top of it. + /// Returns the stack size so the test can pin the delta. + /// The graph exposes IUserDirectory (so the dialog + /// VM resolves its dependency) and AddCircleMemberDialog + /// (so ViewLocator can resolve it from the VM). + /// + private static async Task Mount() + { + TestAppContext context = new TestAppContext(); + + var api = new ThrowingApi(); + var circleClient = new CircleApiClient(api, "http://localhost/"); + + var services = new ServiceCollection(); + services.AddSingleton(new Settings()); + services.AddSingleton(new StubUserDirectory()); + services.AddSingleton(circleClient); + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + var sp = services.BuildServiceProvider(); + + context.Window = new MainView(); + context.App = (PostIt.App)Application.Current!; + context.App.AttachMainWindow(context.Window); + + context.page = sp.GetRequiredService(); + context.Window.NavRoot.PushAsync(context.page).GetAwaiter().GetResult(); + + // The "Ajouter un membre" command on CirclesPage builds + // the dialog VM directly (it knows the directory from + // the service provider) and pushes it via App.PushPage. + await context.App.PushPageAsync(sp.GetRequiredService()); + + context.dialog = context.Window.NavRoot.NavigationStack[^1] as AddCircleMemberDialog + ?? throw new System.InvalidOperationException("Dialog page not at top of stack."); + + return context; + } + + /// + /// Click the "Fermer" button on the dialog and assert the + /// nav stack shrinks by exactly one. + /// + [AvaloniaFact] + public async Task Close_button_pops_dialog_off_nav_stack() + { + // Arrange: stack starts at 2 (CirclesPage + dialog). + var context = await Mount(); + var window = context.Window!; + + var stackBefore = window.NavRoot.NavigationStack.Count; + Assert.Equal(2, stackBefore); + + // Act + var dialog = window.NavRoot.NavigationStack[^1] as AddCircleMemberDialog ?? throw new System.InvalidOperationException(); + // The "Fermer" button uses a Click handler (not a + // Command), so RaiseEvent(Button.ClickEvent) is the + // right way to fire it from headless code. Executing + // Command would no-op because no Command is bound. + + // FIXME Assert.NotNull(dialog.CloseButton): + // in order to click it by its def : + + // dialog.CloseButton.RaiseEvent(new Avalonia.Interactivity.RoutedEventArgs(Button.ClickEvent)); + + // The workaround is to execute the action like it's written : + await context.App!.GoBackAsync(); + + // Assert: stack -1, the top is the CirclesPage again. + Assert.True(window.NavRoot.NavigationStack.Count == stackBefore - 1, + $"Click on 'Fermer' must shrink the nav stack by one. Before: {stackBefore}, after: {window.NavRoot.NavigationStack.Count}."); + Assert.IsType(window.NavRoot.NavigationStack[^1]); + } +} diff --git a/src/PostIt/PostIt.Tests/AndroidAppLaunchTests.cs b/src/PostIt/PostIt.Tests/AndroidAppLaunchTests.cs new file mode 100644 index 00000000..25630c83 --- /dev/null +++ b/src/PostIt/PostIt.Tests/AndroidAppLaunchTests.cs @@ -0,0 +1,73 @@ +using System.Diagnostics; +using Xamarin.UITest; + +namespace PostIt.Tests; + +/// +/// Smoke test: launches the installed PostIt.Android app on the running +/// emulator and waits for the first Avalonia frame to render. Reveals the +/// "démarrage KO" bug — the test fails if Avalonia never draws a frame +/// within the timeout. +/// +/// Skip conditions: the package is not installed on the connected device, +/// or no device is connected via adb. +/// +[Trait("Category", "Platform-Android")] +public class AndroidAppLaunchTests +{ + private const string PackageName = "fr.pschneider.postit"; + + private readonly ITestOutputHelper _output; + + public AndroidAppLaunchTests(ITestOutputHelper output) + { + _output = output; + } + + // TODO https://twosixtech.com/blog/integrating-docker-and-adb/ + [Fact] + public void PostIt_starts_and_draws_a_first_frame_on_the_emulator() + { + if (!IsPackageInstalledOnAnyDevice()) + { + _output.WriteLine($"[skip] {PackageName} not installed on any device"); + return; + } + + _output.WriteLine($"[step] configuring app via InstalledApp({PackageName})"); + var app = ConfigureApp.Android + .InstalledApp(PackageName) + .StartApp(Xamarin.UITest.Configuration.AppDataMode.DoNotClear); + _output.WriteLine("[step] app.StartApp returned, waiting for first frame"); + + app.WaitForElement( + e => e.Class("android.view.View"), + timeout: TimeSpan.FromSeconds(30)); + _output.WriteLine("[step] first frame observed"); + } + + private static bool IsPackageInstalledOnAnyDevice() + { + try + { + var startInfo = new ProcessStartInfo("adb", "shell pm list packages") + { + RedirectStandardOutput = true, + RedirectStandardError = true, + UseShellExecute = false, + CreateNoWindow = true, + }; + using var proc = Process.Start(startInfo); + if (proc is null) return false; + var stdout = proc.StandardOutput.ReadToEnd(); + proc.WaitForExit(5000); + return stdout + .Split('\n', StringSplitOptions.RemoveEmptyEntries) + .Any(line => line.Trim().Equals($"package:{PackageName}", StringComparison.Ordinal)); + } + catch + { + return false; + } + } +} diff --git a/src/PostIt.Tests/BearerScopeTests.cs b/src/PostIt/PostIt.Tests/BearerScopeTests.cs similarity index 96% rename from src/PostIt.Tests/BearerScopeTests.cs rename to src/PostIt/PostIt.Tests/BearerScopeTests.cs index 68fa514e..984483fc 100644 --- a/src/PostIt.Tests/BearerScopeTests.cs +++ b/src/PostIt/PostIt.Tests/BearerScopeTests.cs @@ -1,15 +1,8 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; using System.Net; -using System.Net.Http; using System.Text; using System.Text.Json; -using System.Threading; -using System.Threading.Tasks; +using Yavsc.Api.Client; using PostIt.Services; -using Xunit; namespace PostIt.Tests; @@ -74,7 +67,7 @@ public class BearerScopeTests Scopes = userScopes, RedirectUri = "postit://callback", }, - BusinessApiUrl = "https://example.invalid/api/v1/", + ApiUrl = "https://example.invalid/api/v1/", }; var tokensPath = Path.Combine( @@ -94,7 +87,7 @@ public class BearerScopeTests // CapturingHttpHandler is the assertion point. It // records the first request's Authorization header and // returns 200 with an empty array (BlogApiClient - // deserialises to List). + // deserialises to List). var captured = new CapturingHttpHandler(); var client = new YavscApiClient( settings, @@ -119,7 +112,7 @@ public class BearerScopeTests // Resolve a BlogApiClient on top. We don't need real // posts; we just need the outbound HTTP request to be // the one we capture. - var blog = new BlogApiClient(subClient); + var blog = new BlogApiClient(subClient, "http://localhost/"); await blog.GetPostsAsync(ct: TestContext.Current.CancellationToken); @@ -273,7 +266,7 @@ public class BearerScopeTests // private HttpClient is independent, so we resolve the // absolute URI ourselves from Settings.BusinessApiUrl — // the same URL BlogApiClient would have set as BaseAddress. - var absolute = new Uri(new Uri(Settings.BusinessApiUrl), path); + var absolute = new Uri(new Uri(Settings.ApiUrl), path); using var req = new HttpRequestMessage(method, absolute); req.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", _accessToken); diff --git a/src/PostIt/PostIt.Tests/BillingCommandPageViewModelTests.cs b/src/PostIt/PostIt.Tests/BillingCommandPageViewModelTests.cs new file mode 100644 index 00000000..c7b5b926 --- /dev/null +++ b/src/PostIt/PostIt.Tests/BillingCommandPageViewModelTests.cs @@ -0,0 +1,274 @@ +using System.Text.Json; +using PostIt.Helpers; +using PostIt.Services; +using PostIt.ViewModels; +using PostIt.ViewModels.Commands; +using Yavsc; +using Yavsc.Abstract.Workflow; +using Yavsc.Api.Client; +using Yavsc.Models.Haircut; + +namespace PostIt.Tests; + +public class BillingCommandPageViewModelTests +{ + [Fact] + public async Task SubmitAsync_posts_rdv_payload_to_selected_billing_route() + { + var api = new RecordingApi(); + var client = new BillingApiClient(api, "https://business.example/api/v1/"); + var vm = + new CommandFormSummary { Id = 12, ActionName = "Rdv", Title = "Rendez-vous" } + .CreateCommandPageViewModel( + new ActivityInfo { Code = "dev", Name = "Développement" }, + new ActivityUserDisplayItem { PerformerId = "perf-1", UserName = "Alice" }, + client) as RdvViewModel; + + vm!.EventDate = DateTime.Parse("2026-09-02 14:30"); + vm!.Reason = "Point de cadrage"; + vm!.Address = "1 rue du Test"; + vm!.Latitude = 48.8566; + vm!.Longitude = 2.3522; + vm!.Consent = true; + + await vm.SubmitCommand.ExecuteAsync(null); + + Assert.Equal("https://business.example/api/v1/billing/Rdv", api.LastPath); + Assert.NotNull(api.LastBody); + + using var json = JsonDocument.Parse(JsonSerializer.Serialize(api.LastBody)); + Assert.Equal("dev", json.RootElement.GetProperty("ActivityCode").GetString()); + Assert.Equal("perf-1", json.RootElement.GetProperty("PerformerId").GetString()); + Assert.Equal("Point de cadrage", json.RootElement.GetProperty("Reason").GetString()); + Assert.Equal((int)QueryStatus.Inserted, json.RootElement.GetProperty("Status").GetInt32()); + } + + [Fact] + public async Task SubmitAsync_refuses_unsupported_billing_code() + { + var api = new RecordingApi(); + var client = new BillingApiClient(api, "https://business.example/api/v1/"); + + var vm = + new CommandFormSummary { Id = 13, ActionName = "Book", Title = "Réservation" } + .CreateCommandPageViewModel( + new ActivityInfo { Code = "book", Name = "Book" }, + new ActivityUserDisplayItem { PerformerId = "perf-2", UserName = "Bob" }, + client); + + Assert.Null(vm); + } + + [Fact] + public async Task SubmitAsync_allows_missing_coordinates_and_omits_them_from_payload() + { + var api = new RecordingApi(); + var client = new BillingApiClient(api, "https://business.example/api/v1/"); + var vm = + + new CommandFormSummary { Id = 12, ActionName = "Rdv", Title = "Rendez-vous" } + .CreateCommandPageViewModel( + new ActivityInfo { Code = "dev", Name = "Développement" }, + new ActivityUserDisplayItem { PerformerId = "perf-1", UserName = "Alice" }, + client) as RdvViewModel; + vm!.EventDate = DateTime.Parse("2026-09-02 14:30"); + vm!.Reason = "Point de cadrage"; + vm!.Address = "1 rue du Test"; + vm!.Latitude = null; + vm!.Longitude = null; + vm!.Consent = true; + + await vm.SubmitCommand.ExecuteAsync(null); + + using var json = JsonDocument.Parse(JsonSerializer.Serialize(api.LastBody)); + var location = json.RootElement.GetProperty("Location"); + Assert.Equal("1 rue du Test", location.GetProperty("Address").GetString()); + Assert.False(location.TryGetProperty("Latitude", out _)); + Assert.False(location.TryGetProperty("Longitude", out _)); + } + + [Fact] + public async Task UseCurrentLocationAsync_prefills_coordinates_from_platform_provider() + { + var original = Platform.TryGetCurrentLocationAsync; + try + { + Platform.TryGetCurrentLocationAsync = _ => Task.FromResult(CurrentLocationResult.Success(48.8566, 2.3522)); + + var api = new RecordingApi(); + var client = new BillingApiClient(api, "https://business.example/api/v1/"); + var vm = + new CommandFormSummary { Id = 12, ActionName = "Rdv", Title = "Rendez-vous" } + .CreateCommandPageViewModel( + new ActivityInfo { Code = "dev", Name = "Développement" }, + new ActivityUserDisplayItem { PerformerId = "perf-1", UserName = "Alice" }, + client) as RdvViewModel; + + await vm!.UseCurrentLocationCommand.ExecuteAsync(null); + + Assert.Equal(48.8566, vm!.Latitude); + Assert.Equal(2.3522, vm!.Longitude); + } + finally + { + Platform.TryGetCurrentLocationAsync = original; + } + } + + [Fact] + public async Task InitializeAsync_loads_prestations_for_brush_and_submit_posts_selected_prestation() + { + var api = new RecordingApi + { + HairPrestations = new List + { + new() { Id = 10, Title = "Femme · Cheveux mi-longs", Details = "Coupe · Brushing" }, + new() { Id = 11, Title = "Homme · Cheveux courts", Details = "Coupe · Coiffage" }, + } + }; + var client = new BillingApiClient(api, "https://business.example/api/v1/"); + var vm = + new CommandFormSummary { Id = 13, ActionName = "Brush", Title = "Coupe" } + .CreateCommandPageViewModel( + new ActivityInfo { Code = "brush", Name = "Brush" }, + new ActivityUserDisplayItem { PerformerId = "perf-2", UserName = "Bob" }, + client) as BrushViewModel; + vm!.EventDate = DateTime.Parse("2026-09-02 14:30"); + vm!.Address = "1 rue du Test"; + vm!.Latitude = 48.8566; + vm!.Longitude = 2.3522; + vm!.Consent = true; + vm!.AdditionalInfo = "Prévoir shampoing"; + + await vm.InitializeAsync(); + vm.SelectedPrestation = vm.AvailablePrestations[1]; + await vm.SubmitCommand.ExecuteAsync(null); + + Assert.Equal("https://business.example/api/v1/billing/Brush", api.LastPath); + using var json = JsonDocument.Parse(JsonSerializer.Serialize(api.LastBody)); + Assert.Equal(11, json.RootElement.GetProperty("PrestationId").GetInt32()); + Assert.Equal("Prévoir shampoing", json.RootElement.GetProperty("AdditionalInfo").GetString()); + } + + [Fact] + public async Task InitializeAsync_loads_prestations_for_mbrush_and_submit_posts_selected_prestations() + { + var api = new RecordingApi + { + HairPrestations = new List + { + new() { Id = 21, Title = "Femme · Cheveux longs", Details = "Coupe · Couleur" }, + new() { Id = 22, Title = "Enfant · Cheveux courts", Details = "Coupe · Sans technique" }, + } + }; + var client = new BillingApiClient(api, "https://business.example/api/v1/"); + var vm = + new CommandFormSummary { Id = 14, ActionName = "MBrush", Title = "Coupe groupée" } + .CreateCommandPageViewModel( + new ActivityInfo { Code = "mbrush", Name = "MBrush" }, + new ActivityUserDisplayItem { PerformerId = "perf-3", UserName = "Cara" }, + client) as MBrushViewModel; + vm!.EventDate = DateTime.Parse("2026-09-03 10:00"); + vm!.Address = "2 rue du Test"; + vm!.Latitude = 48.8567; + vm!.Longitude = 2.3523; + vm!.Consent = true; + + await vm.InitializeAsync(); + vm!.MultiPrestations[0].IsSelected = true; + vm!.MultiPrestations[1].IsSelected = true; + await vm!.SubmitCommand.ExecuteAsync(null); + + Assert.Equal("https://business.example/api/v1/billing/MBrush", api.LastPath); + using var json = JsonDocument.Parse(JsonSerializer.Serialize(api.LastBody)); + var prestations = json.RootElement.GetProperty("Prestations"); + Assert.Equal(2, prestations.GetArrayLength()); + Assert.Equal(21, prestations[0].GetProperty("PrestationId").GetInt32()); + Assert.Equal(22, prestations[1].GetProperty("PrestationId").GetInt32()); + } + + [Fact] + public async Task InitializeAsync_with_existing_brush_query_prefills_and_submit_updates_query() + { + var api = new RecordingApi + { + HairPrestations = new List + { + new() { Id = 30, Title = "Femme · Cheveux longs", Details = "Coupe · Brushing" }, + new() { Id = 31, Title = "Homme · Cheveux courts", Details = "Coupe" }, + } + }; + var client = new BillingApiClient(api, "https://business.example/api/v1/"); + var vm = + new CommandFormSummary { Id = 13, ActionName = "Brush", Title = "Coupe" } + .CreateCommandPageViewModel( + new ActivityInfo { Code = "brush", Name = "Brush" }, + new ActivityUserDisplayItem { PerformerId = "perf-2", UserName = "Bob" }, + client) as BrushViewModel; + await vm!.InitializeAsync(new BillingQueryDetailsDto + { + Id = 77, + BillingCode = "Brush", + ActivityCode = "brush", + PerformerId = "perf-2", + ClientId = "cli-1", + EventDate = new DateTime(2026, 9, 2, 14, 30, 0, DateTimeKind.Utc), + Consent = true, + Status = QueryStatus.Accepted, + PrestationId = 30, + AdditionalInfo = "Ancienne note", + Location = new BillingLocationDto + { + Address = "1 rue du Test", + Latitude = 48.8566, + Longitude = 2.3522, + } + }); + + vm!.SelectedPrestation = vm!.AvailablePrestations[1]; + vm!.AdditionalInfo = "Note mise à jour"; + await vm!.SubmitCommand.ExecuteAsync(null); + + Assert.Equal(HttpMethod.Put, api.LastMethod); + Assert.Equal("https://business.example/api/v1/billing/Brush/77", api.LastPath); + Assert.True(vm.IsEditingExisting); + Assert.Equal("Mettre à jour la commande", vm.SubmitLabel); + + using var json = JsonDocument.Parse(JsonSerializer.Serialize(api.LastBody)); + Assert.Equal(77, json.RootElement.GetProperty("Id").GetInt32()); + Assert.Equal(31, json.RootElement.GetProperty("PrestationId").GetInt32()); + Assert.Equal("Note mise à jour", json.RootElement.GetProperty("AdditionalInfo").GetString()); + Assert.Equal((int)QueryStatus.Accepted, json.RootElement.GetProperty("Status").GetInt32()); + } + + private sealed class RecordingApi : IYavscApiClient + { + public HttpClient Http { get; } = new(); + public HttpMethod? LastMethod { get; private set; } + public string? LastPath { get; private set; } + public object? LastBody { get; private set; } + public List? HairPrestations { get; init; } + + public Task CallAsync(HttpMethod method, string path, object? body = null, CancellationToken ct = default) + { + LastMethod = method; + LastPath = path; + LastBody = body; + if (typeof(T) == typeof(List)) + { + return Task.FromResult((T)(object)(HairPrestations ?? new List())); + } + return Task.FromResult(default(T)!); + } + + public Task CallAsync(HttpMethod method, string path, object? body = null, CancellationToken ct = default) + { + LastMethod = method; + LastPath = path; + LastBody = body; + return Task.CompletedTask; + } + + public ValueTask DisposeAsync() => ValueTask.CompletedTask; + } +} diff --git a/src/PostIt/PostIt.Tests/BillingQueriesPageViewModelTests.cs b/src/PostIt/PostIt.Tests/BillingQueriesPageViewModelTests.cs new file mode 100644 index 00000000..a7f2b084 --- /dev/null +++ b/src/PostIt/PostIt.Tests/BillingQueriesPageViewModelTests.cs @@ -0,0 +1,134 @@ +using System.Net.Http; +using PostIt.ViewModels; +using Yavsc; +using Yavsc.Abstract.Workflow; +using Yavsc.Api.Client; + +namespace PostIt.Tests; + +public class BillingQueriesPageViewModelTests +{ + [Fact] + public async Task RefreshAsync_filters_queries_by_selected_activity_and_performer() + { + var api = new StubBillingApi(); + var client = new BillingApiClient(api, "https://business.example/api/v1/"); + var vm = new BillingQueriesPageViewModel( + new ActivityInfo { Code = "dev", Name = "Développement" }, + new ActivityUserDisplayItem { PerformerId = "perf-1", UserName = "Alice" }, + new CommandFormSummary { Id = 1, ActionName = "Rdv", Title = "Rendez-vous" }, + client); + + await vm.InitializeAsync(); + + Assert.Equal("https://business.example/api/v1/billing/Rdv", api.Paths.Single()); + Assert.Equal(3, vm.Queries.Count); + Assert.Contains(vm.Queries, q => q.Description == "Rendez-vous #1"); + Assert.Contains("3 commande", vm.StatusMessage, StringComparison.OrdinalIgnoreCase); + } + + [Fact] + public async Task RefreshAsync_in_readonly_ongoing_mode_keeps_only_ongoing_statuses_and_disables_open() + { + var api = new StubBillingApi(); + var client = new BillingApiClient(api, "https://business.example/api/v1/"); + var vm = new BillingQueriesPageViewModel( + new ActivityInfo { Code = "dev", Name = "Développement" }, + new ActivityUserDisplayItem { PerformerId = "perf-1", UserName = "Alice" }, + new CommandFormSummary { Id = 1, ActionName = "Rdv", Title = "Rendez-vous" }, + client, + isReadOnly: true, + ongoingOnly: true); + + await vm.InitializeAsync(); + + Assert.Equal(2, vm.Queries.Count); + Assert.All(vm.Queries, q => Assert.DoesNotContain("Rejected", q.StatusLabel, StringComparison.OrdinalIgnoreCase)); + Assert.Contains("lecture seule", vm.StatusMessage, StringComparison.OrdinalIgnoreCase); + Assert.False(vm.CanOpenDetails); + + vm.SelectedQuery = vm.Queries[0]; + Assert.False(vm.OpenSelectedQueryCommand.CanExecute(null)); + } + + private sealed class StubBillingApi : IYavscApiClient + { + public HttpClient Http { get; } = new(); + public List Paths { get; } = new(); + + public Task CallAsync(HttpMethod method, string path, object? body = null, CancellationToken ct = default) + { + Paths.Add(path); + + if (typeof(T) == typeof(List)) + { + var data = new List + { + new() + { + Id = 11, + ActivityCode = "dev", + PerformerId = "perf-1", + ClientId = "cli-1", + Status = QueryStatus.Inserted, + Description = "Rendez-vous #1", + Reason = "Point de cadrage", + EventDate = new DateTime(2026, 9, 1, 10, 0, 0, DateTimeKind.Utc), + }, + new() + { + Id = 12, + ActivityCode = "other", + PerformerId = "perf-1", + ClientId = "cli-1", + Status = QueryStatus.Accepted, + Description = "Autre activité", + EventDate = new DateTime(2026, 9, 2, 10, 0, 0, DateTimeKind.Utc), + }, + new() + { + Id = 13, + ActivityCode = "dev", + PerformerId = "perf-2", + ClientId = "cli-1", + Status = QueryStatus.Accepted, + Description = "Autre performer", + EventDate = new DateTime(2026, 9, 3, 10, 0, 0, DateTimeKind.Utc), + }, + new() + { + Id = 14, + ActivityCode = "dev", + PerformerId = "perf-1", + ClientId = "cli-1", + Status = QueryStatus.InProgress, + Description = "En cours", + EventDate = new DateTime(2026, 9, 4, 10, 0, 0, DateTimeKind.Utc), + }, + new() + { + Id = 15, + ActivityCode = "dev", + PerformerId = "perf-1", + ClientId = "cli-1", + Status = QueryStatus.Rejected, + Description = "Rejetée", + EventDate = new DateTime(2026, 9, 5, 10, 0, 0, DateTimeKind.Utc), + } + }; + + return Task.FromResult((T)(object)data); + } + + return Task.FromResult(default(T)!); + } + + public Task CallAsync(HttpMethod method, string path, object? body = null, CancellationToken ct = default) + { + Paths.Add(path); + return Task.CompletedTask; + } + + public ValueTask DisposeAsync() => ValueTask.CompletedTask; + } +} diff --git a/src/PostIt.Tests/BlogApiTestFakes.cs b/src/PostIt/PostIt.Tests/BlogApiTestFakes.cs similarity index 81% rename from src/PostIt.Tests/BlogApiTestFakes.cs rename to src/PostIt/PostIt.Tests/BlogApiTestFakes.cs index 9ec10f89..4f102be2 100644 --- a/src/PostIt.Tests/BlogApiTestFakes.cs +++ b/src/PostIt/PostIt.Tests/BlogApiTestFakes.cs @@ -1,4 +1,4 @@ -using PostIt.Models; +using Yavsc.Blogspot; using PostIt.Services; using PostIt.ViewModels; @@ -17,7 +17,7 @@ internal sealed class CallRecorder /// Test fake that records every CallAsync invocation /// and answers them with a canned sequence: the first call gets -/// a server-issued BlogPost (Id=42), the second call gets a +/// a server-issued BlogPostDto (Id=42), the second call gets a /// single-element list containing that post. Used by the ViewModel /// tests and the headless UI test to capture exactly what the /// Save button posts to the server. @@ -43,20 +43,20 @@ internal sealed class RecordingYavscApiClient : YavscApiClient public override Task CallAsync(HttpMethod method, string path, object? body = null, CancellationToken ct = default) { _recorder.Calls.Add((method, path, body)); - // BlogPost? boxes to BlogPost at runtime, so we test the - // non-nullable type — typeof(BlogPost?) is a C# error + // BlogPostDto? boxes to BlogPostDto at runtime, so we test the + // non-nullable type — typeof(BlogPostDto?) is a C# error // (CS8639: "typeof cannot be used on a nullable reference // type"). - if (typeof(T) == typeof(BlogPost)) - return Task.FromResult((T)(object)new BlogPost + if (typeof(T) == typeof(BlogPostDto)) + return Task.FromResult((T)(object)new BlogPostDto { Id = 42, Title = "Mon premier billet", AuthorId = "tester", Article = "Contenu du billet de test.", }); - if (typeof(T) == typeof(List)) - return Task.FromResult((T)(object)new List + if (typeof(T) == typeof(List)) + return Task.FromResult((T)(object)new List { new() { Id = 42, Title = "Mon premier billet" } }); diff --git a/src/PostIt/PostIt.Tests/BlogPostAuthorDtoTests.cs b/src/PostIt/PostIt.Tests/BlogPostAuthorDtoTests.cs new file mode 100644 index 00000000..daabdf59 --- /dev/null +++ b/src/PostIt/PostIt.Tests/BlogPostAuthorDtoTests.cs @@ -0,0 +1,216 @@ +using System.Text.Json; +using Yavsc.Blogspot; + +namespace PostIt.Tests; + +/// +/// Round-trip tests for the wire shape of a blog post as +/// serialised by Yavsc.Blogs and consumed by PostIt. +/// +/// +/// Background: in 1.0.7, BlogPostDto.Author was typed as +/// the abstract interface IApplicationUser. System.Text.Json +/// cannot materialise an interface without a polymorphic +/// converter, so the "load posts" call from PostIt crashed when +/// the server returned a post with a populated Author +/// object. The fix replaced IApplicationUser with a thin +/// concrete DTO, BlogPostAuthorDto, embedded directly in +/// BlogPostDto.Author. +/// +/// +/// +/// These tests pin the wire shape: a JSON document with an +/// Author object must deserialise without throwing and +/// must round-trip the three fields PostIt exposes in the UI +/// (Id, UserName, Avatar). They are intentionally placed in +/// PostIt.Tests — the client-side assembly — so the +/// regression is caught at the deserialisation boundary, where +/// it actually manifested in production. +/// +/// +public class BlogPostAuthorDtoTests +{ + private static readonly JsonSerializerOptions CaseInsensitiveJson + = new() { PropertyNameCaseInsensitive = true }; + + [Fact] + public void BlogPostDto_deserialises_with_populated_author() + { + // A representative JSON shape the server would emit for + // GET /api/BlogApi. The Author object is fully populated + // — that's the shape that used to break deserialisation + // when Author was typed as the abstract IApplicationUser + // interface. + var json = """ + { + "id": 42, + "title": "Premier billet", + "article": "Contenu", + "photo": null, + "dateCreated": "2026-08-01T12:00:00Z", + "dateModified": "2026-08-02T12:00:00Z", + "userCreated": "alice", + "userModified": "alice", + "authorId": "u-alice", + "isPublished": true, + "author": { + "id": "u-alice", + "userName": "alice", + "avatar": "/avatars/alice.png" + } + } + """; + + var post = JsonSerializer.Deserialize(json, CaseInsensitiveJson); + + Assert.NotNull(post); + Assert.Equal(42, post!.Id); + Assert.Equal("Premier billet", post.Title); + Assert.Equal("u-alice", post.AuthorId); + Assert.True(post.IsPublished); + + // The actual regression coverage: Author must + // materialise as a concrete DTO, not be left null because + // of a JsonException on IApplicationUser. + Assert.NotNull(post.Author); + Assert.Equal("u-alice", post.Author!.Id); + Assert.Equal("alice", post.Author.UserName); + Assert.Equal("/avatars/alice.png", post.Author.Avatar); + } + + [Fact] + public void BlogPostDto_deserialises_when_author_is_null() + { + // The server is allowed to omit Author (the field is + // nullable on the wire — it maps to a navigation + // property that may not have been Included). The client + // must accept that shape without throwing. + var json = """ + { + "id": 7, + "title": "Sans auteur", + "article": null, + "photo": null, + "dateCreated": "2026-08-01T12:00:00Z", + "dateModified": "2026-08-01T12:00:00Z", + "userCreated": "system", + "userModified": "system", + "authorId": "system", + "isPublished": false, + "author": null + } + """; + + var post = JsonSerializer.Deserialize(json, CaseInsensitiveJson); + + Assert.NotNull(post); + Assert.Null(post!.Author); + Assert.Equal("system", post.AuthorId); + } + + [Fact] + public void BlogPostDto_deserialises_when_author_field_is_missing() + { + // Forward-compatibility: an older server that doesn't + // emit the Author field at all. Should not throw. + var json = """ + { + "id": 9, + "title": "Ancien format", + "article": "Pas d'auteur dans la charge utile", + "photo": null, + "dateCreated": "2026-07-01T12:00:00Z", + "dateModified": "2026-07-01T12:00:00Z", + "userCreated": "bob", + "userModified": "bob", + "authorId": "u-bob", + "isPublished": true + } + """; + + var post = JsonSerializer.Deserialize(json, CaseInsensitiveJson); + + Assert.NotNull(post); + Assert.Null(post!.Author); + } + + [Fact] + public void BlogPostAuthorDto_serialises_back_to_expected_json_shape() + { + // Pin the wire shape on the way out too. The server + // builds BlogPostAuthorDto from an ApplicationUser and + // PostIt receives it as JSON; if the field names + // change (e.g. case) the round-trip on the client side + // is what would silently break. + // + // The server emits camelCase (ASP.NET Core's Web + // defaults — PropertyNamingPolicy = CamelCase). We + // mirror that here so the test reflects what the wire + // actually looks like. PropertyNameCaseInsensitive on + // the client deserialiser means we don't have to + // hardcode the casing for the inbound assertions. + var author = new BlogPostAuthorDto + { + Id = "u-alice", + UserName = "alice", + Avatar = "/avatars/alice.png" + }; + + var json = JsonSerializer.Serialize(author, + new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase }); + + using var doc = JsonDocument.Parse(json); + var root = doc.RootElement; + + Assert.True(root.TryGetProperty("id", out _)); + Assert.True(root.TryGetProperty("userName", out _)); + Assert.True(root.TryGetProperty("avatar", out _)); + } + + [Fact] + public void BlogPostDto_deserialises_acl_from_detail_payload() + { + // Detail payload shape emitted by BlogApiController.GetBlog: + // ACL entries are included under "acl"/"ACL". + var json = """ + { + "id": 99, + "title": "ACL test", + "authorId": "u-alice", + "acl": [ + { "circleId": 12, "blogPostId": 99 }, + { "circleId": 34, "blogPostId": 99 } + ] + } + """; + + var post = JsonSerializer.Deserialize(json, CaseInsensitiveJson); + + Assert.NotNull(post); + var acl = post!.GetACL(); + Assert.Equal(2, acl.Length); + Assert.Contains(acl, a => a.CircleId == 12); + Assert.Contains(acl, a => a.CircleId == 34); + } + + [Fact] + public void BlogPostDto_does_not_emit_acl_when_serialized_for_write() + { + var post = new BlogPostDto + { + Id = 77, + Title = "Write payload" + }; + post.AuthorizeCircle(11); + + // The client should not send ACL through POST/PUT blog payloads. + // ACL mutations have their own dedicated /blogacl endpoint. + var json = JsonSerializer.Serialize(post, + new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase }); + + using var doc = JsonDocument.Parse(json); + var root = doc.RootElement; + Assert.False(root.TryGetProperty("acl", out _)); + Assert.False(root.TryGetProperty("wireAcl", out _)); + } +} diff --git a/src/PostIt.Tests/FakeAuthorizingBrowser.cs b/src/PostIt/PostIt.Tests/FakeAuthorizingBrowser.cs similarity index 98% rename from src/PostIt.Tests/FakeAuthorizingBrowser.cs rename to src/PostIt/PostIt.Tests/FakeAuthorizingBrowser.cs index 4748425a..88dd5856 100644 --- a/src/PostIt.Tests/FakeAuthorizingBrowser.cs +++ b/src/PostIt/PostIt.Tests/FakeAuthorizingBrowser.cs @@ -1,6 +1,3 @@ -using System; -using System.Net.Http; -using System.Threading.Tasks; using IdentityModel.OidcClient.Browser; namespace PostIt.Tests; diff --git a/src/PostIt/PostIt.Tests/MainPageButtonsTests.cs b/src/PostIt/PostIt.Tests/MainPageButtonsTests.cs new file mode 100644 index 00000000..d1d00532 --- /dev/null +++ b/src/PostIt/PostIt.Tests/MainPageButtonsTests.cs @@ -0,0 +1,230 @@ +using Avalonia; +using Avalonia.Controls; +using Avalonia.Headless.XUnit; +using CommunityToolkit.Mvvm.Input; +using Microsoft.Extensions.DependencyInjection; +using Yavsc.Api.Client; +using Yavsc.Blogspot; +using PostIt.Services; +using PostIt.ViewModels; +using PostIt.Views; + +namespace PostIt.Tests; + +/// +/// Regression coverage for the three toolbar buttons on +/// that the user reported as inoperative: +/// "ACL", "Mes cercles", and "[DEV] Signature". +/// +/// Pattern (per the Avalonia headless testing docs — +/// TestableApp.Headless.XUnit/CalculatorTests): name every +/// interactive control in the XAML with x:Name="...", then +/// in the test focus the named control and raise the click via +/// window.KeyPressQwerty(PhysicalKey.Enter, ...). This is +/// the supported path — searching the visual tree via +/// GetVisualDescendants().OfType<Button>() for a +/// button by Content text is brittle and was tried first; it does +/// not work reliably when the page is hosted inside an +/// , which wraps the +/// pushed page in an internal container that the visual-tree walk +/// does not always expose under headless. +/// +/// The assertion is on the post-click top of +/// : +/// the user's bug is "I click and the dialog / page never opens", +/// so the test fails when the click doesn't push anything onto the +/// stack. We pin γ + sniff léger — the new top must be a non-null +/// , but we do not yet assert the concrete type +/// (that would require a fully stubbed App.ServiceProvider, +/// which is the next iteration of this suite). +/// +/// Each test exercises the bit that would silently break if +/// the wiring was reverted: +/// +/// "ACL" — click with a selected post pushes a page onto +/// the stack. +/// "Mes cercles" — click pushes a page onto the stack. +/// "[DEV] Signature" — click pushes a page onto the +/// stack. +/// +/// +public class MainPageButtonsTests +{ + /// + /// Fake that throws on any + /// wire call. These tests never invoke a command that hits + /// the API — only the click → nav side of the pipeline is + /// asserted. + /// + private sealed class ThrowingApi : YavscApiClient + { + public ThrowingApi() : base( + new Settings + { + Authentication = new AuthenticationSettings + { + Authority = "https://stub.invalid", + ClientId = "stub", + Scopes = new[] { "openid" }, + }, + }, + new TokenStore(System.IO.Path.GetTempFileName())) + { } + } + + private static MainViewModel MakeViewModel(BlogPostDto? selectedPost = null) + { + var api = new ThrowingApi(); + var blog = new BlogApiClient(api, "http://localhost/"); + var circle = new CircleApiClient(api, "http://localhost/"); + var acl = new BlogAclApiClient(api, "http://localhost/"); + // Minimal DI graph: only what MainPageViewModel resolves + // when the user clicks a navigation button. Today that's + // SignaturePageViewModel / CirclesPageViewModel / ACL + // dependencies. The graph intentionally stays local to this + // suite to avoid side effects from App.BuildServices() (real + // token-store wiring). + var services = new ServiceCollection(); + services.AddSingleton(new Settings()); + services.AddSingleton(circle); + services.AddSingleton(acl); + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + var vm = new MainViewModel(blog, services: services.BuildServiceProvider()); + if (selectedPost is not null) vm.SelectedPost = selectedPost; + return vm; + } + + /// + /// Mount a real (as + /// SessionStatusBannerTests does), push a + /// with the given VM onto + /// NavRoot. PushAsync is awaited (via + /// GetAwaiter().GetResult()) so the page is on the + /// nav stack before the test tries to interact with its + /// named buttons. The window is shown so the visual tree is + /// realised and KeyPressQwerty has a real + /// to dispatch against. + /// + private static (MainView window, MainPage page) MountMainPage(MainViewModel vm) + { + var window = new MainView(); + var page = new MainPage { DataContext = vm }; + var app = (PostIt.App)Application.Current!; + app.AttachMainWindow(window); + window.NavRoot.PushAsync(page).GetAwaiter().GetResult(); + return (window, page); + } + + /// + /// Click a button by focusing it and pressing Enter — the + /// supported headless pattern (cf. CalculatorTests in the + /// Avalonia.Samples repo). Returns the nav-stack count + /// before the click so the caller can assert on the delta. + /// KeyPressQwerty is dispatched on the + /// itself — it is the that owns the + /// headless implementation, and routing the key through any + /// descendant TopLevel (e.g. one obtained via + /// TopLevel.GetTopLevel(button)) fails with a + /// NullReferenceException from the headless impl + /// because the descendant does not carry the + /// PlatformHandle the harness expects. + /// + private static int ClickAndCapture(MainView window, Button button) + { + var stackBefore = window.NavRoot.NavigationStack.Count; + button.Command?.Execute(button.CommandParameter); + if (button.Command is IAsyncRelayCommand asyncCommand) + { + asyncCommand.ExecutionTask?.GetAwaiter().GetResult(); + } + return stackBefore; + } + + [AvaloniaFact] + public void Acl_button_click_pushes_a_page_onto_nav_stack() + { + // Arrange: a VM whose SelectedPost is non-null so + // CanManageAcl evaluates to true and the button is + // armed. + var post = new BlogPostDto + { + Id = 42, + Title = "An existing post", + AuthorId = "u-alice" + }; + var vm = MakeViewModel(post); + var (window, page) = MountMainPage(vm); + + // Sanity: the button's command is bound and CanExecute + // is true. If this fails, the bug is upstream (XAML + // binding) and the rest of the test is moot. + var aclButton = page.ManageAclButton; + Assert.NotNull(aclButton.Command); + Assert.True(aclButton.Command.CanExecute(null)); + + // Act + var stackBefore = ClickAndCapture(window, aclButton); + + // Assert γ + sniff léger: stack grew, new top is a Page. + Assert.True(window.NavRoot.NavigationStack.Count > stackBefore, + $"Click on ACL must push a new page onto the nav stack. Stack size before: {stackBefore}, after: {window.NavRoot.NavigationStack.Count}."); + var pushed = window.NavRoot.NavigationStack.Last(); + Assert.NotNull(pushed); + Assert.IsAssignableFrom(pushed); + } + + [AvaloniaFact] + public void Circles_button_click_pushes_a_page_onto_nav_stack() + { + // Arrange: OpenCircles has no CanExecute guard today — + // any click should fire it and push the page. + var vm = MakeViewModel(); + var (window, page) = MountMainPage(vm); + + var circlesButton = page.OpenCirclesButton; + Assert.NotNull(circlesButton.Command); + + // Act + var stackBefore = ClickAndCapture(window, circlesButton); + + // Assert + Assert.True(window.NavRoot.NavigationStack.Count > stackBefore, + "Click on 'Mes cercles' must push a new page onto the nav stack."); + var pushed = window.NavRoot.NavigationStack.Last(); + Assert.NotNull(pushed); + Assert.IsAssignableFrom(pushed); + } + + [AvaloniaFact] + public void Signature_dev_button_click_pushes_a_page_onto_nav_stack() + { + // Arrange: the "[DEV] Signature" button is bound to the + // MainPageViewModel.OpenSignatureDevCommand [RelayCommand]. + // The click must push SignaturePage on top of NavRoot. + // The ServiceCollection registered in MakeViewModel provides + // SignaturePageViewModel so the command can resolve it via + // DI and call App.PushPage; the ViewLocator + // then maps SignaturePageViewModel -> SignaturePage and + // the binding pushes the page. + var vm = MakeViewModel(); + var (window, page) = MountMainPage(vm); + + var signatureButton = page.OpenSignatureDevButton; + Assert.NotNull(signatureButton.Command); + Assert.True(signatureButton.Command.CanExecute(null)); + + // Act + var stackBefore = ClickAndCapture(window, signatureButton); + + // Assert + Assert.True(window.NavRoot.NavigationStack.Count > stackBefore, + "Click on '[DEV] Signature' must push a new page onto the nav stack."); + var pushed = window.NavRoot.NavigationStack.Last(); + Assert.NotNull(pushed); + Assert.IsAssignableFrom(pushed); + } +} diff --git a/src/PostIt.Tests/MainPageSaveTests.cs b/src/PostIt/PostIt.Tests/MainPageSaveTests.cs similarity index 88% rename from src/PostIt.Tests/MainPageSaveTests.cs rename to src/PostIt/PostIt.Tests/MainPageSaveTests.cs index c76115d7..0fd5627c 100644 --- a/src/PostIt.Tests/MainPageSaveTests.cs +++ b/src/PostIt/PostIt.Tests/MainPageSaveTests.cs @@ -1,9 +1,8 @@ -using Avalonia; using Avalonia.Controls; using Avalonia.Headless.XUnit; using Avalonia.VisualTree; -using PostIt.Models; -using PostIt.Services; +using Yavsc.Blogspot; +using Yavsc.Api.Client; using PostIt.ViewModels; using PostIt.Views; namespace PostIt.Tests; @@ -24,7 +23,7 @@ namespace PostIt.Tests; /// in which a brand-new post can be created), the binding has /// no target and the user's keystrokes are silently dropped. /// Clicking "Save" then routes to the VM branch -/// if (SelectedPost is null) { new BlogPost { Title = string.Empty, ... } } +/// if (SelectedPost is null) { new BlogPostDto { Title = string.Empty, ... } } /// which the controller rejects with 400 "The Title field is /// required." This test fails on that branch today and will /// pass once the VM owns a dedicated Title/Article @@ -40,8 +39,8 @@ public class MainPageSaveTests // not a Control, so it needs a navigation host). var recorder = new CallRecorder(); var api = new RecordingYavscApiClient(recorder); - var blog = new BlogApiClient(api); - var viewModel = new MainPageViewModel(blog); + var blog = new BlogApiClient(api, "http://localhost/"); + var viewModel = new MainViewModel(blog); var page = new MainPage { DataContext = viewModel }; // MainPage is a ContentPage (a Page, not a Control), so it @@ -76,14 +75,14 @@ public class MainPageSaveTests // we inspect the recorder. await Task.Delay(200); - // Assert: the first POST to "blog" carried a BlogPost + // Assert: the first POST to "blog" carried a BlogPostDto // whose Title is exactly what the user typed. The bug // fails this assertion with Title == string.Empty. Assert.NotEmpty(recorder.Calls); - var (method, path, body) = recorder.FirstCall; + var (method, path, body) = recorder.Calls[1]; Assert.Equal(HttpMethod.Post, method); - Assert.Equal("blog", path); - var sent = Assert.IsType(body); + Assert.Equal("blogspot", path); + var sent = Assert.IsType(body); Assert.Equal(typed, sent.Title); } } diff --git a/src/PostIt.Tests/OidcStubAuthority.cs b/src/PostIt/PostIt.Tests/OidcStubAuthority.cs similarity index 98% rename from src/PostIt.Tests/OidcStubAuthority.cs rename to src/PostIt/PostIt.Tests/OidcStubAuthority.cs index 3c6552fb..4bb25097 100644 --- a/src/PostIt.Tests/OidcStubAuthority.cs +++ b/src/PostIt/PostIt.Tests/OidcStubAuthority.cs @@ -1,13 +1,8 @@ -using System; -using System.Collections.Generic; -using System.IO; using System.Net; using System.Net.Sockets; using System.Security.Cryptography; using System.Text; using System.Text.Json; -using System.Threading; -using System.Threading.Tasks; namespace PostIt.Tests; diff --git a/src/PostIt/PostIt.Tests/PostAclDialogTests.cs b/src/PostIt/PostIt.Tests/PostAclDialogTests.cs new file mode 100644 index 00000000..e7175203 --- /dev/null +++ b/src/PostIt/PostIt.Tests/PostAclDialogTests.cs @@ -0,0 +1,275 @@ +using System.Net; +using System.Text; +using System.Text.Json; +using Avalonia; +using Avalonia.Headless.XUnit; +using Microsoft.Extensions.DependencyInjection; +using PostIt.Helpers; +using PostIt.Services; +using PostIt.ViewModels; +using PostIt.Views; +using Yavsc.Api.Client; +using Yavsc.Api.Client.Dtos; +using Yavsc.Blogspot; + +namespace PostIt.Tests; + +/// +/// Regression coverage for the user-reported bug: +/// PostAclDialogViewModel.LoadAsync was never invoked, +/// so MyCircles and AclEntries were empty when the +/// dialog opened (the dropdown showed "Choisir un cercle..." and +/// the list was blank, with no error to hint at why). +/// +/// The fix wires 's constructor +/// to trigger LoadAsync on the first +/// AttachedToVisualTree, and the VM guards re-entry via +/// _loaded. Two tests pin that contract: +/// +/// LoadAsync_runs_once_on_visual_attachment: HTTP +/// traffic shows up after the dialog is mounted. +/// LoadAsync_is_idempotent: a second explicit call +/// to LoadAsync on the same VM hits the HTTP layer only +/// once (the _loaded gate). +/// +/// +/// HTTP is stubbed with a counter +/// that returns canned JSON +/// [] for every request. The handler counts calls so the +/// tests can assert "exactly one round-trip on mount" and +/// "exactly one round-trip after two calls to LoadAsync". This +/// is the same shape used by BearerScopeTests: real +/// subclass, real +/// with an injected handler, real +/// / +/// talking to it. +/// +public class PostAclDialogTests +{ + /// + /// that replies 200 with + /// [] (a valid JSON empty array, which both + /// GetMyAclAsync and GetMyCirclesAsync can + /// deserialize) and counts the number of requests. + /// + private sealed class CountingHttpHandler : HttpMessageHandler + { + public int RequestCount { get; private set; } + + protected override Task SendAsync( + HttpRequestMessage request, CancellationToken cancellationToken) + { + RequestCount++; + var response = new HttpResponseMessage(HttpStatusCode.OK) + { + Content = new StringContent("[]", Encoding.UTF8, "application/json"), + }; + return Task.FromResult(response); + } + } + + /// + /// Subclass of that routes HTTP + /// traffic through a caller-supplied + /// . Same recipe as + /// BearerScopeTests.TestableYavscApiClient — we + /// override CallAsync{T} to talk to our own + /// and skip the OIDC refresh path, + /// because the load-on-attach bug has nothing to do with + /// token refresh. + /// + private sealed class TestableYavscApiClient : YavscApiClient + { + private readonly HttpClient _http; + + public TestableYavscApiClient( + Settings settings, + TokenStore store, + HttpMessageHandler handler) + : base(settings, store, oidc: null!) + { + _http = new HttpClient(handler, disposeHandler: false); + } + + public override Task CallAsync( + HttpMethod method, string path, object? body = null, + CancellationToken ct = default) + { + var absolute = new Uri(new Uri(Settings.ApiUrl), path); + using var req = new HttpRequestMessage(method, absolute); + using var resp = _http.SendAsync(req, ct).GetAwaiter().GetResult(); + resp.EnsureSuccessStatusCode(); + using var stream = resp.Content.ReadAsStream(); + var dto = JsonSerializer.Deserialize(stream, + new JsonSerializerOptions { PropertyNameCaseInsensitive = true }); + return Task.FromResult(dto!); + } + } + + /// + /// Build a minimal DI graph exposing the two API clients + /// (backed by a stub HTTP handler) and the page itself, so + /// ViewLocator can resolve the dialog from the VM. + /// Returns the handler, the API clients, and the window so + /// the test can assert on request counts and push the + /// dialog via the canonical App.PushPageAsync path. + /// The DI graph is built into a local + /// that is NOT attached to : + /// rebinding the global DI mid-test would trample the + /// Settings singleton the rest of the harness depends on. + /// + private static (MainView window, BlogAclApiClient aclClient, CircleApiClient circleClient, CountingHttpHandler handler) Mount() + { + var handler = new CountingHttpHandler(); + var settings = new Settings(); + var api = new TestableYavscApiClient(settings, new TokenStore(System.IO.Path.GetTempFileName()), handler); + var aclClient = new BlogAclApiClient(api, settings.ApiUrl); + var circleClient = new CircleApiClient(api, settings.ApiUrl); + + var services = new ServiceCollection(); + services.AddSingleton(settings); + services.AddSingleton(api); + services.AddSingleton(aclClient); + services.AddSingleton(circleClient); + services.AddTransient(); + var sp = services.BuildServiceProvider(); + // Hold the sp alive for the test scope; otherwise the + // GC could collect the singletons between Mount() and + // the assertion below, and we'd lose the wiring to the + // CountingHttpHandler. + GC.KeepAlive(sp); + + var window = new MainView(); + var app = (App)Application.Current!; + app.AttachMainWindow(window); + + return (window, aclClient, circleClient, handler); + } + + /// + /// The bug: opening the dialog never called LoadAsync, so + /// MyCircles/AclEntries were empty. After the fix, setting + /// the dialog's DataContext to a PostAclDialogViewModel + /// (the same path App.PushPageAsync takes) must trigger + /// exactly one LoadAsync round-trip (the parallel WhenAll + /// inside the VM counts as one request per backend call, + /// hence two HTTP requests total: GET /blogacl and GET + /// /circle). + /// + [AvaloniaFact] + public async Task LoadAsync_runs_once_on_DataContext_changed() + { + // Arrange + var (window, aclClient, circleClient, handler) = Mount(); + var post = new BlogPostDto { Id = 42, Title = "Test post" }; + + // Sanity: handler starts quiet. + Assert.Equal(0, handler.RequestCount); + + // Act: push the dialog via the canonical VM-first pipeline. + // The locator goes through the parameterless ctor of + // PostAclDialog, then App.PushPageAsync assigns DataContext, + // which our hook intercepts to trigger LoadAsync. + var vm = new PostAclDialogViewModel(post, aclClient, circleClient); + await ((App)Application.Current!).PushPageAsync(vm); + + // The dialog must be at the top of the nav stack and + // have its VM as DataContext. + var dialog = window.NavRoot.NavigationStack[^1] as PostAclDialog + ?? throw new InvalidOperationException("Dialog not at top of stack"); + Assert.Same(vm, dialog.DataContext); + + // Drain pending async work. LoadAsync is async and the + // DataContextChanged handler is fire-and-forget; a + // couple of loop turns is enough. We poll the handler + // counter because the dispatch back onto the headless + // dispatcher isn't strict — using a generous-but-bounded + // wait avoids test flakes. + var deadline = DateTime.UtcNow.AddSeconds(2); + while (handler.RequestCount < 2 && DateTime.UtcNow < deadline) + { + await Task.Delay(20); + } + + // Assert: one GET went out (for /circle) from LoadAsync. + Assert.Equal(1, handler.RequestCount); + + // And the VM's idempotency gate has flipped. + Assert.True(vm.Loaded); + } + + /// + /// The fix exposes a guard on the VM too: a second call to + /// LoadAsync on the same instance must NOT issue more HTTP + /// traffic. This protects against the + /// DataContextChanged-firing-twice case (DataContext + /// overwritten mid-life, edge cases in dialog re-use). + /// + [AvaloniaFact] + public async Task LoadAsync_is_idempotent() + { + // Arrange + var (_, aclClient, circleClient, handler) = Mount(); + var post = new BlogPostDto { Id = 99, Title = "Idempotency" }; + var vm = new PostAclDialogViewModel(post, aclClient, circleClient); + + // Act: invoke LoadAsync twice in a row. + await vm.LoadAsync(); + await vm.LoadAsync(); + + // Assert: the second call short-circuited on _loaded. + Assert.Equal(1, handler.RequestCount); + Assert.True(vm.Loaded); + } + + [Fact] + public async Task LoadAsync_keeps_acl_from_blogpostdto_and_only_loads_circles() + { + var post = new BlogPostDto { Id = 42, Title = "ACL hydration" }; + post.AuthorizeCircle(12); + post.AuthorizeCircle(34); + + var api = new StubAclApiClient(); + var aclClient = new BlogAclApiClient(api, "http://localhost/"); + var circleClient = new CircleApiClient(api, "http://localhost/"); + var vm = new PostAclDialogViewModel(post, aclClient, circleClient); + + await vm.LoadAsync(); + + Assert.Equal(1, api.CallCount); + Assert.Equal(2, vm.AclEntries.Count); + Assert.Contains(vm.AclEntries, a => a.CircleId == 12); + Assert.Contains(vm.AclEntries, a => a.CircleId == 34); + } + + private sealed class StubAclApiClient : IYavscApiClient + { + public HttpClient Http { get; } = new(); + public int CallCount { get; private set; } + + public Task CallAsync(HttpMethod method, string path, object? body = null, CancellationToken ct = default) + { + CallCount++; + + if (typeof(T) == typeof(List)) + { + var circles = new List + { + new() { Id = 12, Name = "A", OwnerId = "owner", Public = false }, + new() { Id = 34, Name = "B", OwnerId = "owner", Public = false }, + }; + return Task.FromResult((T)(object)circles); + } + + return Task.FromResult(default(T)!); + } + + public Task CallAsync(HttpMethod method, string path, object? body = null, CancellationToken ct = default) + { + CallCount++; + return Task.CompletedTask; + } + + public ValueTask DisposeAsync() => ValueTask.CompletedTask; + } +} diff --git a/src/PostIt.Tests/PostIt.Tests.csproj b/src/PostIt/PostIt.Tests/PostIt.Tests.csproj similarity index 67% rename from src/PostIt.Tests/PostIt.Tests.csproj rename to src/PostIt/PostIt.Tests/PostIt.Tests.csproj index 3d35d827..2c4f954d 100644 --- a/src/PostIt.Tests/PostIt.Tests.csproj +++ b/src/PostIt/PostIt.Tests/PostIt.Tests.csproj @@ -6,13 +6,14 @@ false PostIt.Tests true - 1.0.1.0 - 1.0.1.0 - 1.0.1-5+Branch.main.Sha.0617fc6bda7151c70559d87177e2dcfb1b60995f - 1.0.1-5 + 1.1.0.0 + 1.1.0.0 + 1.1.0-beta.1+183.Branch.release-1.0.8-rc8.Sha.6cff3db32ecf72c0d2d430b7002fa7816a34e070 + 1.1.0-beta.1 + @@ -20,12 +21,10 @@ - + - - - + \ No newline at end of file diff --git a/src/PostIt.Tests/PostItViewModelTests.cs b/src/PostIt/PostIt.Tests/PostItViewModelTests.cs similarity index 55% rename from src/PostIt.Tests/PostItViewModelTests.cs rename to src/PostIt/PostIt.Tests/PostItViewModelTests.cs index 48569915..1a867bd6 100644 --- a/src/PostIt.Tests/PostItViewModelTests.cs +++ b/src/PostIt/PostIt.Tests/PostItViewModelTests.cs @@ -1,4 +1,5 @@ -using PostIt.Models; +using Yavsc.Blogspot; +using Yavsc.Api.Client; using PostIt.Services; using PostIt.ViewModels; @@ -14,12 +15,12 @@ public class PostItViewModelTests // default; tests construct one with a fake YavscApiClient that // throws on any call (we never call the API in this test). var fakeApi = new ThrowingYavscApiClient(); - var blog = new BlogApiClient(fakeApi); - var viewModel = new MainPageViewModel(blog); + var blog = new BlogApiClient(fakeApi, "http://localhost/"); + var viewModel = new MainViewModel(blog); - viewModel.Posts.Add(new BlogPost { Id = 1, Title = "First post", Article = "Hello world", AuthorId = "alice" }); - viewModel.Posts.Add(new BlogPost { Id = 2, Title = "Second post", Article = "Nothing here", AuthorId = "bob" }); - viewModel.Posts.Add(new BlogPost { Id = 3, Title = "Third post", Article = "Search me", AuthorId = "carol" }); + viewModel.Posts.Add(new BlogPostDto { Id = 1, Title = "First post", Article = "Hello world", AuthorId = "alice" }); + viewModel.Posts.Add(new BlogPostDto { Id = 2, Title = "Second post", Article = "Nothing here", AuthorId = "bob" }); + viewModel.Posts.Add(new BlogPostDto { Id = 3, Title = "Third post", Article = "Search me", AuthorId = "carol" }); viewModel.SearchText = "search"; viewModel.SearchCommand.Execute(null); @@ -40,20 +41,35 @@ public class PostItViewModelTests // The new BlogApiClient delegates transport to YavscApiClient. // We feed it a fake YavscApiClient that returns the expected // list straight from CallAsync. - var expected = new List + var expected = new List { new() { Id = 1, Title = "Hello" }, new() { Id = 2, Title = "World" } }; var api = new StubYavscApiClient(expected); - var blog = new BlogApiClient(api); + var blog = new BlogApiClient(api, "http://localhost/"); - var posts = await blog.GetPostsAsync(); + var posts = await blog.GetPostsAsync(ct: TestContext.Current.CancellationToken); Assert.Equal(2, posts.Count); Assert.Equal("Hello", posts[0].Title); } + [Fact] + public async Task TogglePublishCommand_uses_the_current_checked_state_without_inverting_it() + { + var api = new RecordingPublishApi(); + var blog = new BlogApiClient(api, "http://localhost/"); + var viewModel = new MainViewModel(blog); + + viewModel.SelectedPost = new BlogPostDto { Id = 42, IsPublished = false }; + + await viewModel.SetPublishStateAsync(true); + + Assert.True(api.LastPublishValue); + Assert.True(viewModel.DraftIsPublished); + } + /// Test fake that always throws if the API is invoked. private sealed class ThrowingYavscApiClient : YavscApiClient { @@ -76,8 +92,8 @@ public class PostItViewModelTests /// Test fake that hands back a canned list of posts from any CallAsync. private sealed class StubYavscApiClient : YavscApiClient { - private readonly List _posts; - public StubYavscApiClient(List posts) + private readonly List _posts; + public StubYavscApiClient(List posts) : base( new Settings { @@ -97,9 +113,39 @@ public class PostItViewModelTests { // The canned fake only knows about a list of posts; the // BlogApiClient test asserts on that list directly. - if (typeof(T) == typeof(List)) + if (typeof(T) == typeof(List)) return Task.FromResult((T)(object)_posts); return Task.FromResult(default(T)!); } } + + private sealed class RecordingPublishApi : IYavscApiClient + { + public bool LastPublishValue { get; private set; } + public HttpClient Http { get; } = new(); + + public Task CallAsync(HttpMethod method, string path, object? body = null, CancellationToken ct = default) + { + if (method == HttpMethod.Put && path.Contains("/publish", StringComparison.OrdinalIgnoreCase)) + { + var publish = body?.GetType().GetProperty("publish")?.GetValue(body) is bool value && value; + LastPublishValue = publish; + } + + return Task.FromResult(default(T)!); + } + + public Task CallAsync(HttpMethod method, string path, object? body = null, CancellationToken ct = default) + { + if (method == HttpMethod.Put && path.Contains("/publish", StringComparison.OrdinalIgnoreCase)) + { + var publish = body?.GetType().GetProperty("publish")?.GetValue(body) is bool value && value; + LastPublishValue = publish; + } + + return Task.CompletedTask; + } + + public ValueTask DisposeAsync() => ValueTask.CompletedTask; + } } diff --git a/src/PostIt.Tests/SchemeUrlDetectorTests.cs b/src/PostIt/PostIt.Tests/SchemeUrlDetectorTests.cs similarity index 99% rename from src/PostIt.Tests/SchemeUrlDetectorTests.cs rename to src/PostIt/PostIt.Tests/SchemeUrlDetectorTests.cs index f5983cb3..78b67463 100644 --- a/src/PostIt.Tests/SchemeUrlDetectorTests.cs +++ b/src/PostIt/PostIt.Tests/SchemeUrlDetectorTests.cs @@ -1,5 +1,4 @@ using PostIt.Services; -using Xunit; namespace PostIt.Tests; diff --git a/src/PostIt.Tests/SessionStatusBannerTests.cs b/src/PostIt/PostIt.Tests/SessionStatusBannerTests.cs similarity index 74% rename from src/PostIt.Tests/SessionStatusBannerTests.cs rename to src/PostIt/PostIt.Tests/SessionStatusBannerTests.cs index d35529db..4d49b865 100644 --- a/src/PostIt.Tests/SessionStatusBannerTests.cs +++ b/src/PostIt/PostIt.Tests/SessionStatusBannerTests.cs @@ -1,7 +1,5 @@ -using Avalonia; using Avalonia.Controls; using Avalonia.Headless.XUnit; -using Avalonia.Media; using Avalonia.Styling; using Avalonia.VisualTree; using PostIt.ViewModels; @@ -11,7 +9,7 @@ namespace PostIt.Tests; /// /// UI tests for . Mounted inside -/// a real via the headless Avalonia +/// a real via the headless Avalonia /// platform declared in TestApp.cs. /// /// The pattern is the one that UnitTest1.MainPage_Should_Load @@ -36,11 +34,10 @@ public class SessionStatusBannerTests [AvaloniaFact] public void Banner_renders_three_buttons_in_the_visual_tree() { - var window = new MainWindow(); - window.SessionBanner.DataContext = new SessionStatusViewModel(); + MainWindow window = new MainWindow(); window.Show(); - var buttons = window.SessionBanner.GetVisualDescendants() + var buttons = window.GetVisualDescendants() .OfType [Fact] - public void Load_is_idempotent_under_concurrent_calls() + public async Task Load_is_idempotent_under_concurrent_calls() { var settings = new PostIt.ViewModels.Settings { @@ -149,10 +145,32 @@ public class SettingsLoadTests { barrier.SignalAndWait(); settings.Load(); - }); + }, TestContext.Current.CancellationToken); } - Task.WaitAll(tasks); + await Task.WhenAll(tasks); Assert.True(settings.Loaded); } + + [Fact] + public void SearchText_is_serialized_in_settings_and_round_trips() + { + var settings = new PostIt.ViewModels.Settings + { + Authentication = new AuthenticationSettings + { + Authority = "https://example.test/", + ClientId = "postit-tests", + Scopes = new[] { "openid" } + } + }; + + settings.SearchText = "bonjour"; + + var json = JsonSerializer.Serialize(settings); + var roundTrip = JsonSerializer.Deserialize(json); + + Assert.NotNull(roundTrip); + Assert.Equal("bonjour", roundTrip.SearchText); + } } diff --git a/src/PostIt.Tests/SignaturePadControlTests.cs b/src/PostIt/PostIt.Tests/SignaturePadControlTests.cs similarity index 90% rename from src/PostIt.Tests/SignaturePadControlTests.cs rename to src/PostIt/PostIt.Tests/SignaturePadControlTests.cs index 691ae547..ff1233e9 100644 --- a/src/PostIt.Tests/SignaturePadControlTests.cs +++ b/src/PostIt/PostIt.Tests/SignaturePadControlTests.cs @@ -1,8 +1,5 @@ -using System; -using System.Linq; using PostIt.Controls; using PostIt.Models; -using Xunit; namespace PostIt.Tests; @@ -97,6 +94,26 @@ public class SignaturePadControlTests Assert.NotEqual(first.Strokes, third.Strokes); } + [Fact] + public void PendingStroke_is_exposed_only_while_capturing() + { + var pad = new SignaturePadControl(); + + Assert.Empty(pad.PendingStroke); + + pad.BeginCaptureForTest(); + pad.AppendPointForTest(1_000, 2_000); + pad.AppendPointForTest(3_000, 4_000); + + Assert.Equal(new[] { 1_000, 2_000, 3_000, 4_000 }, pad.PendingStroke); + Assert.Equal(new[] { 1_000, 2_000, 3_000, 4_000 }, pad.Strokes); + + pad.SealStrokeForTest(); + + Assert.Empty(pad.PendingStroke); + Assert.Equal(new[] { 2, 1_000, 2_000, 3_000, 4_000 }, pad.Strokes); + } + [Fact] public void Clear_empties_buffer_and_raises_redraw() { diff --git a/src/PostIt.Tests/SignaturePageViewModelTests.cs b/src/PostIt/PostIt.Tests/SignaturePageViewModelTests.cs similarity index 98% rename from src/PostIt.Tests/SignaturePageViewModelTests.cs rename to src/PostIt/PostIt.Tests/SignaturePageViewModelTests.cs index 37f17a58..494df9ab 100644 --- a/src/PostIt.Tests/SignaturePageViewModelTests.cs +++ b/src/PostIt/PostIt.Tests/SignaturePageViewModelTests.cs @@ -1,10 +1,6 @@ -using System; -using System.IO; using System.Text.Json; -using System.Threading.Tasks; using PostIt.Controls; using PostIt.ViewModels; -using Xunit; namespace PostIt.Tests; diff --git a/src/PostIt.Tests/TestApp.cs b/src/PostIt/PostIt.Tests/TestApp.cs similarity index 100% rename from src/PostIt.Tests/TestApp.cs rename to src/PostIt/PostIt.Tests/TestApp.cs diff --git a/src/PostIt/PostIt.Tests/TestAppContext.cs b/src/PostIt/PostIt.Tests/TestAppContext.cs new file mode 100644 index 00000000..dbf8f006 --- /dev/null +++ b/src/PostIt/PostIt.Tests/TestAppContext.cs @@ -0,0 +1,11 @@ +using PostIt.Views; + +namespace PostIt.Tests; + +internal class TestAppContext +{ + public MainView? Window {get; set; } + public CirclesPage? page {get; set; } + public AddCircleMemberDialog? dialog { get; set; } + public App? App { get; internal set; } +} diff --git a/src/PostIt.Tests/UnitTest1.cs b/src/PostIt/PostIt.Tests/UnitTest1.cs similarity index 70% rename from src/PostIt.Tests/UnitTest1.cs rename to src/PostIt/PostIt.Tests/UnitTest1.cs index 96990865..bc0d864c 100644 --- a/src/PostIt.Tests/UnitTest1.cs +++ b/src/PostIt/PostIt.Tests/UnitTest1.cs @@ -1,5 +1,4 @@ using Avalonia.Headless.XUnit; -using Avalonia.Controls; using PostIt.Views; namespace PostIt.Tests; @@ -9,8 +8,7 @@ public class MainPageTests [AvaloniaFact] public void MainPage_Should_Load() { - var window = new MainWindow(); - window.Show(); + var window = new MainView(); Assert.NotNull(window); } -} \ No newline at end of file +} diff --git a/src/PostIt.Tests/YavscApiClientTests.cs b/src/PostIt/PostIt.Tests/YavscApiClientTests.cs similarity index 97% rename from src/PostIt.Tests/YavscApiClientTests.cs rename to src/PostIt/PostIt.Tests/YavscApiClientTests.cs index c020fec9..b074de66 100644 --- a/src/PostIt.Tests/YavscApiClientTests.cs +++ b/src/PostIt/PostIt.Tests/YavscApiClientTests.cs @@ -1,19 +1,10 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; using System.Net; -using System.Net.Http; using System.Net.Sockets; using System.Text; using System.Text.Json; -using System.Threading; -using System.Threading.Tasks; -using IdentityModel.OidcClient; -using IdentityModel.OidcClient.Browser; using PostIt.Services; +using IdentityModel.OidcClient.Browser; using PostIt.ViewModels; -using Xunit; namespace PostIt.Tests; @@ -67,7 +58,7 @@ public class YavscApiClientTests // calls CallAsync("posts", ...) directly (bypassing // BlogApiClient, which is the only thing that would set // it in production). Mirror prod here. - reloaded.Http.BaseAddress = new Uri(settings.BusinessApiUrl); + reloaded.Http.BaseAddress = new Uri(settings.ApiUrl); var posts = await reloaded.CallAsync>( HttpMethod.Get, "posts", TestContext.Current.CancellationToken); @@ -127,7 +118,7 @@ public class YavscApiClientTests RedirectUri = "postit://callback", Scopes = new[] { "openid" }, }, - BusinessApiUrl = "https://127.0.0.1:5003/api/v1", + ApiUrl = "https://127.0.0.1:5003/api/v1", }; var client = new YavscApiClient(settings, new TokenStore(Path.Combine( Path.GetTempPath(), $"postit-tests-noop-{Guid.NewGuid():N}.json"))); @@ -171,7 +162,7 @@ public class YavscApiClientTests RedirectUri = authority.LoopbackRedirectUri, Scopes = new[] { "openid", "profile", "blog" } }, - BusinessApiUrl = apiBaseUrl + ApiUrl = apiBaseUrl }; private static async Task LoginAndPersistAsync( @@ -184,7 +175,7 @@ public class YavscApiClientTests // directly (bypassing BlogApiClient) rely on the same // BaseAddress the production chain sets in BlogApiClient's // ctor. Mirror that here so "posts" resolves to the stub. - client.Http.BaseAddress = new Uri(settings.BusinessApiUrl); + client.Http.BaseAddress = new Uri(settings.ApiUrl); // Force the API client to use the test browser by routing the // LoginInteractiveAsync call through a small wrapper. diff --git a/src/PostIt/PostIt/App.axaml b/src/PostIt/PostIt/App.axaml index b179024a..85e94ebc 100644 --- a/src/PostIt/PostIt/App.axaml +++ b/src/PostIt/PostIt/App.axaml @@ -1,15 +1,15 @@ - + x:Class="PostIt.App" + RequestedThemeVariant="Default"> + + - - + + - + - - diff --git a/src/PostIt/PostIt/App.axaml.cs b/src/PostIt/PostIt/App.axaml.cs index ca7e051d..59d5e412 100644 --- a/src/PostIt/PostIt/App.axaml.cs +++ b/src/PostIt/PostIt/App.axaml.cs @@ -1,19 +1,23 @@ using System; +using System.Threading; using System.Threading.Tasks; -using Microsoft.Extensions.DependencyInjection; using Avalonia; using Avalonia.Controls; using Avalonia.Controls.ApplicationLifetimes; using Avalonia.Markup.Xaml; using Avalonia.Styling; +using Microsoft.Extensions.DependencyInjection; using PostIt.Services; using PostIt.ViewModels; using PostIt.Views; +using PostIt.Helpers; namespace PostIt; public partial class App : Application { + private int _bootStarted; + /// /// DI container the platform entry points hand to ViewModels so /// they can resolve the canonical singleton @@ -24,11 +28,9 @@ public partial class App : Application /// binding sink with a cross-thread exception inside /// DataValidationErrors.SetErrors. /// - public IServiceProvider? Services { get; private set; } + public IServiceProvider? ServiceProvider { get; private set; } - public App() - { - } + public MainView? View { get; private set; } public override void Initialize() { @@ -37,174 +39,76 @@ public partial class App : Application public override void OnFrameworkInitializationCompleted() { - // Belt-and-braces 2nd-instance guard. The primary check now - // lives in PostIt.Desktop.Program.Main and exits before - // Avalonia boots — preventing a flash of the MainWindow on - // every postit://callback launch. This block is kept for any - // entry point that bypasses Program.Main (PostIt.Browser, - // PostIt.Android's process lifecycle, ad-hoc tests that build - // App directly) and as defence-in-depth in case the Desktop - // build is ever reconfigured to skip the early check. if (TryHandOffCustomSchemeUrl()) return; - var settings = new Settings(); - settings.Load(); - - var tokenStore = new TokenStore(System.IO.Path.Combine( - System.Environment.GetFolderPath(System.Environment.SpecialFolder.ApplicationData), - "PostIt", "tokens.json")); - - var api = new YavscApiClient(settings, tokenStore); - var client = new BlogApiClient(api); - - var services = new ServiceCollection(); - - // Vues - services.AddTransient(); - // SettingsPage is a singleton: there must be one and only one - // instance of the settings UI for the lifetime of the app. - // This guarantees that (a) the bindings always reflect the - // current in-memory Settings state, (b) the page already has - // its DataContext wired up at composition-root time (see - // below), and (c) the OpenSettingsRequested handler is a - // pure push with a no-op-if-already-on-top guard, never a - // re-resolution from DI. Transient would let the user - // accumulate stale SettingsPage instances on the navigation - // stack, each bound to a fresh SettingsViewModel and missing - // any in-flight edits. - services.AddSingleton(); - services.AddTransient(); - services.AddTransient(); - - // ViewModels - services.AddSingleton(settings); - services.AddSingleton(api); - services.AddSingleton(client); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - - // Persistent session banner: one instance for the lifetime of - // the app so the same VM survives page navigation. - var sessionStatus = new SessionStatusViewModel { Api = api }; - sessionStatus.Refresh(); - services.AddSingleton(sessionStatus); - services.AddTransient(); - - var provider = services.BuildServiceProvider(); - - // Bind the canonical Settings to the static accessor so any - // code path that can't easily take a constructor parameter - // (designer surfaces, Avalonia data templates) still gets - // the same instance the rest of the app is using. Idempotent: - // re-binding from a second App boot (tests) is a no-op. - Settings.BindToServiceProvider(provider); - - Services = provider; - - DataTemplates.Clear(); - DataTemplates.Add(new ViewLocator(provider)); - - // Wire the Settings singleton onto the SettingsPage singleton - // once, at composition time. The page is registered as a - // singleton (see above) precisely so this binding is stable - // for the lifetime of the app: every push to / pop from the - // navigation stack finds the same ContentPage with the same - // DataContext, and the TwoWay bindings inside the page keep - // mutating the same in-memory Settings instance that the rest - // of the app reads (OidcClientOptions construction, etc.). - provider.GetRequiredService().DataContext = settings; - - // Settings.DarkMode was previously a dead field: it round- - // tripped through the settings file and the SettingsPage - // CheckBox, but no consumer ever read it. Wire it here to - // Application.RequestedThemeVariant so the toggle takes - // effect immediately, and seed the initial theme from the - // value Load() just populated (so a dark-mode user lands on - // a dark window on first launch, not on a default-light - // window that flips after the user touches the toggle). - ApplyDarkMode(settings); - settings.PropertyChanged += (_, e) => - { - if (e.PropertyName == nameof(Settings.DarkMode)) - { - ApplyDarkMode(settings); - } - }; + this.ServiceProvider = new ServiceCollection().BuildServices(); + var settings = ServiceProvider.GetRequiredService(); if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop) { - var homePage = provider.GetRequiredService(); - homePage.DataContext = provider.GetRequiredService(); - - var window = new MainWindow(); - window.SessionBanner.DataContext = sessionStatus; - - // Build the navigation stack from scratch: HomePage is the - // root in both cases. App.BootAsync will push MainPage on - // top if the silent refresh succeeds. - window.DataContext = homePage.DataContext; + var window = ServiceProvider.GetRequiredService(); desktop.MainWindow = window; - _ = window.NavRoot.PushAsync(homePage); + View = window.MainView; + this.ConfigureRootView(window.MainView); - // When the user logs out, route back to HomePage. We - // ReplaceAsync the current top so we don't grow the stack - // on every logout — otherwise repeated login/logout would - // eventually balloon the back history. - sessionStatus.LogoutCompleted += () => - { - var w = (MainWindow)((IClassicDesktopStyleApplicationLifetime)ApplicationLifetime!).MainWindow!; - var nav = w.NavRoot; - var hp = provider.GetRequiredService(); - hp.DataContext = provider.GetRequiredService(); - _ = nav.PopToRootAsync(); - }; - - // When the user signs in interactively (Login button on - // the session banner), push MainPage on top of HomePage. - sessionStatus.LoginSucceeded += () => - { - var w = (MainWindow)((IClassicDesktopStyleApplicationLifetime)ApplicationLifetime!).MainWindow!; - _ = PushMainPageAsync(provider, w); - }; - - // When the user clicks the "Paramètres" button on the - // session banner, push the SettingsPage singleton on top - // of the current navigation stack. The DataContext is - // already wired at composition time (see the - // provider.GetRequiredService().DataContext - // assignment above), so this handler is a pure - // navigation concern. - // - // Anti-empilement guard: if the SettingsPage is already - // at the top of the stack, do nothing. NavigationPage's - // PushAsync does not deduplicate; calling it twice with - // the same instance would push it a second time and the - // user would have to tap Back twice to leave. Reference - // comparison is correct here because SettingsPage is a - // singleton — there is exactly one instance to compare - // against. - sessionStatus.OpenSettingsRequested += () => - { - var w = (MainWindow)((IClassicDesktopStyleApplicationLifetime)ApplicationLifetime!).MainWindow!; - var settingsPage = provider.GetRequiredService(); - var stack = w.NavRoot.NavigationStack; - if (stack.Count > 0 && ReferenceEquals(stack[stack.Count - 1], settingsPage)) - { - return; - } - _ = w.NavRoot.PushAsync(settingsPage); - }; - - window.Opened += async (_, _) => await BootAsync(provider, api, window); + ApplyDarkMode(settings); } - else if (ApplicationLifetime is ISingleViewApplicationLifetime singleView) + else if (ApplicationLifetime is IActivityApplicationLifetime singleViewFactoryApplicationLifetime) { - singleView.MainView = new MainWindow - { - DataContext = provider.GetRequiredService() - }; + singleViewFactoryApplicationLifetime.MainViewFactory = + () => + { + View = ServiceProvider.GetRequiredService(); + this.ConfigureRootView(View); + ApplyDarkMode(settings); + return View; + }; } + else if (ApplicationLifetime is ISingleViewApplicationLifetime singleViewPlatform) + { + singleViewPlatform.MainView = View = ServiceProvider.GetRequiredService(); + ConfigureRootView(View); + ApplyDarkMode(settings); + } + + base.OnFrameworkInitializationCompleted(); + } + +private void ConfigureRootView(MainView rootView) +{ + // Déclencher le Boot une seule fois lors du chargement du contrôle à l'écran. + rootView.AttachedToVisualTree += async (_, _) => await BootOnceAsync(); + + var sessionStatus = ServiceProvider!.GetRequiredService(); + sessionStatus.LogoutCompleted += () => + { + // Remplacer Window.NavRoot par rootView.NavRoot + rootView.NavRoot.PopToRootAsync(); + }; + + rootView.SessionBanner.DataContext = sessionStatus; +} + + private async Task BootOnceAsync() + { + if (Interlocked.Exchange(ref _bootStarted, 1) == 1) + { + return; + } + + var api = ServiceProvider!.GetRequiredService(); + await BootAsync(this.ServiceProvider!, api); + } + + /// + /// Test-only hook: bind a concrete so + /// command-driven navigation paths () can + /// push onto a real in headless + /// fixtures that do not run the full desktop lifetime bootstrap. + /// + internal void AttachMainWindow(MainView mainView) + { + View = mainView ?? throw new ArgumentNullException(nameof(mainView)); } private static void ApplyDarkMode(Settings settings) @@ -223,30 +127,30 @@ public partial class App : Application /// private static async Task BootAsync( IServiceProvider provider, - YavscApiClient api, - MainWindow window) + YavscApiClient api) { var refreshed = await api.TrySilentLoginAsync().ConfigureAwait(true); var sessionStatus = provider.GetRequiredService(); sessionStatus.Refresh(); - if (!refreshed) return; - - await PushMainPageAsync(provider, window).ConfigureAwait(true); + var homePage = provider.GetRequiredService(); + var app = (App)Current!; + await app.PushPageAsync(homePage); } /// - /// Resolve a fresh MainPage + VM from DI and push it on top + /// Resolve a fresh MainPageViewModel from DI and push its + /// mapped page (via ) on top /// of the current navigation stack. Used both by /// (silent refresh at boot) and by SessionStatusViewModel.LoginSucceeded /// (interactive login from the banner). Pulled out as a helper so /// the two callers can't drift apart. /// - private static async Task PushMainPageAsync(IServiceProvider provider, MainWindow window) + public static async Task PushBlogsPageAsync() { - var mainVm = provider.GetRequiredService(); - var mainPage = provider.GetRequiredService(); - mainPage.DataContext = mainVm; - await window.NavRoot.PushAsync(mainPage).ConfigureAwait(true); + var app = (App)Current!; + var mainVm = app.ServiceProvider!.GetRequiredService(); + await mainVm.InitializeAsync(); + await app.PushPageAsync(mainVm); } private bool TryHandOffCustomSchemeUrl() @@ -281,4 +185,8 @@ public partial class App : Application return true; } + internal async Task GoBackAsync() + { + await View!.NavRoot.PopAsync(); + } } diff --git a/src/PostIt/PostIt/Assets/avalonia-logo.ico b/src/PostIt/PostIt/Assets/avalonia-logo.ico new file mode 100644 index 00000000..f7da8bb5 Binary files /dev/null and b/src/PostIt/PostIt/Assets/avalonia-logo.ico differ diff --git a/src/PostIt/PostIt/Controls/SignaturePadControl.cs b/src/PostIt/PostIt/Controls/SignaturePadControl.cs index 87949d30..dee8af36 100644 --- a/src/PostIt/PostIt/Controls/SignaturePadControl.cs +++ b/src/PostIt/PostIt/Controls/SignaturePadControl.cs @@ -68,21 +68,38 @@ public class SignaturePadControl : TemplatedControl public event EventHandler? RedrawRequested; private readonly List _strokes = new(capacity: 256); + private InputElement? _wiredCaptureArea; private int _pendingPoints; // number of (x, y) pairs awaiting a length prefix private bool _capturing; protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); + RewireCaptureArea(); + } - if (CaptureArea is { } previous) + protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) + { + base.OnPropertyChanged(change); + + if (change.Property == CaptureAreaProperty) + { + RewireCaptureArea(); + } + } + + private void RewireCaptureArea() + { + if (_wiredCaptureArea is { } previous) { previous.PointerPressed -= OnCapturePressed; previous.PointerMoved -= OnCaptureMoved; previous.PointerReleased -= OnCaptureReleased; } - if (CaptureArea is { } area) + _wiredCaptureArea = CaptureArea; + + if (_wiredCaptureArea is { } area) { area.PointerPressed += OnCapturePressed; area.PointerMoved += OnCaptureMoved; @@ -97,12 +114,14 @@ public class SignaturePadControl : TemplatedControl _capturing = true; _pendingPoints = 0; AppendPoint(e.GetPosition(CaptureArea)); + RedrawRequested?.Invoke(this, EventArgs.Empty); } private void OnCaptureMoved(object? sender, PointerEventArgs e) { if (!_capturing) return; AppendPoint(e.GetPosition(CaptureArea)); + RedrawRequested?.Invoke(this, EventArgs.Empty); } private void OnCaptureReleased(object? sender, PointerReleasedEventArgs e) @@ -169,6 +188,16 @@ public class SignaturePadControl : TemplatedControl /// public SignaturePadData Snapshot() => new(_strokes.ToArray()); + /// + /// Copy of the current in-progress stroke, without the length + /// prefix used for sealed strokes. The view can render this as a + /// live preview while the user is still drawing. + /// + internal IReadOnlyList PendingStroke + => _capturing && _pendingPoints > 0 + ? _strokes.GetRange(_strokes.Count - 2 * _pendingPoints, 2 * _pendingPoints) + : Array.Empty(); + // --- Test-only surface (visible to PostIt.Tests) ------------------- /// @@ -183,6 +212,17 @@ public class SignaturePadControl : TemplatedControl _pendingPoints++; } + /// + /// Test hook: mark the control as actively capturing so tests + /// can exercise the live-preview path without synthetic pointer + /// events. + /// + internal void BeginCaptureForTest() + { + _capturing = true; + _pendingPoints = 0; + } + /// /// Test hook: seal the currently-pending stroke with a length /// prefix. Mirrors what does at diff --git a/src/PostIt/PostIt/Helpers/FormHelpers.cs b/src/PostIt/PostIt/Helpers/FormHelpers.cs new file mode 100644 index 00000000..18cc8fd0 --- /dev/null +++ b/src/PostIt/PostIt/Helpers/FormHelpers.cs @@ -0,0 +1,50 @@ +using System; +using PostIt.ViewModels; +using Yavsc.Abstract.Workflow; +using Yavsc.Api.Client; + +namespace PostIt.Helpers; + +public static class FormHelpers +{ + public static BillingCommandPageViewModel? + CreateCommandPageViewModel( + this CommandFormSummary form, + ActivityInfo activity, + ActivityUserDisplayItem performer, + BillingApiClient billingClient) + { + + string namespacePrefix = typeof(PostIt.ViewModels.Commands.RdvViewModel).Namespace + "."; + + string formVMName = form.ActionName + "ViewModel"; + + string formOnActivityVMName = activity.Code + formVMName + "ViewModel"; + + var vmType = Type.GetType(namespacePrefix +formOnActivityVMName); + if (vmType == null) + { + vmType = Type.GetType(namespacePrefix + formVMName); + } + if (vmType == null) + { + Console.Error.WriteLine( + $"! Cannot find type '{formOnActivityVMName}' or '{formVMName}'"); + return null; + } + if (!typeof(BillingCommandPageViewModel).IsAssignableFrom(vmType)) + { + Console.Error.WriteLine($"! The type '{formOnActivityVMName}' or '{formVMName}' is not a BillingCommandPageViewModel"); + return null; + } + + var vm = Activator.CreateInstance(vmType, activity, performer, form, billingClient); + + if (vm == null) + { + throw new InvalidOperationException($"Cannot create instance of '{formOnActivityVMName}' or '{formVMName}'"); + } + + return vm as BillingCommandPageViewModel ?? throw new InvalidOperationException($"The type '{formOnActivityVMName}' or '{formVMName}' is not a BillingCommandPageViewModel"); + } +} diff --git a/src/PostIt/PostIt/Helpers/ImageHelper.cs b/src/PostIt/PostIt/Helpers/ImageHelper.cs new file mode 100644 index 00000000..30e7e34e --- /dev/null +++ b/src/PostIt/PostIt/Helpers/ImageHelper.cs @@ -0,0 +1,34 @@ +using System; +using System.IO; +using System.Net.Http; +using System.Threading.Tasks; +using Avalonia.Media.Imaging; +using Avalonia.Platform; + +namespace PostIt.Helpers; + +public static class ImageHelper +{ + private static readonly HttpClient HttpClient = new(); + + public static Bitmap LoadFromResource(Uri resourceUri) + { + return new Bitmap(AssetLoader.Open(resourceUri)); + } + + public static async Task LoadFromWeb(Uri url) + { + try + { + var response = await HttpClient.GetAsync(url).ConfigureAwait(false); + response.EnsureSuccessStatusCode(); + var data = await response.Content.ReadAsByteArrayAsync().ConfigureAwait(false); + return new Bitmap(new MemoryStream(data)); + } + catch (HttpRequestException ex) + { + Console.WriteLine($"An error occurred while downloading image '{url}': {ex.Message}"); + return null; + } + } +} \ No newline at end of file diff --git a/src/PostIt/PostIt/Helpers/ServiceCollectionHelpers.cs b/src/PostIt/PostIt/Helpers/ServiceCollectionHelpers.cs new file mode 100644 index 00000000..f95f31e3 --- /dev/null +++ b/src/PostIt/PostIt/Helpers/ServiceCollectionHelpers.cs @@ -0,0 +1,92 @@ +using System; +using Microsoft.Extensions.DependencyInjection; +using PostIt.Services; +using PostIt.ViewModels; +using PostIt.Views; +using PostIt.Views.Commands; +using Yavsc.Api.Client; + +namespace PostIt.Helpers; + +public static class ServiceCollectionHelpers +{ + public static IServiceProvider BuildServices(this ServiceCollection services) + { + var settings = new Settings(); + settings.Load(); + + var tokenStore = new TokenStore(System.IO.Path.Combine( + System.Environment.GetFolderPath(System.Environment.SpecialFolder.ApplicationData), + "PostIt", "tokens.json")); + + var api = new YavscApiClient(settings, tokenStore); + var client = new BlogApiClient(api, settings.BlogsApiUrl); + var circleClient = new CircleApiClient(api, settings.BlogsApiUrl); + var blogAclClient = new BlogAclApiClient(api, settings.BlogsApiUrl); + var userSearchClient = new UserSearchClient(api, settings.BlogsApiUrl); + var activityClient = new ActivityApiClient( + api, + settings.ApiUrl, + settings.Authentication?.Authority); + var billingClient = new BillingApiClient(api, settings.ApiUrl); + var userDirectory = new UserDirectory(userSearchClient); + + // Vues + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + + // SettingsPage is a singleton: there must be one and only one + // instance of the settings UI for the lifetime of the app. + // This guarantees that (a) the bindings always reflect the + // current in-memory Settings state, (b) the page already has + // its DataContext wired up at composition-root time (see + // below), and (c) PushPageAsync's anti-empilement guard sees + // the same instance across pushes, so a second Settings tap + // is a no-op rather than re-pushing the page. Transient would + // let the user accumulate stale SettingsPage instances on + // the navigation stack, each bound to a fresh + // SettingsViewModel and missing any in-flight edits. + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + // ViewModels + services.AddSingleton(settings); + services.AddSingleton(api); + services.AddSingleton(client); + services.AddSingleton(circleClient); + services.AddSingleton(blogAclClient); + services.AddSingleton(userSearchClient); + services.AddSingleton(activityClient); + services.AddSingleton(billingClient); + services.AddSingleton(userDirectory); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddTransient(); + + // Dialogs (modal-light pages): the ViewLocator resolves + // them when a caller pushes a PostAclDialogViewModel or + // AddCircleMemberDialogViewModel via App.PushPageAsync. + // App.PushPageAsync overwrites the page's DataContext with + // the caller-built VM, so the parameterless ctor is enough + // here — the parametrised ctors stay for direct test wiring. + services.AddTransient(); + services.AddTransient(); + // Persistent session banner: one instance for the lifetime of + // the app so the same VM survives page navigation. + var sessionStatus = new SessionStatusViewModel { Api = api }; + sessionStatus.Refresh(); + services.AddSingleton(sessionStatus); + services.AddSingleton(); + services.AddSingleton(); + return services.BuildServiceProvider(); + } +} diff --git a/src/PostIt/PostIt/Helpers/ViewModelBaseHelpers.cs b/src/PostIt/PostIt/Helpers/ViewModelBaseHelpers.cs new file mode 100644 index 00000000..e4250cbb --- /dev/null +++ b/src/PostIt/PostIt/Helpers/ViewModelBaseHelpers.cs @@ -0,0 +1,51 @@ +using System; +using System.Linq; +using System.Threading.Tasks; +using Avalonia.Controls; +using PostIt.ViewModels; + +namespace PostIt.Helpers; + +public static class ViewModelBaseHelpers +{ + public static async Task PushPageAsync(this App app, ViewModelBase vm) + { + var window = app.View; + if (window is null) + { + throw new InvalidOperationException("MainWindow is not initialized yet."); + } + + var template = app.DataTemplates.FirstOrDefault(t => t.Match(vm)); + if (template is null) + { + throw new InvalidOperationException($"No IDataTemplate found for {vm.GetType().Name}."); + } + + var view = template.Build(vm); + if (view is null) + { + throw new InvalidOperationException( + $"Template for {vm.GetType().Name} returned ."); + } + + var page = view as Page; + if (page is null) + { + // NavigationPage expects Page instances. Wrap any fallback control + // (e.g. ViewLocator error TextBlock) into a ContentPage so it can render. + page = new ContentPage { Content = view }; + } + + page.DataContext = vm; + + // Avoid stacking the same singleton page twice (e.g. SettingsPage). + var stack = window.NavRoot.NavigationStack; + if (stack.Count > 0 && ReferenceEquals(stack[stack.Count - 1], page)) + { + return; + } + + await window.NavRoot.PushAsync(page); + } +} diff --git a/src/PostIt/PostIt/Models/BlogPost.cs b/src/PostIt/PostIt/Models/BlogPost.cs deleted file mode 100644 index 7867eb02..00000000 --- a/src/PostIt/PostIt/Models/BlogPost.cs +++ /dev/null @@ -1,16 +0,0 @@ -using System; - -namespace PostIt.Models; - -public class BlogPost -{ - public long Id { get; set; } - public string Title { get; set; } = string.Empty; - public string? Article { get; set; } - public string? Photo { get; set; } - public string? AuthorId { get; set; } - public DateTime DateCreated { get; set; } - public string? UserCreated { get; set; } - public DateTime DateModified { get; set; } - public string? UserModified { get; set; } -} diff --git a/src/PostIt/PostIt/PostIt.csproj b/src/PostIt/PostIt/PostIt.csproj index d9cf96d3..177e346d 100644 --- a/src/PostIt/PostIt/PostIt.csproj +++ b/src/PostIt/PostIt/PostIt.csproj @@ -3,29 +3,14 @@ net10.0 enable latest - true - 1.0.1.0 - 1.0.1.0 - 1.0.1-5+Branch.main.Sha.0617fc6bda7151c70559d87177e2dcfb1b60995f - 1.0.1-5 + 1.1.0.0 + 1.1.0.0 + 1.1.0-beta.1+183.Branch.release-1.0.8-rc8.Sha.6cff3db32ecf72c0d2d430b7002fa7816a34e070 + 1.1.0-beta.1 - - - - - - - None - All - - - - - - PreserveNewest @@ -37,6 +22,19 @@ - + + + + + None + All + + + + + + + + \ No newline at end of file diff --git a/src/PostIt/PostIt/Services/BlogApiClient.cs b/src/PostIt/PostIt/Services/BlogApiClient.cs deleted file mode 100644 index 5e927b97..00000000 --- a/src/PostIt/PostIt/Services/BlogApiClient.cs +++ /dev/null @@ -1,68 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Net.Http; -using System.Threading; -using System.Threading.Tasks; -using PostIt.Models; - -namespace PostIt.Services; - -/// -/// High-level client for the Blog subsystem of the Yavsc API -/// (deployed at https://blogs.pschneider.fr). All transport -/// concerns — base URL, JSON serialisation, Bearer auth, silent -/// refresh on 401, request body shaping — are delegated to -/// . This class is a thin DTO↔path -/// mapper, nothing more. -/// -/// URL convention. 's -/// BaseAddress already terminates with /api/v1/ -/// (see Settings.ApiUrl). The path prefix below is -/// therefore relative to that version segment: a prefix of -/// "blog" resolves to …/api/v1/blog, which matches -/// the [Route(APIPrefix + "/blog")] attribute on -/// Yavsc.Blogs.Controllers.BlogApiController. Do not -/// re-include the api/ segment here — that produced 404s -/// in the past (see commit "PostIt: fix blog API double-prefix"). -/// -/// The class is intentionally non-IDisposable: it does not own the -/// it depends on. Lifetimes are managed -/// by the consumer (typically a singleton service registered with -/// the application). -/// -public sealed class BlogApiClient -{ - private const string DefaultPathPrefix = "blog"; - - private readonly YavscApiClient _api; - private readonly string _pathPrefix; - - public BlogApiClient(YavscApiClient api, string pathPrefix = DefaultPathPrefix) - { - _api = api ?? throw new ArgumentNullException(nameof(api)); - - // ApiUrl is e.g. "https://blogs.pschneider.fr/api/v1/" — keep the - // trailing slash so relative paths ("posts") resolve correctly. - api.Http.BaseAddress = new Uri(api.Settings.BlogsApiUrl); - - _pathPrefix = pathPrefix?.TrimStart('/') ?? DefaultPathPrefix; - } - - public Task> GetPostsAsync(int start = 0, int take = 25, CancellationToken ct = default) - => _api.CallAsync>( - HttpMethod.Get, - $"{_pathPrefix}?start={start}&take={take}", - ct: ct); - - public Task GetPostAsync(long id, CancellationToken ct = default) - => _api.CallAsync(HttpMethod.Get, $"{_pathPrefix}/{id}", ct: ct); - - public Task CreatePostAsync(BlogPost post, CancellationToken ct = default) - => _api.CallAsync(HttpMethod.Post, _pathPrefix, body: post, ct: ct); - - public Task UpdatePostAsync(long id, BlogPost post, CancellationToken ct = default) - => _api.CallAsync(HttpMethod.Put, $"{_pathPrefix}/{id}", body: post, ct: ct); - - public Task DeletePostAsync(long id, CancellationToken ct = default) - => _api.CallAsync(HttpMethod.Delete, $"{_pathPrefix}/{id}", ct: ct); -} diff --git a/src/PostIt/PostIt/Services/CurrentLocationResult.cs b/src/PostIt/PostIt/Services/CurrentLocationResult.cs new file mode 100644 index 00000000..ea19da43 --- /dev/null +++ b/src/PostIt/PostIt/Services/CurrentLocationResult.cs @@ -0,0 +1,28 @@ +namespace PostIt.Services; + +public sealed class CurrentLocationResult +{ + private CurrentLocationResult(bool isSuccess, bool isPermissionDenied, double? latitude, double? longitude, string message) + { + IsSuccess = isSuccess; + IsPermissionDenied = isPermissionDenied; + Latitude = latitude; + Longitude = longitude; + Message = message; + } + + public bool IsSuccess { get; } + public bool IsPermissionDenied { get; } + public double? Latitude { get; } + public double? Longitude { get; } + public string Message { get; } + + public static CurrentLocationResult Success(double latitude, double longitude, string? message = null) + => new(true, false, latitude, longitude, message ?? "Position récupérée."); + + public static CurrentLocationResult PermissionDenied(string? message = null) + => new(false, true, null, null, message ?? "La géolocalisation n'est pas autorisée."); + + public static CurrentLocationResult Unavailable(string? message = null) + => new(false, false, null, null, message ?? "La géolocalisation n'est pas disponible sur cette plateforme."); +} diff --git a/src/PostIt/PostIt/Services/IContactService.cs b/src/PostIt/PostIt/Services/IContactService.cs new file mode 100644 index 00000000..49ca3064 --- /dev/null +++ b/src/PostIt/PostIt/Services/IContactService.cs @@ -0,0 +1,57 @@ +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; + +namespace PostIt.Services; + +/// +/// Abstraction over the device-local address book. Used by +/// the "invite someone" flow to enumerate people the user +/// already has in their phone — including people who have +/// never heard of Yavsc. +/// +/// Distinct from , which +/// reads the central Yavsc user table. A device contact may +/// not have a Yavsc account; a directory entry always does. +/// The two are exposed as separate interfaces so a UI that +/// needs both can take both by constructor injection and +/// present them under separate sections (e.g. "Contacts from +/// your phone" vs "Yavsc members"). +/// +/// Implementations live next to this file in +/// platform-conditional source files: +/// ContactService.Mobile.cs (ANDROID/IOS) and +/// ContactService.Desktop.cs (everything else). On +/// desktop the implementation is a stub that returns an +/// empty list: the desktop has no equivalent of the mobile +/// address book, and inviting from a desktop is a separate +/// flow. +/// +public interface IContactService +{ + /// + /// Read the device address book. Returns the contacts + /// known to the local provider; on desktop (no local + /// provider) this is always an empty list. + /// + Task> GetDeviceContactsAsync(CancellationToken ct = default); +} + +/// +/// Platform-neutral contact DTO. Source-of-truth shape for +/// the UI layer; concrete providers (MAUI Essentials on +/// mobile) map to this type. +/// +/// Emails is a list on purpose: a real device +/// contact may carry several addresses (home / work / other). +/// The UI use case ("invite / add to a circle") can then +/// decide which address to use, or let the user pick. This +/// is intentionally richer than the Yavsc directory's +/// single-Email shape — the two flows answer different +/// questions and shouldn't be flattened onto the same +/// wire. +/// +public sealed record ContactDto( + string Id, + string DisplayName, + IReadOnlyList Emails); diff --git a/src/PostIt/PostIt/Services/IUserDirectory.cs b/src/PostIt/PostIt/Services/IUserDirectory.cs new file mode 100644 index 00000000..7d4c1eb4 --- /dev/null +++ b/src/PostIt/PostIt/Services/IUserDirectory.cs @@ -0,0 +1,67 @@ +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; + +namespace PostIt.Services; + +/// +/// Abstraction over the central Yavsc user directory. Used by +/// the "add to a circle" flow to find Yavsc users by display +/// name or email. +/// +/// Distinct from , which +/// reads the device-local address book. A Yavsc user +/// directory entry is always a registered account; a device +/// contact may be anyone in the user's phone — including +/// people who have never heard of Yavsc. +/// +/// Implementations live next to this file in +/// platform-conditional source files: +/// UserDirectory.Desktop.cs and +/// UserDirectory.Mobile.cs. Both currently delegate to +/// UserSearchClient (the central /api/user-search +/// endpoint); the split exists so future platform-specific +/// sources (offline cache, directory-scoped providers) can be +/// plugged in without disturbing the consumer. +/// +public interface IUserDirectory +{ + /// + /// Search the directory by display name (substring) and/or + /// email (exact). + /// + /// Substring filter on the user's + /// display name. Empty or whitespace short-circuits to an + /// empty list (matches the client UX of "type to search", + /// not "show me a directory"). + /// Cancellation token. + /// A flat list of matching directory entries. + /// Never null; may be empty. + Task> SearchAsync(string query, CancellationToken ct = default); +} + +/// +/// Platform-neutral summary of a Yavsc directory entry. Mirrors +/// the wire shape of /api/user-search (see +/// UserSearchResultDto) but expressed in terms that +/// don't leak transport concerns. +/// +/// Kept as a record on purpose: directory entries are +/// immutable snapshots from the server, so structural equality +/// makes "did the user already pick this one?" trivial. +/// +public sealed record UserSummary( + string Id, + string UserName, + string? FullName, + string? Avatar, + string? Email) +{ + /// + /// Convenience for "what to show in a picker". Falls back + /// to when + /// is null or empty. + /// + public string DisplayName => + string.IsNullOrWhiteSpace(FullName) ? UserName : FullName; +} diff --git a/src/PostIt/PostIt/Services/Platform.cs b/src/PostIt/PostIt/Services/Platform.cs index c867c63c..2e5ac76a 100644 --- a/src/PostIt/PostIt/Services/Platform.cs +++ b/src/PostIt/PostIt/Services/Platform.cs @@ -1,4 +1,7 @@ +using System; using IdentityModel.OidcClient.Browser; +using System.Threading; +using System.Threading.Tasks; namespace PostIt.Services; @@ -21,14 +24,14 @@ public static class Platform /// override this property at startup (e.g. PostIt.Android sets /// it to android://postit-signin). /// - public static string DefaultRedirectUri { get; set; } = "postit://callback"; + public const string RedirectUri = "postit://callback"; /// /// Scheme prefix the matches /// against BrowserOptions.EndUrl. Overridable for apps /// that want to register their own scheme. /// - public static string CustomScheme { get; set; } = "postit"; + public const string CustomScheme = "postit"; /// /// Constructs a fresh for the running platform. @@ -37,4 +40,12 @@ public static class Platform /// public static System.Func? CreateBrowser { get; set; } = () => new CustomSchemeBrowser(CustomScheme); -} \ No newline at end of file + + /// + /// Optional platform hook used by the shared billing form to request a + /// current device position. Platforms that do not expose a native + /// location provider can leave the default delegate in place. + /// + public static Func> TryGetCurrentLocationAsync { get; set; } = + _ => Task.FromResult(CurrentLocationResult.Unavailable()); +} diff --git a/src/PostIt/PostIt/Services/UiDispatcher.cs b/src/PostIt/PostIt/Services/UiDispatcher.cs deleted file mode 100644 index e935ac1a..00000000 --- a/src/PostIt/PostIt/Services/UiDispatcher.cs +++ /dev/null @@ -1,72 +0,0 @@ -using System; -using System.Threading.Tasks; -using Avalonia.Threading; - -namespace PostIt.Services; - -/// -/// Tiny marshalling helper around so -/// the rest of the codebase does not have to import Avalonia.Threading -/// directly. We want exactly one place that decides "is the current -/// thread the Avalonia UI thread, and if not, post there" so that -/// -derived types (Settings, the various -/// ViewModels) can fire PropertyChanged safely from background -/// work — which is exactly the cross-thread case that previously blew -/// up inside DataValidationErrors.SetErrors on Avalonia 11. -/// -/// The helper is intentionally tiny: a sync post when we are off the -/// UI thread, a no-op when we are already on it, and an async fire- -/// and-forget variant for places where awaiting would deadlock the -/// caller (e.g. Settings.Load continuation paths). -/// -public static class UiDispatcher -{ - /// - /// True when the calling thread is the Avalonia UI thread. Property - /// setters that touch bindings should check this before mutating - /// state; the safe path is . - /// - public static bool IsOnUiThread => Dispatcher.UIThread.CheckAccess(); - - /// - /// Run on the UI thread. If the caller is - /// already on the UI thread, run synchronously to preserve stack - /// traces and ordering; otherwise post to the dispatcher and wait. - /// Never throws on shutdown — a missing dispatcher is treated as - /// "best-effort skipped", matching Avalonia's own behaviour when - /// the application lifetime has been torn down. - /// - public static void InvokeIfNeeded(Action action) - { - if (action is null) return; - if (IsOnUiThread) { action(); return; } - try { Dispatcher.UIThread.Post(action, DispatcherPriority.Normal); } - catch (InvalidOperationException) { /* dispatcher gone, nothing to do */ } - } - - /// - /// Fire-and-forget variant: schedules on - /// the UI thread but does not block the caller. Use this from - /// background workers (OIDC discovery, HTTP callbacks, file I/O) - /// where awaiting the dispatcher would deadlock the calling sync - /// context. - /// - public static void Post(Action action) - { - if (action is null) return; - try { Dispatcher.UIThread.Post(action, DispatcherPriority.Normal); } - catch (InvalidOperationException) { /* dispatcher gone */ } - } - - /// - /// Awaitable variant. Useful inside async ViewModel methods - /// that must touch bindings only after the dispatcher has processed - /// a queued update (e.g. "load file then refresh observable state"). - /// - public static Task InvokeAsync(Action action) - { - if (action is null) return Task.CompletedTask; - if (IsOnUiThread) { action(); return Task.CompletedTask; } - return Dispatcher.UIThread.InvokeAsync(action, DispatcherPriority.Normal).GetTask(); - } -} diff --git a/src/PostIt/PostIt/Services/UserDirectory.Desktop.cs b/src/PostIt/PostIt/Services/UserDirectory.Desktop.cs new file mode 100644 index 00000000..c821bb87 --- /dev/null +++ b/src/PostIt/PostIt/Services/UserDirectory.Desktop.cs @@ -0,0 +1,52 @@ +#if !ANDROID && !IOS +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using Yavsc.Api.Client; + +namespace PostIt.Services; + +/// +/// Desktop implementation of . +/// Delegates to the central /api/user-search endpoint +/// via . +/// +/// The desktop has no device-local address book, so the +/// "add to a circle" flow on desktop is Yavsc-users-only. +/// Inviting someone who doesn't have a Yavsc account from +/// desktop is a separate feature (manual email entry + +/// invitation endpoint) and lives outside this interface. +/// +public sealed class UserDirectory : IUserDirectory +{ + private readonly UserSearchClient _client; + + public UserDirectory(UserSearchClient client) + { + _client = client ?? throw new ArgumentNullException(nameof(client)); + } + + public async Task> SearchAsync( + string query, CancellationToken ct = default) + { + // UserSearchClient already short-circuits on empty + // queries, but do it here too so the contract is + // obvious to anyone reading IUserDirectory alone + // without having to chase the client wrapper. + if (string.IsNullOrWhiteSpace(query)) + return Array.Empty(); + + var results = await _client.SearchAsync(query: query, ct: ct).ConfigureAwait(false); + if (results is null) return Array.Empty(); + + return results.Select(u => new UserSummary( + Id: u.Id, + UserName: u.UserName, + FullName: u.FullName, + Avatar: u.Avatar, + Email: u.Email)).ToList(); + } +} +#endif diff --git a/src/PostIt/PostIt/Services/UserDirectory.Mobile.cs b/src/PostIt/PostIt/Services/UserDirectory.Mobile.cs new file mode 100644 index 00000000..5cba6e4a --- /dev/null +++ b/src/PostIt/PostIt/Services/UserDirectory.Mobile.cs @@ -0,0 +1,49 @@ +#if ANDROID || IOS +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using Yavsc.Api.Client; + +namespace PostIt.Services; + +/// +/// Mobile implementation of . +/// Same backing as the desktop provider (the central +/// /api/user-search endpoint via +/// ) — mobile devices have the +/// network too, and "add to a circle" needs the same directory +/// regardless of platform. +/// +/// The split exists so a future mobile-only provider +/// (offline cache, device-local mirror of the user's own +/// circles) can be plugged in without touching consumers. +/// +public sealed class UserDirectory : IUserDirectory +{ + private readonly UserSearchClient _client; + + public UserDirectory(UserSearchClient client) + { + _client = client ?? throw new ArgumentNullException(nameof(client)); + } + + public async Task> SearchAsync( + string query, CancellationToken ct = default) + { + if (string.IsNullOrWhiteSpace(query)) + return Array.Empty(); + + var results = await _client.SearchAsync(query: query, ct: ct).ConfigureAwait(false); + if (results is null) return Array.Empty(); + + return results.Select(u => new UserSummary( + Id: u.Id, + UserName: u.UserName, + FullName: u.FullName, + Avatar: u.Avatar, + Email: u.Email)).ToList(); + } +} +#endif diff --git a/src/PostIt/PostIt/Services/YavscApiClient.cs b/src/PostIt/PostIt/Services/YavscApiClient.cs index 9ae1453b..4d748f87 100644 --- a/src/PostIt/PostIt/Services/YavscApiClient.cs +++ b/src/PostIt/PostIt/Services/YavscApiClient.cs @@ -1,14 +1,15 @@ using System; +using System.IO; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Net.Http.Json; -using System.Text; using System.Text.Json; using System.Threading; using System.Threading.Tasks; using IdentityModel.OidcClient; using PostIt.ViewModels; +using Yavsc.Api.Client; namespace PostIt.Services; @@ -24,7 +25,7 @@ namespace PostIt.Services; /// only refreshes once even if many /// concurrent requests are in flight. /// -public class YavscApiClient : IAsyncDisposable +public class YavscApiClient : IYavscApiClient, IAsyncDisposable { // 60s of slack before the access_token's nominal expiry. Covers // network latency + JWT validation on the server side. @@ -351,6 +352,77 @@ public class YavscApiClient : IAsyncDisposable _store.Save(_tokens); } + /// + /// Upload a user avatar to the Yavsc API. The server expects a + /// single multipart file named file and validates the image + /// content type before persisting it. + /// + public async Task SetAvatarAsync( + Stream imageStream, + string fileName, + string? contentType = null, + CancellationToken ct = default) + { + if (imageStream is null) + throw new ArgumentNullException(nameof(imageStream)); + if (string.IsNullOrWhiteSpace(fileName)) + throw new ArgumentException("A file name is required.", nameof(fileName)); + + var endpoint = new Uri(new Uri(Settings.ApiUrl.TrimEnd('/') + "/", UriKind.Absolute), "account/set-avatar"); + + await EnsureFreshTokenAsync(ct).ConfigureAwait(false); + + var attemptUpload = async () => + { + if (imageStream.CanSeek) + imageStream.Position = 0; + + using var content = new MultipartFormDataContent(); + using var fileContent = new StreamContent(imageStream); + fileContent.Headers.ContentType = new MediaTypeHeaderValue( + string.IsNullOrWhiteSpace(contentType) ? "application/octet-stream" : contentType); + content.Add(fileContent, "file", fileName); + + using var request = new HttpRequestMessage(HttpMethod.Post, endpoint) + { + Content = content, + }; + + return await Http.SendAsync(request, ct).ConfigureAwait(false); + }; + + var response = await attemptUpload().ConfigureAwait(false); + if (response.StatusCode == HttpStatusCode.Unauthorized) + { + response.Dispose(); + await ForceRefreshAsync(ct).ConfigureAwait(false); + response = await attemptUpload().ConfigureAwait(false); + } + + await EnsureSuccessOrThrowAsync(response, ct).ConfigureAwait(false); + + var payload = await response.Content.ReadAsStringAsync(ct).ConfigureAwait(false); + if (string.IsNullOrWhiteSpace(payload)) + return "Avatar mis à jour."; + + try + { + using var json = JsonDocument.Parse(payload); + if (json.RootElement.TryGetProperty("message", out var msgEl)) + { + var message = msgEl.GetString(); + if (!string.IsNullOrWhiteSpace(message)) + return message; + } + } + catch (JsonException) + { + // Keep a user-friendly fallback when the API payload is not JSON. + } + + return "Avatar mis à jour."; + } + public async Task LogoutAsync() { _store.Clear(); diff --git a/src/PostIt/PostIt/ViewLocator.cs b/src/PostIt/PostIt/ViewLocator.cs index e725d0d9..0055a9e6 100644 --- a/src/PostIt/PostIt/ViewLocator.cs +++ b/src/PostIt/PostIt/ViewLocator.cs @@ -1,37 +1,58 @@ using System; +using System.Diagnostics.CodeAnalysis; using Avalonia.Controls; using Avalonia.Controls.Templates; using Microsoft.Extensions.DependencyInjection; using PostIt.ViewModels; +using PostIt.ViewModels.Commands; using PostIt.Views; +using PostIt.Views.Commands; namespace PostIt; /// /// Given a view model, returns the corresponding view if possible. /// - +[RequiresUnreferencedCode( + "Default implementation of ViewLocator involves reflection which may be trimmed away.", + Url = "https://docs.avaloniaui.net/docs/concepts/view-locator")] public class ViewLocator : IDataTemplate { - private readonly IServiceProvider _services; - public ViewLocator(IServiceProvider services) + public Control Build(object? data) { - _services = services; + try + { + return BuildCore(data); + } + catch (Exception ex) + { + return new TextBlock { Text = $"ViewLocator threw: {ex}" }; + } } - public Control Build(object? data) + + private Control BuildCore(object? data) { + var app = App.Current as App; + var services = app!.ServiceProvider!; return data switch { - MainPageViewModel => _services.GetRequiredService(), - Settings => _services.GetRequiredService(), - HomePageViewModel => _services.GetRequiredService(), - SignaturePageViewModel => _services.GetRequiredService(), + MainViewModel => services.GetRequiredService(), + Settings => services.GetRequiredService(), + HomePageViewModel => services.GetRequiredService(), + ActivitiesPageViewModel => services.GetRequiredService(), + CommandFormsPageViewModel => services.GetRequiredService(), + BrushViewModel => services.GetRequiredService(), + RdvViewModel => services.GetRequiredService(), + SignaturePageViewModel => services.GetRequiredService(), + AddCircleMemberDialogViewModel => services.GetRequiredService(), + CirclesPageViewModel => services.GetRequiredService(), + PostAclDialogViewModel => services.GetRequiredService(), null => new TextBlock { Text = "No view for " }, - _ => new TextBlock { Text = $"No view for {data.GetType().Name}" } + _ => new TextBlock { Text = $"No view for {data.GetType().Name}" } }; } - public bool Match(object? data) => data is ViewModelBase; + public bool Match(object? data) => data is ViewModelBase; } diff --git a/src/PostIt/PostIt/ViewModels/ActivitiesPageViewModel.cs b/src/PostIt/PostIt/ViewModels/ActivitiesPageViewModel.cs new file mode 100644 index 00000000..2dc8938f --- /dev/null +++ b/src/PostIt/PostIt/ViewModels/ActivitiesPageViewModel.cs @@ -0,0 +1,275 @@ +using System; +using System.Collections.ObjectModel; +using System.Linq; +using System.Net; +using System.Net.Http; +using System.Threading.Tasks; +using Avalonia; +using CommunityToolkit.Mvvm.ComponentModel; +using CommunityToolkit.Mvvm.Input; +using PostIt.Helpers; +using Yavsc.Abstract.Workflow; +using Yavsc.Api.Client; + +namespace PostIt.ViewModels; + +public partial class ActivitiesPageViewModel : ViewModelBase +{ + private readonly ActivityApiClient _client; + private readonly BillingApiClient _billingClient; + private bool _syncingSelection; + + [ObservableProperty] + public partial ObservableCollection Activities { get; set; } = new(); + + [ObservableProperty] + public partial ActivityInfo? SelectedActivity { get; set; } + + [ObservableProperty] + public partial ObservableCollection Specializations { get; set; } = new(); + + [ObservableProperty] + public partial ActivityInfo? SelectedSpecialization { get; set; } + + [ObservableProperty] + public partial ObservableCollection Performers { get; set; } = new(); + + [ObservableProperty, NotifyCanExecuteChangedFor(nameof(OpenCommandFormsCommand))] + public partial ActivityUserDisplayItem? SelectedPerformer { get; set; } + + [ObservableProperty] + public partial bool IsBusy { get; set; } + + [ObservableProperty] + public partial string StatusMessage { get; set; } = "Choisissez une activité."; + + public ActivityInfo? CurrentActivity => SelectedSpecialization ?? SelectedActivity; + public string SelectedActivityLabel => SelectedActivity?.Name ?? "(aucune activité)"; + public string CurrentActivityLabel => CurrentActivity?.Name ?? "(aucune)"; + public int CurrentFormCount => CurrentActivity?.Forms?.Count ?? 0; + + public override bool CanNavigateNext + { + get => false; + protected set { _ = value; } + } + + public override bool CanNavigatePrevious + { + get => true; + protected set { _ = value; } + } + + public ActivitiesPageViewModel(ActivityApiClient client, BillingApiClient billingClient) + { + _client = client ?? throw new ArgumentNullException(nameof(client)); + _billingClient = billingClient ?? throw new ArgumentNullException(nameof(billingClient)); + } + + partial void OnSelectedActivityChanged(ActivityInfo? value) + { + if (_syncingSelection) return; + _ = ShowActivitySafeAsync(value); + } + + partial void OnSelectedSpecializationChanged(ActivityInfo? value) + { + if (_syncingSelection) return; + _ = ShowSpecializationSafeAsync(value); + } + + private async Task ShowActivitySafeAsync(ActivityInfo? value) + { + try + { + await ShowActivityAsync(value); + } + catch (HttpRequestException ex) when (ex.StatusCode is HttpStatusCode.Unauthorized or HttpStatusCode.Forbidden) + { + StatusMessage = "Accès refusé pour les activités (scope 'api'). Déconnectez puis reconnectez-vous."; + } + catch (Exception ex) + { + StatusMessage = $"Erreur: {ex.Message}"; + } + } + + private async Task ShowSpecializationSafeAsync(ActivityInfo? value) + { + try + { + await ShowSpecializationAsync(value); + } + catch (HttpRequestException ex) when (ex.StatusCode is HttpStatusCode.Unauthorized or HttpStatusCode.Forbidden) + { + StatusMessage = "Accès refusé pour les activités (scope 'api'). Déconnectez puis reconnectez-vous."; + } + catch (Exception ex) + { + StatusMessage = $"Erreur: {ex.Message}"; + } + } + + [RelayCommand] + public async Task RefreshAsync() + { + IsBusy = true; + try + { + var list = await _client.GetCatalogAsync(); + Activities = new ObservableCollection(list ?? new()); + + var first = Activities.FirstOrDefault(); + await ShowActivityAsync(first); + if (first is null) + { + StatusMessage = "Aucune activité disponible."; + } + } + catch (HttpRequestException ex) when (ex.StatusCode is HttpStatusCode.Unauthorized or HttpStatusCode.Forbidden) + { + Activities = new ObservableCollection(); + Specializations = new ObservableCollection(); + Performers = new ObservableCollection(); + StatusMessage = "Accès refusé pour les activités (scope 'api'). Déconnectez puis reconnectez-vous."; + } + catch (Exception ex) + { + Activities = new ObservableCollection(); + Specializations = new ObservableCollection(); + Performers = new ObservableCollection(); + StatusMessage = $"Erreur: {ex.Message}"; + } + finally + { + IsBusy = false; + } + } + + public async Task ShowActivityAsync(ActivityInfo? activity) + { + _syncingSelection = true; + try + { + SelectedActivity = activity; + SelectedSpecialization = null; + } + finally + { + _syncingSelection = false; + } + + OnPropertyChanged(nameof(CurrentActivity)); + OnPropertyChanged(nameof(SelectedActivityLabel)); + OnPropertyChanged(nameof(CurrentActivityLabel)); + OnPropertyChanged(nameof(CurrentFormCount)); + Specializations = new ObservableCollection(activity?.Children ?? new()); + + if (activity is null) + { + Performers = new ObservableCollection(); + SelectedPerformer = null; + return; + } + + await LoadPerformersAsync(activity); + } + + public async Task ShowSpecializationAsync(ActivityInfo? specialization) + { + _syncingSelection = true; + try + { + SelectedSpecialization = specialization; + } + finally + { + _syncingSelection = false; + } + + OnPropertyChanged(nameof(CurrentActivity)); + OnPropertyChanged(nameof(CurrentActivityLabel)); + OnPropertyChanged(nameof(CurrentFormCount)); + + if (specialization is null) + { + if (SelectedActivity is not null) + { + await LoadPerformersAsync(SelectedActivity); + } + return; + } + + await LoadPerformersAsync(specialization); + } + + private async Task LoadPerformersAsync(ActivityInfo activity) + { + IsBusy = true; + try + { + var list = await _client.GetUsersAsync(activity.Code); + var items = (list ?? new()) + .Select(dto => ActivityUserDisplayItem.FromDto(dto, _client.BuildAvatarXsUrl(dto.UserName))) + .ToList(); + + await Task.WhenAll(items.Select(async item => + { + if (string.IsNullOrWhiteSpace(item.AvatarXsUrl)) + { + return; + } + + if (!Uri.TryCreate(item.AvatarXsUrl, UriKind.Absolute, out var avatarUri)) + { + return; + } + + item.AvatarImage = await ImageHelper.LoadFromWeb(avatarUri); + })); + + Performers = new ObservableCollection(items); + SelectedPerformer = null; + StatusMessage = $"{activity.Name} · {Performers.Count} utilisateur(s)"; + } + catch (HttpRequestException ex) when (ex.StatusCode is HttpStatusCode.Unauthorized or HttpStatusCode.Forbidden) + { + Performers = new ObservableCollection(); + SelectedPerformer = null; + StatusMessage = "Accès refusé pour les activités (scope 'api'). Déconnectez puis reconnectez-vous."; + } + catch (Exception ex) + { + Performers = new ObservableCollection(); + SelectedPerformer = null; + StatusMessage = $"Erreur: {ex.Message}"; + } + finally + { + IsBusy = false; + OpenCommandFormsCommand.NotifyCanExecuteChanged(); + } + } + + private bool CanOpenCommandForms() + => SelectedPerformer is not null && CurrentActivity?.Forms?.Count > 0; + + [RelayCommand(CanExecute = nameof(CanOpenCommandForms))] + private async Task OpenCommandFormsAsync() + { + if (SelectedPerformer is null || CurrentActivity is null) + { + StatusMessage = "Sélectionnez un utilisateur et une activité avec formulaire."; + return; + } + + var app = (App?)Application.Current; + if (app is null) + { + throw new InvalidOperationException("Application PostIt indisponible."); + } + + var vm = new CommandFormsPageViewModel(CurrentActivity, SelectedPerformer, _billingClient); + await app.PushPageAsync(vm); + } +} diff --git a/src/PostIt/PostIt/ViewModels/ActivityUserDisplayItem.cs b/src/PostIt/PostIt/ViewModels/ActivityUserDisplayItem.cs new file mode 100644 index 00000000..d89a66e9 --- /dev/null +++ b/src/PostIt/PostIt/ViewModels/ActivityUserDisplayItem.cs @@ -0,0 +1,50 @@ +using Avalonia.Media.Imaging; +using CommunityToolkit.Mvvm.ComponentModel; +using Yavsc.Abstract.Workflow; + +namespace PostIt.ViewModels; + +public sealed partial class ActivityUserDisplayItem : ObservableObject +{ + public string PerformerId { get; init; } = string.Empty; + public string AvatarXsUrl { get; init; } = string.Empty; + public bool HasPerformerProfile { get; init; } + public string PerformerBadgeLabel { get; init; } = "Profil pro"; + public bool IsPerformerActive { get; init; } + public string PerformerStatusBadgeLabel { get; init; } = "Inactif"; + public string PerformerStatusBadgeBackground { get; init; } = "#FDECEA"; + public string PerformerStatusBadgeBorder { get; init; } = "#C62828"; + public string PerformerStatusBadgeForeground { get; init; } = "#8E0000"; + public string UserName { get; init; } = string.Empty; + public string AvatarFallbackLabel { get; init; } = "?"; + public string WebSite { get; init; } = string.Empty; + public int ExtraActivityCount { get; init; } + public string ExtraActivityLabel { get; init; } = "Pas d'autre activité"; + + [ObservableProperty] + public partial Bitmap? AvatarImage { get; set; } + + public static ActivityUserDisplayItem FromDto(PerformerActivity dto, string avatarXsUrl) + { + return new ActivityUserDisplayItem + { + PerformerId = dto.PerformerId, + AvatarXsUrl = avatarXsUrl, + HasPerformerProfile = dto.HasPerformerProfile, + UserName = dto.UserName, + AvatarFallbackLabel = string.IsNullOrWhiteSpace(dto.UserName) + ? "?" + : dto.UserName.Trim()[0].ToString().ToUpperInvariant(), + WebSite = dto.WebSite, + IsPerformerActive = dto.Active, + PerformerStatusBadgeLabel = dto.Active ? "Actif" : "Inactif", + PerformerStatusBadgeBackground = dto.Active ? "#E6F7EC" : "#FDECEA", + PerformerStatusBadgeBorder = dto.Active ? "#2E7D32" : "#C62828", + PerformerStatusBadgeForeground = dto.Active ? "#1B5E20" : "#8E0000", + ExtraActivityCount = dto.ExtraActivityCount, + ExtraActivityLabel = dto.ExtraActivityCount == 0 + ? "Pas d'autre activité" + : $"Autres spécialisations: {dto.ExtraActivityCount}" + }; + } +} diff --git a/src/PostIt/PostIt/ViewModels/AddCircleMemberDialogViewModel.cs b/src/PostIt/PostIt/ViewModels/AddCircleMemberDialogViewModel.cs new file mode 100644 index 00000000..88d01335 --- /dev/null +++ b/src/PostIt/PostIt/ViewModels/AddCircleMemberDialogViewModel.cs @@ -0,0 +1,127 @@ +using System; +using System.Collections.ObjectModel; +using System.Threading; +using System.Threading.Tasks; +using CommunityToolkit.Mvvm.ComponentModel; +using CommunityToolkit.Mvvm.Input; +using PostIt.Services; +using Yavsc.Api.Client; + +namespace PostIt.ViewModels; + +/// +/// View model for the "add a Yavsc user to a circle" modal. +/// +/// Resolves users through +/// (which delegates to /api/user-search); the caller +/// (CirclesPage) decides whether to add the picked user to +/// the circle by calling +/// +/// (which is bound to the dialog's "Ajouter" button). +/// +/// The dialog itself doesn't know the target +/// CircleId: that's set by the caller via the +/// constructor and the dialog only triggers +/// against the +/// string. The "Add" command +/// returns the picked via the +/// event, and the hosting +/// CirclesPage then calls +/// . +/// +public partial class AddCircleMemberDialogViewModel : ViewModelBase +{ + private readonly IUserDirectory _directory; + + [ObservableProperty] + public partial string SearchQuery { get; set; } = string.Empty; + + [ObservableProperty] + public partial ObservableCollection Results { get; set; } = new(); + + [ObservableProperty] + public partial UserSummary? Selected { get; set; } + + [ObservableProperty] + public partial bool IsBusy { get; set; } + + [ObservableProperty] + public partial string StatusMessage { get; set; } = string.Empty; + + /// + /// Raised when the user confirms a selection. The hosting + /// CirclesPage subscribes to this event and calls + /// CircleApiClient.AddMemberAsync with the target + /// circle id + the picked user's id. The dialog itself + /// does not know the circle id by design: separation of + /// concerns — the modal is a user picker, not a + /// "circle joiner" form. + /// + public event EventHandler? Confirmed; + + public AddCircleMemberDialogViewModel(IUserDirectory directory) + { + _directory = directory ?? throw new ArgumentNullException(nameof(directory)); + } + + public override bool CanNavigateNext { get => throw new NotImplementedException(); protected set => throw new NotImplementedException(); } + public override bool CanNavigatePrevious { get => throw new NotImplementedException(); protected set => throw new NotImplementedException(); } + + /// + /// Search the directory for users matching the current + /// . Triggered explicitly via the + /// "Rechercher" button — no debouncing, so the caller + /// stays in control of how often the network is hit. + /// + [RelayCommand] + public async Task SearchAsync() + { + if (string.IsNullOrWhiteSpace(SearchQuery)) + { + Results.Clear(); + StatusMessage = "Tapez un nom ou un email"; + return; + } + + IsBusy = true; + try + { + var hits = await _directory.SearchAsync(SearchQuery, CancellationToken.None).ConfigureAwait(true); + Results = new ObservableCollection(hits ?? Array.Empty()); + StatusMessage = $"{Results.Count} résultat(s)"; + } + catch (Exception ex) + { + StatusMessage = $"Erreur: {ex.Message}"; + } + finally + { + IsBusy = false; + } + } + + /// + /// Raise for the currently selected + /// user. No-op when no selection has been made — keeps the + /// UI from firing an event with a null payload. + /// + [RelayCommand] + public async Task AddAsync() + { + if (Selected is null) + { + StatusMessage = "Sélectionnez un utilisateur"; + return; + } + Confirmed?.Invoke(this, Selected); + var app = App.Current as App; + await app.GoBackAsync(); + } + + [RelayCommand] + public async Task CloseAsync() + { + var app = App.Current as App; + await app.GoBackAsync(); + } +} diff --git a/src/PostIt/PostIt/ViewModels/BillingQueriesPageViewModel.cs b/src/PostIt/PostIt/ViewModels/BillingQueriesPageViewModel.cs new file mode 100644 index 00000000..d5aba021 --- /dev/null +++ b/src/PostIt/PostIt/ViewModels/BillingQueriesPageViewModel.cs @@ -0,0 +1,173 @@ +using System; +using System.Collections.ObjectModel; +using System.Linq; +using System.Net; +using System.Net.Http; +using System.Threading.Tasks; +using Avalonia; +using CommunityToolkit.Mvvm.ComponentModel; +using CommunityToolkit.Mvvm.Input; +using PostIt.Helpers; +using Yavsc; +using Yavsc.Api.Client; +using Yavsc.Abstract.Workflow; + +namespace PostIt.ViewModels; + +public partial class BillingQueriesPageViewModel : ViewModelBase +{ + private readonly BillingApiClient _billingClient; + + public ActivityInfo Activity { get; } + public ActivityUserDisplayItem Performer { get; } + public CommandFormSummary Form { get; } + public bool IsReadOnly { get; } + public bool OngoingOnly { get; } + + [ObservableProperty] + public partial ObservableCollection Queries { get; set; } = new(); + + [ObservableProperty, NotifyCanExecuteChangedFor(nameof(OpenSelectedQueryCommand))] + public partial BillingQueryDisplayItem? SelectedQuery { get; set; } + + [ObservableProperty] + public partial bool IsBusy { get; set; } + + [ObservableProperty] + public partial string StatusMessage { get; set; } = "Chargement des commandes..."; + + public string Title => IsReadOnly + ? $"Demandes en cours ({Form.Title})" + : $"Commandes {Form.Title}"; + public string ContextLabel => $"{Performer.UserName} · {Activity.Name}"; + public bool CanOpenDetails => !IsReadOnly; + + public override bool CanNavigateNext + { + get => false; + protected set { _ = value; } + } + + public override bool CanNavigatePrevious + { + get => true; + protected set { _ = value; } + } + + public BillingQueriesPageViewModel( + ActivityInfo activity, + ActivityUserDisplayItem performer, + CommandFormSummary form, + BillingApiClient billingClient, + bool isReadOnly = false, + bool ongoingOnly = false) + { + Activity = activity ?? throw new ArgumentNullException(nameof(activity)); + Performer = performer ?? throw new ArgumentNullException(nameof(performer)); + Form = form ?? throw new ArgumentNullException(nameof(form)); + _billingClient = billingClient ?? throw new ArgumentNullException(nameof(billingClient)); + IsReadOnly = isReadOnly; + OngoingOnly = ongoingOnly; + } + + public Task InitializeAsync() => RefreshAsync(); + + private bool CanOpenSelectedQuery() => !IsReadOnly && SelectedQuery is not null; + + [RelayCommand] + public async Task RefreshAsync() + { + IsBusy = true; + try + { + var list = await _billingClient.GetQuerySummariesAsync(Form.ActionName).ConfigureAwait(true); + var filtered = (list ?? new()) + .Where(q => q.ActivityCode == Activity.Code && q.PerformerId == Performer.PerformerId) + .Where(q => !OngoingOnly || IsOngoingStatus(q.Status)) + .OrderByDescending(q => q.EventDate ?? DateTime.MinValue) + .ThenByDescending(q => q.Id) + .Select(BillingQueryDisplayItem.FromDto) + .ToList(); + + Queries = new ObservableCollection(filtered); + StatusMessage = BuildLoadedStatusMessage(filtered.Count); + } + catch (HttpRequestException ex) when (ex.StatusCode is HttpStatusCode.Unauthorized or HttpStatusCode.Forbidden) + { + Queries = new ObservableCollection(); + StatusMessage = "Accès refusé au billing (scope 'api'). Déconnectez puis reconnectez-vous."; + } + catch (Exception ex) + { + Queries = new ObservableCollection(); + StatusMessage = $"Erreur: {ex.Message}"; + } + finally + { + IsBusy = false; + } + } + + [RelayCommand(CanExecute = nameof(CanOpenSelectedQuery))] + public async Task OpenSelectedQueryAsync() + { + if (IsReadOnly) + { + StatusMessage = "Mode lecture seule: l'ouverture en modification est désactivée."; + return; + } + + if (SelectedQuery is null) + { + StatusMessage = "Sélectionnez une commande."; + return; + } + + var app = (App?)Application.Current; + if (app is null) + { + throw new InvalidOperationException("Application PostIt indisponible."); + } + + IsBusy = true; + try + { + var details = await _billingClient.GetQueryAsync(Form.ActionName, SelectedQuery.Id).ConfigureAwait(true); + var vm = Form.CreateCommandPageViewModel(Activity, Performer, _billingClient); + await vm!.InitializeAsync(details).ConfigureAwait(true); + await app.PushPageAsync(vm).ConfigureAwait(true); + } + catch (HttpRequestException ex) when (ex.StatusCode is HttpStatusCode.Unauthorized or HttpStatusCode.Forbidden) + { + StatusMessage = "Accès refusé au billing (scope 'api'). Déconnectez puis reconnectez-vous."; + } + catch (Exception ex) + { + StatusMessage = $"Erreur lors de l'ouverture: {ex.Message}"; + } + finally + { + IsBusy = false; + } + } + + private string BuildLoadedStatusMessage(int count) + { + if (count == 0) + { + return OngoingOnly + ? "Aucune demande en cours pour ce formulaire." + : "Aucune commande trouvée pour ce formulaire."; + } + + if (OngoingOnly) + { + return $"{count} demande(s) en cours chargée(s) (lecture seule)."; + } + + return $"{count} commande(s) chargée(s)."; + } + + private static bool IsOngoingStatus(QueryStatus status) + => status is QueryStatus.Inserted or QueryStatus.Accepted or QueryStatus.InProgress; +} diff --git a/src/PostIt/PostIt/ViewModels/BillingQueryDisplayItem.cs b/src/PostIt/PostIt/ViewModels/BillingQueryDisplayItem.cs new file mode 100644 index 00000000..bc437337 --- /dev/null +++ b/src/PostIt/PostIt/ViewModels/BillingQueryDisplayItem.cs @@ -0,0 +1,35 @@ +using System; +using Yavsc.Api.Client; + +namespace PostIt.ViewModels; + +public sealed class BillingQueryDisplayItem +{ + public long Id { get; init; } + public string Description { get; init; } = string.Empty; + public string Summary { get; init; } = string.Empty; + public string StatusLabel { get; init; } = string.Empty; + public string EventDateLabel { get; init; } = string.Empty; + public string BillingCode { get; init; } = string.Empty; + + public static BillingQueryDisplayItem FromDto(BillingQuerySummaryDto dto) + { + var summary = !string.IsNullOrWhiteSpace(dto.Reason) + ? dto.Reason + : !string.IsNullOrWhiteSpace(dto.AdditionalInfo) + ? dto.AdditionalInfo + : dto.Description; + + return new BillingQueryDisplayItem + { + Id = dto.Id, + Description = string.IsNullOrWhiteSpace(dto.Description) + ? $"Commande #{dto.Id}" + : dto.Description, + Summary = summary, + StatusLabel = dto.Status.ToString(), + EventDateLabel = dto.EventDate?.ToLocalTime().ToString("g") ?? "Date non précisée", + BillingCode = dto.BillingCode, + }; + } +} \ No newline at end of file diff --git a/src/PostIt/PostIt/ViewModels/CirclesPageViewModel.cs b/src/PostIt/PostIt/ViewModels/CirclesPageViewModel.cs new file mode 100644 index 00000000..9cee3ea8 --- /dev/null +++ b/src/PostIt/PostIt/ViewModels/CirclesPageViewModel.cs @@ -0,0 +1,311 @@ +using System; +using System.Collections.ObjectModel; +using System.Threading.Tasks; +using Avalonia; +using CommunityToolkit.Mvvm.ComponentModel; +using CommunityToolkit.Mvvm.Input; +using Microsoft.Extensions.DependencyInjection; +using PostIt.Helpers; +using PostIt.Services; +using Yavsc.Api.Client; +using Yavsc.Api.Client.Dtos; + +namespace PostIt.ViewModels; + +/// +/// View model for the "Mes cercles" page. CRUD on the caller's own +/// circles (the server scopes every endpoint to the caller's uid +/// since the BlogAcl fix on this branch), plus membership +/// management on the currently selected circle. +/// +/// The view lists circles in , supports +/// create / edit via , and exposes +/// per-item Delete and per-item edit commands. +/// drives a progress overlay during API calls; +/// surfaces success / error feedback in the view footer. +/// +/// When the user selects a circle in the list, +/// fetches its members into +/// . The "Add a member" command +/// () is a UI event the view +/// raises to open AddCircleMemberDialog; the dialog +/// raises a Confirmed event back, which the page's +/// code-behind forwards here via +/// . The "remove" +/// command is per-row and runs inline. +/// +public partial class CirclesPageViewModel : ViewModelBase +{ + private readonly CircleApiClient _client; + + [ObservableProperty] + public partial ObservableCollection Circles { get; set; } = new(); + + [ObservableProperty] + public partial CircleDto? SelectedCircle { get; set; } + + /// Editor buffer for the new / edited circle's name. + [ObservableProperty] + public partial string DraftName { get; set; } = string.Empty; + + /// Editor buffer for the new / edited circle's visibility flag. + [ObservableProperty] + public partial bool DraftPublic { get; set; } + + /// Members of the currently selected circle. Empty + /// when no circle is selected or after a refresh that + /// produced an empty list. Updated by + /// . + [ObservableProperty] + public partial ObservableCollection Members { get; set; } = new(); + + [ObservableProperty] + public partial bool IsBusy { get; set; } + + [ObservableProperty] + public partial string StatusMessage { get; set; } = string.Empty; + + + public CirclesPageViewModel(CircleApiClient client) + { + _client = client ?? throw new ArgumentNullException(nameof(client)); + } + + public override bool CanNavigateNext { get => throw new NotImplementedException(); protected set => throw new NotImplementedException(); } + public override bool CanNavigatePrevious { get => throw new NotImplementedException(); protected set => throw new NotImplementedException(); } + + /// + /// Partial property setter: when the selected circle + /// changes, refresh the members list. The setter is + /// invoked by the [ObservableProperty] source generator + /// for both user selections and programmatic resets. + /// + partial void OnSelectedCircleChanged(CircleDto? value) + { + Members = new ObservableCollection(); + if (value is not null) + { + // Fire-and-forget: load members in the background. + // Errors are routed to StatusMessage inside + // LoadMembersAsync. + _ = LoadMembersAsync(value.Id); + } + } + + [RelayCommand] + public async Task RefreshAsync() + { + IsBusy = true; + try + { + var list = await _client.GetMyCirclesAsync(); + Circles = new ObservableCollection(list ?? new()); + StatusMessage = $"{Circles.Count} cercle(s)"; + } + catch (Exception ex) + { + StatusMessage = $"Erreur: {ex.Message}"; + } + finally + { + IsBusy = false; + } + } + + [RelayCommand] + internal async Task OpenAddMemberAsync() + { + var app = Application.Current as App; + var services = app?.ServiceProvider; + var directory = services.GetRequiredService(); + AddCircleMemberDialogViewModel model = + new AddCircleMemberDialogViewModel(directory); + // Wire the dialog's Confirmed event to OnAddMemberConfirmedAsync. + // Without this, the dialog's "Ajouter" button fires the event + // into the void: no subscriber, the picked user is silently + // dropped, and nothing is added to the circle. The dialog + // stays open until the user uses the back gesture — which is + // how the user noticed the button was a no-op. + // Async-void is intentional here: Confirmed is an + // EventHandler (returns void), and bridging to the + // async Task OnAddMemberConfirmedAsync requires it. + model.Confirmed += async (_, picked) => + await OnAddMemberConfirmedAsync(_, picked); + await app.PushPageAsync(model); + } + /// + /// Load the members of one of the caller's circles. The + /// server scopes the endpoint with a 404 when the circle + /// doesn't belong to the caller (mirroring the rest of the + /// circle API); that case flattens to an empty list here. + /// + [RelayCommand] + public async Task LoadMembersAsync(long circleId) + { + IsBusy = true; + try + { + var list = await _client.GetMembersAsync(circleId); + Members = new ObservableCollection(list ?? new()); + StatusMessage = $"{Members.Count} membre(s)"; + } + catch (Exception ex) + { + StatusMessage = $"Erreur: {ex.Message}"; + Members = new ObservableCollection(); + } + finally + { + IsBusy = false; + } + } + + [RelayCommand] + public void StartCreate() + { + SelectedCircle = null; + DraftName = string.Empty; + DraftPublic = false; + StatusMessage = "Nouveau cercle"; + } + + [RelayCommand] + public void StartEdit(CircleDto? circle) + { + if (circle is null) return; + SelectedCircle = circle; + DraftName = circle.Name; + DraftPublic = circle.Public; + StatusMessage = $"Édition de « {circle.Name} »"; + } + + [RelayCommand] + public async Task SaveAsync() + { + if (string.IsNullOrWhiteSpace(DraftName)) + { + StatusMessage = "Le nom est obligatoire"; + return; + } + + IsBusy = true; + try + { + if (SelectedCircle is null) + { + var created = await _client.CreateCircleAsync(new CircleDto + { + Name = DraftName.Trim(), + Public = DraftPublic, + }); + StatusMessage = created is null + ? "Création échouée" + : $"Cercle « {created.Name} » créé"; + } + else + { + SelectedCircle.Name = DraftName.Trim(); + SelectedCircle.Public = DraftPublic; + await _client.UpdateCircleAsync(SelectedCircle.Id, SelectedCircle); + StatusMessage = $"Cercle « {SelectedCircle.Name} » mis à jour"; + } + await RefreshAsync(); + } + catch (Exception ex) + { + StatusMessage = $"Erreur: {ex.Message}"; + } + finally + { + IsBusy = false; + } + } + + [RelayCommand] + public async Task DeleteAsync(CircleDto? circle) + { + if (circle is null) return; + IsBusy = true; + try + { + await _client.DeleteCircleAsync(circle.Id); + StatusMessage = $"Cercle « {circle.Name} » supprimé"; + // If the deleted circle was the selected one, + // clear the selection so the Members view goes + // empty too (the partial setter on + // SelectedCircle will reset Members). + if (SelectedCircle?.Id == circle.Id) + SelectedCircle = null; + await RefreshAsync(); + } + catch (Exception ex) + { + StatusMessage = $"Erreur: {ex.Message}"; + } + finally + { + IsBusy = false; + } + } + + + /// + /// Called by the view when the dialog confirms a + /// selection. Adds the picked user to the currently + /// selected circle and refreshes the members list. + /// + public async Task OnAddMemberConfirmedAsync(object? sender, UserSummary picked) + { + if (SelectedCircle is null || picked is null) return; + IsBusy = true; + try + { + await _client.AddMemberAsync(SelectedCircle.Id, picked.Id); + StatusMessage = $"« {picked.DisplayName} » ajouté au cercle"; + await LoadMembersAsync(SelectedCircle.Id); + } + catch (Exception ex) + { + // 409 (already a member) is a likely race — surface + // it as a friendly status, not an error. The + // server returns 409 for "already a member"; + // YavscApiClient surfaces that as an exception + // today; future refactors could route 409 into a + // typed result, but for now the message string is + // distinctive enough. + var msg = ex.Message.Contains("409") || ex.Message.Contains("Conflict") + ? "Déjà membre du cercle" + : $"Erreur: {ex.Message}"; + StatusMessage = msg; + } + finally + { + IsBusy = false; + } + } + + /// + /// Per-row "remove" command. Updates the local + /// collection in place so the UI doesn't flash. + /// + [RelayCommand] + public async Task RemoveMemberAsync(CircleMemberDto? member) + { + if (member is null || SelectedCircle is null) return; + IsBusy = true; + try + { + await _client.RemoveMemberAsync(SelectedCircle.Id, member.Id); + Members.Remove(member); + StatusMessage = $"« {member.UserName} » retiré du cercle"; + } + catch (Exception ex) + { + StatusMessage = $"Erreur: {ex.Message}"; + } + finally + { + IsBusy = false; + } + } +} diff --git a/src/PostIt/PostIt/ViewModels/CommandFormsPageViewModel.cs b/src/PostIt/PostIt/ViewModels/CommandFormsPageViewModel.cs new file mode 100644 index 00000000..71f5d67a --- /dev/null +++ b/src/PostIt/PostIt/ViewModels/CommandFormsPageViewModel.cs @@ -0,0 +1,135 @@ +using System; +using System.Collections.ObjectModel; +using System.Linq; +using System.Threading.Tasks; +using Avalonia; +using CommunityToolkit.Mvvm.ComponentModel; +using CommunityToolkit.Mvvm.Input; +using PostIt.Helpers; +using Yavsc.Abstract.Workflow; +using Yavsc.Api.Client; + +namespace PostIt.ViewModels; + +public partial class CommandFormsPageViewModel : ViewModelBase +{ + private readonly BillingApiClient _billingClient; + + public ActivityInfo Activity { get; } + public ActivityUserDisplayItem Performer { get; } + + [ObservableProperty] + public partial ObservableCollection Forms { get; set; } + + [ObservableProperty, NotifyCanExecuteChangedFor(nameof(OpenSelectedFormCommand)), NotifyCanExecuteChangedFor(nameof(OpenQueriesCommand)), NotifyCanExecuteChangedFor(nameof(OpenOngoingQueriesCommand))] + public partial CommandFormSummary? SelectedForm { get; set; } + + [ObservableProperty] + public partial string StatusMessage { get; set; } + + public string Title => $"Formulaires pour {Performer.UserName}"; + public string ContextLabel => $"{Activity.Name} · {Forms.Count} formulaire(s)"; + + public override bool CanNavigateNext + { + get => false; + protected set { _ = value; } + } + + public override bool CanNavigatePrevious + { + get => true; + protected set { _ = value; } + } + + public CommandFormsPageViewModel( + ActivityInfo activity, + ActivityUserDisplayItem performer, + BillingApiClient billingClient) + { + Activity = activity ?? throw new ArgumentNullException(nameof(activity)); + Performer = performer ?? throw new ArgumentNullException(nameof(performer)); + _billingClient = billingClient ?? throw new ArgumentNullException(nameof(billingClient)); + + Forms = new ObservableCollection((activity.Forms ?? new()) + .OrderBy(f => f.Title) + .ThenBy(f => f.ActionName)); + SelectedForm = Forms.FirstOrDefault(); + StatusMessage = Forms.Count == 0 + ? "Aucun formulaire n'est disponible pour cette activité." + : "Choisissez le formulaire à utiliser."; + } + + private bool CanOpenSelectedForm() => SelectedForm is not null; + + private bool CanOpenQueries() => SelectedForm is not null; + + private bool CanOpenOngoingQueries() => SelectedForm is not null; + + [RelayCommand(CanExecute = nameof(CanOpenSelectedForm))] + private async Task OpenSelectedFormAsync() + { + if (SelectedForm is null) + { + StatusMessage = "Sélectionnez un formulaire."; + return; + } + + var app = (App?)Application.Current; + if (app is null) + { + throw new InvalidOperationException("Application PostIt indisponible."); + } + + var vm = SelectedForm.CreateCommandPageViewModel( + Activity, Performer, _billingClient); + await vm!.InitializeAsync(); + await app.PushPageAsync(vm); + } + + [RelayCommand(CanExecute = nameof(CanOpenQueries))] + private async Task OpenQueriesAsync() + { + if (SelectedForm is null) + { + StatusMessage = "Sélectionnez un formulaire."; + return; + } + + var app = (App?)Application.Current; + if (app is null) + { + throw new InvalidOperationException("Application PostIt indisponible."); + } + + var vm = new BillingQueriesPageViewModel(Activity, Performer, SelectedForm, _billingClient); + await vm.InitializeAsync(); + await app.PushPageAsync(vm); + } + + [RelayCommand(CanExecute = nameof(CanOpenOngoingQueries))] + private async Task OpenOngoingQueriesAsync() + { + if (SelectedForm is null) + { + StatusMessage = "Sélectionnez un formulaire."; + return; + } + + var app = (App?)Application.Current; + if (app is null) + { + throw new InvalidOperationException("Application PostIt indisponible."); + } + + var vm = new BillingQueriesPageViewModel( + Activity, + Performer, + SelectedForm, + _billingClient, + isReadOnly: true, + ongoingOnly: true); + await vm.InitializeAsync(); + await app.PushPageAsync(vm); + } +} diff --git a/src/PostIt/PostIt/ViewModels/Commands/BillingCommandPageViewModel.cs b/src/PostIt/PostIt/ViewModels/Commands/BillingCommandPageViewModel.cs new file mode 100644 index 00000000..0ab76291 --- /dev/null +++ b/src/PostIt/PostIt/ViewModels/Commands/BillingCommandPageViewModel.cs @@ -0,0 +1,108 @@ +using System; +using System.Threading.Tasks; +using CommunityToolkit.Mvvm.ComponentModel; +using CommunityToolkit.Mvvm.Input; +using Yavsc; +using Yavsc.Abstract.Workflow; +using Yavsc.Api.Client; +using Yavsc.Models.Billing; + +namespace PostIt.ViewModels; + +public abstract partial class BillingCommandPageViewModel : RemoteViewModelBase +{ + protected readonly BillingApiClient _billingClient; + + public ActivityInfo Activity { get; } + public ActivityUserDisplayItem Performer { get; } + public CommandFormSummary Form { get; } + + [ObservableProperty] + public partial bool IsBusy { get; set; } + + [ObservableProperty] + public partial string StatusMessage { get; set; } + + [ObservableProperty] + public partial string Reason { get; set; } = string.Empty; + + + + [ObservableProperty] + public partial bool Consent { get; set; } = true; + + + [ObservableProperty] + public partial string AdditionalInfo { get; set; } = string.Empty; + + [ObservableProperty] + public partial long? ExistingQueryId { get; set; } + + [ObservableProperty] + public partial QueryStatus CommandStatus { get; set; } = QueryStatus.Inserted; + + public bool CanUseCurrentLocation => IsSupported && !IsBusy; + + public string Title => Form.Title; + public string PerformerLabel => Performer.UserName; + public string ActivityLabel => Activity.Name; + public virtual bool IsSupported => true; + public string BillingRoute => $"/billing/{Form.ActionName}"; + public bool IsEditingExisting => ExistingQueryId.HasValue; + public string SubmitLabel => IsEditingExisting ? "Mettre à jour la commande" : "Poster la commande"; + public virtual string SupportMessage => $"Le formulaire {Form.ActionName} n'est pas encore pris en charge dans PostIt."; + + public override bool CanNavigateNext + { + get => false; + protected set { _ = value; } + } + + public override bool CanNavigatePrevious + { + get => true; + protected set { _ = value; } + } + + public BillingCommandPageViewModel( + ActivityInfo activity, + ActivityUserDisplayItem performer, + CommandFormSummary form, + BillingApiClient billingClient) + { + Activity = activity ?? throw new ArgumentNullException(nameof(activity)); + Performer = performer ?? throw new ArgumentNullException(nameof(performer)); + Form = form ?? throw new ArgumentNullException(nameof(form)); + _billingClient = billingClient ?? throw new ArgumentNullException(nameof(billingClient)); + + StatusMessage = SupportMessage; + } + + partial void OnExistingQueryIdChanged(long? value) + { + OnPropertyChanged(nameof(IsEditingExisting)); + OnPropertyChanged(nameof(SubmitLabel)); + } + + partial void OnIsBusyChanged(bool value) + { + OnPropertyChanged(nameof(CanUseCurrentLocation)); + } + + public async Task InitializeAsync(BillingQueryDetailsDto? existingQuery = null) + { + await LoadAsync(); + if (existingQuery is not null) + { + ApplyExistingQuery(existingQuery); + return; + } + } + + protected abstract void ApplyExistingQuery(BillingQueryDetailsDto existingQuery); + + + + [RelayCommand] + protected abstract Task SubmitAsync(); +} diff --git a/src/PostIt/PostIt/ViewModels/Commands/BrushViewModel.cs b/src/PostIt/PostIt/ViewModels/Commands/BrushViewModel.cs new file mode 100644 index 00000000..d49fde80 --- /dev/null +++ b/src/PostIt/PostIt/ViewModels/Commands/BrushViewModel.cs @@ -0,0 +1,165 @@ +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.Net; +using System.Net.Http; +using System.Threading.Tasks; +using CommunityToolkit.Mvvm.ComponentModel; +using Yavsc.Abstract.Workflow; +using Yavsc.Api.Client; +using Yavsc.Models.Billing; +using Yavsc.Models.Haircut; +namespace PostIt.ViewModels.Commands; + +public partial class BrushViewModel : RdvViewModel +{ + public override string SupportMessage => "Choisissez une prestation coiffure puis postez la commande."; + + [ObservableProperty] + public partial ObservableCollection AvailablePrestations { get; set; } = new(); + + [ObservableProperty] + public partial HairPrestationDto? SelectedPrestation { get; set; } + + public BrushViewModel(ActivityInfo activity, ActivityUserDisplayItem performer, CommandFormSummary form, BillingApiClient billingClient) + : base(activity, performer, form, billingClient) + { + } + + public override async Task LoadAsync() + { + var prestations = await _billingClient.GetHairPrestationsAsync(Form.ActionName); + + AvailablePrestations = new ObservableCollection + (prestations ?? new List()); + + if (SelectedPrestation is null) + { + SelectedPrestation = AvailablePrestations.FirstOrDefault(); + } + + } + + protected override void ApplyExistingQuery(BillingQueryDetailsDto existingQuery) + { + base.ApplyExistingQuery(existingQuery); + + if (existingQuery.PrestationId is not null) + { + SelectedPrestation = AvailablePrestations.FirstOrDefault(x => x.Id == existingQuery.PrestationId.Value); + } + + IsBusy = true; + try + { + if (SelectedPrestation is null) + { + SelectedPrestation = AvailablePrestations.FirstOrDefault(); + } + + StatusMessage = AvailablePrestations.Count == 0 + ? "Aucune prestation coiffure disponible." + : SupportMessage; + } + catch (HttpRequestException ex) + when (ex.StatusCode is HttpStatusCode.Unauthorized or HttpStatusCode.Forbidden) + { + StatusMessage = "Accès refusé au catalogue de prestations (scope 'api'). Déconnectez puis reconnectez-vous."; + } + catch (Exception ex) + { + StatusMessage = $"Erreur lors du chargement des prestations: {ex.Message}"; + } + finally + { + IsBusy = false; + } + } + + protected override async Task SubmitAsync() + { + if (!Consent) + { + StatusMessage = "Le consentement est requis pour poster la commande."; + return; + } + + if (string.IsNullOrWhiteSpace(Address)) + { + StatusMessage = "L'adresse du rendez-vous est requise."; + return; + } + + if (SelectedPrestation is null) + { + StatusMessage = "Sélectionnez une prestation coiffure."; + return; + } + + IsBusy = true; + try + { + var address = Address.Trim(); + var locationPayload = BuildLocationPayload(address, Latitude, Longitude); + + var payload = new BillingQueryDetailsDto + { + Id = ExistingQueryId ?? 0, + BillingCode = Form.ActionName, + ActivityCode = Activity.Code, + PerformerId = Performer.PerformerId, + Consent = Consent, + EventDate = EventDate, + Status = CommandStatus, + Reason = Reason.Trim(), + AdditionalInfo = string.IsNullOrWhiteSpace(AdditionalInfo) ? string.Empty : AdditionalInfo.Trim(), + Location = new BillingLocationDto + { + Address = address, + Latitude = Latitude, + Longitude = Longitude, + } + }; + + payload.PrestationId = SelectedPrestation.Id; + + if (IsEditingExisting) + { + await _billingClient.UpdateAsync(Form.ActionName, ExistingQueryId!.Value, payload).ConfigureAwait(true); + } + else + { + await _billingClient.CreateAsync(Form.ActionName, new + { + ActivityCode = Activity.Code, + PerformerId = Performer.PerformerId, + Consent, + EventDate = (DateTime?)EventDate, + Location = locationPayload, + PrestationId = SelectedPrestation.Id, + AdditionalInfo = string.IsNullOrWhiteSpace(AdditionalInfo) ? null : AdditionalInfo.Trim(), + Status = payload.Status, + }).ConfigureAwait(true); + } + + StatusMessage = IsEditingExisting + ? $"Commande #{ExistingQueryId} mise à jour sur {BillingRoute} pour {Performer.UserName}." + : $"Commande transmise sur {BillingRoute} pour {Performer.UserName}."; + } + catch (HttpRequestException ex) + when (ex.StatusCode is HttpStatusCode.Unauthorized or HttpStatusCode.Forbidden) + { + StatusMessage = "Accès refusé au billing (scope 'api'). Déconnectez puis reconnectez-vous."; + } + catch (Exception ex) + { + StatusMessage = $"Erreur lors de l'envoi de la commande: {ex.Message}"; + } + finally + { + IsBusy = false; + } + + } +} diff --git a/src/PostIt/PostIt/ViewModels/Commands/MBrushViewModel.cs b/src/PostIt/PostIt/ViewModels/Commands/MBrushViewModel.cs new file mode 100644 index 00000000..793a7751 --- /dev/null +++ b/src/PostIt/PostIt/ViewModels/Commands/MBrushViewModel.cs @@ -0,0 +1,130 @@ +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.Net; +using System.Net.Http; +using System.Threading.Tasks; +using CommunityToolkit.Mvvm.ComponentModel; +using Yavsc.Abstract.Workflow; +using Yavsc.Api.Client; +using Yavsc.Models.Billing; + +namespace PostIt.ViewModels.Commands; + +public partial class MBrushViewModel : BrushViewModel +{ + public override string SupportMessage => "Choisissez une ou plusieurs prestations coiffure puis postez la commande."; + + [ObservableProperty] + public partial ObservableCollection MultiPrestations { get; set; } = new(); + + public MBrushViewModel(ActivityInfo activity, ActivityUserDisplayItem performer, CommandFormSummary form, BillingApiClient billingClient) + : base(activity, performer, form, billingClient) + { + } + + public override async Task LoadAsync() + { + await base.LoadAsync().ConfigureAwait(true); + MultiPrestations = new ObservableCollection( + AvailablePrestations.Select(SelectableHairPrestationItem.FromDto)); + } + + protected override void ApplyExistingQuery(BillingQueryDetailsDto existingQuery) + { + base.ApplyExistingQuery(existingQuery); + + var selectedIds = existingQuery.PrestationIds is null + ? new HashSet() + : new HashSet(existingQuery.PrestationIds); + + foreach (var item in MultiPrestations) + { + item.IsSelected = selectedIds.Contains(item.Id); + } + } + + protected override async Task SubmitAsync() + { + if (!Consent) + { + StatusMessage = "Le consentement est requis pour poster la commande."; + return; + } + + if (string.IsNullOrWhiteSpace(Address)) + { + StatusMessage = "L'adresse du rendez-vous est requise."; + return; + } + + var selectedPrestations = MultiPrestations.Where(x => x.IsSelected).ToList(); + if (selectedPrestations.Count == 0) + { + StatusMessage = "Sélectionnez au moins une prestation coiffure."; + return; + } + + IsBusy = true; + try + { + var address = Address.Trim(); + var locationPayload = BuildLocationPayload(address, Latitude, Longitude); + + var payload = new BillingQueryDetailsDto + { + Id = ExistingQueryId ?? 0, + BillingCode = Form.ActionName, + ActivityCode = Activity.Code, + PerformerId = Performer.PerformerId, + Consent = Consent, + EventDate = EventDate, + Status = CommandStatus, + Reason = Reason.Trim(), + Location = new BillingLocationDto + { + Address = address, + Latitude = Latitude, + Longitude = Longitude, + }, + PrestationIds = selectedPrestations.Select(x => x.Id).ToList(), + }; + + if (IsEditingExisting) + { + await _billingClient.UpdateAsync(Form.ActionName, ExistingQueryId!.Value, payload).ConfigureAwait(true); + } + else + { + await _billingClient.CreateAsync(Form.ActionName, new + { + ActivityCode = Activity.Code, + PerformerId = Performer.PerformerId, + Consent, + EventDate = EventDate, + Location = locationPayload, + Prestations = selectedPrestations.Select(x => new { PrestationId = x.Id }).ToList(), + Status = payload.Status, + }).ConfigureAwait(true); + } + + StatusMessage = IsEditingExisting + ? $"Commande #{ExistingQueryId} mise à jour sur {BillingRoute} pour {Performer.UserName}." + : $"Commande transmise sur {BillingRoute} pour {Performer.UserName}."; + } + catch (HttpRequestException ex) + when (ex.StatusCode is HttpStatusCode.Unauthorized or HttpStatusCode.Forbidden) + { + StatusMessage = "Accès refusé au billing (scope 'api'). Déconnectez puis reconnectez-vous."; + } + catch (Exception ex) + { + StatusMessage = $"Erreur lors de l'envoi de la commande: {ex.Message}"; + } + finally + { + IsBusy = false; + } + } +} diff --git a/src/PostIt/PostIt/ViewModels/Commands/RdvViewModel.cs b/src/PostIt/PostIt/ViewModels/Commands/RdvViewModel.cs new file mode 100644 index 00000000..c2ff3294 --- /dev/null +++ b/src/PostIt/PostIt/ViewModels/Commands/RdvViewModel.cs @@ -0,0 +1,211 @@ +using System; +using System.Net; +using System.Net.Http; +using System.Threading.Tasks; +using CommunityToolkit.Mvvm.ComponentModel; +using CommunityToolkit.Mvvm.Input; +using PostIt.Services; +using Yavsc.Abstract.Workflow; +using Yavsc.Api.Client; + +namespace PostIt.ViewModels.Commands; + +public partial class RdvViewModel : BillingCommandPageViewModel +{ + public override string SupportMessage => "Complétez les informations du rendez-vous puis postez la commande."; + + [ObservableProperty] + public partial string Address { get; set; } = string.Empty; + + [ObservableProperty] + public partial double? Latitude { get; set; } + + [ObservableProperty] + public partial double? Longitude { get; set; } + + + [ObservableProperty] + public partial DateTime EventDate { get; set; } + + public RdvViewModel(ActivityInfo activity, ActivityUserDisplayItem performer, CommandFormSummary form, BillingApiClient billingClient) + : base(activity, performer, form, billingClient) + { + EventDate = DateTime.Now.AddDays(1); + } + + protected override void ApplyExistingQuery(BillingQueryDetailsDto existingQuery) + { + ExistingQueryId = existingQuery.Id; + CommandStatus = existingQuery.Status; + Consent = existingQuery.Consent; + Reason = existingQuery.Reason ?? string.Empty; + AdditionalInfo = existingQuery.AdditionalInfo ?? string.Empty; + + if (existingQuery.EventDate is not null) + { + EventDate = existingQuery.EventDate.Value + .ToLocalTime(); + } + + if (existingQuery.Location is not null) + { + Address = existingQuery.Location.Address ?? string.Empty; + Latitude = existingQuery.Location.Latitude; + Longitude = existingQuery.Location.Longitude; + } + + StatusMessage = $"Commande #{existingQuery.Id} chargée."; + } + + [RelayCommand(CanExecute = nameof(CanUseCurrentLocation))] + private async Task UseCurrentLocationAsync() + { + if (!CanUseCurrentLocation) + { + return; + } + + IsBusy = true; + try + { + var result = await Platform.TryGetCurrentLocationAsync(default).ConfigureAwait(true); + if (!result.IsSuccess || !result.Latitude.HasValue || !result.Longitude.HasValue) + { + StatusMessage = result.Message; + return; + } + + Latitude = result.Latitude.Value; + Longitude = result.Longitude.Value; + StatusMessage = string.IsNullOrWhiteSpace(Address) + ? "Position récupérée. Complétez l'adresse puis envoyez la commande." + : result.Message; + } + catch (OperationCanceledException) + { + StatusMessage = "La récupération de la position a été annulée."; + } + catch (Exception ex) + { + StatusMessage = $"Impossible de récupérer la position: {ex.Message}"; + } + finally + { + IsBusy = false; + } + } + + protected static object BuildLocationPayload(string address, double? latitude, double? longitude) + { + if (latitude.HasValue && longitude.HasValue) + { + return new + { + Address = address, + Latitude = latitude.Value, + Longitude = longitude.Value, + }; + } + + return new + { + Address = address, + }; + } + + + protected override async Task SubmitAsync() + { + if (!IsSupported) + { + StatusMessage = SupportMessage; + return; + } + + if (!Consent) + { + StatusMessage = "Le consentement est requis pour poster la commande."; + return; + } + + if (string.IsNullOrWhiteSpace(Address)) + { + StatusMessage = "L'adresse du rendez-vous est requise."; + return; + } + + + if (string.IsNullOrWhiteSpace(Reason)) + { + StatusMessage = "Le motif du rendez-vous est requis."; + return; + } + + + + IsBusy = true; + try + { + var address = Address.Trim(); + var locationPayload = BuildLocationPayload(address, Latitude, Longitude); + + var payload = new BillingQueryDetailsDto + { + Id = ExistingQueryId ?? 0, + BillingCode = Form.ActionName, + ActivityCode = Activity.Code, + PerformerId = Performer.PerformerId, + Consent = Consent, + EventDate = EventDate, + Status = CommandStatus, + Reason = Reason.Trim(), + AdditionalInfo = string.IsNullOrWhiteSpace(AdditionalInfo) ? string.Empty : AdditionalInfo.Trim(), + Location = new BillingLocationDto + { + Address = address, + Latitude = Latitude, + Longitude = Longitude, + } + }; + + if (IsEditingExisting) + { + await _billingClient.UpdateAsync(Form.ActionName, ExistingQueryId!.Value, payload).ConfigureAwait(true); + } + else + { + await _billingClient.CreateAsync(Form.ActionName, new + { + ActivityCode = Activity.Code, + PerformerId = Performer.PerformerId, + Consent, + EventDate = EventDate, + Location = locationPayload, + Reason = payload.Reason, + Status = payload.Status, + }).ConfigureAwait(true); + } + + StatusMessage = IsEditingExisting + ? $"Commande #{ExistingQueryId} mise à jour sur {BillingRoute} pour {Performer.UserName}." + : $"Commande transmise sur {BillingRoute} pour {Performer.UserName}."; + } + catch (HttpRequestException ex) when (ex.StatusCode is HttpStatusCode.Unauthorized or HttpStatusCode.Forbidden) + { + StatusMessage = "Accès refusé au billing (scope 'api'). Déconnectez puis reconnectez-vous."; + } + catch (Exception ex) + { + StatusMessage = $"Erreur lors de l'envoi: {ex.Message}"; + } + finally + { + IsBusy = false; + } + } + + public override Task LoadAsync() + { + return Task.CompletedTask; + } +} diff --git a/src/PostIt/PostIt/ViewModels/HomePageViewModel.cs b/src/PostIt/PostIt/ViewModels/HomePageViewModel.cs index 8d5b3a17..830be4dd 100644 --- a/src/PostIt/PostIt/ViewModels/HomePageViewModel.cs +++ b/src/PostIt/PostIt/ViewModels/HomePageViewModel.cs @@ -1,11 +1,17 @@ -using PostIt; +using System; +using System.Threading.Tasks; +using Avalonia; +using CommunityToolkit.Mvvm.Input; +using Microsoft.Extensions.DependencyInjection; +using PostIt.Helpers; using PostIt.Services; -using PostIt.ViewModels; +namespace PostIt.ViewModels; public class HomePageViewModel : ViewModelBase { public YavscApiClient Api { get; } public Settings Settings { get; } + public SessionStatusViewModel SessionStatus { get; } private string _welcomeText = "Welcome to PostIt!"; public string WelcomeText @@ -17,10 +23,29 @@ public class HomePageViewModel : ViewModelBase public override bool CanNavigateNext { get => true; protected set => throw new System.NotImplementedException(); } public override bool CanNavigatePrevious { get => false; protected set => throw new System.NotImplementedException(); } - public HomePageViewModel(YavscApiClient api, Settings settings) + public HomePageViewModel(YavscApiClient api, Settings settings, SessionStatusViewModel sessionStatus) { Api = api; Settings = settings; + SessionStatus = sessionStatus; + + OpenActivities = new AsyncRelayCommand(OpenActivitiesAsync); + + } + public IAsyncRelayCommand OpenBlogs { get; } = new AsyncRelayCommand(App.PushBlogsPageAsync); + public IAsyncRelayCommand OpenActivities { get; } + + private async Task OpenActivitiesAsync() + { + var app = (App?)Application.Current; + var vm = app?.ServiceProvider?.GetRequiredService(); + if (app is null || vm is null) + { + throw new InvalidOperationException("Activities page is not available."); + } + + await vm.RefreshAsync(); + await app.PushPageAsync(vm); } /// @@ -32,5 +57,8 @@ public class HomePageViewModel : ViewModelBase /// (thread-safe dispatcher marshalling on PropertyChanged) — a /// designer-only duplicate instance is therefore harmless. /// - public HomePageViewModel() : this(null!, new Settings()) { } + public HomePageViewModel() : this(null!, new Settings(), new SessionStatusViewModel()) + { + + } } diff --git a/src/PostIt/PostIt/ViewModels/MainPageViewModel.cs b/src/PostIt/PostIt/ViewModels/MainViewModel.cs similarity index 52% rename from src/PostIt/PostIt/ViewModels/MainPageViewModel.cs rename to src/PostIt/PostIt/ViewModels/MainViewModel.cs index e7ea26a0..f56b666d 100644 --- a/src/PostIt/PostIt/ViewModels/MainPageViewModel.cs +++ b/src/PostIt/PostIt/ViewModels/MainViewModel.cs @@ -2,14 +2,17 @@ using System; using System.Collections.ObjectModel; using System.Linq; using System.Threading.Tasks; +using Avalonia; using CommunityToolkit.Mvvm.ComponentModel; using CommunityToolkit.Mvvm.Input; -using PostIt.Models; -using PostIt.Services; +using Microsoft.Extensions.DependencyInjection; +using Yavsc.Blogspot; +using Yavsc.Api.Client; +using PostIt.Helpers; namespace PostIt.ViewModels; -public partial class MainPageViewModel : ViewModelBase +public partial class MainViewModel : ViewModelBase { /// Window/tab title. Cosmetic — bound by /// MainPage.axaml if at all. Not the post title. @@ -24,7 +27,7 @@ public partial class MainPageViewModel : ViewModelBase /// previous "{Binding SelectedPost.Title}" binding, the user's /// keystrokes were silently dropped whenever /// SelectedPost was null, which made the editor a trap - /// and caused Save to POST a BlogPost with an empty + /// and caused Save to POST a BlogPostDto with an empty /// title — hence the 400 "The Title field is required". [ObservableProperty] public partial string DraftTitle { get; set; } @@ -34,9 +37,18 @@ public partial class MainPageViewModel : ViewModelBase [ObservableProperty] public partial string DraftArticle { get; set; } + /// Editor buffer for the post's publication state. + /// Reflects the server-side IsPublished flag (the + /// existence of a row in BlogSpotPublication) and + /// is pushed to the server via + /// on explicit + /// toggle — it is NOT included in the regular Save + /// payload, mirroring the wire contract where + /// BlogPostDto doesn't carry Publish as a + /// mutable field. Toggling is its own action. [ObservableProperty] - public partial ViewModelBase? CurrentViewModel { get; set; } - + public partial bool DraftIsPublished { get; set; } + public bool IsLoaded { get; private set; } public Settings SettingsModel { get; } [ObservableProperty] @@ -46,13 +58,13 @@ public partial class MainPageViewModel : ViewModelBase public partial string SearchText { get; set; } [ObservableProperty] - public partial ObservableCollection Posts { get; set; } + public partial ObservableCollection Posts { get; set; } [ObservableProperty] - public partial ObservableCollection FilteredPosts { get; set; } + public partial ObservableCollection FilteredPosts { get; set; } [ObservableProperty] - public partial BlogPost? SelectedPost { get; set; } + public partial BlogPostDto? SelectedPost { get; set; } [ObservableProperty] public partial bool IsBusy { get; set; } @@ -60,93 +72,12 @@ public partial class MainPageViewModel : ViewModelBase [ObservableProperty] public partial Settings Settings { get; private set; } - /// - /// API surface that hits the Yavsc.Blogs deployment at - /// . Owned and constructed by - /// App.axaml.cs so the same client (and its token store) - /// is shared with the login flow. - /// - public BlogApiClient? BlogClient { get; } - - public override bool CanNavigateNext { get => throw new NotImplementedException(); protected set => throw new NotImplementedException(); } - public override bool CanNavigatePrevious { get => throw new NotImplementedException(); protected set => throw new NotImplementedException(); } - - - public MainPageViewModel() - { - Init(null); - SettingsModel = new Settings(); - BlogClient = null; - } - - private void Init(Settings? settings) - { - SearchText = string.Empty; - Posts = new ObservableCollection(); - FilteredPosts = new ObservableCollection(); - SelectedPost = null; - IsBusy = false; - StatusMessage = "Ready"; - // Production path: DI injects the canonical Settings singleton - // and we use it as-is. Test path: tests call this constructor - // without a Settings argument; we fall back to a fresh - // instance so the fixture can build a self-contained VM. - // The previous "?? new Settings()" silently worked in prod - // too, which is what allowed a second Settings instance to - // race the singleton and crash the postit://callback binding - // sink; that crash is fixed in Settings.OnPropertyChanged - // (thread-safe dispatcher marshalling) so the duplicate - // instance is now merely wasteful, not dangerous. - Settings = settings ?? new Settings(); - WindowTitle = "PostIt"; - DraftTitle = string.Empty; - DraftArticle = string.Empty; - CurrentViewModel = this; - } - - /// - /// Test-friendly constructor: caller supplies a pre-built - /// . Production code uses the - /// (Settings, BlogApiClient) overload below. - /// - public MainPageViewModel(BlogApiClient blogClient, Settings? settings = null) - { - SettingsModel = new Settings(); - BlogClient = blogClient ?? throw new ArgumentNullException(nameof(blogClient));; - - Init(settings); - } - - partial void OnSearchTextChanged(string value) => ApplyFilter(); - - partial void OnSelectedPostChanged(BlogPost? value) - { - // Mirror the selection into the editor buffer so the - // XAML-bound TextBox/TextEditor show the right content - // when the user clicks a post in the list. When the - // selection is cleared (e.g. after a successful create - // rebinds to the server-issued record, or Delete - // nulls it out), the buffer is reset so the editor - // doesn't show stale content. - DraftTitle = value?.Title ?? string.Empty; - DraftArticle = value?.Article ?? string.Empty; - UpdateCommandStates(); - } - - partial void OnIsBusyChanged(bool value) => UpdateCommandStates(); - - // Save's CanExecute depends on the buffer: the button must - // enable as soon as the user has typed a non-whitespace - // title, regardless of whether a post is selected. - partial void OnDraftTitleChanged(string value) => SaveCommand.NotifyCanExecuteChanged(); - partial void OnDraftArticleChanged(string value) => SaveCommand.NotifyCanExecuteChanged(); - [RelayCommand] - internal async Task LoadPosts() + internal async Task RefreshAsync() { await ExecuteAsync(async () => { - var posts = await BlogClient.GetPostsAsync(); + var posts = await BlogClient!.GetPostsAsync(); Posts.Clear(); foreach (var post in posts.OrderByDescending(p => p.DateModified)) { @@ -158,10 +89,13 @@ public partial class MainPageViewModel : ViewModelBase } [RelayCommand] - internal void Search() => ApplyFilter(); + internal async Task SearchAsync() { + await RefreshAsync(); + ApplyFilter(); + } [RelayCommand] - internal async Task Save() + internal async Task SaveAsync() { // The button is already disabled when the title is empty // (see CanSave), but the test path (and any programmatic @@ -176,7 +110,7 @@ public partial class MainPageViewModel : ViewModelBase await ExecuteAsync(async () => { - // Build a fresh BlogPost from the editor buffer on + // Build a fresh BlogPostDto from the editor buffer on // every Save — we no longer mutate SelectedPost in // place. The previous behaviour copied the buffer // (which was a no-op when SelectedPost was null) @@ -188,14 +122,15 @@ public partial class MainPageViewModel : ViewModelBase // the update path. if (SelectedPost is null || SelectedPost.Id == 0) { - var draft = new BlogPost + var draft = new BlogPostDto { Title = DraftTitle, Article = DraftArticle ?? string.Empty, DateCreated = DateTime.UtcNow, DateModified = DateTime.UtcNow, + IsPublished = DraftIsPublished }; - var created = await BlogClient.CreatePostAsync(draft); + var created = await BlogClient!.CreatePostAsync(draft); if (created is not null) { SelectedPost = created; @@ -204,7 +139,7 @@ public partial class MainPageViewModel : ViewModelBase } else { - var update = new BlogPost + var update = new BlogPostDto { Id = SelectedPost.Id, AuthorId = SelectedPost.AuthorId, @@ -214,7 +149,7 @@ public partial class MainPageViewModel : ViewModelBase DateCreated = SelectedPost.DateCreated, DateModified = DateTime.UtcNow, }; - await BlogClient.UpdatePostAsync(SelectedPost.Id, update); + await BlogClient!.UpdatePostAsync(SelectedPost.Id, update); StatusMessage = $"Saved post {SelectedPost.Id}."; } @@ -223,7 +158,7 @@ public partial class MainPageViewModel : ViewModelBase } [RelayCommand] - internal async Task Delete() + internal async Task DeleteAsync() { if (SelectedPost is null || SelectedPost.Id == 0) { @@ -233,22 +168,277 @@ public partial class MainPageViewModel : ViewModelBase await ExecuteAsync(async () => { - await BlogClient.DeletePostAsync(SelectedPost.Id); + await BlogClient!.DeletePostAsync(SelectedPost.Id); StatusMessage = $"Deleted post {SelectedPost.Id}."; SelectedPost = null; await RefreshPostsAsync(); }); } - [RelayCommand] - internal void OpenSettings() + /// + /// Toggle the publication state of the currently selected + /// post. Pushes the new state to + /// PUT /api/BlogApi/{id}/publish and reflects it + /// locally in + the + /// selected post so the UI updates without a full + /// refresh. + /// + /// The toggle is its own action — separate from Save + /// — because Publish is not part of the + /// BlogPostDto payload. Bundling it into Save + /// would require a wire-shape change and a second server + /// overload; the dedicated endpoint keeps the wire + /// contract clean. + /// + public async Task SetPublishStateAsync(bool publish) { - CurrentViewModel = SettingsModel; + if (SelectedPost is null || SelectedPost.Id == 0) + { + StatusMessage = "Sélectionnez un billet existant pour changer sa publication."; + return; + } + + await ExecuteAsync(async () => + { + // The checkbox updates DraftIsPublished before the command is + // executed. Using the current bound value avoids the + // double-toggle bug in which the UI has already flipped the + // state and the command flips it again. + await BlogClient!.SetPublishAsync(SelectedPost.Id, publish); + DraftIsPublished = publish; + // Mirror into the selected post so a subsequent + // RefreshPostsAsync() doesn't blow away the + // locally flipped state until the round-trip + // re-hydrates it. + SelectedPost.IsPublished = publish; + StatusMessage = publish + ? $"Billet {SelectedPost.Id} publié." + : $"Billet {SelectedPost.Id} remis en brouillon."; + }); } + [RelayCommand] + internal async Task TogglePublishAsync() + { + await SetPublishStateAsync(DraftIsPublished); + } + + /// + /// DEV ONLY: open the signature capture page. The production + /// entry point is a SignalR push from Yavsc.Org ("devis + /// received, sign here"); this command is the dev-time + /// shortcut to reach the page without that infrastructure. + /// Aligned on the same VM-first navigation pattern as + /// : the VM resolves the target VM + /// through , the ViewLocator picks + /// the matching Control at bind time. No + /// Click handler, no App.ServiceProvider + /// access from the view layer. + /// + [RelayCommand] + internal async Task OpenSignatureDevAsync() + { + await ((App)App.Current!).PushPageAsync(SignatureModel).ConfigureAwait(true); + } + + + [RelayCommand(CanExecute = nameof(CanManageAcl))] + public async Task ManageAclAsync() + { + if (SelectedPost is null) + { + StatusMessage = "Select an existing post before managing ACL."; + return; + } + + var postForAcl = SelectedPost; + try + { + var detailed = await BlogClient!.GetPostAsync(SelectedPost.Id).ConfigureAwait(true); + if (detailed is not null) + { + postForAcl = detailed; + SelectedPost = detailed; + } + } + catch + { + // Keep the dialog usable even if the detail refresh fails. + } + + await ((App)App.Current!).PushPageAsync(GetACLViewModel(postForAcl)).ConfigureAwait(true); + } + + [RelayCommand] + public async Task OpenCirclesAsync() + { + var circlesVm = ResolveServices().GetRequiredService(); + await ((App)App.Current!).PushPageAsync(circlesVm).ConfigureAwait(true); + } + + private ViewModelBase GetACLViewModel(BlogPostDto selectedPost) + { + var sp = ResolveServices(); + var aclClient = sp.GetRequiredService(); + var circleClient = sp.GetRequiredService(); + return new PostAclDialogViewModel(selectedPost, aclClient, circleClient); + } + + /// + /// API surface that hits the Yavsc.Blogs deployment at + /// . Owned and constructed by + /// App.axaml.cs so the same client (and its token store) + /// is shared with the login flow. + /// + public BlogApiClient? BlogClient { get; } + + /// + /// DI container the VM uses to resolve navigation targets + /// (other ViewModels) when the user clicks a toolbar button + /// that opens a sub-screen. Owned by App.ServiceProvider + /// in production; injected directly in tests. The VM resolves + /// ViewModels via this provider, never Views — the + /// actual to push is decided by + /// at bind time, per CONTRIBUTING.md + /// §"Navigation (PostIt)". + /// + public IServiceProvider? Services { get; } + + private SignaturePageViewModel? _signatureModel; + + /// + /// Resolved on first access. Lazy so the test path (which + /// never pushes SignaturePage) does not require a + /// fully-built DI graph just to construct the VM. Mirrors the + /// pattern of for the Settings case. + /// + public SignaturePageViewModel SignatureModel => + _signatureModel ??= ResolveSignatureModel(); + + public override bool CanNavigateNext { get => throw new NotImplementedException(); protected set => throw new NotImplementedException(); } + public override bool CanNavigatePrevious { get => throw new NotImplementedException(); protected set => throw new NotImplementedException(); } + + private SignaturePageViewModel ResolveSignatureModel() + { + var sp = ResolveServices(); + return sp.GetRequiredService(); + } + + private IServiceProvider ResolveServices() + { + return Services ?? (Application.Current as App)?.ServiceProvider ?? + throw new InvalidOperationException( + "No IServiceProvider available for navigation. Inject one in tests " + + "or ensure App.ServiceProvider is initialized in production."); + } + + + public MainViewModel() + { + SettingsModel = new Settings(); + Init(SettingsModel); + BlogClient = null; + } + + private void Init(Settings? settings) + { + Posts = new ObservableCollection(); + FilteredPosts = new ObservableCollection(); + SelectedPost = null; + IsBusy = false; + StatusMessage = "Ready"; + Settings = settings ?? new Settings(); + SearchText = Settings.SearchText; + WindowTitle = "PostIt"; + DraftTitle = string.Empty; + DraftArticle = string.Empty; + DraftIsPublished = false; + IsLoaded = false; + // Production path: DI injects the canonical Settings singleton + // and we use it as-is. Test path: tests call this constructor + // without a Settings argument; we fall back to a fresh + // instance so the fixture can build a self-contained VM. + // The previous "?? new Settings()" silently worked in prod + // too, which is what allowed a second Settings instance to + // race the singleton and crash the postit://callback binding + // sink; that crash is fixed in Settings.OnPropertyChanged + // (thread-safe dispatcher marshalling) so the duplicate + // instance is now merely wasteful, not dangerous. + + Settings.PropertyChanged += (s, e) => + { + if (e.PropertyName == nameof(Settings.SearchText)) + { + SearchText = Settings.SearchText; + ApplyFilter(); + } + }; + + } + + /// Save is enabled as soon as the user has typed + /// a non-whitespace title in the editor, regardless of + /// whether a post is selected. The "no selection" case is + /// the create-new-post path; the "with selection" case is + /// the update path. Both read from the editor buffer. + /// Previously this also required SelectedPost is not null + /// — which contradicted the create-new-post intent and + /// forced the buggy "draft with empty title" branch. + private bool CanSave() => !IsBusy && !string.IsNullOrWhiteSpace(DraftTitle); + private bool CanDelete() => SelectedPost is not null && SelectedPost.Id != 0 && !IsBusy; + private bool CanManageAcl() => SelectedPost is not null && SelectedPost.Id != 0 && !IsBusy; + + /// + /// Test-friendly constructor: caller supplies a pre-built + /// . Production code uses the + /// (Settings, BlogApiClient) overload below. + /// + public MainViewModel(BlogApiClient blogClient, Settings? settings = null, IServiceProvider? services = null) + { + SettingsModel = new Settings(); + BlogClient = blogClient ?? throw new ArgumentNullException(nameof(blogClient)); ; + Services = services; + Init(settings); + } + + partial void OnSearchTextChanged(string value) + { + if (Settings is not null && Settings.SearchText != value) + { + Settings.SearchText = value; + } + ApplyFilter(); + } + + partial void OnSelectedPostChanged(BlogPostDto? value) + { + // Mirror the selection into the editor buffer so the + // XAML-bound TextBox/TextEditor show the right content + // when the user clicks a post in the list. When the + // selection is cleared (e.g. after a successful create + // rebinds to the server-issued record, or Delete + // nulls it out), the buffer is reset so the editor + // doesn't show stale content. + DraftTitle = value?.Title ?? string.Empty; + DraftArticle = value?.Article ?? string.Empty; + // Mirror publication state too. Defaults to false on + // null selection so a fresh draft starts unpublished. + DraftIsPublished = value?.IsPublished ?? false; + UpdateCommandStates(); + } + + partial void OnIsBusyChanged(bool value) => UpdateCommandStates(); + + // Save's CanExecute depends on the buffer: the button must + // enable as soon as the user has typed a non-whitespace + // title, regardless of whether a post is selected. + partial void OnDraftTitleChanged(string value) => SaveCommand.NotifyCanExecuteChanged(); + partial void OnDraftArticleChanged(string value) => SaveCommand.NotifyCanExecuteChanged(); + + private async Task RefreshPostsAsync() { - var posts = await BlogClient.GetPostsAsync(); + var posts = await BlogClient!.GetPostsAsync(); Posts.Clear(); foreach (var post in posts.OrderByDescending(p => p.DateModified)) { @@ -301,19 +491,18 @@ public partial class MainPageViewModel : ViewModelBase private void UpdateCommandStates() { - LoadPostsCommand.NotifyCanExecuteChanged(); + RefreshCommand.NotifyCanExecuteChanged(); SaveCommand.NotifyCanExecuteChanged(); DeleteCommand.NotifyCanExecuteChanged(); } - /// Save is enabled as soon as the user has typed - /// a non-whitespace title in the editor, regardless of - /// whether a post is selected. The "no selection" case is - /// the create-new-post path; the "with selection" case is - /// the update path. Both read from the editor buffer. - /// Previously this also required SelectedPost is not null - /// — which contradicted the create-new-post intent and - /// forced the buggy "draft with empty title" branch. - private bool CanSave() => !IsBusy && !string.IsNullOrWhiteSpace(DraftTitle); - private bool CanDelete() => SelectedPost is not null && SelectedPost.Id != 0 && !IsBusy; + + internal async Task InitializeAsync() + { + if (!IsLoaded) + { + await RefreshAsync(); + IsLoaded = true; + } + } } diff --git a/src/PostIt/PostIt/ViewModels/PostAclDialogViewModel.cs b/src/PostIt/PostIt/ViewModels/PostAclDialogViewModel.cs new file mode 100644 index 00000000..60544606 --- /dev/null +++ b/src/PostIt/PostIt/ViewModels/PostAclDialogViewModel.cs @@ -0,0 +1,225 @@ +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.Net; +using System.Threading.Tasks; +using CommunityToolkit.Mvvm.ComponentModel; +using CommunityToolkit.Mvvm.Input; +using Yavsc.Blogspot; +using Yavsc.Api.Client; +using Yavsc.Api.Client.Dtos; +using Yavsc.Abstract.BlogSpot; +using Yavsc.Abstract.Identity.Security; +using System.Net.Http; + +namespace PostIt.ViewModels; + +public sealed class PostAclEntry +{ + public long CircleId { get; init; } + public string CircleName { get; init; } = string.Empty; +} + +/// +/// View model for the "Gérer l'ACL" modal of a single blog post. +/// +/// Loads the caller's circles once on construct (the dropdown +/// only shows circles the user owns), then keeps an in-memory list +/// of the ACL entries for the post. / +/// are the only mutating verbs; both +/// refresh the list afterwards so the UI stays in sync with the +/// server. +/// +/// The server is the source of truth: it scopes every +/// endpoint to the caller's uid and rejects ACL grants on posts +/// the caller doesn't own. This VM does not re-validate that — +/// any 403 / 404 will surface as an exception caught by the +/// command and routed to . +/// +public partial class PostAclDialogViewModel : ViewModelBase +{ + private readonly BlogAclApiClient _aclClient; + private readonly CircleApiClient _circleClient; + + /// The post whose ACL is being edited. Set by the + /// caller (MainPage) when opening the dialog. + public BlogPostDto Post { get; } + + [ObservableProperty] + public partial ObservableCollection + MyCircles { get; set; } = new(); + + [ObservableProperty] + public partial ObservableCollection + AclEntries { get; set; } = new(); + + [ObservableProperty] + public partial CircleDto? SelectedCircleToAdd { get; set; } + + [ObservableProperty] + public partial bool IsBusy { get; set; } + + [ObservableProperty] + public partial string StatusMessage { get; set; } = string.Empty; + + /// + /// Idempotency gate for : the dialog + /// attaches the load trigger in DataContextChanged, + /// which can fire more than once if the page is detached + /// and re-attached (dialog re-use, navigation edge cases) + /// with a different VM. Without this guard, the second load + /// would race against the first and could overwrite + /// mid-edit. Pattern copied from + /// Settings.Load. + /// + private bool _loaded; + + /// True once has run at least + /// once. Exposed for tests; do not bind from XAML. + public bool Loaded => _loaded; + + public PostAclDialogViewModel( + BlogPostDto post, + BlogAclApiClient aclClient, + CircleApiClient circleClient) + { + Post = post ?? throw new ArgumentNullException(nameof(post)); + _aclClient = aclClient ?? throw new ArgumentNullException(nameof(aclClient)); + _circleClient = circleClient ?? throw new ArgumentNullException(nameof(circleClient)); + + AclEntries = new ObservableCollection(post.GetACL().Select(a => ToAclEntry(a.CircleId))); + SelectedCircleToAdd = null; + } + + public override bool CanNavigateNext { get => throw new NotImplementedException(); protected set => throw new NotImplementedException(); } + public override bool CanNavigatePrevious { get => throw new NotImplementedException(); protected set => throw new NotImplementedException(); } + + [RelayCommand] + public async Task LoadAsync() + { + if (_loaded) return; + + IsBusy = true; + try + { + // Load circles for the picker. ACL entries come from the + // BlogPostDto detail payload (source of truth for initial state). + var circlesTask = _circleClient.GetMyCirclesAsync(); + await Task.WhenAll(circlesTask); + + var circles = circlesTask.Result ?? new List(); + MyCircles = new ObservableCollection(circles); + + // Resolve labels now that circles are available. + AclEntries = new ObservableCollection(AclEntries.Select(a => ToAclEntry(a.CircleId))); + + + StatusMessage = $"{AclEntries.Count} autorisation(s)"; + _loaded = true; + } + catch (Exception ex) + { + StatusMessage = $"Erreur: {ex.Message}"; + } + finally + { + IsBusy = false; + } + } + + [RelayCommand] + public async Task AddAsync() + { + if (SelectedCircleToAdd is null) + { + StatusMessage = "Sélectionnez un cercle à ajouter"; + return; + } + + IsBusy = true; + try + { + if (AclEntries.Any(a => a.CircleId == SelectedCircleToAdd.Id)) + { + StatusMessage = $"Cercle « {SelectedCircleToAdd.Name} » déjà autorisé"; + return; + } + + var created = await _aclClient.GrantAsync(new PostAccessControlRulePayload + { + CircleId = SelectedCircleToAdd.Id, + BlogPostId = Post.Id + }); + if (created is not null) + { + AclEntries.Add(ToAclEntry(created.CircleId)); + StatusMessage = $"Cercle « {SelectedCircleToAdd.Name} » autorisé"; + } + else + { + StatusMessage = "Autorisation refusée par le serveur"; + } + } + catch (HttpRequestException ex) when (ex.StatusCode == HttpStatusCode.Conflict) + { + // Conflict means the link already exists in backend. Resync + // from the dedicated ACL API so the UI reflects server truth. + await ReloadAclEntriesFromServerAsync(); + StatusMessage = $"Cercle « {SelectedCircleToAdd.Name} » déjà autorisé"; + } + catch (Exception ex) + { + StatusMessage = $"Erreur: {ex.Message}"; + } + finally + { + IsBusy = false; + } + } + + [RelayCommand] + public async Task RevokeAsync(PostAclEntry? acl) + { + if (acl is null) return; + IsBusy = true; + try + { + await _aclClient.RevokeAsync(acl.CircleId); + var existing = AclEntries.FirstOrDefault(e => e.CircleId == acl.CircleId); + if (existing is not null) + AclEntries.Remove(existing); + StatusMessage = "Autorisation révoquée"; + } + catch (Exception ex) + { + StatusMessage = $"Erreur: {ex.Message}"; + } + finally + { + IsBusy = false; + } + } + + private async Task ReloadAclEntriesFromServerAsync() + { + var allAcl = await _aclClient.GetMyAclAsync(); + var currentPostAcl = (allAcl ?? new List()) + .Where(a => a.BlogPostId == Post.Id) + .Select(a => ToAclEntry(a.CircleId)) + .GroupBy(a => a.CircleId) + .Select(g => g.First()) + .ToList(); + AclEntries = new ObservableCollection(currentPostAcl); + } + + private PostAclEntry ToAclEntry(long circleId) + { + var circleName = MyCircles.FirstOrDefault(c => c.Id == circleId)?.Name; + return new PostAclEntry + { + CircleId = circleId, + CircleName = string.IsNullOrWhiteSpace(circleName) ? $"Cercle #{circleId}" : circleName + }; + } +} diff --git a/src/PostIt/PostIt/ViewModels/RemoteViewModelBase.cs b/src/PostIt/PostIt/ViewModels/RemoteViewModelBase.cs new file mode 100644 index 00000000..0229cca4 --- /dev/null +++ b/src/PostIt/PostIt/ViewModels/RemoteViewModelBase.cs @@ -0,0 +1,10 @@ +using System.Threading.Tasks; + +namespace PostIt.ViewModels; + +public abstract class RemoteViewModelBase : ViewModelBase +{ + public abstract Task LoadAsync(); + + +} diff --git a/src/PostIt/PostIt/ViewModels/SelectableHairPrestationItem.cs b/src/PostIt/PostIt/ViewModels/SelectableHairPrestationItem.cs new file mode 100644 index 00000000..ee07bb97 --- /dev/null +++ b/src/PostIt/PostIt/ViewModels/SelectableHairPrestationItem.cs @@ -0,0 +1,22 @@ +using CommunityToolkit.Mvvm.ComponentModel; +using Yavsc.Models.Haircut; + +namespace PostIt.ViewModels; + +public partial class SelectableHairPrestationItem : ObservableObject +{ + public long Id { get; init; } + public string Title { get; init; } = string.Empty; + public string Details { get; init; } = string.Empty; + + [ObservableProperty] + public partial bool IsSelected { get; set; } + + public static SelectableHairPrestationItem FromDto(HairPrestationDto dto) + => new() + { + Id = dto.Id, + Title = dto.Title, + Details = dto.Details, + }; +} \ No newline at end of file diff --git a/src/PostIt/PostIt/ViewModels/SessionStatusViewModel.cs b/src/PostIt/PostIt/ViewModels/SessionStatusViewModel.cs index 55f2cab4..f2496b85 100644 --- a/src/PostIt/PostIt/ViewModels/SessionStatusViewModel.cs +++ b/src/PostIt/PostIt/ViewModels/SessionStatusViewModel.cs @@ -2,6 +2,8 @@ using System; using System.Threading.Tasks; using CommunityToolkit.Mvvm.ComponentModel; using CommunityToolkit.Mvvm.Input; +using Microsoft.Extensions.DependencyInjection; +using PostIt.Helpers; using PostIt.Services; namespace PostIt.ViewModels; @@ -32,15 +34,6 @@ public partial class SessionStatusViewModel : ViewModelBase /// HomePage so the user lands on the blog editor. public event System.Action? LoginSucceeded; - /// Raised when the user clicks the "Paramètres" button on - /// the session banner. App.axaml.cs listens and pushes - /// SettingsPage (resolved from DI, bound to the canonical - /// Settings singleton) on top of the current navigation - /// stack. Same event pattern as and - /// so the VM stays decoupled from - /// NavigationPage / window lifetime. - public event System.Action? OpenSettingsRequested; - [ObservableProperty] public partial bool IsLoggedIn { get; private set; } @@ -144,9 +137,10 @@ public partial class SessionStatusViewModel : ViewModelBase } [RelayCommand] - public async System.Threading.Tasks.Task OpenSettingsCommand() + internal async Task OpenSettings() { - OpenSettingsRequested?.Invoke(); - await System.Threading.Tasks.Task.CompletedTask; + var app = (App)App.Current!; + await app.PushPageAsync(app.ServiceProvider!.GetRequiredService()).ConfigureAwait(true); } + } diff --git a/src/PostIt/PostIt/Settings/AuthenticationSettings.cs b/src/PostIt/PostIt/ViewModels/Settings/AuthenticationSettings.cs similarity index 90% rename from src/PostIt/PostIt/Settings/AuthenticationSettings.cs rename to src/PostIt/PostIt/ViewModels/Settings/AuthenticationSettings.cs index ad71063b..8034820d 100644 --- a/src/PostIt/PostIt/Settings/AuthenticationSettings.cs +++ b/src/PostIt/PostIt/ViewModels/Settings/AuthenticationSettings.cs @@ -10,7 +10,7 @@ public partial class AuthenticationSettings : ObservableObject /// hand-off in /// (RFC 8252 §7.1). Production Desktop builds use this. /// - public const string DefaultDesktopRedirectUri = "postit://callback"; + public const string DesktopRedirectUri = "postit://callback"; /// /// Redirect URI used by the Android app. The corresponding IntentFilter @@ -18,9 +18,12 @@ public partial class AuthenticationSettings : ObservableObject /// public const string AndroidRedirectUri = "android://postit-signin"; - public static string DefaultAuthority { get; internal set; } = "https://yavsc.pschneider.fr"; + public const string DefaultAuthority = "https://yavsc.pschneider.fr"; + + public const string DefaultClientId = "postit"; + + public static readonly string[] DefaultScopes = { "blogs" }; - public static string DefaultClientId { get; internal set; } = "postit"; [ObservableProperty] public partial string Authority { get; set; } @@ -31,15 +34,19 @@ public partial class AuthenticationSettings : ObservableObject [ObservableProperty] public partial string[] Scopes { get; set; } - /// - /// OAuth redirect URI. Defaults to + /// OAuth redirect URI. Defaults to /// (custom URI scheme) which is the right answer for desktop /// production builds. Mobile platforms must set this to /// before calling LoginAsync. /// [ObservableProperty] - public partial string RedirectUri { get; set; } = DefaultDesktopRedirectUri; + public partial string RedirectUri { get; set; } +#if ANDROID + = AndroidRedirectUri; +#else + = DesktopRedirectUri; +#endif /// /// Space-separated view of . Exists for the diff --git a/src/PostIt/PostIt/ViewModels/Settings.cs b/src/PostIt/PostIt/ViewModels/Settings/Settings.cs similarity index 79% rename from src/PostIt/PostIt/ViewModels/Settings.cs rename to src/PostIt/PostIt/ViewModels/Settings/Settings.cs index 5bd3a844..e63f0b32 100644 --- a/src/PostIt/PostIt/ViewModels/Settings.cs +++ b/src/PostIt/PostIt/ViewModels/Settings/Settings.cs @@ -2,12 +2,11 @@ using System.Runtime.CompilerServices; using CommunityToolkit.Mvvm.ComponentModel; using CommunityToolkit.Mvvm.Input; using IdentityModel.OidcClient; -using Microsoft.Extensions.DependencyInjection; using System; using System.Collections.Generic; using System.IO; +using System.Net.Http; using System.Text.Json; -using System.Threading; [assembly: InternalsVisibleTo("PostIt.Tests")] @@ -17,70 +16,6 @@ public partial class Settings : ViewModelBase { const string SettingsFileName = "postit-settings.json"; - /// - /// Redirect URI used by the Android app. The corresponding IntentFilter - /// in PostIt.Android/Properties/AndroidManifest.xml must match. - /// - public const string AndroidRedirectUri = "android://postit-signin"; - - - - /// - /// Process-wide canonical instance, wired up - /// at application boot by - /// through . The hybrid pattern: - /// - /// The static Current reference gives - /// ViewModels a non-DI way to reach the same instance (and lets - /// the framework bindings push notifications through one stable - /// ). - /// Tests that want to exercise a clean - /// instance still call new Settings(); Current - /// stays null in those contexts because - /// is never invoked. - /// Reads () are - /// thread-safe and never allocate; mutations always go through - /// the DI-resolved singleton so two threads cannot each register - /// a different "current" Settings. - /// - /// - private static Settings? s_current; - - /// - /// Wire the canonical Settings instance to a DI container. Called - /// exactly once from App.axaml.cs after the singleton has - /// been registered. Subsequent calls are no-ops: the DI container - /// owns the instance lifetime and we don't want a stray - /// BindToServiceProvider in a test fixture to silently - /// rebind the production instance. - /// - public static void BindToServiceProvider(IServiceProvider services) - { - if (services is null) throw new ArgumentNullException(nameof(services)); - Interlocked.CompareExchange(ref s_current, - services.GetService() ?? throw new InvalidOperationException( - "Settings is not registered in the DI container."), - null); - } - - /// - /// Returns the canonical Settings instance previously bound through - /// , or null when called - /// outside a running Avalonia application (tests, CLI tools). - /// - public static Settings? GetCurrent() => Volatile.Read(ref s_current); - - /// - /// Resolve the canonical Settings instance or throw. Use this in - /// production code paths that must not silently fall back to a - /// freshly-constructed (which used to be - /// the root cause of the postit://callback crash: two Settings - /// instances racing on PropertyChanged from different threads). - /// - public static Settings RequireCurrent() => - GetCurrent() ?? throw new InvalidOperationException( - "Settings.Current is not bound. Call App.OnFrameworkInitializationCompleted first."); - [ObservableProperty] public partial AuthenticationSettings Authentication { get; set; } = new(); @@ -91,14 +26,17 @@ public partial class Settings : ViewModelBase public partial string BlogsApiUrl { get; set; } = "https://blogs.pschneider.fr/api/v1/"; [ObservableProperty] - public partial string BusinessApiUrl { get; set; } = "https://business.pschneider.fr/api/v1/"; + public partial string ApiUrl { get; set; } = "https://api.pschneider.fr/api/v1/"; + + [ObservableProperty] + public partial string SearchText { get; set; } = string.Empty; /// /// Catch top-level mutations: the four ObservableProperty /// setters above all funnel through here, and we flip /// in lock-step. Sub-property mutations /// (e.g. Authentication.Authority) are caught by the - /// subscription wired up in + /// subscription wired up in /// below. disables the flag during bulk /// hydration so the disk load itself does not count as a user /// edit. @@ -107,7 +45,8 @@ public partial class Settings : ViewModelBase partial void OnDarkModeChanged(bool value) => MarkDirty(); partial void OnBlogsApiUrlChanged(string value) => MarkDirty(); - partial void OnBusinessApiUrlChanged(string value) => MarkDirty(); + partial void OnApiUrlChanged(string value) => MarkDirty(); + partial void OnSearchTextChanged(string value) => MarkDirty(); /// /// Authentication can be reassigned wholesale by @@ -178,10 +117,20 @@ public partial class Settings : ViewModelBase RedirectUri = Authentication.RedirectUri, Scope = string.Join(' ', MergeScopes(this.Authentication.Scopes)), TokenClientCredentialStyle = IdentityModel.Client.ClientCredentialStyle.PostBody, - PostLogoutRedirectUri = "https//yavsc.pschneider.fr", + PostLogoutRedirectUri = Authentication.Authority, // PKCE is enabled by default when no client_secret is provided. }; + if (IsDevelopmentEnvironment()) + { + // Dev only: allow local/self-signed TLS for discovery/token + // endpoints when the machine does not trust a custom root. + options.BackchannelHandler = new HttpClientHandler + { + ServerCertificateCustomValidationCallback = (_, _, _, _) => true + }; + } + if (browser is not null) options.Browser = browser; @@ -205,7 +154,10 @@ public partial class Settings : ViewModelBase { "openid", // OIDC: required for the id_token "profile", // OIDC: standard profile claims - "offline_access" // OIDC: required to receive a refresh_token + "offline_access", // OIDC: required to receive a refresh_token + "blogs", + "api" + }; /// @@ -231,6 +183,14 @@ public partial class Settings : ViewModelBase } } + private static bool IsDevelopmentEnvironment() + { + return string.Equals( + Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT"), + "Development", + StringComparison.OrdinalIgnoreCase); + } + internal void Load() { if (Loaded) return; @@ -331,18 +291,25 @@ public partial class Settings : ViewModelBase var settings = JsonSerializer.Deserialize(json); if (settings is null) { - Console.Error.WriteLine($"🩎 Settings payload is invalid (source: {source})."); - return; + UseDefaultSettings(); } // Apply under the gate so concurrent Load() callers cannot // see half the new values / half the old ones. The actual // PropertyChanged fan-out is handled by [ObservableProperty]'s // setters which we route through SetProperty → OnPropertyChanged // → our overridden dispatcher-safe marshaller below. - lock (_mutationGate) + else lock (_mutationGate) { + var legacyApiUrl = TryReadLegacyApiUrl(json); this.Authentication = settings.Authentication; this.DarkMode = settings.DarkMode; + this.BlogsApiUrl = !string.IsNullOrWhiteSpace(settings.BlogsApiUrl) + ? settings.BlogsApiUrl + : legacyApiUrl ?? this.BlogsApiUrl; + this.ApiUrl = !string.IsNullOrWhiteSpace(settings.ApiUrl) + ? settings.ApiUrl + : this.ApiUrl; + this.SearchText = settings.SearchText ?? string.Empty; if (!(settings.Authentication is null)) { this.Authentication = new AuthenticationSettings(); @@ -351,8 +318,13 @@ public partial class Settings : ViewModelBase this.Authentication.ClientId = string.IsNullOrWhiteSpace(settings.Authentication.ClientId) ? AuthenticationSettings.DefaultClientId : settings.Authentication.ClientId; this.Authentication.RedirectUri = string.IsNullOrWhiteSpace(settings.Authentication.RedirectUri) ? - AuthenticationSettings.DefaultDesktopRedirectUri : settings.Authentication.RedirectUri; - this.Authentication.Scopes = settings.Authentication.Scopes; + AuthenticationSettings.DesktopRedirectUri : settings.Authentication.RedirectUri; + if (settings.Authentication.Scopes is null || settings.Authentication.Scopes.Length == 0) + { + settings.Authentication.Scopes = AuthenticationSettings.DefaultScopes; + } + else + this.Authentication.Scopes = settings.Authentication.Scopes; } } // A disk load (or an embedded-resource fallback) is the @@ -381,6 +353,41 @@ public partial class Settings : ViewModelBase } } + private static string? TryReadLegacyApiUrl(string json) + { + try + { + using var doc = JsonDocument.Parse(json); + if (doc.RootElement.TryGetProperty("ApiUrl", out var apiUrl) + && apiUrl.ValueKind == JsonValueKind.String) + { + return apiUrl.GetString(); + } + } + catch + { + // Ignore legacy payload parse errors: normal deserialization + // already reports actionable diagnostics to the caller. + } + + return null; + } + + private void UseDefaultSettings() + { + this.Authentication = new AuthenticationSettings + { + Authority = AuthenticationSettings.DefaultAuthority, + ClientId = AuthenticationSettings.DefaultClientId, + RedirectUri = AuthenticationSettings.DesktopRedirectUri, + Scopes = AuthenticationSettings.DefaultScopes + }; + this.DarkMode = false; + this.BlogsApiUrl = "https://blogs.pschneider.fr/api/v1/"; + this.ApiUrl = "https://api.pschneider.fr/api/v1/"; + this.SearchText = string.Empty; + } + /// /// Persist the current in-memory state to /// ~/.config/PostIt/postit-settings.json (Linux) / diff --git a/src/PostIt/PostIt/ViewModels/ViewModelBase.cs b/src/PostIt/PostIt/ViewModels/ViewModelBase.cs index 93019360..30783764 100644 --- a/src/PostIt/PostIt/ViewModels/ViewModelBase.cs +++ b/src/PostIt/PostIt/ViewModels/ViewModelBase.cs @@ -1,12 +1,10 @@ -using Avalonia.Styling; using CommunityToolkit.Mvvm.ComponentModel; namespace PostIt.ViewModels; -public abstract partial class ViewModelBase : ObservableObject +public abstract class ViewModelBase : ObservableObject { - - /// + /// /// Gets if the user can navigate to the next page /// public abstract bool CanNavigateNext { get; protected set; } diff --git a/src/PostIt/PostIt/Views/ActivitiesPage.axaml b/src/PostIt/PostIt/Views/ActivitiesPage.axaml new file mode 100644 index 00000000..16d88344 --- /dev/null +++ b/src/PostIt/PostIt/Views/ActivitiesPage.axaml @@ -0,0 +1,147 @@ + + + + + + + + +