Compare commits

...
Author SHA1 Message Date
4bca36906e optimisation of workflows : Skiasharp deps already installed
All checks were successful
Forgejo Release / release (push) Successful in 5m35s
2026-09-19 16:37:57 +01:00
4b7ac2dec8 test(blogs): configure SiteSettings.Blog in MappedClaimsBlogsWebServerFixture
BlogSpotService's constructor throws InvalidOperationException
("SiteSettings.Blog is not configured.") when IOptions<SiteSettings>.Blog
is null, so every request to BlogApiController 500'd resolving the
service — all 3 BlogApiMappedClaimsTests were failing with
InternalServerError.

The mapped-claims fixture never configured SiteSettings (the main
BlogsWebServerFixture does, pointing Blog at a per-run temp dir).
Mirror that: Configure<SiteSettings>(s => s.Blog = <temp dir>)
before AddScoped<BlogSpotService>(). These tests are JSON-only
(AttachFiles short-circuits), but the service must be constructible.

Verified: BlogApiMappedClaimsTests 3/3 green; full Yavsc.Blogs.Tests
37/37 green.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-09-19 14:14:28 +01:00
92af3c0428 build: disable StaticWebAssets cache to stop MSB4018 race
DefineStaticWebAssets.ReadOrCreateCache opens the *.dswa.cache.json
files under obj/.../ via File.OpenRead with no try/catch, so under
parallel solution builds a sharing-violation / TOCTOU race on the cache
file escapes as MSB4018 and fails the whole build (seen on
Yavsc.Blogs during the rc15 solution build).

Set StaticWebAssetsCacheDefineStaticWebAssetsEnabled=false so
CacheManifestPath is empty and ReadOrCreateCache short-circuits to a
no-file-I/O path. The cache is a pure build-speed optimization; no
effect on output correctness, only on incremental rebuild speed of the
wwwroot-light web projects.

Verified: Yavsc.Api (transitive web deps) and Yavsc.Blogs.Tests build
clean, and zero *.dswa.cache.json files are produced.

Refs:
  https://source.dot.net/Microsoft.NET.Sdk.StaticWebAssets.Tasks/DefineStaticWebAssets.Cache.cs.html
  https://github.com/dotnet/sdk/issues/49039

Co-Authored-By: Claude <noreply@anthropic.com>
2026-09-19 13:53:25 +01:00
5470924cdb changelog: add 1.0.8-rc15 entry
Cover the 60 commits since 1.0.8-rc14: blog attachments + Markdown
preview, the Estimate pipeline (list/edition/validation + API + EF
migrations), provider ongoing requests, file-ACL and genericEstimate
migrations, POSTIT_SETTINGS_JSON, billing filtered by user, shared
YavscMessageSender, Gitleaks CI, and the test stabilization wave.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-09-19 12:56:02 +01:00
289626bd89 preview the Markdown 2026-09-18 19:45:35 +01:00
f038c08276 +MarkdownViewer 2026-09-18 13:58:31 +01:00
98be57f798 post the file 2026-09-18 13:38:42 +01:00
64df506f3d corrige la création du lien 2026-09-18 12:13:00 +01:00
6a1bd23ca5 test: cover BlogApiClient.CreateMultipartContent shape + server round-trip
Expose CreateMultipartContent as public so the blogs backend tests can
assert on its wire shape directly and round-trip it through the live
BlogsWebServerFixture host. New CreateMultipartContentTests:
- shape: blog part is camelCase JSON with WhenWritingNull, one file
  part per attachment (filename, Content-Type, octet-stream fallback);
- round-trip: POST the built body to /api/v1/blogspot, assert 201
  Created + attachment row + file landed under BlogFilesRoot.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-09-18 11:39:45 +01:00
74cfa10b6b -Config.Temp 2026-09-18 11:13:44 +01:00
3160eada93 refacto site settings 2026-09-17 23:54:36 +01:00
af5c1a3e92 BlogAttachmentLinkTests 2026-09-17 00:57:52 +01:00
4d17a39258 Supprime un faux message d'erreur 2026-09-16 19:48:13 +01:00
6ae814ef8a better indications 2026-09-16 18:53:17 +01:00
2787939ad7 new defaults 2026-09-16 18:23:52 +01:00
07a2986769 code cleanup 2026-09-16 18:23:42 +01:00
8bf6f20048 fixes the upload 2026-09-16 18:23:27 +01:00
eb22e4a5ab Estimate lists 2026-09-15 00:19:23 +01:00
6e92c57c1d install native dependencies 2026-09-14 10:07:10 +01:00
cdd963e8b7 fixes the pipeline 2026-09-14 00:47:28 +01:00
812a3301e7 removes the ItemGroup.Using Include=Xunit 2026-09-14 00:40:30 +01:00
c6d75f1d77 build before testing (sunit not found by MSBuild task) 2026-09-14 00:02:54 +01:00
d172f00c5b Merge remote-tracking branch 'origin/main' into feat/files-control 2026-09-13 23:39:41 +01:00
99a8707504 The Estimate is validated 2026-09-13 23:29:06 +01:00
027c0e1a03 Estimate UI 2026-09-13 18:54:27 +01:00
9550f9fe2d better and simpler UI 2026-09-13 17:51:42 +01:00
3cb98f6603 POSTIT_SETTINGS_JSON env var 2026-09-13 13:34:39 +01:00
37300206fb list only my billing codes 2026-09-13 03:49:07 +01:00
3003e6fe93 take the scanning in account 2026-09-13 03:25:09 +01:00
ee373f81dc use Sqlite 2026-09-13 03:22:22 +01:00
9a77209304 got saved a RdvQuery 2026-09-13 03:09:12 +01:00
9cae5b1f55 tests en vert 2026-09-12 17:31:18 +01:00
128735a237 fixe tests 2026-09-12 16:49:36 +01:00
9f55ef84da GetOpenIdConfiguration_returns_ok against testing host 2026-09-12 14:30:50 +01:00
80f9040ac3 Use a shared YavscMessageSender 2026-09-12 13:57:25 +01:00
bcf36709d7 Add provider ongoing requests flow and sort persistence 2026-09-12 13:29:49 +01:00
9d3e4c8b78 generic estimate 2026-09-12 12:59:44 +01:00
4b2e2a1c08 fixes the tests 2026-09-11 18:37:28 +01:00
4a28bc63f9 MainPage => BlogsPage 2026-09-11 18:37:26 +01:00
15317207c6 Bad test, fix the test 2026-09-11 18:37:25 +01:00
1e0dc07a2c Test the release, don't ignore test return code 2026-09-11 18:37:24 +01:00
69d404bc49 Bad test, fix the test 2026-09-11 13:42:29 +01:00
2cd5c6b68a Test the release, don't ignore test return code 2026-09-11 13:25:32 +01:00
2ee8b3dbec implements a dico 2026-09-11 12:45:13 +01:00
7bd169bf61 We don't need these "release" branches 2026-09-11 11:01:46 +01:00
78721a34de user the CommandBar 2026-09-07 20:53:23 +01:00
d3392f1e08 db testing 2026-09-07 20:02:56 +01:00
b356c17a2c Removes an abusive assertion, that went wrong 2026-09-07 19:16:23 +01:00
7b4538b03a Post Files 2026-09-07 15:41:33 +01:00
cf5c2f4b39 code reorg 2026-09-07 14:39:53 +01:00
17fd68b474 code format 2026-09-07 14:12:34 +01:00
82b5d06230 scan the commit 2026-09-07 13:20:50 +01:00
ed456ab3d1 Gitleaks integration 2026-09-07 12:56:48 +01:00
867d756a26 cleanup 2026-09-07 12:28:24 +01:00
f079165212 test 2026-09-07 12:20:55 +01:00
e877a59606 picket scan 2026-09-07 12:08:57 +01:00
5bd0e998a2 Secret scan 2026-09-07 11:57:00 +01:00
e2d1953faf CircleAuthorizationToFile EF migration 2026-09-07 11:02:41 +01:00
31a723f5fa unique email handling 2026-09-07 10:58:20 +01:00
92aa68c03c code reorg 2026-09-07 10:30:45 +01:00
223 changed files with 28449 additions and 2130 deletions

View file

@ -19,18 +19,19 @@ on:
required: false
type: boolean
push:
branches: [ "main" ]
branches: [ "main", "release/*", "hotfix/*", "fix/*" ]
pull_request:
branches: [ "main", "release/*" ]
branches: [ "main", "release/*", "hotfix/*", "fix/*" ]
jobs:
build:
runs-on: docker
container:
image: pazof/yavsc-build-env:debian13-dotnet10-android36-jdk21-v1
image: pazof/yavsc-build-env:debian13-dotnet10-android36-jdk21-v2
steps:
- name: Clone yavsc
run: |
set -e
cd /src
git clone https://forgejo.pschneider.fr/notazof/yavsc.git _src
cd _src
@ -40,12 +41,17 @@ jobs:
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: Secret scan
run: |
echo "🔍 Scanning for secrets..."
cd /src/_src && dotnet tool restore && dotnet picket git --verbose --redact --exit-code 1 --log-opts -n10 \
- name: Build
run: |
echo "🏗️ Building the solution..."
cd /src/_src && dotnet build --verbosity normal
- name: Test
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 ($?)!"
--filter="Category!=Platform-Android"

View file

@ -52,7 +52,7 @@ jobs:
release:
runs-on: docker
container:
image: pazof/yavsc-build-env:debian13-dotnet10-android36-jdk21-v1
image: pazof/yavsc-build-env:debian13-dotnet10-android36-jdk21-v2
steps:
- name: Clone du repo au tag demandé
env:
@ -200,6 +200,7 @@ jobs:
RELEASE_BODY: ${{ env.RELEASE_BODY }}
IS_PRERELEASE: ${{ env.IS_PRERELEASE }}
run: |
set -e
if [[ -z "$TAG" ]]; then
echo "::error::No tag resolved for the API call."
exit 1

45
.gitleaksignore Normal file
View file

@ -0,0 +1,45 @@
# Exclure uniquement les dossiers de sortie de compilation
bin/
obj/
src/*/bin/
src/*/obj/
test/*/bin/
test/*/obj/
# Toolchain front (Node / esbuild)
node_modules/
build/
package-lock.json
# Exclure les caches lourds
.git/
.vs/
.env
.*.env
*.csproj.lscache
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
tmp/
DataDir/
*.tests.trx
*.tests.html
*.log

27
.vscode/launch.json vendored
View file

@ -4,6 +4,22 @@
// Pour plus d'informations, visitez : https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "PostIt Desktop",
"type": "dotnet",
"request": "launch",
"projectPath": "${workspaceFolder}/src/PostIt/PostIt.Desktop/PostIt.Desktop.csproj"
},
{
"name": "PostIt Desktop local",
"type": "coreclr",
"request": "launch",
"program": "${workspaceFolder}/src/PostIt/PostIt.Desktop/bin/Debug/net10.0/PostIt.Desktop.dll",
"env": {
"POSTIT_SETTINGS_JSON": "/home/paul/Workspace/yavsc/src/PostIt/PostIt/postit-settings.json"
},
"preLaunchTask": "dotnet: build-postit-desktop"
},
{
"name": "Android Debug",
"type": "mono",
@ -20,10 +36,10 @@
"port": 55555
},
{
"name": "API",
"name": "Yavsc API",
"type": "dotnet",
"request": "launch",
"projectPath": "${workspaceFolder}/src/Api/Api.csproj"
"projectPath": "${workspaceFolder}/src/Yavsc.Api/Yavsc.Api.csproj"
},
{
"name": "Yavsc Org",
@ -37,12 +53,7 @@
"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",

42
.vscode/tasks.json vendored
View file

@ -47,7 +47,10 @@
"group": "build",
"isBuildCommand": true,
"isTestCommand": false,
"isBackground": true
"isBackground": true,
"options": {
"cwd": "${workspaceFolder}"
}
},
{
"label": "test blogs backend",
@ -63,6 +66,28 @@
"isDefault": false
}
},
{
"label": "test api backend (npgsql)",
"type": "process",
"problemMatcher": "$msCompile",
"command": "dotnet",
"args": [
"test",
"Yavsc.Api.Test.csproj",
"-v",
"minimal"
],
"options": {
"cwd": "src/Yavsc.Api.Test",
"env": {
"YAVSC_API_TEST_DB_PROVIDER": "npgsql"
}
},
"group": {
"kind": "test",
"isDefault": false
}
},
{
"label": "build-webapi",
"type": "process",
@ -76,6 +101,21 @@
"kind": "build"
},
"isBackground": true
},
{
"label": "dotnet: build-postit-desktop",
"type": "process",
"isBuildCommand": true,
"isTestCommand": false,
"isBackground": true,
"command": "dotnet",
"args": ["build", "/property:GenerateFullPaths=true"],
"options": {
"cwd": "src/PostIt/PostIt.Desktop"
},
"group": {
"kind": "build"
}
}
]
}

View file

@ -1,5 +1,45 @@
# Changelog
## [1.0.8-rc15] - unstable
### Added
* [PostIt] Saisie et envoi de pieces jointes sur un billet de blog: le client monte les fichiers en `multipart/form-data` lors du `Save`, ajoute un lien Markdown par piece jointe a l'article, puis re-PUT le billet. Une collection `DraftAttachments` porte les fichiers en cours d'edition.
* [PostIt] Apercu Markdown dans l'editeur de blogs (integration `MarkdownViewer.Core`) avec bascule edition/preview sur `BlogsPage`.
* [PostIt] Gestion des devis: page de liste `EstimateListPage` (vues client et prestataire), page d'edition `EstimateEditionPage` avec lignes de devis (`EstimateLineItemViewModel`), et flux de validation d'un devis.
* [PostIt] Flux des requetes en cours cote prestataire (`ProviderOngoingRequestsPage`) avec tri persistant.
* [Yavsc.Api] Endpoints devis `GET /api/v1/estimate/asclient` et `GET /api/v1/estimate/asprovider` pour lister les devis en cours selon le role.
* [Yavsc.Api] Endpoint `GET /api/v1/billing/provider/ongoing` et `POST /api/v1/billing/prosign/{billingCode}/{id}` pour le flux prestataire.
* [Yavsc.Api.Client] `EstimateApiClient` + DTOs (`EstimateDto`, `EstimateLineDto`) pour le pipeline devis cote client lourd.
* [Yavsc.Api.Client] Reprise de l'upload de fichiers blog dans `BlogApiClient` (`CreateMultipartContent`, `BlogUploadFile`) — la meme forme filaire que PostIt utilise en production.
* [Yavsc.Abstract] `FileServerUrlHelpers` pour deriver les URLs publiques des fichiers utilisateur depuis l'autorite OIDC (alignement sur `UserFilesPath`).
* [Yavsc.Server] `BlogSpotService.AttachFiles` : ecrit les pieces jointes sous la racine des fichiers utilisateur (`{UserFilesDirName}/{user}/blogs/{postId}/{fileName}`).
* [Yavsc.Blogs] `BlogApiController` accepte `multipart/form-data` (champ `blog` + parts `file`) sur `POST` et `PUT /api/v1/blogspot`, en plus du payload JSON existant.
* [PostIt] Variable d'environnement `POSTIT_SETTINGS_JSON` pour surcharger les parametres au lancement (utile en CI/test).
* [Yavsc.Server] Migration EF `fileACL`: `CircleAuthorizationToFile` gagne `OwnerId` + `Access` et un graphe proprieetaire, base du controle d'acces fichier par cercle.
* [Yavsc.Server] Migration EF `genericEstimate`: `Estimate.Query` passe de `RdvQuery` a `NominativeServiceCommand?` pour supporter des devis non lies a un RDV.
* [Yavsc.Server] Migrations EF `NominativeServiceCommand` et `AddHairCutQueryLocationId` (localisation de la coupe).
* [CI] Integration du scan de secrets Gitleaks dans le pipeline Forgejo + `.gitleaksignore`.
* [Tests] Non-regressions: round-trip multipart blog (`BlogApiTests`, `CreateMultipartContentTests` forme + serveur), `BlogAttachmentLinkTests`, `FileServerUrlHelpersTests`, `EstimateApiControllerTests`, VMs `EstimateList`/`EstimateEdition`/`ProviderOngoingRequests`, `BillingControllerTests` (filtrage par utilisateur), `GetOpenIdConfiguration` contre l'hote de test.
### Changed
* [PostIt] Renommage `MainPage` -> `BlogsPage` (et `PushMainPageAsync` -> `PushBlogsPageAsync`) pour refletter le role de la page.
* [PostIt] Refacto des `SiteSettings` : reorganisation des parametres, nouvelles valeurs par defaut, et indications plus claires dans les `appsettings`.
* [Yavsc.Api] `BillingController` ne liste plus que les codes billing de l'utilisateur authentifie (filtre par `UserId`), au lieu de l'ensemble des requetes prestataire.
* [Yavsc.Api] Mutualisation d'un `YavscMessageSender` partage dans l'hote API (au lieu d'une instance par controller).
* [Yavsc.Org] La detection du doublon d'email a l'inscription utilise desormais le code erreur generic `DbException` 23505 (fournisseur-agnostique) au lieu de `PostgresException`, pour rester correct en test SQLite.
* [PostIt] `YavscApiClient` tolere les corps vides (`204 No Content` sur `PUT /blogspot/{id}`) au lieu de lever un `JsonException`.
* [CI] Le pipeline compile avant les tests, installe les dependances natives, et retire le `ItemGroup.Using Include=Xunit` superflu.
### Fixed
* [PostIt] Suppression d'un faux message d'erreur affiche apres un `PUT /blogspot/{id}` reussi (204 traite comme succes, plus comme une reponse vide invalide).
* [PostIt] Correction de la creation des liens de pieces jointes (`TryAppendAttachmentLinks`) : segment proprietaire et chemin `blogs/{id}/{fileName}` alignes sur ce que `AttachFiles` ecrit reellement.
* [Yavsc.Blogs] Correction de l'upload / de la persistance des pieces jointes (`FileSystemHelpers` + `BlogApiController` multipart).
* [Tests] Stabilisation des suites: seeds billing avec metadonnees d'audit, `GetOpenIdConfiguration_returns_ok` contre l'hote de test, retraits d'assertions abusives, tests SQLite verts.
* [PostIt] Nettoyage de fichiers temporaires accidentels et ignore des repertoires `tmp` dans le depot.
## [1.0.8-rc14] - unstable
### Added

View file

@ -2,5 +2,16 @@
<PropertyGroup>
<RootNamespace>Yavsc</RootNamespace>
<NoWarn>NU1701, NU1901, NU1902, NU1507</NoWarn>
<!-- Disable the StaticWebAssets build cache (the *.dswa.cache.json
files written under obj/.../ by DefineStaticWebAssets).
ReadOrCreateCache opens them with File.OpenRead and no
try/catch, so under parallel solution builds a sharing
violation / TOCTOU race on the cache file escapes as
MSB4018 and fails the whole build (seen on Yavsc.Blogs
during the rc15 solution build). The cache is a pure
build-speed optimization; turning it off has no effect on
output correctness, only on incremental rebuild speed of
the (wwwroot-light) web projects. -->
<StaticWebAssetsCacheDefineStaticWebAssetsEnabled>false</StaticWebAssetsCacheDefineStaticWebAssetsEnabled>
</PropertyGroup>
</Project>

View file

@ -48,70 +48,4 @@ docker-build:
docker-run:
docker run -d -p 5000:5000 --name yavsc yavsc
# Crée une branche release/<V> depuis main, met à jour les
# `<Version>` 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=<version>"; \
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 release
.PHONY: test install docker-image docker-build docker-run

View file

@ -95,6 +95,15 @@ showConfig:
@echo CONFIGURATION: $(CONFIGURATION)
@echo BASEAPPDIR: $(BASEAPPDIR)
showApiLogs:
@sudo journalctl -u yavscApi.service -S "2 min ago" | tee yavscApi.log
showOrgLogs:
@sudo journalctl -u yavscOrg.service -S "2 min ago" | tee yavscOrg.log
showBlogsLogs:
@sudo journalctl -u yavscBlogs.service -S "2 min ago" | tee yavscBlogs.log
clean:
@rm -rf generated

View file

@ -1,5 +0,0 @@
# Read me
## Note aux icones
㝉®🅬⛒⛑🩎🩺🞫🞮🞕🞖🞆🔴🔵🔲🖂🔧🔩🔐🔌💾💼💬💭👿👾🏷🎯🏹🌍🎎💩

View file

@ -1,5 +1,13 @@
{
"version": 1,
"isRoot": true,
"tools": {}
"tools": {
"picket": {
"version": "0.2.12",
"commands": [
"picket"
],
"rollForward": false
}
}
}

View file

@ -1,35 +1,31 @@
<Project>
<Import
Project="$([MSBuild]::GetPathOfFileAbove('Directory.Packages.props', '$(MSBuildThisFileDirectory)../'))" />
<Import Project="$([MSBuild]::GetPathOfFileAbove('Directory.Packages.props', '$(MSBuildThisFileDirectory)../'))" />
<!-- PostIt-product-specific versions -->
<!-- https://learn.microsoft.com/en-us/nuget/consume-packages/central-package-management -->
<PropertyGroup>
<ManagePackageVersionsCentrally>true</ManagePackageVersionsCentrally>
<AvaloniaVersionBase>12.1.1</AvaloniaVersionBase>
</PropertyGroup>
<ItemGroup>
<PackageVersion Include="Avalonia" Version="$(AvaloniaVersionBase)" />
<PackageVersion Include="Avalonia.Themes.Fluent" Version="$(AvaloniaVersionBase)" />
<PackageVersion Include="Avalonia.Desktop" Version="$(AvaloniaVersionBase)" />
<PackageVersion Include="Avalonia.Browser" Version="$(AvaloniaVersionBase)" />
<PackageVersion Include="Avalonia.Android" Version="$(AvaloniaVersionBase)" />
<PackageVersion Include="Avalonia.Headless" Version="$(AvaloniaVersionBase)" />
<PackageVersion Include="Avalonia.Headless.Xunit" Version="$(AvaloniaVersionBase)" />
<PackageVersion Include="Avalonia.Fonts.Inter" Version="$(AvaloniaVersionBase)" />
<PackageVersion Include="Mapsui" Version="5.1.0" />
<PackageVersion Include="Mapsui.Avalonia12" Version="5.1.0" />
<PackageVersion Include="Material.Avalonia" Version="3.19.0" />
<PackageVersion Include="AvaloniaUI.DiagnosticsSupport" Version="2.2.3" />
<PackageVersion Include="CommunityToolkit.Mvvm" Version="8.4.2" />
<PackageVersion Include="Xamarin.AndroidX.Browser" Version="1.10.0.1" />
<PackageVersion Include="Xamarin.AndroidX.Core.SplashScreen" Version="1.2.0" />
<PackageVersion Include="Xamarin.AndroidX.Lifecycle.Runtime" Version="2.10.0.1" />
<PackageVersion Include="Xamarin.AndroidX.Lifecycle.Common" Version="2.10.0.1" />
<PackageVersion Include="Xamarin.UITest" Version="4.4.2" />
<PackageVersion Include="Microsoft.Extensions.DependencyInjection" Version="10.0.11" />
</ItemGroup>
</Project>
<PropertyGroup>
<ManagePackageVersionsCentrally>true</ManagePackageVersionsCentrally>
<AvaloniaVersionBase>12.1.1</AvaloniaVersionBase>
</PropertyGroup>
<ItemGroup>
<PackageVersion Include="Avalonia" Version="$(AvaloniaVersionBase)" />
<PackageVersion Include="Avalonia.Themes.Fluent" Version="$(AvaloniaVersionBase)" />
<PackageVersion Include="Avalonia.Desktop" Version="$(AvaloniaVersionBase)" />
<PackageVersion Include="Avalonia.Browser" Version="$(AvaloniaVersionBase)" />
<PackageVersion Include="Avalonia.Android" Version="$(AvaloniaVersionBase)" />
<PackageVersion Include="Avalonia.Headless" Version="$(AvaloniaVersionBase)" />
<PackageVersion Include="Avalonia.Headless.Xunit" Version="$(AvaloniaVersionBase)" />
<PackageVersion Include="Avalonia.Fonts.Inter" Version="$(AvaloniaVersionBase)" />
<PackageVersion Include="Mapsui" Version="5.1.0" />
<PackageVersion Include="Mapsui.Avalonia12" Version="5.1.0" />
<PackageVersion Include="MarkdownViewer.Core" Version="1.0.5" />
<PackageVersion Include="Material.Avalonia" Version="3.19.0" />
<PackageVersion Include="AvaloniaUI.DiagnosticsSupport" Version="2.2.3" />
<PackageVersion Include="CommunityToolkit.Mvvm" Version="8.4.2" />
<PackageVersion Include="Xamarin.AndroidX.Browser" Version="1.10.0.1" />
<PackageVersion Include="Xamarin.AndroidX.Core.SplashScreen" Version="1.2.0" />
<PackageVersion Include="Xamarin.AndroidX.Lifecycle.Runtime" Version="2.10.0.1" />
<PackageVersion Include="Xamarin.AndroidX.Lifecycle.Common" Version="2.10.0.1" />
<PackageVersion Include="Xamarin.UITest" Version="4.4.2" />
<PackageVersion Include="Microsoft.Extensions.DependencyInjection" Version="10.0.11" />
</ItemGroup>
</Project>

View file

@ -11,8 +11,8 @@
<AndroidEnableProfiledAot>false</AndroidEnableProfiledAot>
<AssemblyVersion>1.1.0.0</AssemblyVersion>
<FileVersion>1.1.0.0</FileVersion>
<InformationalVersion>1.1.0-beta.1+183.Branch.release-1.0.8-rc8.Sha.6cff3db32ecf72c0d2d430b7002fa7816a34e070</InformationalVersion>
<Version>1.1.0-beta.1</Version>
<InformationalVersion>1.1.0-feat-sign-estimate.1+306.Branch.feat-sign-estimate.Sha.e9a33695b38154859729b61d1280e596f1597acf</InformationalVersion>
<Version>1.1.0-feat-sign-estimate.1</Version>
</PropertyGroup>
<ItemGroup>
<AndroidResource Include="Icon.png">

View file

@ -6,8 +6,8 @@
<Nullable>enable</Nullable>
<AssemblyVersion>1.1.0.0</AssemblyVersion>
<FileVersion>1.1.0.0</FileVersion>
<InformationalVersion>1.1.0-beta.1+183.Branch.release-1.0.8-rc8.Sha.6cff3db32ecf72c0d2d430b7002fa7816a34e070</InformationalVersion>
<Version>1.1.0-beta.1</Version>
<InformationalVersion>1.1.0-feat-sign-estimate.1+306.Branch.feat-sign-estimate.Sha.e9a33695b38154859729b61d1280e596f1597acf</InformationalVersion>
<Version>1.1.0-feat-sign-estimate.1</Version>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Avalonia.Browser" />

View file

@ -7,8 +7,8 @@
<Nullable>enable</Nullable>
<AssemblyVersion>1.1.0.0</AssemblyVersion>
<FileVersion>1.1.0.0</FileVersion>
<InformationalVersion>1.1.0-beta.1+183.Branch.release-1.0.8-rc8.Sha.6cff3db32ecf72c0d2d430b7002fa7816a34e070</InformationalVersion>
<Version>1.1.0-beta.1</Version>
<InformationalVersion>1.1.0-feat-sign-estimate.1+306.Branch.feat-sign-estimate.Sha.e9a33695b38154859729b61d1280e596f1597acf</InformationalVersion>
<Version>1.1.0-feat-sign-estimate.1</Version>
</PropertyGroup>
<PropertyGroup>
<ApplicationManifest>app.manifest</ApplicationManifest>

View file

@ -162,6 +162,12 @@ public class ActivitiesPageViewModelTests
return Task.CompletedTask;
}
public Task<T> CallAsync<T>(HttpMethod method, string path, Func<HttpContent> contentFactory, CancellationToken ct = default)
=> CallAsync<T>(method, path, (object?)null, ct);
public Task CallAsync(HttpMethod method, string path, Func<HttpContent> contentFactory, CancellationToken ct = default)
=> CallAsync(method, path, (object?)null, ct);
public ValueTask DisposeAsync() => ValueTask.CompletedTask;
}
}

View file

@ -352,6 +352,12 @@ public class BillingCommandPageViewModelTests
return Task.CompletedTask;
}
public Task<T> CallAsync<T>(HttpMethod method, string path, Func<HttpContent> contentFactory, CancellationToken ct = default)
=> CallAsync<T>(method, path, (object?)null, ct);
public Task CallAsync(HttpMethod method, string path, Func<HttpContent> contentFactory, CancellationToken ct = default)
=> CallAsync(method, path, (object?)null, ct);
public ValueTask DisposeAsync() => ValueTask.CompletedTask;
}
}

View file

@ -45,10 +45,8 @@ public class BillingQueriesPageViewModelTests
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));
Assert.True(vm.Queries.Count > 0);
}
private sealed class StubBillingApi : IYavscApiClient
@ -129,6 +127,12 @@ public class BillingQueriesPageViewModelTests
return Task.CompletedTask;
}
public Task<T> CallAsync<T>(HttpMethod method, string path, Func<HttpContent> contentFactory, CancellationToken ct = default)
=> CallAsync<T>(method, path, (object?)null, ct);
public Task CallAsync(HttpMethod method, string path, Func<HttpContent> contentFactory, CancellationToken ct = default)
=> CallAsync(method, path, (object?)null, ct);
public ValueTask DisposeAsync() => ValueTask.CompletedTask;
}
}

View file

@ -62,4 +62,17 @@ internal sealed class RecordingYavscApiClient : YavscApiClient
});
return Task.FromResult(default(T)!);
}
/// <summary>Multipart overload: BlogApiClient routes
/// Create/UpdatePostAsync with attachments through here.
/// Without this override the call would fall through to the
/// base <see cref="YavscApiClient"/> and attempt a real HTTP
/// round-trip against the stub authority. The body is a
/// factory, so we record the delegate itself; tests that
/// care about the multipart shape invoke it.</summary>
public override Task<T> CallAsync<T>(HttpMethod method, string path, Func<HttpContent> contentFactory, CancellationToken ct = default)
{
_recorder.Calls.Add((method, path, contentFactory));
return Task.FromResult(default(T)!);
}
}

View file

@ -0,0 +1,79 @@
using Yavsc.Blogspot;
using Yavsc.Api.Client;
using PostIt.ViewModels;
namespace PostIt.Tests;
/// <summary>
/// Pins the markdown link that <see cref="BlogsViewModel.SaveAsync"/>
/// appends to the article after a successful attachment upload.
///
/// <para>The link must be an absolute URL derived from the OIDC
/// authority via <c>FileServerUrlHelpers.GetUserFilesUri</c>
/// (Yavsc.Abstract): the <c>/files</c> file server is hosted by
/// Yavsc.Org — the IdP — not by the blogs API host, so a link
/// built from <c>BlogsApiUrl</c> (or left relative) 404s when the
/// reader opens the post. The regression this guards: a generated
/// link of the shape <c>/files/{user}/blogs/{id}/{name}</c>
/// (relative, authority-less) instead of
/// <c>https://{authority}/files/{user}/blogs/{id}/{name}</c>.</para>
/// </summary>
public class BlogAttachmentLinkTests
{
[Fact]
public async Task Save_with_attachment_appends_absolute_link_derived_from_the_oidc_authority()
{
const string authority = "https://idp.example.test";
var recorder = new CallRecorder();
var api = new RecordingYavscApiClient(recorder);
var blog = new BlogApiClient(api, "https://blogs.example.test/api/v1/");
var settings = new Settings
{
Authentication = new AuthenticationSettings
{
Authority = authority,
ClientId = "stub",
Scopes = new[] { "openid" },
},
};
var vm = new BlogsViewModel(blog, settings);
// Update branch: an existing post is selected, the user
// edits the buffers and attaches a file.
vm.SelectedPost = new BlogPostDto
{
Id = 42,
AuthorId = "tester",
Title = "Avant",
Article = "Contenu initial.",
DateCreated = DateTime.UtcNow,
DateModified = DateTime.UtcNow,
};
vm.DraftTitle = "Après";
vm.DraftArticle = "Contenu modifié.";
vm.DraftAttachments.Add(new BlogUploadFile(
"note.txt",
System.Text.Encoding.UTF8.GetBytes("payload test"),
"text/plain"));
await vm.SaveAsync();
// The update branch issues two PUTs: the multipart one
// carrying the file, then — because TryAppendAttachmentLinks
// appended a link — a JSON one carrying the final article.
var linkPut = recorder.Calls.LastOrDefault(
c => c.method == HttpMethod.Put);
Assert.NotEqual(default, linkPut);
var sent = Assert.IsType<System.Func<HttpContent>>(linkPut.body);
var multipartContent = Assert.IsType<MultipartFormDataContent>(sent());
var expectedUrl = $"{authority}/files/tester/blogs/42/note.txt";
var sentStringContent = multipartContent.First() as StringContent ;
var sentString = await sentStringContent.ReadAsStringAsync(TestContext.Current.CancellationToken);
Assert.Contains($"- [note.txt]({expectedUrl})", sentString);
// The regression shape: a relative, authority-less link.
Assert.DoesNotContain("](/files/", sentString);
}
}

View file

@ -0,0 +1,270 @@
using System.Net.Http;
using PostIt.ViewModels;
using Yavsc;
using Yavsc.Api.Client;
namespace PostIt.Tests;
public class EstimateEditionPageViewModelTests
{
private static BillingQuerySummaryDto SampleQuery() => new()
{
Id = 42,
BillingCode = "Brush",
ActivityCode = "hair",
PerformerId = "perf-1",
ClientId = "cli-1",
Status = QueryStatus.InProgress,
Description = "Coupe simple",
EventDate = new DateTime(2026, 9, 12, 10, 0, 0, DateTimeKind.Utc),
};
private static EstimateEditionPageViewModel CreateViewModel(StubEstimateApi api, BillingQuerySummaryDto? query = null)
{
var client = new EstimateApiClient(api, "https://business.example/api/v1/");
return new EstimateEditionPageViewModel(query ?? SampleQuery(), client);
}
[Fact]
public void Constructor_prefills_description_and_adds_a_first_line()
{
var api = new StubEstimateApi();
var vm = CreateViewModel(api);
Assert.Equal("Coupe simple", vm.EstimateDescription);
Assert.Single(vm.Lines);
Assert.Same(vm.Lines[0], vm.SelectedLine);
Assert.Contains("#42", vm.ContextLabel);
Assert.Contains("cli-1", vm.ContextLabel);
}
[Fact]
public void AddLine_appends_and_selects_the_new_line()
{
var api = new StubEstimateApi();
var vm = CreateViewModel(api);
vm.AddLineCommand.Execute(null);
Assert.Equal(2, vm.Lines.Count);
Assert.Same(vm.Lines[1], vm.SelectedLine);
}
[Fact]
public void RemoveLine_removes_the_selected_line()
{
var api = new StubEstimateApi();
var vm = CreateViewModel(api);
var first = vm.Lines[0];
vm.RemoveLineCommand.Execute(null);
Assert.Empty(vm.Lines);
Assert.Null(vm.SelectedLine);
Assert.False(vm.RemoveLineCommand.CanExecute(null));
Assert.DoesNotContain(first, vm.Lines);
}
[Fact]
public void Total_sums_line_totals_and_tracks_edits()
{
var api = new StubEstimateApi();
var vm = CreateViewModel(api);
vm.Lines[0].Count = 2;
vm.Lines[0].UnitaryCost = 15.5m;
Assert.Equal(31m, vm.Total);
Assert.Equal($"{31m:0.00} EUR", vm.TotalLabel);
vm.AddLineCommand.Execute(null);
vm.Lines[1].Count = 1;
vm.Lines[1].UnitaryCost = 9m;
Assert.Equal(40m, vm.Total);
}
[Fact]
public async Task Send_without_title_warns_and_does_not_post()
{
var api = new StubEstimateApi();
var vm = CreateViewModel(api);
vm.Lines[0].Name = "Coupe";
vm.Lines[0].Description = "Coupe simple";
vm.Lines[0].UnitaryCost = 25m;
await vm.SendCommand.ExecuteAsync(null);
Assert.Null(api.LastBody);
Assert.Equal(StatusSeverity.Warning, vm.ActionStatus.Severity);
Assert.Contains("titre", vm.ActionStatus.Message);
}
[Fact]
public async Task Send_without_any_line_warns_and_does_not_post()
{
var api = new StubEstimateApi();
var vm = CreateViewModel(api);
vm.EstimateTitle = "Devis coupe";
vm.Lines.Clear();
await vm.SendCommand.ExecuteAsync(null);
Assert.Null(api.LastBody);
Assert.Equal(StatusSeverity.Warning, vm.ActionStatus.Severity);
Assert.Contains("ligne", vm.ActionStatus.Message);
}
[Fact]
public async Task Send_with_a_blank_line_name_warns_and_does_not_post()
{
var api = new StubEstimateApi();
var vm = CreateViewModel(api);
vm.EstimateTitle = "Devis coupe";
vm.Lines[0].Description = "Oubli du nom";
await vm.SendCommand.ExecuteAsync(null);
Assert.Null(api.LastBody);
Assert.Equal(StatusSeverity.Warning, vm.ActionStatus.Severity);
Assert.Contains("nom", vm.ActionStatus.Message);
}
[Fact]
public async Task Send_posts_the_estimate_payload_to_the_estimate_route()
{
var api = new StubEstimateApi();
var vm = CreateViewModel(api);
vm.EstimateTitle = " Devis coupe ";
vm.Lines[0].Name = "Coupe";
vm.Lines[0].Description = "Coupe simple";
vm.Lines[0].Count = 2.4m;
vm.Lines[0].UnitaryCost = 25m;
await vm.SendCommand.ExecuteAsync(null);
Assert.Equal("https://business.example/api/v1/estimate", api.LastPath);
Assert.Equal(HttpMethod.Post, api.LastMethod);
var payload = Assert.IsType<EstimateDto>(api.LastBody);
Assert.Equal(42, payload.CommandId);
Assert.Equal("cli-1", payload.ClientId);
Assert.Equal("Brush", payload.CommandType);
Assert.Equal("Devis coupe", payload.Title);
Assert.Equal("Coupe simple", payload.Description);
Assert.Empty(payload.AttachedFiles);
Assert.Empty(payload.AttachedGraphics);
var line = Assert.Single(payload.Bill);
Assert.Equal("Coupe", line.Name);
Assert.Equal(2, line.Count);
Assert.Equal(25m, line.UnitaryCost);
Assert.Equal("EUR", line.Currency);
}
[Fact]
public async Task Send_marks_the_page_as_sent_and_disables_resend()
{
var api = new StubEstimateApi();
var vm = CreateViewModel(api);
vm.EstimateTitle = "Devis coupe";
vm.Lines[0].Name = "Coupe";
vm.Lines[0].Description = "Coupe simple";
vm.Lines[0].UnitaryCost = 25m;
await vm.SendCommand.ExecuteAsync(null);
Assert.True(vm.HasSent);
Assert.False(vm.SendCommand.CanExecute(null));
Assert.Equal("Devis envoyé", vm.SendLabel);
Assert.Equal(StatusSeverity.Info, vm.ActionStatus.Severity);
Assert.Contains("#7", vm.ActionStatus.Message);
}
[Fact]
public async Task Send_surfaces_server_errors_as_error_status()
{
var api = new StubEstimateApi { Failure = new HttpRequestException("boom", null, System.Net.HttpStatusCode.InternalServerError) };
var vm = CreateViewModel(api);
vm.EstimateTitle = "Devis coupe";
vm.Lines[0].Name = "Coupe";
vm.Lines[0].Description = "Coupe simple";
await vm.SendCommand.ExecuteAsync(null);
Assert.False(vm.HasSent);
Assert.Equal(StatusSeverity.Error, vm.ActionStatus.Severity);
Assert.True(vm.SendCommand.CanExecute(null));
}
[Fact]
public async Task Send_accepts_negative_amounts_for_discount_lines()
{
var api = new StubEstimateApi();
var vm = CreateViewModel(api);
vm.EstimateTitle = "Devis avec remise";
vm.Lines[0].Name = "Coupe";
vm.Lines[0].Description = "Coupe simple";
vm.Lines[0].UnitaryCost = 25m;
vm.AddLineCommand.Execute(null);
vm.Lines[1].Name = "Remise fidélité";
vm.Lines[1].Description = "Remise client régulier";
vm.Lines[1].UnitaryCost = -5m;
Assert.Equal(20m, vm.Total);
await vm.SendCommand.ExecuteAsync(null);
var payload = Assert.IsType<EstimateDto>(api.LastBody);
Assert.Equal(2, payload.Bill.Count);
Assert.Equal(-5m, payload.Bill[1].UnitaryCost);
Assert.True(vm.HasSent);
}
private sealed class StubEstimateApi : IYavscApiClient
{
public HttpClient Http { get; } = new();
public string? LastPath { get; private set; }
public HttpMethod? LastMethod { get; private set; }
public object? LastBody { get; private set; }
public Exception? Failure { get; init; }
public Task<T> CallAsync<T>(HttpMethod method, string path, object? body = null, CancellationToken ct = default)
{
LastMethod = method;
LastPath = path;
LastBody = body;
if (Failure is not null)
{
throw Failure;
}
if (typeof(T) == typeof(EstimateCreatedDto))
{
var payload = (EstimateDto)body!;
var created = new EstimateCreatedDto { Id = 7, Bill = payload.Bill };
return Task.FromResult((T)(object)created);
}
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 Task<T> CallAsync<T>(HttpMethod method, string path, Func<HttpContent> contentFactory, CancellationToken ct = default)
=> CallAsync<T>(method, path, (object?)null, ct);
public Task CallAsync(HttpMethod method, string path, Func<HttpContent> contentFactory, CancellationToken ct = default)
=> CallAsync(method, path, (object?)null, ct);
public ValueTask DisposeAsync() => ValueTask.CompletedTask;
}
}

View file

@ -0,0 +1,134 @@
using System.Net.Http;
using PostIt.ViewModels;
using Yavsc.Api.Client;
namespace PostIt.Tests;
public class EstimateListPageViewModelTests
{
[Fact]
public async Task Client_perspective_calls_asclient_endpoint()
{
var api = new StubEstimateListApi();
var client = new EstimateApiClient(api, "https://business.example/api/v1/");
var vm = new EstimateListPageViewModel(client, EstimateListPerspective.Client);
await vm.InitializeAsync();
Assert.Contains("https://business.example/api/v1/estimate/asclient", api.Paths);
Assert.Equal("Mes devis à valider", vm.Title);
Assert.Equal(2, vm.Estimates.Count);
// Most recent first
Assert.Equal(2, vm.Estimates[0].Id);
Assert.Equal(1, vm.Estimates[1].Id);
}
[Fact]
public async Task Provider_perspective_calls_asprovider_endpoint()
{
var api = new StubEstimateListApi();
var client = new EstimateApiClient(api, "https://business.example/api/v1/");
var vm = new EstimateListPageViewModel(client, EstimateListPerspective.Provider);
await vm.InitializeAsync();
Assert.Contains("https://business.example/api/v1/estimate/asprovider", api.Paths);
Assert.Equal("Mes devis en attente", vm.Title);
Assert.Equal(2, vm.Estimates.Count);
}
[Fact]
public async Task FilterText_filters_by_title_and_counterpart()
{
var api = new StubEstimateListApi();
var client = new EstimateApiClient(api, "https://business.example/api/v1/");
var vm = new EstimateListPageViewModel(client, EstimateListPerspective.Provider);
await vm.InitializeAsync();
vm.FilterText = "plomberie";
Assert.Single(vm.Estimates);
Assert.Equal(1, vm.Estimates[0].Id);
vm.FilterText = "BOB";
Assert.Single(vm.Estimates);
Assert.Equal("bob", vm.Estimates[0].ClientId);
vm.FilterText = string.Empty;
Assert.Equal(2, vm.Estimates.Count);
}
[Fact]
public async Task Empty_result_sets_an_info_status()
{
var api = new StubEstimateListApi { Empty = true };
var client = new EstimateApiClient(api, "https://business.example/api/v1/");
var vm = new EstimateListPageViewModel(client, EstimateListPerspective.Client);
await vm.InitializeAsync();
Assert.Empty(vm.Estimates);
Assert.Contains("Aucun devis", vm.StatusMessage);
}
private sealed class StubEstimateListApi : IYavscApiClient
{
public HttpClient Http { get; } = new();
public List<string> Paths { get; } = new();
public bool Empty { get; init; }
public Task<T> CallAsync<T>(HttpMethod method, string path, object? body = null, CancellationToken ct = default)
{
Paths.Add(path);
if (typeof(T) == typeof(List<EstimateDto>))
{
var items = Empty
? new List<EstimateDto>()
: new List<EstimateDto>
{
new()
{
Id = 1,
Title = "Devis plomberie",
Description = "Réparation fuite",
ClientId = "bob",
OwnerId = "alice",
CommandType = "Rdv",
Bill = new List<EstimateLineDto>
{
new() { Name = "Main d'œuvre", Description = "Intervention", Count = 1, UnitaryCost = 80m },
},
},
new()
{
Id = 2,
Title = "Devis électricité",
Description = "Mise aux normes",
ClientId = "carol",
OwnerId = "alice",
CommandType = "Rdv",
Bill = new List<EstimateLineDto>(),
},
};
return Task.FromResult((T)(object)items);
}
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 Task<T> CallAsync<T>(HttpMethod method, string path, Func<HttpContent> contentFactory, CancellationToken ct = default)
=> CallAsync<T>(method, path, (object?)null, ct);
public Task CallAsync(HttpMethod method, string path, Func<HttpContent> contentFactory, CancellationToken ct = default)
=> CallAsync(method, path, (object?)null, ct);
public ValueTask DisposeAsync() => ValueTask.CompletedTask;
}
}

View file

@ -0,0 +1,15 @@
using PostIt.ViewModels;
namespace PostIt.Tests;
public class HomePageProviderFlowTests
{
[Fact]
public void HomePage_exposes_provider_requests_command()
{
var vm = new HomePageViewModel();
Assert.NotNull(vm.OpenProviderRequests);
Assert.True(vm.OpenProviderRequests.CanExecute(null));
}
}

View file

@ -8,6 +8,8 @@ using Yavsc.Blogspot;
using PostIt.Services;
using PostIt.ViewModels;
using PostIt.Views;
using PostIt.Views.Blogs;
using PostIt.Helpers;
namespace PostIt.Tests;
@ -72,13 +74,13 @@ public class MainPageButtonsTests
{ }
}
private static MainViewModel MakeViewModel(BlogPostDto? selectedPost = null)
private static BlogsViewModel 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
// Minimal DI graph: only what BlogsViewModel resolves
// when the user clicks a navigation button. Today that's
// SignaturePageViewModel / CirclesPageViewModel / ACL
// dependencies. The graph intentionally stays local to this
@ -93,7 +95,7 @@ public class MainPageButtonsTests
services.AddTransient<SignaturePage>();
services.AddTransient<CirclesPage>();
services.AddTransient<PostAclDialog>();
var vm = new MainViewModel(blog, services: services.BuildServiceProvider());
var vm = new BlogsViewModel(blog, services: services.BuildServiceProvider());
if (selectedPost is not null) vm.SelectedPost = selectedPost;
return vm;
}
@ -101,7 +103,7 @@ public class MainPageButtonsTests
/// <summary>
/// Mount a real <see cref="MainView"/> (as
/// <c>SessionStatusBannerTests</c> does), push a
/// <see cref="MainPage"/> with the given VM onto
/// <see cref="BlogsPage"/> with the given VM onto
/// <c>NavRoot</c>. <c>PushAsync</c> is awaited (via
/// <c>GetAwaiter().GetResult()</c>) so the page is on the
/// nav stack before the test tries to interact with its
@ -109,13 +111,17 @@ public class MainPageButtonsTests
/// realised and <c>KeyPressQwerty</c> has a real
/// <see cref="TopLevel"/> to dispatch against.
/// </summary>
private static (MainView window, MainPage page) MountMainPage(MainViewModel vm)
private static (MainView window, BlogsPage page) MountMainPage(BlogsViewModel vm)
{
var window = new MainView();
var page = new MainPage { DataContext = vm };
var page = new BlogsPage { DataContext = vm };
var app = (PostIt.App)Application.Current!;
app.AttachMainWindow(window);
window.NavRoot.PushAsync(page).GetAwaiter().GetResult();
var mainWindow = new Window { Content = window };
mainWindow.Show();
return (window, page);
}
@ -145,7 +151,7 @@ public class MainPageButtonsTests
}
[AvaloniaFact]
public void Acl_button_click_pushes_a_page_onto_nav_stack()
public async Task 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
@ -178,7 +184,7 @@ public class MainPageButtonsTests
}
[AvaloniaFact]
public void Circles_button_click_pushes_a_page_onto_nav_stack()
public async Task 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.
@ -203,7 +209,7 @@ public class MainPageButtonsTests
public void Signature_dev_button_click_pushes_a_page_onto_nav_stack()
{
// Arrange: the "[DEV] Signature" button is bound to the
// MainPageViewModel.OpenSignatureDevCommand [RelayCommand].
// BlogsViewModel.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

View file

@ -5,10 +5,11 @@ using Yavsc.Blogspot;
using Yavsc.Api.Client;
using PostIt.ViewModels;
using PostIt.Views;
using PostIt.Views.Blogs;
namespace PostIt.Tests;
/// <summary>
/// Headless UI tests for the "Save" flow in <see cref="MainPage"/>.
/// Headless UI tests for the "Save" flow in <see cref="BlogsPage"/>.
/// The pattern is the one <c>SessionStatusBannerTests</c>
/// established: <c>[AvaloniaFact]</c>, a <see cref="Window"/>
/// hosting the page (via a <see cref="Frame"/> because
@ -40,9 +41,9 @@ public class MainPageSaveTests
var recorder = new CallRecorder();
var api = new RecordingYavscApiClient(recorder);
var blog = new BlogApiClient(api, "http://localhost/");
var viewModel = new MainViewModel(blog);
var viewModel = new BlogsViewModel(blog);
var page = new MainPage { DataContext = viewModel };
var page = new BlogsPage { DataContext = viewModel };
// MainPage is a ContentPage (a Page, not a Control), so it
// must be hosted in a navigation surface. The production
// MainWindow.axaml uses NavigationPage, and the API is the
@ -63,9 +64,7 @@ public class MainPageSaveTests
const string typed = "Mon premier billet";
titleBox.Text = typed;
var saveButton = window.GetVisualDescendants()
.OfType<Button>()
.Single(b => b.Content as string == "Save");
var saveButton = page.SaveButton;
saveButton.Command!.Execute(null);
// The Save command is async (RelayCommand over Task) but

View file

@ -270,6 +270,12 @@ public class PostAclDialogTests
return Task.CompletedTask;
}
public Task<T> CallAsync<T>(HttpMethod method, string path, Func<HttpContent> contentFactory, CancellationToken ct = default)
=> CallAsync<T>(method, path, (object?)null, ct);
public Task CallAsync(HttpMethod method, string path, Func<HttpContent> contentFactory, CancellationToken ct = default)
=> CallAsync(method, path, (object?)null, ct);
public ValueTask DisposeAsync() => ValueTask.CompletedTask;
}
}

View file

@ -8,8 +8,8 @@
<ManagePackageVersionsCentrally>true</ManagePackageVersionsCentrally>
<AssemblyVersion>1.1.0.0</AssemblyVersion>
<FileVersion>1.1.0.0</FileVersion>
<InformationalVersion>1.1.0-beta.1+183.Branch.release-1.0.8-rc8.Sha.6cff3db32ecf72c0d2d430b7002fa7816a34e070</InformationalVersion>
<Version>1.1.0-beta.1</Version>
<InformationalVersion>1.1.0-feat-sign-estimate.1+306.Branch.feat-sign-estimate.Sha.e9a33695b38154859729b61d1280e596f1597acf</InformationalVersion>
<Version>1.1.0-feat-sign-estimate.1</Version>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" />

View file

@ -11,25 +11,23 @@ public class PostItViewModelTests
[Fact]
public void SearchCommand_filters_posts_by_title_article_or_author()
{
// MainPageViewModel no longer owns a BlogApiClient instance by
// BlogsViewModel no longer owns a BlogApiClient instance by
// 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, "http://localhost/");
var viewModel = new MainViewModel(blog);
var viewModel = new BlogsViewModel(blog);
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);
Assert.Single(viewModel.FilteredPosts);
Assert.Equal(3, viewModel.FilteredPosts[0].Id);
viewModel.SearchText = "bob";
viewModel.SearchCommand.Execute(null);
Assert.Single(viewModel.FilteredPosts);
Assert.Equal(2, viewModel.FilteredPosts[0].Id);
@ -60,7 +58,7 @@ public class PostItViewModelTests
{
var api = new RecordingPublishApi();
var blog = new BlogApiClient(api, "http://localhost/");
var viewModel = new MainViewModel(blog);
var viewModel = new BlogsViewModel(blog);
viewModel.SelectedPost = new BlogPostDto { Id = 42, IsPublished = false };
@ -146,6 +144,12 @@ public class PostItViewModelTests
return Task.CompletedTask;
}
public Task<T> CallAsync<T>(HttpMethod method, string path, Func<HttpContent> contentFactory, CancellationToken ct = default)
=> CallAsync<T>(method, path, (object?)null, ct);
public Task CallAsync(HttpMethod method, string path, Func<HttpContent> contentFactory, CancellationToken ct = default)
=> CallAsync(method, path, (object?)null, ct);
public ValueTask DisposeAsync() => ValueTask.CompletedTask;
}
}

View file

@ -0,0 +1,238 @@
using System.Net.Http;
using PostIt.ViewModels;
using Yavsc;
using Yavsc.Api.Client;
namespace PostIt.Tests;
public class ProviderOngoingRequestsPageViewModelTests
{
[Fact]
public async Task RefreshAsync_calls_provider_endpoint_and_filters_out_unknown_billing_codes()
{
var api = new StubProviderApi();
var client = new BillingApiClient(api, "https://business.example/api/v1/");
var vm = new ProviderOngoingRequestsPageViewModel(client);
await vm.InitializeAsync();
Assert.Contains("https://business.example/api/v1/bill/provider/ongoing", api.Paths);
Assert.Equal(3, vm.Queries.Count);
Assert.Equal(12, vm.Queries[0].Id);
Assert.Equal(11, vm.Queries[1].Id);
Assert.Equal(10, vm.Queries[2].Id);
}
[Fact]
public async Task FilterText_filters_by_activity_code_and_status()
{
var api = new StubProviderApi();
var client = new BillingApiClient(api, "https://business.example/api/v1/");
var vm = new ProviderOngoingRequestsPageViewModel(client);
await vm.InitializeAsync();
vm.FilterText = "mbrush";
Assert.Single(vm.Queries);
Assert.Equal("MBrush", vm.Queries[0].BillingCode);
vm.FilterText = "accepted";
Assert.Single(vm.Queries);
Assert.Equal(QueryStatus.Accepted, vm.Queries[0].Status);
}
[Fact]
public async Task OpenSelectedEditorCommand_can_execute_only_when_selection_exists()
{
var api = new StubProviderApi();
var client = new BillingApiClient(api, "https://business.example/api/v1/");
var vm = new ProviderOngoingRequestsPageViewModel(client);
await vm.InitializeAsync();
Assert.False(vm.OpenSelectedEditorCommand.CanExecute(null));
vm.SelectedQuery = vm.Queries[0];
Assert.True(vm.OpenSelectedEditorCommand.CanExecute(null));
}
[Fact]
public async Task SelectedSortOption_date_keeps_most_recent_first()
{
var api = new StubProviderApi();
var client = new BillingApiClient(api, "https://business.example/api/v1/");
var vm = new ProviderOngoingRequestsPageViewModel(client);
await vm.InitializeAsync();
vm.SelectedSortOption = ProviderOngoingRequestsPageViewModel.SortByDate;
Assert.Equal(new long[] { 12, 11, 10 }, vm.Queries.Select(q => q.Id).ToArray());
}
[Fact]
public async Task SelectedSortOption_date_ascending_keeps_oldest_first()
{
var api = new StubProviderApi();
var client = new BillingApiClient(api, "https://business.example/api/v1/");
var vm = new ProviderOngoingRequestsPageViewModel(client);
await vm.InitializeAsync();
vm.SelectedSortOption = ProviderOngoingRequestsPageViewModel.SortByDateAsc;
Assert.Equal(new long[] { 10, 11, 12 }, vm.Queries.Select(q => q.Id).ToArray());
}
[Fact]
public async Task SelectedSortOption_status_prioritizes_inprogress_then_accepted_then_inserted()
{
var api = new StubProviderApi();
var client = new BillingApiClient(api, "https://business.example/api/v1/");
var vm = new ProviderOngoingRequestsPageViewModel(client);
await vm.InitializeAsync();
vm.SelectedSortOption = ProviderOngoingRequestsPageViewModel.SortByStatus;
Assert.Equal(new long[] { 11, 12, 10 }, vm.Queries.Select(q => q.Id).ToArray());
}
[Fact]
public void Constructor_reads_saved_sort_option_from_settings()
{
var api = new StubProviderApi();
var client = new BillingApiClient(api, "https://business.example/api/v1/");
var settings = new Settings
{
ProviderOngoingRequestsSortOption = ProviderOngoingRequestsPageViewModel.SortByStatus,
};
var vm = new ProviderOngoingRequestsPageViewModel(client, settings);
Assert.Equal(ProviderOngoingRequestsPageViewModel.SortByStatus, vm.SelectedSortOption);
}
[Fact]
public void Constructor_falls_back_to_default_when_saved_sort_is_invalid()
{
var api = new StubProviderApi();
var client = new BillingApiClient(api, "https://business.example/api/v1/");
var settings = new Settings
{
ProviderOngoingRequestsSortOption = "invalide",
};
var vm = new ProviderOngoingRequestsPageViewModel(client, settings);
Assert.Equal(ProviderOngoingRequestsPageViewModel.SortByDate, vm.SelectedSortOption);
}
[Fact]
public async Task CreateEstimateForSelectedCommand_requires_a_selection()
{
var api = new StubProviderApi();
var client = new BillingApiClient(api, "https://business.example/api/v1/");
var estimateClient = new EstimateApiClient(api, "https://business.example/api/v1/");
var vm = new ProviderOngoingRequestsPageViewModel(client, estimateClient: estimateClient);
await vm.InitializeAsync();
Assert.False(vm.CreateEstimateForSelectedCommand.CanExecute(null));
vm.SelectedQuery = vm.Queries[0];
Assert.True(vm.CreateEstimateForSelectedCommand.CanExecute(null));
}
[Fact]
public async Task CreateEstimateForSelectedCommand_is_disabled_without_estimate_client()
{
var api = new StubProviderApi();
var client = new BillingApiClient(api, "https://business.example/api/v1/");
var vm = new ProviderOngoingRequestsPageViewModel(client);
await vm.InitializeAsync();
vm.SelectedQuery = vm.Queries[0];
Assert.False(vm.CreateEstimateForSelectedCommand.CanExecute(null));
}
private sealed class StubProviderApi : IYavscApiClient
{
public HttpClient Http { get; } = new();
public List<string> Paths { get; } = new();
public Task<T> CallAsync<T>(HttpMethod method, string path, object? body = null, CancellationToken ct = default)
{
Paths.Add(path);
if (typeof(T) == typeof(List<BillingQuerySummaryDto>))
{
var data = new List<BillingQuerySummaryDto>
{
new()
{
Id = 10,
BillingCode = "Rdv",
ActivityCode = "dev",
PerformerId = "perf-1",
ClientId = "cli-1",
Status = QueryStatus.Inserted,
Description = "Rendez-vous",
EventDate = new DateTime(2026, 9, 10, 10, 0, 0, DateTimeKind.Utc),
},
new()
{
Id = 11,
BillingCode = "MBrush",
ActivityCode = "hair",
PerformerId = "perf-1",
ClientId = "cli-2",
Status = QueryStatus.InProgress,
Description = "Coupe multiple",
EventDate = new DateTime(2026, 9, 11, 10, 0, 0, DateTimeKind.Utc),
},
new()
{
Id = 12,
BillingCode = "Brush",
ActivityCode = "hair",
PerformerId = "perf-1",
ClientId = "cli-3",
Status = QueryStatus.Accepted,
Description = "Coupe simple",
EventDate = new DateTime(2026, 9, 12, 10, 0, 0, DateTimeKind.Utc),
},
new()
{
Id = 13,
BillingCode = "",
ActivityCode = "unknown",
PerformerId = "perf-1",
ClientId = "cli-4",
Status = QueryStatus.Accepted,
Description = "Doit être filtrée",
EventDate = new DateTime(2026, 9, 13, 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 Task<T> CallAsync<T>(HttpMethod method, string path, Func<HttpContent> contentFactory, CancellationToken ct = default)
=> CallAsync<T>(method, path, (object?)null, ct);
public Task CallAsync(HttpMethod method, string path, Func<HttpContent> contentFactory, CancellationToken ct = default)
=> CallAsync(method, path, (object?)null, ct);
public ValueTask DisposeAsync() => ValueTask.CompletedTask;
}
}

View file

@ -74,6 +74,12 @@ public class RdvPageHeadlessTests
public Task CallAsync(HttpMethod method, string path, object? body = null, CancellationToken ct = default)
=> Task.CompletedTask;
public Task<T> CallAsync<T>(HttpMethod method, string path, Func<HttpContent> contentFactory, CancellationToken ct = default)
=> CallAsync<T>(method, path, (object?)null, ct);
public Task CallAsync(HttpMethod method, string path, Func<HttpContent> contentFactory, CancellationToken ct = default)
=> CallAsync(method, path, (object?)null, ct);
public ValueTask DisposeAsync() => ValueTask.CompletedTask;
}
}
}

View file

@ -46,35 +46,48 @@ public partial class App : Application
if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
{
var window = ServiceProvider.GetRequiredService<MainWindow>();
desktop.MainWindow = window;
View = window.MainView;
this.ConfigureRootView(window.MainView);
ApplyDarkMode(settings);
InitializeClassicDesktopLifetime(settings, desktop);
}
else if (ApplicationLifetime is IActivityApplicationLifetime singleViewFactoryApplicationLifetime)
{
singleViewFactoryApplicationLifetime.MainViewFactory =
() =>
{
View = ServiceProvider.GetRequiredService<MainView>();
this.ConfigureRootView(View);
ApplyDarkMode(settings);
return View;
};
InitializeActivityLifetime(settings, singleViewFactoryApplicationLifetime);
}
else if (ApplicationLifetime is ISingleViewApplicationLifetime singleViewPlatform)
{
singleViewPlatform.MainView = View = ServiceProvider.GetRequiredService<MainView>();
ConfigureRootView(View);
ApplyDarkMode(settings);
InitializeSingleViewLifetime(settings, singleViewPlatform);
}
base.OnFrameworkInitializationCompleted();
}
private void ConfigureRootView(MainView rootView)
public void InitializeSingleViewLifetime(Settings settings, ISingleViewApplicationLifetime singleViewPlatform)
{
singleViewPlatform.MainView = View = ServiceProvider!.GetRequiredService<MainView>();
ConfigureRootView(View);
ApplyDarkMode(settings);
}
public void InitializeActivityLifetime(Settings settings, IActivityApplicationLifetime singleViewFactoryApplicationLifetime)
{
singleViewFactoryApplicationLifetime.MainViewFactory =
() =>
{
this.ConfigureRootView(ServiceProvider!.GetRequiredService<MainView>());
ApplyDarkMode(settings);
return View!;
};
}
public void InitializeClassicDesktopLifetime(Settings settings, IClassicDesktopStyleApplicationLifetime desktop)
{
var window = ServiceProvider!.GetRequiredService<MainWindow>();
desktop.MainWindow = window;
this.ConfigureRootView(window.MainView);
ApplyDarkMode(settings);
}
public void ConfigureRootView(MainView rootView)
{
// Déclencher le Boot une seule fois lors du chargement du contrôle à l'écran.
rootView.AttachedToVisualTree += async (_, _) => await BootOnceAsync();
@ -87,6 +100,7 @@ private void ConfigureRootView(MainView rootView)
};
rootView.SessionBanner.DataContext = sessionStatus;
this.View = rootView;
}
private async Task BootOnceAsync()
@ -148,7 +162,7 @@ private void ConfigureRootView(MainView rootView)
public static async Task PushBlogsPageAsync()
{
var app = (App)Current!;
var mainVm = app.ServiceProvider!.GetRequiredService<MainViewModel>();
var mainVm = app.ServiceProvider!.GetRequiredService<BlogsViewModel>();
await mainVm.InitializeAsync();
await app.PushPageAsync(mainVm);
}

View file

@ -3,6 +3,7 @@ using Microsoft.Extensions.DependencyInjection;
using PostIt.Services;
using PostIt.ViewModels;
using PostIt.Views;
using PostIt.Views.Blogs;
using PostIt.Views.Commands;
using Yavsc.Api.Client;
@ -29,12 +30,13 @@ public static class ServiceCollectionHelpers
() => settings.ApiUrl,
() => settings.Authentication?.Authority);
var billingClient = new BillingApiClient(api, () => settings.ApiUrl);
var estimateClient = new EstimateApiClient(api, () => settings.ApiUrl);
var userDirectory = new UserDirectory(userSearchClient);
var reverseGeocoding = new NominatimReverseGeocodingService();
// Vues
services.AddSingleton<MainView>();
services.AddSingleton<MainPage>();
services.AddSingleton<BlogsPage>();
services.AddSingleton<MainWindow>();
// SettingsPage is a singleton: there must be one and only one
@ -58,6 +60,10 @@ public static class ServiceCollectionHelpers
services.AddTransient<BrushPage>();
services.AddTransient<BillingQueriesPage>();
services.AddTransient<BillingQueryDetailsPage>();
services.AddTransient<ProviderOngoingRequestsPage>();
services.AddTransient<EstimateEditionPage>();
services.AddTransient<EstimateListPage>();
// ViewModels
services.AddSingleton(settings);
services.AddSingleton<YavscApiClient>(api);
@ -67,6 +73,7 @@ public static class ServiceCollectionHelpers
services.AddSingleton(userSearchClient);
services.AddSingleton(activityClient);
services.AddSingleton(billingClient);
services.AddSingleton(estimateClient);
services.AddSingleton<IReverseGeocodingService>(reverseGeocoding);
services.AddSingleton<IUserDirectory>(userDirectory);
services.AddSingleton<HomePageViewModel>();
@ -89,7 +96,7 @@ public static class ServiceCollectionHelpers
sessionStatus.Refresh();
services.AddSingleton(sessionStatus);
services.AddSingleton<SessionStatusBanner>();
services.AddSingleton<MainViewModel>();
services.AddSingleton<BlogsViewModel>();
return services.BuildServiceProvider();
}
}

View file

@ -8,7 +8,7 @@ namespace PostIt.Helpers;
public static class ViewModelBaseHelpers
{
public static async Task PushPageAsync(this App app, ViewModelBase vm)
public static async Task<Page> PushPageAsync(this App app, ViewModelBase vm)
{
var window = app.View;
if (window is null)
@ -43,9 +43,11 @@ public static class ViewModelBaseHelpers
var stack = window.NavRoot.NavigationStack;
if (stack.Count > 0 && ReferenceEquals(stack[stack.Count - 1], page))
{
return;
return page;
}
await window.NavRoot.PushAsync(page);
return page;
}
}

View file

@ -5,8 +5,8 @@
<LangVersion>latest</LangVersion>
<AssemblyVersion>1.1.0.0</AssemblyVersion>
<FileVersion>1.1.0.0</FileVersion>
<InformationalVersion>1.1.0-beta.1+183.Branch.release-1.0.8-rc8.Sha.6cff3db32ecf72c0d2d430b7002fa7816a34e070</InformationalVersion>
<Version>1.1.0-beta.1</Version>
<InformationalVersion>1.1.0-feat-sign-estimate.1+306.Branch.feat-sign-estimate.Sha.e9a33695b38154859729b61d1280e596f1597acf</InformationalVersion>
<Version>1.1.0-feat-sign-estimate.1</Version>
</PropertyGroup>
<ItemGroup>
<AvaloniaResource Include="Assets\**" />
@ -33,6 +33,7 @@
<PackageReference Include="Mapsui.Avalonia12" />
<PackageReference Include="CommunityToolkit.Mvvm" />
<PackageReference Include="IdentityModel.OidcClient" />
<PackageReference Include="MarkdownViewer.Core" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" />
</ItemGroup>
<ItemGroup>

View file

@ -191,13 +191,52 @@ public class YavscApiClient : IYavscApiClient, IAsyncDisposable
object? body = null,
CancellationToken ct = default)
{
using var response = await SendAsync(method, path, body, ct).ConfigureAwait(false);
using var response = await SendAsync(method, path, body is null ? null : () => JsonContent.Create(body), ct).ConfigureAwait(false);
await EnsureSuccessOrThrowAsync(response, ct).ConfigureAwait(false);
var stream = await response.Content.ReadAsStreamAsync(ct).ConfigureAwait(false);
var dto = await JsonSerializer.DeserializeAsync<T>(stream,
new JsonSerializerOptions { PropertyNameCaseInsensitive = true }, ct).ConfigureAwait(false);
return dto!;
return await ReadJsonAsync<T>(response, ct).ConfigureAwait(false);
}
/// <summary>
/// Call a multipart endpoint, transparently refreshing the token if needed.
/// </summary>
public virtual async Task<T> CallAsync<T>(
HttpMethod method,
string path,
Func<HttpContent> contentFactory,
CancellationToken ct = default)
{
if (contentFactory is null)
throw new ArgumentNullException(nameof(contentFactory));
using var response = await SendAsync(method, path, contentFactory, ct).ConfigureAwait(false);
await EnsureSuccessOrThrowAsync(response, ct).ConfigureAwait(false);
return await ReadJsonAsync<T>(response, ct).ConfigureAwait(false);
}
/// <summary>
/// Deserialise the response body as <typeparamref name="T"/>,
/// tolerating an empty body. <c>PUT /blogspot/{id}</c> answers
/// <c>204 No Content</c>: without this guard,
/// <c>JsonSerializer.DeserializeAsync</c> throws
/// <c>JsonException: The input does not contain any JSON
/// tokens</c> and the VM surfaces a successful save as an
/// error. Callers that genuinely need a payload
/// (<c>GetPostAsync</c>, <c>CreatePostAsync</c>) are unaffected:
/// their endpoints always return a body.
/// </summary>
private static async Task<T> ReadJsonAsync<T>(HttpResponseMessage response, CancellationToken ct)
{
if (response.StatusCode == HttpStatusCode.NoContent)
return default!;
var payload = await response.Content.ReadAsStringAsync(ct).ConfigureAwait(false);
if (string.IsNullOrWhiteSpace(payload))
return default!;
return JsonSerializer.Deserialize<T>(payload,
new JsonSerializerOptions { PropertyNameCaseInsensitive = true })!;
}
/// <summary>
@ -217,7 +256,23 @@ public class YavscApiClient : IYavscApiClient, IAsyncDisposable
object? body = null,
CancellationToken ct = default)
{
using var response = await SendAsync(method, path, body, ct).ConfigureAwait(false);
using var response = await SendAsync(method, path, body is null ? null : () => JsonContent.Create(body), ct).ConfigureAwait(false);
await EnsureSuccessOrThrowAsync(response, ct).ConfigureAwait(false);
}
/// <summary>
/// Call a multipart endpoint that returns no useful body (DELETE, etc.).
/// </summary>
public async Task CallAsync(
HttpMethod method,
string path,
Func<HttpContent> contentFactory,
CancellationToken ct = default)
{
if (contentFactory is null)
throw new ArgumentNullException(nameof(contentFactory));
using var response = await SendAsync(method, path, contentFactory, ct).ConfigureAwait(false);
await EnsureSuccessOrThrowAsync(response, ct).ConfigureAwait(false);
}
@ -232,7 +287,7 @@ public class YavscApiClient : IYavscApiClient, IAsyncDisposable
=> CallAsync(method, path, body: null, ct);
private async Task<HttpResponseMessage> SendAsync(
HttpMethod method, string path, object? body, CancellationToken ct)
HttpMethod method, string path, Func<HttpContent>? contentFactory, CancellationToken ct)
{
if (_tokens is null)
throw new InvalidOperationException("Not logged in. Call LoginInteractiveAsync first.");
@ -240,8 +295,8 @@ public class YavscApiClient : IYavscApiClient, IAsyncDisposable
await EnsureFreshTokenAsync(ct).ConfigureAwait(false);
using var req = new HttpRequestMessage(method, path);
if (body is not null)
req.Content = JsonContent.Create(body);
if (contentFactory is not null)
req.Content = contentFactory();
var response = await Http.SendAsync(req, ct).ConfigureAwait(false);
if (response.StatusCode == HttpStatusCode.Unauthorized)
@ -252,8 +307,8 @@ public class YavscApiClient : IYavscApiClient, IAsyncDisposable
await ForceRefreshAsync(ct).ConfigureAwait(false);
using var retry = new HttpRequestMessage(method, path);
if (body is not null)
retry.Content = JsonContent.Create(body);
if (contentFactory is not null)
retry.Content = contentFactory();
response = await Http.SendAsync(retry, ct).ConfigureAwait(false);
}

View file

@ -6,6 +6,7 @@ using Microsoft.Extensions.DependencyInjection;
using PostIt.ViewModels;
using PostIt.ViewModels.Commands;
using PostIt.Views;
using PostIt.Views.Blogs;
using PostIt.Views.Commands;
namespace PostIt;
@ -38,7 +39,7 @@ public class ViewLocator : IDataTemplate
var services = app!.ServiceProvider!;
return data switch
{
MainViewModel => services.GetRequiredService<MainPage>(),
BlogsViewModel => services.GetRequiredService<BlogsPage>(),
Settings => services.GetRequiredService<SettingsPage>(),
HomePageViewModel => services.GetRequiredService<HomePage>(),
ActivitiesPageViewModel => services.GetRequiredService<ActivitiesPage>(),
@ -51,6 +52,9 @@ public class ViewLocator : IDataTemplate
PostAclDialogViewModel => services.GetRequiredService<PostAclDialog>(),
BillingQueriesPageViewModel => services.GetRequiredService<BillingQueriesPage>(),
BillingQueryDetailsPageViewModel => services.GetRequiredService<BillingQueryDetailsPage>(),
ProviderOngoingRequestsPageViewModel => services.GetRequiredService<ProviderOngoingRequestsPage>(),
EstimateEditionPageViewModel => services.GetRequiredService<EstimateEditionPage>(),
EstimateListPageViewModel => services.GetRequiredService<EstimateListPage>(),
null => new TextBlock { Text = "No view for <null>" },
_ => new TextBlock { Text = $"No view for {data.GetType().Name}" }
};

View file

@ -43,7 +43,7 @@ public partial class BillingQueriesPageViewModel : ViewModelBase, IActionStatusV
? $"Demandes en cours ({Form.Title})"
: $"Commandes {Form.Title}";
public string ContextLabel => $"{Performer.UserName} · {Activity.Name}";
public bool CanOpenDetails => true;
public bool CanOpenDetails => !IsReadOnly;
public override bool CanNavigateNext
{
@ -75,7 +75,7 @@ public partial class BillingQueriesPageViewModel : ViewModelBase, IActionStatusV
public Task InitializeAsync() => RefreshAsync();
private bool CanOpenSelectedQuery() => SelectedQuery is not null;
private bool CanOpenSelectedQuery() => CanOpenDetails && SelectedQuery is not null;
[RelayCommand]
public async Task RefreshAsync()

View file

@ -0,0 +1,293 @@
using System;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
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.Api.Client;
namespace PostIt.ViewModels;
/// <summary>
/// Edition d'un devis (<c>Estimate</c>) créé en réponse à une demande
/// client (<see cref="BillingQuerySummaryDto"/>) consultée depuis la
/// page « Mes demandes en cours ». L'envoi poste le devis sur
/// <c>api/v1/estimate</c>; côté serveur, la commande liée
/// (<see cref="BillingQuerySummaryDto.Id"/>) est alors marquée comme
/// validée par le prestataire.
/// </summary>
public partial class EstimateEditionPageViewModel : ViewModelBase, IActionStatusViewModel
{
private readonly EstimateApiClient _estimateClient;
private readonly BillingQuerySummaryDto _query;
public long QueryId => _query.Id;
public string ClientId => _query.ClientId;
public string BillingCode => _query.BillingCode;
public string Title => $"Devis — demande #{_query.Id}";
public string ContextLabel
=> $"Demande #{_query.Id} · {BillingCode} · client {ClientId}";
public string QueryDescription => string.IsNullOrWhiteSpace(_query.Description)
? "(sans description)"
: _query.Description;
[ObservableProperty]
public partial string EstimateTitle { get; set; } = string.Empty;
[ObservableProperty]
public partial string EstimateDescription { get; set; } = string.Empty;
[ObservableProperty]
public partial ObservableCollection<EstimateLineItemViewModel> Lines { get; set; } = new();
[ObservableProperty, NotifyCanExecuteChangedFor(nameof(RemoveLineCommand))]
public partial EstimateLineItemViewModel? SelectedLine { get; set; }
[ObservableProperty, NotifyCanExecuteChangedFor(nameof(SendCommand))]
public partial bool IsBusy { get; set; }
/// <summary>
/// True une fois le devis accepté par le serveur: l'envoi est
/// désactivé pour éviter les doublons, il ne reste que « Retour ».
/// </summary>
[ObservableProperty, NotifyCanExecuteChangedFor(nameof(SendCommand))]
public partial bool HasSent { get; set; }
[ObservableProperty]
public partial string StatusMessage { get; set; } = "Prêt.";
[ObservableProperty]
public partial StatusNotice ActionStatus { get; set; } = StatusNotice.Info("Prêt.");
public decimal Total => Lines.Sum(line => line.LineTotal);
public string TotalLabel => $"{Total:0.00} {Lines.FirstOrDefault()?.Currency ?? "EUR"}";
public string SendLabel => HasSent ? "Devis envoyé" : "Envoyer le devis";
public override bool CanNavigateNext
{
get => false;
protected set { _ = value; }
}
public override bool CanNavigatePrevious
{
get => true;
protected set { _ = value; }
}
public EstimateEditionPageViewModel(BillingQuerySummaryDto query, EstimateApiClient estimateClient)
{
_query = query ?? throw new ArgumentNullException(nameof(query));
_estimateClient = estimateClient ?? throw new ArgumentNullException(nameof(estimateClient));
EstimateDescription = query.Description ?? string.Empty;
Lines.CollectionChanged += OnLinesCollectionChanged;
AddLine();
this.SetInfoStatus("Complétez le devis puis envoyez-le. La demande associée sera validée.");
}
[RelayCommand]
private void AddLine()
{
var line = new EstimateLineItemViewModel();
Lines.Add(line);
SelectedLine = line;
}
private bool CanRemoveLine() => SelectedLine is not null && !IsBusy && !HasSent;
[RelayCommand(CanExecute = nameof(CanRemoveLine))]
private void RemoveLine()
{
if (SelectedLine is null)
{
return;
}
var index = Lines.IndexOf(SelectedLine);
Lines.Remove(SelectedLine);
SelectedLine = Lines.Count == 0
? null
: Lines[Math.Min(index, Lines.Count - 1)];
}
private bool CanSend() => !IsBusy && !HasSent;
[RelayCommand(CanExecute = nameof(CanSend))]
private async Task SendAsync()
{
if (!TryValidate(out var validationMessage))
{
this.SetWarningStatus(validationMessage);
return;
}
IsBusy = true;
try
{
var payload = BuildPayload();
var created = await _estimateClient.CreateAsync(payload).ConfigureAwait(true);
HasSent = true;
OnPropertyChanged(nameof(SendLabel));
this.SetInfoStatus(
$"Devis #{created.Id} envoyé ({created.Bill.Count} ligne(s)). La demande #{QueryId} est validée.");
}
catch (HttpRequestException ex) when (ex.StatusCode is HttpStatusCode.Unauthorized or HttpStatusCode.Forbidden)
{
this.SetWarningStatus("Accès refusé à l'API devis (scope 'api'). Déconnectez puis reconnectez-vous.");
}
catch (Exception ex)
{
this.SetErrorStatus($"Erreur lors de l'envoi du devis: {ex.Message}");
}
finally
{
IsBusy = false;
}
}
[RelayCommand]
private async Task BackAsync()
{
var app = (App?)Application.Current;
if (app is null)
{
throw new InvalidOperationException("Application PostIt indisponible.");
}
await app.GoBackAsync().ConfigureAwait(true);
}
internal EstimateDto BuildPayload()
{
return new EstimateDto
{
CommandId = QueryId,
ClientId = ClientId,
CommandType = BillingCode,
Title = EstimateTitle.Trim(),
Description = EstimateDescription.Trim(),
Bill = Lines.Select(line => new EstimateLineDto
{
Id = line.Id,
Name = line.Name.Trim(),
Description = line.Description.Trim(),
Count = Math.Max(1, (int)Math.Round(line.Count)),
UnitaryCost = line.UnitaryCost,
Currency = string.IsNullOrWhiteSpace(line.Currency) ? "EUR" : line.Currency.Trim(),
}).ToList(),
};
}
private bool TryValidate(out string message)
{
if (string.IsNullOrWhiteSpace(EstimateTitle))
{
message = "Le titre du devis est requis.";
return false;
}
if (string.IsNullOrWhiteSpace(ClientId))
{
message = "La demande sélectionnée n'identifie pas de client.";
return false;
}
if (string.IsNullOrWhiteSpace(BillingCode))
{
message = "La demande sélectionnée n'a pas de code de facturation.";
return false;
}
if (Lines.Count == 0)
{
message = "Ajoutez au moins une ligne au devis.";
return false;
}
foreach (var line in Lines)
{
if (string.IsNullOrWhiteSpace(line.Name))
{
message = "Chaque ligne doit avoir un nom.";
return false;
}
if (line.Name.Trim().Length > 256)
{
message = $"Le nom de la ligne « {line.Name.Trim()[..20]}… » dépasse 256 caractères.";
return false;
}
if (string.IsNullOrWhiteSpace(line.Description))
{
message = $"La ligne « {line.Name.Trim()} » doit avoir une description.";
return false;
}
if (line.Description.Trim().Length > 512)
{
message = $"La description de la ligne « {line.Name.Trim()} » dépasse 512 caractères.";
return false;
}
if (line.Count < 1)
{
message = $"La quantité de la ligne « {line.Name.Trim()} » doit être d'au moins 1.";
return false;
}
}
message = string.Empty;
return true;
}
private void OnLinesCollectionChanged(object? sender, NotifyCollectionChangedEventArgs e)
{
if (e.OldItems is not null)
{
foreach (var item in e.OldItems.OfType<EstimateLineItemViewModel>())
{
item.PropertyChanged -= OnLinePropertyChanged;
}
}
if (e.NewItems is not null)
{
foreach (var item in e.NewItems.OfType<EstimateLineItemViewModel>())
{
item.PropertyChanged += OnLinePropertyChanged;
}
}
RaiseTotalsChanged();
}
private void OnLinePropertyChanged(object? sender, PropertyChangedEventArgs e)
{
if (e.PropertyName is nameof(EstimateLineItemViewModel.LineTotal)
or nameof(EstimateLineItemViewModel.Currency))
{
RaiseTotalsChanged();
}
}
private void RaiseTotalsChanged()
{
OnPropertyChanged(nameof(Total));
OnPropertyChanged(nameof(TotalLabel));
}
}

View file

@ -0,0 +1,35 @@
using CommunityToolkit.Mvvm.ComponentModel;
namespace PostIt.ViewModels;
/// <summary>
/// Editable estimate line. <see cref="Count"/> is exposed as a
/// <see cref="decimal"/> so it binds directly to
/// <c>NumericUpDown.Value</c> (<c>decimal?</c>); it is rounded back
/// to an integer when the DTO is built.
/// </summary>
public partial class EstimateLineItemViewModel : ObservableObject
{
public long Id { get; set; }
[ObservableProperty]
public partial string Name { get; set; } = string.Empty;
[ObservableProperty]
public partial string Description { get; set; } = string.Empty;
[ObservableProperty, NotifyPropertyChangedFor(nameof(LineTotal))]
[NotifyPropertyChangedFor(nameof(LineTotalLabel))]
public partial decimal Count { get; set; } = 1m;
[ObservableProperty, NotifyPropertyChangedFor(nameof(LineTotal))]
[NotifyPropertyChangedFor(nameof(LineTotalLabel))]
public partial decimal UnitaryCost { get; set; }
[ObservableProperty]
public partial string Currency { get; set; } = "EUR";
public decimal LineTotal => Count * UnitaryCost;
public string LineTotalLabel => $"{LineTotal:0.00}";
}

View file

@ -0,0 +1,156 @@
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 CommunityToolkit.Mvvm.Input;
using PostIt.Helpers;
using Yavsc.Api.Client;
namespace PostIt.ViewModels;
/// <summary>
/// Point de vue d'une liste de devis en cours (non encore validés par
/// le client).
/// </summary>
public enum EstimateListPerspective
{
/// <summary>« Mes devis à valider » — l'utilisateur courant est le client.</summary>
Client,
/// <summary>« Mes devis en attente » — l'utilisateur courant est le fournisseur.</summary>
Provider,
}
/// <summary>
/// Liste des devis en cours servie par <c>GET api/v1/estimate/asclient</c>
/// ou <c>GET api/v1/estimate/asprovider</c> selon la perspective choisie.
/// </summary>
public partial class EstimateListPageViewModel : ViewModelBase, IActionStatusViewModel
{
private readonly EstimateApiClient _estimateClient;
private readonly EstimateListPerspective _perspective;
private List<EstimateDto> _allEstimates = new();
public EstimateListPerspective Perspective => _perspective;
public string Title => _perspective == EstimateListPerspective.Client
? "Mes devis à valider"
: "Mes devis en attente";
public string Subtitle => _perspective == EstimateListPerspective.Client
? "Point de vue client"
: "Point de vue fournisseur";
/// <summary>
/// Libellé de la colonne « autre partie » : côté client on montre
/// le fournisseur (OwnerId), côté fournisseur on montre le client.
/// </summary>
public string CounterpartLabel => _perspective == EstimateListPerspective.Client
? "Fournisseur"
: "Client";
[ObservableProperty]
public partial ObservableCollection<EstimateDto> Estimates { get; set; } = new();
[ObservableProperty]
public partial string FilterText { get; set; } = string.Empty;
[ObservableProperty]
public partial EstimateDto? SelectedEstimate { get; set; }
[ObservableProperty]
public partial bool IsBusy { get; set; }
[ObservableProperty]
public partial string StatusMessage { get; set; } = "Chargement des devis...";
[ObservableProperty]
public partial StatusNotice ActionStatus { get; set; } = StatusNotice.Info("Chargement des devis...");
public override bool CanNavigateNext
{
get => false;
protected set { _ = value; }
}
public override bool CanNavigatePrevious
{
get => true;
protected set { _ = value; }
}
public EstimateListPageViewModel(EstimateApiClient estimateClient, EstimateListPerspective perspective)
{
_estimateClient = estimateClient ?? throw new ArgumentNullException(nameof(estimateClient));
_perspective = perspective;
}
public Task InitializeAsync() => RefreshAsync();
[RelayCommand]
public async Task RefreshAsync()
{
IsBusy = true;
try
{
var items = (_perspective == EstimateListPerspective.Client
? await _estimateClient.GetOngoingEstimatesAsClientAsync().ConfigureAwait(true)
: await _estimateClient.GetOngoingEstimatesAsProviderAsync().ConfigureAwait(true))
?? new List<EstimateDto>();
_allEstimates = items
.OrderByDescending(x => x.Id)
.ToList();
ApplyFilter();
this.SetInfoStatus(_allEstimates.Count == 0
? "Aucun devis en cours."
: $"{_allEstimates.Count} devis en cours chargé(s).");
}
catch (HttpRequestException ex) when (ex.StatusCode is HttpStatusCode.Unauthorized or HttpStatusCode.Forbidden)
{
_allEstimates = new List<EstimateDto>();
Estimates = new ObservableCollection<EstimateDto>();
this.SetWarningStatus("Accès refusé (scope 'api'). Déconnectez puis reconnectez-vous.");
}
catch (Exception ex)
{
_allEstimates = new List<EstimateDto>();
Estimates = new ObservableCollection<EstimateDto>();
this.SetErrorStatus($"Erreur: {ex.Message}");
}
finally
{
IsBusy = false;
}
}
partial void OnFilterTextChanged(string value)
{
ApplyFilter();
}
private void ApplyFilter()
{
var query = FilterText?.Trim();
var filtered = string.IsNullOrWhiteSpace(query)
? _allEstimates
: _allEstimates.Where(x =>
ContainsInsensitive(x.Title, query)
|| ContainsInsensitive(x.Description, query)
|| ContainsInsensitive(x.CommandType, query)
|| ContainsInsensitive(x.ClientId, query)
|| ContainsInsensitive(x.OwnerId, query))
.ToList();
Estimates = new ObservableCollection<EstimateDto>(filtered);
}
private static bool ContainsInsensitive(string? value, string query)
=> !string.IsNullOrWhiteSpace(value)
&& value.Contains(query, StringComparison.OrdinalIgnoreCase);
}

View file

@ -0,0 +1,390 @@
using System;
using System.Collections.ObjectModel;
using System.Collections.Generic;
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.Abstract.Workflow;
using Yavsc.Api.Client;
namespace PostIt.ViewModels;
public partial class ProviderOngoingRequestsPageViewModel : ViewModelBase, IActionStatusViewModel
{
public const string SortByDate = "Date (plus récent d'abord)";
public const string SortByDateAsc = "Date (plus ancien d'abord)";
public const string SortByStatus = "Statut (en cours d'abord)";
private readonly BillingApiClient _billingClient;
private readonly EstimateApiClient? _estimateClient;
private readonly Settings? _settings;
private List<BillingQuerySummaryDto> _allQueries = new();
[ObservableProperty]
public partial ObservableCollection<BillingQuerySummaryDto> Queries { get; set; } = new();
[ObservableProperty]
public partial string FilterText { get; set; } = string.Empty;
public IReadOnlyList<string> SortOptions { get; } = new[]
{
SortByDate,
SortByDateAsc,
SortByStatus,
};
[ObservableProperty]
public partial string SelectedSortOption { get; set; } = SortByDate;
[ObservableProperty, NotifyCanExecuteChangedFor(nameof(OpenSelectedQueryCommand))]
[NotifyCanExecuteChangedFor(nameof(OpenSelectedEditorCommand))]
[NotifyCanExecuteChangedFor(nameof(CreateEstimateForSelectedCommand))]
public partial BillingQuerySummaryDto? SelectedQuery { get; set; }
[ObservableProperty]
public partial bool IsBusy { get; set; }
[ObservableProperty]
public partial string StatusMessage { get; set; } = "Chargement des demandes fournisseur...";
[ObservableProperty]
public partial StatusNotice ActionStatus { get; set; } = StatusNotice.Info("Chargement des demandes fournisseur...");
public string Title => "Mes demandes en cours";
public override bool CanNavigateNext
{
get => false;
protected set { _ = value; }
}
public override bool CanNavigatePrevious
{
get => true;
protected set { _ = value; }
}
public ProviderOngoingRequestsPageViewModel(
BillingApiClient billingClient,
Settings? settings = null,
EstimateApiClient? estimateClient = null)
{
_billingClient = billingClient ?? throw new ArgumentNullException(nameof(billingClient));
_estimateClient = estimateClient;
_settings = settings;
if (_settings is not null)
{
var preferredSort = NormalizeSortOption(_settings.ProviderOngoingRequestsSortOption);
if (!string.Equals(preferredSort, SelectedSortOption, StringComparison.Ordinal))
{
SelectedSortOption = preferredSort;
}
}
}
public Task InitializeAsync() => RefreshAsync();
[RelayCommand]
public async Task RefreshAsync()
{
IsBusy = true;
try
{
var items = await _billingClient.GetProviderOngoingQueriesAsync().ConfigureAwait(true) ?? new();
_allQueries = items
.Where(x => !string.IsNullOrWhiteSpace(x.BillingCode))
.OrderByDescending(x => x.EventDate ?? DateTime.MinValue)
.ThenByDescending(x => x.Id)
.ToList();
ApplyFilter();
this.SetInfoStatus(_allQueries.Count == 0
? "Aucune demande en cours pour votre profil fournisseur."
: $"{_allQueries.Count} demande(s) en cours chargée(s).");
}
catch (HttpRequestException ex) when (ex.StatusCode is HttpStatusCode.Unauthorized or HttpStatusCode.Forbidden)
{
_allQueries = new List<BillingQuerySummaryDto>();
Queries = new ObservableCollection<BillingQuerySummaryDto>();
this.SetWarningStatus("Accès refusé au billing (scope 'api'). Déconnectez puis reconnectez-vous.");
}
catch (Exception ex)
{
_allQueries = new List<BillingQuerySummaryDto>();
Queries = new ObservableCollection<BillingQuerySummaryDto>();
this.SetErrorStatus($"Erreur: {ex.Message}");
}
finally
{
IsBusy = false;
}
}
private bool CanOpenSelectedQuery() => SelectedQuery is not null;
private bool CanOpenSelectedEditor() => SelectedQuery is not null;
[RelayCommand(CanExecute = nameof(CanOpenSelectedQuery))]
public async Task OpenSelectedQueryAsync()
{
if (SelectedQuery is null)
{
this.SetWarningStatus("Sélectionnez une demande.");
return;
}
var app = (App?)Application.Current;
if (app is null)
{
throw new InvalidOperationException("Application PostIt indisponible.");
}
IsBusy = true;
try
{
var details = await _billingClient
.GetQueryAsync(SelectedQuery.BillingCode, SelectedQuery.Id)
.ConfigureAwait(true);
var (activity, performer, form) = BuildNavigationContext(SelectedQuery);
var vm = new BillingQueryDetailsPageViewModel(
activity,
performer,
form,
_billingClient,
details,
isReadOnly: false);
await app.PushPageAsync(vm).ConfigureAwait(true);
}
catch (Exception ex)
{
this.SetErrorStatus($"Erreur lors de l'ouverture: {ex.Message}");
}
finally
{
IsBusy = false;
}
}
[RelayCommand(CanExecute = nameof(CanOpenSelectedEditor))]
public async Task OpenSelectedEditorAsync()
{
if (SelectedQuery is null)
{
this.SetWarningStatus("Sélectionnez une demande.");
return;
}
var app = (App?)Application.Current;
if (app is null)
{
throw new InvalidOperationException("Application PostIt indisponible.");
}
IsBusy = true;
try
{
var details = await _billingClient
.GetQueryAsync(SelectedQuery.BillingCode, SelectedQuery.Id)
.ConfigureAwait(true);
var (activity, performer, form) = BuildNavigationContext(SelectedQuery);
var vm = form.CreateCommandPageViewModel(activity, performer, _billingClient);
if (vm is null)
{
this.SetWarningStatus($"Le formulaire '{form.ActionName}' n'est pas pris en charge en édition.");
return;
}
await vm.InitializeAsync(details).ConfigureAwait(true);
await app.PushPageAsync(vm).ConfigureAwait(true);
}
catch (Exception ex)
{
this.SetErrorStatus($"Erreur lors de l'ouverture en édition: {ex.Message}");
}
finally
{
IsBusy = false;
}
}
private bool CanCreateEstimateForSelected() => SelectedQuery is not null && _estimateClient is not null;
[RelayCommand(CanExecute = nameof(CanCreateEstimateForSelected))]
public async Task CreateEstimateForSelectedAsync()
{
if (SelectedQuery is null)
{
this.SetWarningStatus("Sélectionnez une demande.");
return;
}
if (_estimateClient is null)
{
this.SetWarningStatus("Le client devis n'est pas disponible.");
return;
}
var app = (App?)Application.Current;
if (app is null)
{
throw new InvalidOperationException("Application PostIt indisponible.");
}
var vm = new EstimateEditionPageViewModel(SelectedQuery, _estimateClient);
await app.PushPageAsync(vm).ConfigureAwait(true);
}
partial void OnFilterTextChanged(string value)
{
ApplyFilter();
}
partial void OnSelectedSortOptionChanged(string value)
{
var normalized = NormalizeSortOption(value);
if (!string.Equals(normalized, value, StringComparison.Ordinal))
{
SelectedSortOption = normalized;
return;
}
PersistSortPreference(value);
ApplyFilter();
}
private void ApplyFilter()
{
var query = FilterText?.Trim();
var filtered = string.IsNullOrWhiteSpace(query)
? _allQueries
: _allQueries.Where(x =>
ContainsInsensitive(x.Description, query)
|| ContainsInsensitive(x.ActivityCode, query)
|| ContainsInsensitive(x.BillingCode, query)
|| ContainsInsensitive(x.ClientId, query)
|| ContainsInsensitive(x.Status.ToString(), query))
.ToList();
var sorted = ApplySort(filtered);
Queries = new ObservableCollection<BillingQuerySummaryDto>(sorted);
}
private List<BillingQuerySummaryDto> ApplySort(IEnumerable<BillingQuerySummaryDto> source)
{
if (string.Equals(SelectedSortOption, SortByStatus, StringComparison.Ordinal))
{
return source
.OrderBy(x => GetStatusRank(x.Status))
.ThenByDescending(x => x.EventDate ?? DateTime.MinValue)
.ThenByDescending(x => x.Id)
.ToList();
}
if (string.Equals(SelectedSortOption, SortByDateAsc, StringComparison.Ordinal))
{
return source
.OrderBy(x => x.EventDate ?? DateTime.MinValue)
.ThenBy(x => x.Id)
.ToList();
}
return source
.OrderByDescending(x => x.EventDate ?? DateTime.MinValue)
.ThenByDescending(x => x.Id)
.ToList();
}
private void PersistSortPreference(string selectedSort)
{
if (_settings is null)
{
return;
}
if (string.Equals(_settings.ProviderOngoingRequestsSortOption, selectedSort, StringComparison.Ordinal))
{
return;
}
_settings.ProviderOngoingRequestsSortOption = selectedSort;
try
{
_settings.Save();
}
catch
{
this.SetWarningStatus("Le tri a été appliqué, mais sa sauvegarde a échoué.");
}
}
private static string NormalizeSortOption(string? sortOption)
{
if (string.Equals(sortOption, SortByDate, StringComparison.Ordinal)
|| string.Equals(sortOption, SortByDateAsc, StringComparison.Ordinal)
|| string.Equals(sortOption, SortByStatus, StringComparison.Ordinal))
{
return sortOption!;
}
return SortByDate;
}
private static int GetStatusRank(QueryStatus status)
=> status switch
{
QueryStatus.InProgress => 0,
QueryStatus.Accepted => 1,
QueryStatus.Inserted => 2,
QueryStatus.Success => 3,
QueryStatus.Rejected => 4,
QueryStatus.Failed => 5,
_ => 99,
};
private static bool ContainsInsensitive(string? source, string query)
=> !string.IsNullOrWhiteSpace(source)
&& source.Contains(query, StringComparison.OrdinalIgnoreCase);
private static (ActivityInfo activity, ActivityUserDisplayItem performer, CommandFormSummary form)
BuildNavigationContext(BillingQuerySummaryDto query)
{
var activity = new ActivityInfo
{
Code = query.ActivityCode,
Name = string.IsNullOrWhiteSpace(query.ActivityCode)
? "Activité"
: query.ActivityCode,
};
var performer = new ActivityUserDisplayItem
{
PerformerId = query.PerformerId,
UserName = "Mon profil fournisseur",
AvatarFallbackLabel = "M",
IsPerformerActive = true,
PerformerStatusBadgeLabel = "Actif",
PerformerStatusBadgeBackground = "#E6F7EC",
PerformerStatusBadgeBorder = "#2E7D32",
PerformerStatusBadgeForeground = "#1B5E20",
};
var form = new CommandFormSummary
{
ActionName = query.BillingCode,
Title = query.BillingCode,
};
return (activity, performer, form);
}
}

View file

@ -1,5 +1,6 @@
using System;
using System.Collections.ObjectModel;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Avalonia;
@ -8,11 +9,12 @@ using CommunityToolkit.Mvvm.Input;
using Microsoft.Extensions.DependencyInjection;
using Yavsc.Blogspot;
using Yavsc.Api.Client;
using Yavsc.Abstract.Files;
using PostIt.Helpers;
namespace PostIt.ViewModels;
public partial class MainViewModel : ViewModelBase, IActionStatusViewModel
public partial class BlogsViewModel : ViewModelBase, IActionStatusViewModel
{
/// <summary>Window/tab title. Cosmetic — bound by
/// <c>MainPage.axaml</c> if at all. Not the post title.</summary>
@ -66,6 +68,9 @@ public partial class MainViewModel : ViewModelBase, IActionStatusViewModel
[ObservableProperty]
public partial ObservableCollection<BlogPostDto> FilteredPosts { get; set; }
[ObservableProperty]
public partial ObservableCollection<BlogUploadFile> DraftAttachments { get; set; }
[ObservableProperty]
public partial BlogPostDto? SelectedPost { get; set; }
@ -75,6 +80,9 @@ public partial class MainViewModel : ViewModelBase, IActionStatusViewModel
[ObservableProperty]
public partial Settings Settings { get; private set; }
[ObservableProperty]
public partial bool IsMarkdownViewerVisible { get; set; }
[RelayCommand]
internal async Task RefreshAsync()
{
@ -91,12 +99,6 @@ public partial class MainViewModel : ViewModelBase, IActionStatusViewModel
});
}
[RelayCommand]
internal async Task SearchAsync() {
await RefreshAsync();
ApplyFilter();
}
[RelayCommand]
internal async Task SaveAsync()
{
@ -113,9 +115,11 @@ public partial class MainViewModel : ViewModelBase, IActionStatusViewModel
await ExecuteAsync(async () =>
{
var attachments = DraftAttachments.ToArray();
// Build a fresh BlogPostDto from the editor buffer on
// every Save — we no longer mutate SelectedPost in
// place. The previous behaviour copied the buffer
// place. The previous behavior copied the buffer
// (which was a no-op when SelectedPost was null)
// back onto the model and relied on a
// [Required] violation to surface the missing
@ -133,15 +137,33 @@ public partial class MainViewModel : ViewModelBase, IActionStatusViewModel
DateModified = DateTime.UtcNow,
IsPublished = DraftIsPublished
};
var created = await BlogClient!.CreatePostAsync(draft);
var created = await BlogClient!.CreatePostAsync(draft, attachments);
if (created is not null)
{
SelectedPost = created;
if (TryAppendAttachmentLinks(created, attachments))
{
var linkUpdate = new BlogPostDto
{
Id = created.Id,
AuthorId = created.AuthorId,
Photo = created.Photo,
Title = DraftTitle,
Article = DraftArticle ?? string.Empty,
DateCreated = created.DateCreated,
DateModified = DateTime.UtcNow,
};
await BlogClient.UpdatePostAsync(created.Id, linkUpdate);
}
this.SetInfoStatus($"Billet {created.Id} créé.");
DraftAttachments.Clear();
}
}
else
{
TryAppendAttachmentLinks(SelectedPost, attachments);
var update = new BlogPostDto
{
Id = SelectedPost.Id,
@ -152,8 +174,9 @@ public partial class MainViewModel : ViewModelBase, IActionStatusViewModel
DateCreated = SelectedPost.DateCreated,
DateModified = DateTime.UtcNow,
};
await BlogClient!.UpdatePostAsync(SelectedPost.Id, update);
await BlogClient!.UpdatePostAsync(SelectedPost.Id, update, attachments);
this.SetInfoStatus($"Billet {SelectedPost.Id} enregistré.");
DraftAttachments.Clear();
}
await RefreshPostsAsync();
@ -336,8 +359,9 @@ public partial class MainViewModel : ViewModelBase, IActionStatusViewModel
}
public MainViewModel()
public BlogsViewModel()
{
WindowTitle = "Blog";
SettingsModel = new Settings();
Init(SettingsModel);
BlogClient = null;
@ -347,11 +371,13 @@ public partial class MainViewModel : ViewModelBase, IActionStatusViewModel
{
Posts = new ObservableCollection<BlogPostDto>();
FilteredPosts = new ObservableCollection<BlogPostDto>();
DraftAttachments = new ObservableCollection<BlogUploadFile>();
SelectedPost = null;
IsBusy = false;
this.SetInfoStatus("Prêt.");
Settings = settings ?? new Settings();
SearchText = Settings.SearchText;
IsMarkdownViewerVisible = false;
WindowTitle = "PostIt";
DraftTitle = string.Empty;
DraftArticle = string.Empty;
@ -396,8 +422,9 @@ public partial class MainViewModel : ViewModelBase, IActionStatusViewModel
/// <see cref="BlogApiClient"/>. Production code uses the
/// (Settings, BlogApiClient) overload below.
/// </summary>
public MainViewModel(BlogApiClient blogClient, Settings? settings = null, IServiceProvider? services = null)
public BlogsViewModel(BlogApiClient blogClient, Settings? settings = null, IServiceProvider? services = null)
{
WindowTitle = "Blog";
SettingsModel = new Settings();
BlogClient = blogClient ?? throw new ArgumentNullException(nameof(blogClient)); ;
Services = services;
@ -427,6 +454,7 @@ public partial class MainViewModel : ViewModelBase, IActionStatusViewModel
// Mirror publication state too. Defaults to false on
// null selection so a fresh draft starts unpublished.
DraftIsPublished = value?.IsPublished ?? false;
DraftAttachments.Clear();
UpdateCommandStates();
}
@ -508,4 +536,55 @@ public partial class MainViewModel : ViewModelBase, IActionStatusViewModel
IsLoaded = true;
}
}
private bool TryAppendAttachmentLinks(BlogPostDto post, IReadOnlyCollection<BlogUploadFile> attachments)
{
if (attachments.Count == 0)
return false;
var ownerSegment = post.Author?.UserName;
if (string.IsNullOrWhiteSpace(ownerSegment))
ownerSegment = post.AuthorId;
if (string.IsNullOrWhiteSpace(ownerSegment))
return false;
var article = DraftArticle ?? string.Empty;
var links = new List<string>();
foreach (var attachment in attachments)
{
var relativePath = $"{EscapePathSegment(ownerSegment)}/blogs/{post.Id}/{EscapePathSegment(attachment.FileName)}";
var fileUrl = ResolveUserFileUrl(relativePath);
var markdownLine = $"- [{attachment.FileName}]({fileUrl})";
if (!article.Contains(markdownLine, StringComparison.Ordinal))
links.Add(markdownLine);
}
if (links.Count == 0)
return false;
var prefix = article.Length == 0
? ""
: (article.EndsWith("\n", StringComparison.Ordinal) ? "\n" : "\n\n");
DraftArticle = article + prefix + string.Join("\n", links);
return true;
}
private string ResolveUserFileUrl(string relativePath)
{
var authority = Settings?.Authentication?.Authority;
if (!string.IsNullOrWhiteSpace(authority)
&& Uri.TryCreate(authority, UriKind.Absolute, out var baseUri))
{
return FileServerUrlHelpers.GetUserFilesUri(baseUri, relativePath).ToString();
}
return $"{Yavsc.Constants.UserFilesPath}/{relativePath}";
}
private static string EscapePathSegment(string segment)
=> Uri.EscapeDataString(segment);
}

View file

@ -12,6 +12,9 @@ namespace PostIt.ViewModels.Commands;
public partial class RdvViewModel : BillingCommandPageViewModel
{
private long? _existingLocationId;
private bool _hydratingExistingQuery;
public override string SupportMessage => "Complétez les informations du rendez-vous puis postez la commande.";
[ObservableProperty]
@ -56,6 +59,7 @@ public partial class RdvViewModel : BillingCommandPageViewModel
protected override void ApplyExistingQuery(BillingQueryDetailsDto existingQuery)
{
_hydratingExistingQuery = true;
ExistingQueryId = existingQuery.Id;
CommandStatus = existingQuery.Status;
Consent = existingQuery.Consent;
@ -70,11 +74,18 @@ public partial class RdvViewModel : BillingCommandPageViewModel
if (existingQuery.Location is not null)
{
_existingLocationId = existingQuery.Location.Id;
Address = existingQuery.Location.Address ?? string.Empty;
SuggestedAddress = string.Empty;
Latitude = existingQuery.Location.Latitude;
Longitude = existingQuery.Location.Longitude;
}
else
{
_existingLocationId = null;
}
_hydratingExistingQuery = false;
this.SetInfoStatus($"Commande #{existingQuery.Id} chargée.");
}
@ -117,20 +128,22 @@ public partial class RdvViewModel : BillingCommandPageViewModel
}
}
protected static object BuildLocationPayload(string address, double? latitude, double? longitude)
protected static BillingLocationDto BuildLocationPayload(string address, double? latitude, double? longitude, long? locationId = null)
{
if (latitude.HasValue && longitude.HasValue)
{
return new
return new BillingLocationDto
{
Id = locationId,
Address = address,
Latitude = latitude.Value,
Longitude = longitude.Value,
};
}
return new
return new BillingLocationDto
{
Id = locationId,
Address = address,
};
}
@ -223,6 +236,30 @@ public partial class RdvViewModel : BillingCommandPageViewModel
OnPropertyChanged(nameof(EventDateSelection));
}
partial void OnAddressChanged(string value)
{
if (_hydratingExistingQuery)
return;
_existingLocationId = null;
}
partial void OnLatitudeChanged(double? value)
{
if (_hydratingExistingQuery)
return;
_existingLocationId = null;
}
partial void OnLongitudeChanged(double? value)
{
if (_hydratingExistingQuery)
return;
_existingLocationId = null;
}
protected override async Task SubmitAsync()
{
@ -257,7 +294,7 @@ public partial class RdvViewModel : BillingCommandPageViewModel
try
{
var address = Address.Trim();
var locationPayload = BuildLocationPayload(address, Latitude, Longitude);
var locationPayload = BuildLocationPayload(address, Latitude, Longitude, IsEditingExisting ? _existingLocationId : null);
var payload = new BillingQueryDetailsDto
{
@ -270,12 +307,7 @@ public partial class RdvViewModel : BillingCommandPageViewModel
Status = CommandStatus,
Reason = Reason.Trim(),
AdditionalInfo = string.IsNullOrWhiteSpace(AdditionalInfo) ? string.Empty : AdditionalInfo.Trim(),
Location = new BillingLocationDto
{
Address = address,
Latitude = Latitude,
Longitude = Longitude,
}
Location = locationPayload
};
if (IsEditingExisting)

View file

@ -5,6 +5,7 @@ using CommunityToolkit.Mvvm.Input;
using Microsoft.Extensions.DependencyInjection;
using PostIt.Helpers;
using PostIt.Services;
using Yavsc.Api.Client;
namespace PostIt.ViewModels;
public class HomePageViewModel : ViewModelBase
@ -30,10 +31,16 @@ public class HomePageViewModel : ViewModelBase
SessionStatus = sessionStatus;
OpenActivities = new AsyncRelayCommand(OpenActivitiesAsync);
OpenProviderRequests = new AsyncRelayCommand(OpenProviderRequestsAsync);
OpenClientEstimates = new AsyncRelayCommand(() => OpenEstimateListAsync(EstimateListPerspective.Client));
OpenProviderEstimates = new AsyncRelayCommand(() => OpenEstimateListAsync(EstimateListPerspective.Provider));
OpenBlogs = new AsyncRelayCommand(App.PushBlogsPageAsync);
}
public IAsyncRelayCommand OpenBlogs { get; } = new AsyncRelayCommand(App.PushBlogsPageAsync);
public IAsyncRelayCommand OpenBlogs { get; }
public IAsyncRelayCommand OpenActivities { get; }
public IAsyncRelayCommand OpenProviderRequests { get; }
public IAsyncRelayCommand OpenClientEstimates { get; }
public IAsyncRelayCommand OpenProviderEstimates { get; }
private async Task OpenActivitiesAsync()
{
@ -48,6 +55,46 @@ public class HomePageViewModel : ViewModelBase
await app.PushPageAsync(vm);
}
private async Task OpenProviderRequestsAsync()
{
var app = (App?)Application.Current;
if (app is null)
{
throw new InvalidOperationException("Application PostIt indisponible.");
}
var billingClient = app.ServiceProvider?.GetRequiredService<BillingApiClient>();
if (billingClient is null)
{
throw new InvalidOperationException("Client billing indisponible.");
}
var estimateClient = app.ServiceProvider?.GetRequiredService<EstimateApiClient>();
var vm = new ProviderOngoingRequestsPageViewModel(billingClient, Settings, estimateClient);
await vm.InitializeAsync();
await app.PushPageAsync(vm);
}
private async Task OpenEstimateListAsync(EstimateListPerspective perspective)
{
var app = (App?)Application.Current;
if (app is null)
{
throw new InvalidOperationException("Application PostIt indisponible.");
}
var estimateClient = app.ServiceProvider?.GetRequiredService<EstimateApiClient>();
if (estimateClient is null)
{
throw new InvalidOperationException("Client devis indisponible.");
}
var vm = new EstimateListPageViewModel(estimateClient, perspective);
await vm.InitializeAsync();
await app.PushPageAsync(vm);
}
/// <summary>
/// Avalonia designer constructor. Builds a self-contained VM
/// with a freshly-constructed Settings so the XAML preview can

View file

@ -23,8 +23,8 @@ public sealed class StatusNotice
(Glyph, Background, BorderBrush, Foreground) = severity switch
{
StatusSeverity.Error => ("!", "#FDECEA", "#C62828", "#7F1D1D"),
StatusSeverity.Warning => ("~", "#FFF8E1", "#E6A700", "#7C4A03"),
StatusSeverity.Error => ("!", "#7F1D1D", "#C62828", "#e1f0f6"),
StatusSeverity.Warning => ("~", "#7C4A03", "#E6A700", "#eaeaea"),
_ => ("i", "#E8F0FE", "#5B8DEF", "#1E3A8A"),
};
}

View file

@ -22,7 +22,7 @@ public partial class AuthenticationSettings : ObservableObject
public const string DefaultClientId = "postit";
public static readonly string[] DefaultScopes = { "blogs" };
public static readonly string[] DefaultScopes = { "blogs", "api" };
[ObservableProperty]
public partial string Authority { get; set; }

View file

@ -15,7 +15,8 @@ namespace PostIt.ViewModels;
public partial class Settings : ViewModelBase
{
const string SettingsFileName = "postit-settings.json";
[JsonIgnore]
public string? SettingsFileFullName { get; private set; }
[ObservableProperty]
public partial AuthenticationSettings Authentication { get; set; } = new();
@ -32,10 +33,70 @@ public partial class Settings : ViewModelBase
[ObservableProperty]
public partial string SearchText { get; set; } = string.Empty;
[ObservableProperty]
public partial bool IsMarkdownViewerVisible { get; set; } = false;
[ObservableProperty]
public partial string ProviderOngoingRequestsSortOption { get; set; } = string.Empty;
[ObservableProperty]
[JsonIgnore]
public partial StatusNotice ActionStatus { get; set; } = StatusNotice.Info("Pret.");
public bool Loaded { get; private set; } = false;
/// <summary>
/// True when the in-memory state has drifted from the last
/// <see cref="Load"/> or <see cref="Save"/> snapshot. The
/// Settings page binds the Sauver button's <c>IsEnabled</c> to
/// this flag, so it only enables when the user has actually
/// touched something since the last load / save. Cleared by
/// <see cref="Load"/> (and by <see cref="ApplyJson"/>), set by
/// every successful setter on the four top-level mutable
/// properties and on the sub-properties of
/// <see cref="Authentication"/>.
/// </summary>
[ObservableProperty]
public partial bool IsDirty { get; private set; } = false;
/// <summary>
/// Guards every mutation of the observable state. <c>[ObservableProperty]</c>
/// generates setters that call <c>SetProperty(...)</c> which fires
/// <c>PropertyChanged</c>. Avalonia bindings consume that event on
/// the UI thread, and a stray background-thread update is exactly
/// what crashed <c>DataValidationErrors.SetErrors</c> on
/// <c>postit://callback</c> re-launches. The lock makes mutations
/// atomic; <see cref="OnPropertyChanged(PropertyChangedEventArgs)"/>
/// then marshals the notification onto the UI thread so bindings
/// observe the change on the right thread.
/// </summary>
private readonly object _mutationGate = new();
/// <summary>
/// Scopes the PostIt client always requires from the OIDC provider,
/// regardless of what the user has in their settings file.
///
/// <para>PostIt calls into the Blog API (and any other Yavsc API
/// gated by an <c>[Authorize("…Scope")]</c> policy) and is silent
/// about the contract: a missing scope here surfaces as a 401
/// on the very first API call after login, with no obvious link
/// to the settings. The "feature" scopes the user must opt into
/// (e.g. <c>blogs</c>) are still their choice — we only force the
/// structural ones that OIDC itself needs.</para>
/// </summary>
private static readonly string[] BuiltInScopes = new[]
{
"openid", // OIDC: required for the id_token
"profile", // OIDC: standard profile claims
"offline_access", // OIDC: required to receive a refresh_token
"blogs",
"api"
};
private readonly string DEFAULT_SETTINGS_FILENAME = "postit-settings.json";
public void SetActionStatus(string message, StatusSeverity severity = StatusSeverity.Info)
{
ActionStatus = severity switch
@ -62,6 +123,7 @@ public partial class Settings : ViewModelBase
partial void OnBlogsApiUrlChanged(string value) => MarkDirty();
partial void OnApiUrlChanged(string value) => MarkDirty();
partial void OnSearchTextChanged(string value) => MarkDirty();
partial void OnProviderOngoingRequestsSortOptionChanged(string value) => MarkDirty();
/// <summary>
/// Authentication can be reassigned wholesale by
@ -82,35 +144,6 @@ public partial class Settings : ViewModelBase
MarkDirty();
}
public bool Loaded { get; private set; } = false;
/// <summary>
/// True when the in-memory state has drifted from the last
/// <see cref="Load"/> or <see cref="Save"/> snapshot. The
/// Settings page binds the Sauver button's <c>IsEnabled</c> to
/// this flag, so it only enables when the user has actually
/// touched something since the last load / save. Cleared by
/// <see cref="Load"/> (and by <see cref="ApplyJson"/>), set by
/// every successful setter on the four top-level mutable
/// properties and on the sub-properties of
/// <see cref="Authentication"/>.
/// </summary>
[ObservableProperty]
public partial bool IsDirty { get; private set; } = false;
/// <summary>
/// Guards every mutation of the observable state. <c>[ObservableProperty]</c>
/// generates setters that call <c>SetProperty(...)</c> which fires
/// <c>PropertyChanged</c>. Avalonia bindings consume that event on
/// the UI thread, and a stray background-thread update is exactly
/// what crashed <c>DataValidationErrors.SetErrors</c> on
/// <c>postit://callback</c> re-launches. The lock makes mutations
/// atomic; <see cref="OnPropertyChanged(PropertyChangedEventArgs)"/>
/// then marshals the notification onto the UI thread so bindings
/// observe the change on the right thread.
/// </summary>
private readonly object _mutationGate = new();
/// <summary>
/// Build OidcClient options configured for Authorization Code + PKCE
/// (no client secret). The browser implementation should be supplied
@ -174,27 +207,6 @@ public partial class Settings : ViewModelBase
Authentication.RefreshScopeListText();
}
/// <summary>
/// Scopes the PostIt client always requires from the OIDC provider,
/// regardless of what the user has in their settings file.
///
/// <para>PostIt calls into the Blog API (and any other Yavsc API
/// gated by an <c>[Authorize("…Scope")]</c> policy) and is silent
/// about the contract: a missing scope here surfaces as a 401
/// on the very first API call after login, with no obvious link
/// to the settings. The "feature" scopes the user must opt into
/// (e.g. <c>blogs</c>) are still their choice — we only force the
/// structural ones that OIDC itself needs.</para>
/// </summary>
private static readonly string[] BuiltInScopes = new[]
{
"openid", // OIDC: required for the id_token
"profile", // OIDC: standard profile claims
"offline_access", // OIDC: required to receive a refresh_token
"blogs",
"api"
};
/// <summary>
/// Merge user-configured scopes with the built-in ones. User scopes
@ -247,16 +259,42 @@ public partial class Settings : ViewModelBase
return;
}
}
if (Environment.GetEnvironmentVariable("POSTIT_SETTINGS_JSON") is string envJson
&& !string.IsNullOrWhiteSpace(envJson))
{
Console.WriteLine("🔎 Loading settings from POSTIT_SETTINGS_JSON environment variable.");
FileInfo configByEnvFileInfo = new FileInfo(envJson);
if (!configByEnvFileInfo.Exists)
{
throw new Exception($"🩎 Settings file not found at {configByEnvFileInfo.FullName}");
}
string json = File.ReadAllText(configByEnvFileInfo.FullName);
ApplyJson(json, "POSTIT_SETTINGS_JSON");
SettingsFileFullName = configByEnvFileInfo.FullName;
Loaded = true;
return;
}
string configDir = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
"PostIt"
);
Directory.CreateDirectory(configDir);
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
"PostIt"
);
string configPath = Path.Combine(configDir, SettingsFileName);
if (SettingsFileFullName is not null)
{
// Already set by a previous Load() or by the environment
// variable path above. Use it as-is.
}
else if (Environment.GetEnvironmentVariable("POSTIT_SETTINGS_JSON") is string envPath
&& !string.IsNullOrWhiteSpace(envPath))
{
SettingsFileFullName = envPath;
}
else
{
SettingsFileFullName = Path.Combine(configDir, "postit-settings.json");
}
FileInfo configFileInfo = new FileInfo(configPath);
FileInfo configFileInfo = new FileInfo(SettingsFileFullName);
if (!configFileInfo.Exists)
{
@ -285,6 +323,7 @@ public partial class Settings : ViewModelBase
using var reader = new StreamReader(stream);
var json = reader.ReadToEnd();
ApplyJson(json, $"user file {configFileInfo.FullName}");
SettingsFileFullName = configFileInfo.FullName;
Loaded = true;
}
catch (Exception ex)
@ -336,7 +375,7 @@ public partial class Settings : ViewModelBase
// → our overridden dispatcher-safe marshaller below.
else lock (_mutationGate)
{
var legacyApiUrl = TryReadLegacyApiUrl(json);
var legacyApiUrl = TryReadApiUrl(json);
this.Authentication = settings.Authentication;
this.DarkMode = settings.DarkMode;
this.BlogsApiUrl = !string.IsNullOrWhiteSpace(settings.BlogsApiUrl)
@ -346,6 +385,7 @@ public partial class Settings : ViewModelBase
? settings.ApiUrl
: this.ApiUrl;
this.SearchText = settings.SearchText ?? string.Empty;
this.ProviderOngoingRequestsSortOption = settings.ProviderOngoingRequestsSortOption ?? string.Empty;
if (!(settings.Authentication is null))
{
this.Authentication = new AuthenticationSettings();
@ -391,7 +431,7 @@ public partial class Settings : ViewModelBase
}
}
private static string? TryReadLegacyApiUrl(string json)
private static string? TryReadApiUrl(string json)
{
try
{
@ -424,6 +464,7 @@ public partial class Settings : ViewModelBase
this.BlogsApiUrl = "https://blogs.pschneider.fr/api/v1/";
this.ApiUrl = "https://api.pschneider.fr/api/v1/";
this.SearchText = string.Empty;
this.ProviderOngoingRequestsSortOption = string.Empty;
}
/// <summary>
@ -446,11 +487,17 @@ public partial class Settings : ViewModelBase
{
SetActionStatus("Enregistrement des parametres...", StatusSeverity.Info);
var configDir = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
"PostIt");
Directory.CreateDirectory(configDir);
var configPath = Path.Combine(configDir, SettingsFileName);
if (SettingsFileFullName is null)
{
var configDir = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
"PostIt");
Directory.CreateDirectory(configDir);
SettingsFileFullName = Path.Combine(configDir, DEFAULT_SETTINGS_FILENAME);
}
var configPath = SettingsFileFullName!;
Directory.CreateDirectory(Path.GetDirectoryName(configPath)!);
lock (_mutationGate)
{
@ -466,7 +513,7 @@ public partial class Settings : ViewModelBase
UnixFileMode.UserRead | UnixFileMode.UserWrite);
IsDirty = false;
SetActionStatus("Parametres sauvegardes.", StatusSeverity.Info);
Console.WriteLine($"💾 Settings saved to {configPath}");
}
catch (Exception ex)

View file

@ -34,13 +34,13 @@
<Grid Grid.Row="3" Margin="0,12,0,0" ColumnDefinitions="Auto,8,Auto,8,Auto,12,*">
<Button Grid.Column="0"
Content="Ouvrir le formulaire"
Content="Ouvrir le formulaire de demande"
Command="{Binding OpenSelectedFormCommand}" />
<Button Grid.Column="2"
Content="Voir les commandes"
Content="Voir les demandes non validées"
Command="{Binding OpenQueriesCommand}" />
<Button Grid.Column="4"
Content="Demandes en cours (lecture seule)"
Content="Demandes en cours (validées, en lecture seule)"
Command="{Binding OpenOngoingQueriesCommand}" />
<postitControls:StatusBar Grid.Column="6"
DataContext="{Binding ActionStatus}" />

View file

@ -0,0 +1,151 @@
<ContentPage xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:vm="using:PostIt.ViewModels"
xmlns:postitControls="using:PostIt.Controls"
x:Class="PostIt.Views.EstimateEditionPage"
x:DataType="vm:EstimateEditionPageViewModel"
Header="Edition de devis">
<Grid RowDefinitions="Auto,Auto,*,Auto" Margin="12">
<StackPanel Grid.Row="0" Spacing="3">
<TextBlock Text="{Binding Title}"
FontSize="20"
FontWeight="Bold" />
<TextBlock Text="{Binding ContextLabel}" Opacity="0.75" />
</StackPanel>
<Grid Grid.Row="1" ColumnDefinitions="Auto,8,*" Margin="0,10,0,8">
<Button Grid.Column="0"
Content="Retour"
Command="{Binding BackCommand}" />
</Grid>
<ScrollViewer Grid.Row="2">
<StackPanel Spacing="10">
<Border BorderThickness="1"
BorderBrush="#22000000"
CornerRadius="8"
Padding="10">
<Grid ColumnDefinitions="Auto,12,*" RowDefinitions="Auto,Auto,Auto" RowSpacing="8">
<TextBlock Grid.Row="0"
Grid.Column="0"
Text="Demande"
FontWeight="SemiBold"
VerticalAlignment="Center" />
<TextBlock Grid.Row="0"
Grid.Column="2"
Text="{Binding QueryDescription}"
TextWrapping="Wrap"
Opacity="0.75" />
<TextBlock Grid.Row="1"
Grid.Column="0"
Text="Titre"
FontWeight="SemiBold"
VerticalAlignment="Center" />
<TextBox Grid.Row="1"
Grid.Column="2"
Text="{Binding EstimateTitle}"
PlaceholderText="Titre du devis" />
<TextBlock Grid.Row="2"
Grid.Column="0"
Text="Description"
FontWeight="SemiBold"
VerticalAlignment="Top" />
<TextBox Grid.Row="2"
Grid.Column="2"
Text="{Binding EstimateDescription}"
PlaceholderText="Description détaillée du devis"
AcceptsReturn="True"
TextWrapping="Wrap"
MinHeight="70" />
</Grid>
</Border>
<Border BorderThickness="1"
BorderBrush="#22000000"
CornerRadius="8"
Padding="10">
<StackPanel Spacing="8">
<Grid ColumnDefinitions="*,Auto,8,Auto">
<TextBlock Grid.Column="0"
Text="Lignes du devis"
FontWeight="SemiBold"
VerticalAlignment="Center" />
<Button Grid.Column="1"
Content="Ajouter une ligne"
Command="{Binding AddLineCommand}" />
<Button Grid.Column="3"
Content="Retirer la ligne"
Command="{Binding RemoveLineCommand}" />
</Grid>
<ListBox ItemsSource="{Binding Lines}"
SelectedItem="{Binding SelectedLine, Mode=TwoWay}">
<ListBox.ItemTemplate>
<DataTemplate x:DataType="vm:EstimateLineItemViewModel">
<Border BorderThickness="1"
BorderBrush="#22000000"
CornerRadius="6"
Padding="8"
Margin="0,0,0,8">
<Grid ColumnDefinitions="*,8,110,8,130,8,90"
RowDefinitions="Auto,Auto"
RowSpacing="6">
<TextBox Grid.Row="0"
Grid.Column="0"
Text="{Binding Name}"
PlaceholderText="Nom de la ligne" />
<NumericUpDown Grid.Row="0"
Grid.Column="2"
Value="{Binding Count}"
Minimum="1"
Increment="1"
FormatString="0" />
<NumericUpDown Grid.Row="0"
Grid.Column="4"
Value="{Binding UnitaryCost}"
Increment="0.5"
FormatString="0.00" />
<TextBlock Grid.Row="0"
Grid.Column="6"
Text="{Binding LineTotalLabel}"
VerticalAlignment="Center"
HorizontalAlignment="Right"
FontWeight="SemiBold" />
<TextBox Grid.Row="1"
Grid.Column="0"
Grid.ColumnSpan="7"
Text="{Binding Description}"
PlaceholderText="Description de la ligne" />
</Grid>
</Border>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<Grid ColumnDefinitions="*,Auto">
<TextBlock Grid.Column="1"
Text="{Binding TotalLabel, StringFormat='Total : {0}'}"
FontSize="16"
FontWeight="Bold"
HorizontalAlignment="Right" />
</Grid>
</StackPanel>
</Border>
</StackPanel>
</ScrollViewer>
<Grid Grid.Row="3" ColumnDefinitions="Auto,8,*,Auto" Margin="0,12,0,0">
<Button Grid.Column="0"
Content="{Binding SendLabel}"
Command="{Binding SendCommand}" />
<postitControls:StatusBar Grid.Column="2"
DataContext="{Binding ActionStatus}" />
<ProgressBar Grid.Column="3"
Width="120"
IsIndeterminate="True"
IsVisible="{Binding IsBusy}" />
</Grid>
</Grid>
</ContentPage>

View file

@ -0,0 +1,17 @@
using Avalonia.Controls;
using Avalonia.Markup.Xaml;
namespace PostIt.Views;
public partial class EstimateEditionPage : ContentPage
{
public EstimateEditionPage()
{
InitializeComponent();
}
private void InitializeComponent()
{
AvaloniaXamlLoader.Load(this);
}
}

View file

@ -0,0 +1,71 @@
<ContentPage xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:vm="using:PostIt.ViewModels"
xmlns:dto="using:Yavsc.Api.Client"
xmlns:postitControls="using:PostIt.Controls"
x:Class="PostIt.Views.EstimateListPage"
x:DataType="vm:EstimateListPageViewModel"
Header="{Binding Title}">
<Grid RowDefinitions="Auto,Auto,*,Auto" Margin="12">
<StackPanel Grid.Row="0" Spacing="3">
<TextBlock Text="{Binding Title}" FontSize="20" FontWeight="Bold" />
<TextBlock Text="{Binding Subtitle}" Opacity="0.75" />
</StackPanel>
<Grid Grid.Row="1" ColumnDefinitions="Auto,8,*" Margin="0,10,0,8">
<Button Grid.Column="0" Content="Rafraîchir" Command="{Binding RefreshCommand}" />
<TextBox Grid.Column="2"
PlaceholderText="Filtrer: titre, description, type, partie..."
Text="{Binding FilterText, Mode=TwoWay}" />
</Grid>
<ListBox Grid.Row="2"
ItemsSource="{Binding Estimates}"
SelectedItem="{Binding SelectedEstimate, Mode=TwoWay}">
<ListBox.ItemTemplate>
<DataTemplate x:DataType="dto:EstimateDto">
<Border BorderThickness="1"
BorderBrush="#22000000"
CornerRadius="8"
Padding="10"
Margin="0,0,0,8">
<Grid RowDefinitions="Auto,Auto" ColumnDefinitions="*,Auto">
<TextBlock Grid.Row="0"
Grid.Column="0"
Text="{Binding Title}"
FontWeight="Bold"
TextWrapping="Wrap" />
<TextBlock Grid.Row="0"
Grid.Column="1"
Text="{Binding Id}"
FontSize="11"
Opacity="0.75"
HorizontalAlignment="Right" />
<TextBlock Grid.Row="1"
Grid.Column="0"
Margin="0,6,0,0"
Text="{Binding Description}"
FontSize="11"
Opacity="0.75"
TextWrapping="Wrap" />
<TextBlock Grid.Row="1"
Grid.Column="1"
Margin="0,6,0,0"
Text="{Binding Bill.Count}"
FontSize="11"
Opacity="0.65"
HorizontalAlignment="Right" />
</Grid>
</Border>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<Grid Grid.Row="3" ColumnDefinitions="*,Auto" Margin="0,12,0,0">
<postitControls:StatusBar Grid.Column="0"
DataContext="{Binding ActionStatus}" />
<ProgressBar Grid.Column="1" Width="120" IsIndeterminate="True" IsVisible="{Binding IsBusy}" />
</Grid>
</Grid>
</ContentPage>

View file

@ -0,0 +1,17 @@
using Avalonia.Controls;
using Avalonia.Markup.Xaml;
namespace PostIt.Views;
public partial class EstimateListPage : ContentPage
{
public EstimateListPage()
{
InitializeComponent();
}
private void InitializeComponent()
{
AvaloniaXamlLoader.Load(this);
}
}

View file

@ -0,0 +1,102 @@
<ContentPage xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:vm="using:PostIt.ViewModels"
xmlns:dto="using:Yavsc.Api.Client"
xmlns:postitControls="using:PostIt.Controls"
x:Class="PostIt.Views.ProviderOngoingRequestsPage"
x:DataType="vm:ProviderOngoingRequestsPageViewModel"
Header="Mes demandes en cours">
<Grid RowDefinitions="Auto,Auto,Auto,*,Auto" Margin="12">
<StackPanel Grid.Row="0" Spacing="3">
<TextBlock Text="{Binding Title}" FontSize="20" FontWeight="Bold" />
<TextBlock Text="Point de vue fournisseur" Opacity="0.75" />
</StackPanel>
<Grid Grid.Row="1" ColumnDefinitions="Auto,8,Auto,8,*,8,Auto" Margin="0,10,0,8">
<Button Grid.Column="0" Content="Rafraîchir" Command="{Binding RefreshCommand}" />
<ComboBox Grid.Column="2"
Width="220"
ItemsSource="{Binding SortOptions}"
SelectedItem="{Binding SelectedSortOption, Mode=TwoWay}" />
<TextBox Grid.Column="4"
PlaceholderText="Filtrer: activité, code, client, statut..."
Text="{Binding FilterText, Mode=TwoWay}" />
<TextBlock Grid.Column="6"
HorizontalAlignment="Right"
VerticalAlignment="Center"
Text="{Binding Queries.Count, StringFormat='Résultats : {0}'}"
Opacity="0.7" />
</Grid>
<TextBlock Grid.Row="2"
Text="Astuce: sélectionnez une ligne puis ouvrez le détail ou l'édition directe."
Opacity="0.65"
FontSize="11"
Margin="0,0,0,8" />
<Grid Grid.Row="3" RowDefinitions="*,Auto">
<ListBox Grid.Row="0"
ItemsSource="{Binding Queries}"
SelectedItem="{Binding SelectedQuery, Mode=TwoWay}">
<ListBox.ItemTemplate>
<DataTemplate x:DataType="dto:BillingQuerySummaryDto">
<Border BorderThickness="1"
BorderBrush="#22000000"
CornerRadius="8"
Padding="10"
Margin="0,0,0,8">
<Grid RowDefinitions="Auto,Auto" ColumnDefinitions="*,Auto">
<TextBlock Grid.Row="0"
Grid.Column="0"
Text="{Binding Description}"
FontWeight="Bold"
TextWrapping="Wrap" />
<TextBlock Grid.Row="0"
Grid.Column="1"
Text="{Binding Status}"
FontSize="11"
Opacity="0.75"
HorizontalAlignment="Right" />
<TextBlock Grid.Row="1"
Grid.Column="0"
Margin="0,6,0,0"
Text="{Binding ActivityCode, StringFormat='Activité : {0}'}"
FontSize="11"
Opacity="0.75" />
<TextBlock Grid.Row="1"
Grid.Column="1"
Margin="0,6,0,0"
Text="{Binding BillingCode, StringFormat='Code : {0}'}"
FontSize="11"
Opacity="0.65"
HorizontalAlignment="Right" />
</Grid>
</Border>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<StackPanel Grid.Row="1"
Orientation="Horizontal"
HorizontalAlignment="Right"
Margin="0,8,0,0"
Spacing="8">
<Button Content="Ouvrir le détail"
Command="{Binding OpenSelectedQueryCommand}" />
<Button Content="Ouvrir en édition"
Command="{Binding OpenSelectedEditorCommand}"
/>
<Button Content="Créer un devis"
Command="{Binding CreateEstimateForSelectedCommand}"
/>
</StackPanel>
</Grid>
<Grid Grid.Row="4" ColumnDefinitions="*,Auto" Margin="0,12,0,0">
<postitControls:StatusBar Grid.Column="0"
DataContext="{Binding ActionStatus}" />
<ProgressBar Grid.Column="1" Width="120" IsIndeterminate="True" IsVisible="{Binding IsBusy}" />
</Grid>
</Grid>
</ContentPage>

View file

@ -0,0 +1,17 @@
using Avalonia.Controls;
using Avalonia.Markup.Xaml;
namespace PostIt.Views;
public partial class ProviderOngoingRequestsPage : ContentPage
{
public ProviderOngoingRequestsPage()
{
InitializeComponent();
}
private void InitializeComponent()
{
AvaloniaXamlLoader.Load(this);
}
}

View file

@ -0,0 +1,161 @@
<ContentPage xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:vm="using:PostIt.ViewModels"
xmlns:postitControls="using:PostIt.Controls"
xmlns:models="using:Yavsc.Blogspot"
xmlns:views="using:PostIt.Views.Blogs"
xmlns:AvaloniaEdit="clr-namespace:AvaloniaEdit;assembly=AvaloniaEdit"
xmlns:md="using:MarkdownViewer.Core.Controls"
mc:Ignorable="d"
x:Class="PostIt.Views.Blogs.BlogsPage"
x:DataType="vm:BlogsViewModel"
HorizontalAlignment="Stretch"
VerticalAlignment="Stretch">
<Design.DataContext>
<vm:BlogsViewModel />
</Design.DataContext>
<ScrollViewer
VerticalScrollBarVisibility="Visible"
HorizontalScrollBarVisibility="Disabled"
Padding="5"
Margin="5"
>
<StackPanel HorizontalAlignment="Stretch">
<StackPanel Orientation="Horizontal" Spacing="10" Margin="5">
<TextBlock Text="Blog Posts" FontSize="20" FontWeight="SemiBold" />
<TextBox HorizontalAlignment="Right"
Text="{Binding SearchText, Mode=TwoWay}" PlaceholderText="Filter by title or author..." />
</StackPanel>
<CommandBar IsDynamicOverflowEnabled="True"
HorizontalAlignment="Right" >
<CommandBar.PrimaryCommands>
<CommandBarButton Label="Refresh" Command="{Binding RefreshAsync}">
<CommandBarButton.Icon>
<PathIcon Data="{StaticResource RefreshIcon}" />
</CommandBarButton.Icon>
</CommandBarButton>
<CommandBarButton x:Name="SaveButton" Label="Save" Command="{Binding SaveAsync}">
<CommandBarButton.Icon>
<PathIcon Data="{StaticResource SaveIcon}" />
</CommandBarButton.Icon>
</CommandBarButton>
<CommandBarButton Label="Delete" Command="{Binding DeleteAsync}">
<CommandBarButton.Icon>
<PathIcon Data="{StaticResource DeleteIcon}" />
</CommandBarButton.Icon>
</CommandBarButton>
<CommandBarButton Label="Ajouter fichiers" Click="AddAttachment_Click"
x:Name="AddAttachmentButton">
<CommandBarButton.Icon>
<PathIcon Data="{StaticResource AddIcon}" />
</CommandBarButton.Icon>
</CommandBarButton>
<CommandBarButton x:Name="ManageAclButton"
Label="ACL"
Command="{Binding ManageAclAsync}">
<CommandBarButton.Icon>
<PathIcon Data="{StaticResource AclIcon}" />
</CommandBarButton.Icon>
</CommandBarButton>
<CommandBarButton x:Name="OpenCirclesButton"
Label="Mes cercles" Command="{Binding OpenCirclesAsync}">
<CommandBarButton.Icon>
<PathIcon Data="{StaticResource CircleIcon}" />
</CommandBarButton.Icon>
</CommandBarButton>
<CommandBarToggleButton Label="Publié"
IsChecked="{Binding DraftIsPublished, Mode=TwoWay}">
<CommandBarToggleButton.Icon>
<PathIcon Data="{StaticResource PublishedIcon}" />
</CommandBarToggleButton.Icon>
</CommandBarToggleButton>
<CommandBarToggleButton Label="Markdown Viewer"
IsChecked="{Binding IsMarkdownViewerVisible, Mode=TwoWay}">
<CommandBarToggleButton.Icon>
<PathIcon Data="{StaticResource MarkdownIcon}" />
</CommandBarToggleButton.Icon>
</CommandBarToggleButton>
<CommandBarButton x:Name="OpenSignatureDevButton"
Label="[DEV] Signature" Command="{Binding OpenSignatureDevAsync}">
<CommandBarButton.Icon>
<PathIcon Data="{StaticResource SignIcon}" />
</CommandBarButton.Icon>
</CommandBarButton>
</CommandBar.PrimaryCommands>
</CommandBar>
<Grid Margin="12" RowSpacing="12">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Border Grid.Row="1" BorderBrush="Gray" BorderThickness="1" Padding="8">
<ListBox ItemsSource="{Binding FilteredPosts}"
SelectedItem="{Binding SelectedPost, Mode=TwoWay}">
<ListBox.ItemTemplate>
<DataTemplate x:DataType="models:BlogPostDto">
<StackPanel Spacing="4" >
<TextBlock Text="{Binding Title}" FontWeight="SemiBold" />
<TextBlock Text="{Binding DateModified, StringFormat='Updated: {0:yyyy-MM-dd HH:mm}'}" FontSize="10" Foreground="Gray" />
<TextBlock Text="{Binding AuthorId}" FontSize="10" Foreground="DarkSlateGray" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Border>
<md:MarkdownViewer Grid.Row="2" Name="MarkdownViewer"
IsVisible="{Binding IsMarkdownViewerVisible}"
MarkdownText="{Binding DraftArticle}" />
<Border Grid.Row="2" BorderBrush="Gray" BorderThickness="1" Padding="8"
IsVisible="{Binding !IsMarkdownViewerVisible}">
<Grid RowSpacing="10"
HorizontalAlignment="Stretch"
VerticalAlignment="Stretch">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<TextBlock Grid.Row="0" Text="Post detail" FontWeight="SemiBold" />
<TextBox x:Name="DraftTitleTextBox"
Grid.Row="1" Text="{Binding DraftTitle, Mode=TwoWay}" PlaceholderText="Title" />
<TextBox Grid.Row="2" PlaceholderText="Write something here !"
Text="{Binding DraftArticle, Mode=TwoWay}"
MinHeight="320"
HorizontalAlignment="Stretch"
VerticalAlignment="Stretch" />
<Border Grid.Row="3" BorderBrush="LightGray" BorderThickness="1" Padding="8">
<StackPanel Spacing="4">
<TextBlock Text="Pièces jointes" FontWeight="SemiBold" />
<ItemsControl ItemsSource="{Binding DraftAttachments}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding FileName}" />
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</StackPanel>
</Border>
<postitControls:StatusBar Grid.Row="4"
DataContext="{Binding ActionStatus}" />
</Grid>
</Border>
</Grid>
</StackPanel>
</ScrollViewer>
</ContentPage>

View file

@ -0,0 +1,71 @@
using System;
using System.IO;
using System.Linq;
using Avalonia.Controls;
using Avalonia.Platform.Storage;
using Avalonia.Controls.Primitives;
namespace PostIt.Views.Blogs;
public partial class BlogsPage : ContentPage
{
public BlogsPage()
{
InitializeComponent();
}
protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
base.OnApplyTemplate(e);
if (DataContext is ViewModels.BlogsViewModel vm)
{
if (!vm.IsLoaded)
{
vm.RefreshAsync().Wait();
}
}
}
private async void AddAttachment_Click(object? sender, Avalonia.Interactivity.RoutedEventArgs e)
{
var topLevel = TopLevel.GetTopLevel(this);
if (topLevel is null || DataContext is not ViewModels.BlogsViewModel vm)
return;
var files = await topLevel.StorageProvider.OpenFilePickerAsync(new FilePickerOpenOptions
{
Title = "Choisir des fichiers à joindre au billet",
AllowMultiple = true,
});
if (files.Count == 0)
return;
var uploads = new System.Collections.Generic.List<Yavsc.Api.Client.BlogUploadFile>(files.Count);
foreach (var file in files)
{
await using var stream = await file.OpenReadAsync();
using var memory = new MemoryStream();
await stream.CopyToAsync(memory);
uploads.Add(new Yavsc.Api.Client.BlogUploadFile(file.Name, memory.ToArray(), GetMimeType(file.Name)));
}
vm.DraftAttachments.Clear();
foreach (var upload in uploads)
vm.DraftAttachments.Add(upload);
}
private static string GetMimeType(string fileName)
{
var ext = Path.GetExtension(fileName)?.ToLowerInvariant();
return ext switch
{
".png" => "image/png",
".jpg" or ".jpeg" => "image/jpeg",
".webp" => "image/webp",
".gif" => "image/gif",
".pdf" => "application/pdf",
_ => "application/octet-stream"
};
}
}

View file

@ -22,5 +22,17 @@
Command="{Binding OpenActivities}"
HorizontalAlignment="Center"
IsEnabled="{Binding SessionStatus.IsLoggedIn}"/>
<Button Content="Mes demandes en cours"
Command="{Binding OpenProviderRequests}"
HorizontalAlignment="Center"
IsEnabled="{Binding SessionStatus.IsLoggedIn}"/>
<Button Content="Mes devis à valider"
Command="{Binding OpenClientEstimates}"
HorizontalAlignment="Center"
IsEnabled="{Binding SessionStatus.IsLoggedIn}"/>
<Button Content="Mes devis en attente"
Command="{Binding OpenProviderEstimates}"
HorizontalAlignment="Center"
IsEnabled="{Binding SessionStatus.IsLoggedIn}"/>
</StackPanel>
</ContentPage>

View file

@ -6,11 +6,11 @@
xmlns:views="using:PostIt.Views"
mc:Ignorable="d" d:DesignWidth="800" d:DesignHeight="450"
x:Class="PostIt.Views.MainView"
x:DataType="vm:MainViewModel">
x:DataType="vm:HomePageViewModel">
<Design.DataContext>
<!-- This only sets the DataContext for the previewer in an IDE,
to set the actual DataContext for runtime, set the DataContext property in code (look at App.axaml.cs) -->
<vm:MainViewModel />
<vm:HomePageViewModel />
</Design.DataContext>
<DockPanel LastChildFill="True">

View file

@ -13,7 +13,7 @@ public partial class MainView : UserControl
protected override void OnDataContextChanged(EventArgs e)
{
base.OnDataContextChanged(e);
if (DataContext is ViewModels.MainViewModel vm)
if (DataContext is ViewModels.BlogsViewModel vm)
{
if (!vm.IsLoaded)
{

View file

@ -1,114 +0,0 @@
<ContentPage xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:vm="using:PostIt.ViewModels"
xmlns:postitControls="using:PostIt.Controls"
xmlns:models="using:Yavsc.Blogspot"
xmlns:views="using:PostIt.Views"
xmlns:AvaloniaEdit="clr-namespace:AvaloniaEdit;assembly=AvaloniaEdit"
mc:Ignorable="d"
x:Class="PostIt.Views.MainPage"
x:DataType="vm:MainViewModel"
HorizontalAlignment="Stretch"
VerticalAlignment="Stretch">
<Design.DataContext>
<vm:MainViewModel />
</Design.DataContext>
<Grid Margin="12" RowSpacing="12"
HorizontalAlignment="Stretch"
VerticalAlignment="Stretch">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Border Grid.Row="0"
HorizontalAlignment="Stretch"
VerticalAlignment="Top"
Padding="0">
<WrapPanel Orientation="Horizontal">
<Button Command="{Binding RefreshAsync}" Content="🗘 Refresh" />
<Button Command="{Binding SearchAsync}" Content="🔍 Filter" />
<Button Command="{Binding SaveAsync}" Content="Save" />
<Button Command="{Binding DeleteAsync}" Content="Delete" />
<Button x:Name="ManageAclButton"
Command="{Binding ManageAclAsync}"
Content="ACL" />
<Button x:Name="OpenCirclesButton"
Command="{Binding OpenCirclesAsync}"
Content="Mes cercles" />
<!-- Publication toggle: a CheckBox wired to
DraftIsPublished. Clicking it fires
TogglePublishCommand, which pushes the
new state to /api/blog/{id}/publish.
The CheckBox is the canonical
AvaloniaXaml 'toggle' surface; binding
IsChecked TwoWay keeps the visual state
and the buffer in sync. -->
<CheckBox Content="Publié"
IsChecked="{Binding DraftIsPublished, Mode=TwoWay}"
Command="{Binding TogglePublishAsync}"
VerticalAlignment="Center"/>
<!--
DEV ONLY: temporary shortcut to open the signature
capture page. Production entry point is a SignalR
push from Yavsc.Org ("devis received, sign here").
Remove this button and its Click handler in
MainPage.axaml.cs once the SignalR handler lands.
-->
<Button x:Name="OpenSignatureDevButton"
Command="{Binding OpenSignatureDevAsync}"
Content="[DEV] Signature"
ToolTip.Tip="DEV ONLY — to remove when SignalR handler lands" />
</WrapPanel>
</Border>
<Border Grid.Row="1" BorderBrush="Gray" BorderThickness="1" Padding="8">
<ListBox ItemsSource="{Binding FilteredPosts}" SelectedItem="{Binding SelectedPost, Mode=TwoWay}"
HorizontalAlignment="Stretch" VerticalAlignment="Stretch" MinHeight="40">
<ListBox.ItemTemplate>
<DataTemplate x:DataType="models:BlogPostDto">
<StackPanel Spacing="4">
<TextBlock Text="{Binding Title}" FontWeight="SemiBold" />
<TextBlock Text="{Binding DateModified, StringFormat='Updated: {0:yyyy-MM-dd HH:mm}'}" FontSize="10" Foreground="Gray" />
<TextBlock Text="{Binding AuthorId}" FontSize="10" Foreground="DarkSlateGray" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Border>
<Border Grid.Row="2" BorderBrush="Gray" BorderThickness="1" Padding="8">
<Grid RowSpacing="10"
HorizontalAlignment="Stretch"
VerticalAlignment="Stretch">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<TextBlock Grid.Row="0" Text="Post detail" FontWeight="SemiBold" />
<TextBox Grid.Row="1" Text="{Binding DraftTitle, Mode=TwoWay}" PlaceholderText="Title" />
<TextBox Grid.Row="2" PlaceholderText="Write something here !"
Text="{Binding DraftArticle, Mode=TwoWay}"
MinHeight="320"
HorizontalAlignment="Stretch"
VerticalAlignment="Stretch">
</TextBox>
<postitControls:StatusBar Grid.Row="3"
DataContext="{Binding ActionStatus}" />
</Grid>
</Border>
</Grid>
</ContentPage>

View file

@ -1,25 +0,0 @@
using System;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
namespace PostIt.Views;
public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
}
protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
base.OnApplyTemplate(e);
if (DataContext is ViewModels.MainViewModel vm)
{
if (!vm.IsLoaded)
{
vm.RefreshAsync().Wait();
}
}
}
}

View file

@ -1,15 +0,0 @@
{
"Authentication": {
"ClientId": "postit",
"Authority": "https://yavsc.pschneider.fr"
},
"RedirectUri": "postit://callback",
"DarkMode": false,
"ApiUrl": "https://api.pschneider.fr/api/v1/",
"Scopes": [
"openid",
"profile",
"offline_access",
"blogs"
]
}

View file

@ -0,0 +1,17 @@
{
"Authentication": {
"ClientId": "postit",
"Authority": "https://yavsc.pschneider.fr",
"Scopes": [
"openid",
"profile",
"offline_access",
"blogs",
"api"
],
"RedirectUri": "postit://callback"
},
"DarkMode": false,
"ApiUrl": "https://api.pschneider.fr/api/v1/"
}

View file

@ -1,15 +1,21 @@
{
"Authentication": {
"ClientId": "postit",
"Authority": "https://yavsc.pschneider.fr/"
},
"RedirectUri": "postit://callback",
"DarkMode": true,
"ApiUrl": "https://api.pschneider.fr/api/v1/",
"Authentication": {
"Authority": "https://localhost:5001",
"ClientId": "postit",
"Scopes": [
"openid",
"profile",
"offline_access",
"blogs"
]
}
"blogs",
"api"
],
"RedirectUri": "postit://callback"
},
"DarkMode": true,
"BlogsApiUrl": "https://localhost:5003/api/v1/",
"ApiUrl": "https://localhost:5005/api/v1/",
"SearchText": "",
"ProviderOngoingRequestsSortOption": "",
"Loaded": true,
"IsDirty": true,
"CanNavigateNext": false,
"CanNavigatePrevious": true,
"SaveCommand": {}
}

View file

@ -7,8 +7,6 @@ namespace Yavsc.Server.Helpers
{
public static class AbstractFileSystemHelpers
{
public static string UserBillsDirName { set; get; }
public static string UserFilesDirName { set; get; }
/// <summary>
/// Is Valid this Path?
@ -64,17 +62,6 @@ namespace Yavsc.Server.Helpers
return sb.ToString();
}
public static UserDirectoryInfo GetUserFiles(string userId, string subdir)
{
UserDirectoryInfo di = new UserDirectoryInfo(UserFilesDirName, userId, subdir);
return di;
}
public static bool IsRegularFile(string userName, string subdir)
{
FileInfo fi = new FileInfo( Path.Combine(Path.Combine(UserFilesDirName, userName), subdir));
return fi.Exists;
}
// Server side only supports POSIX file systems
public const char RemoteDirectorySeparator = '/';

View file

@ -0,0 +1,67 @@
namespace Yavsc.Abstract.Files;
/// <summary>
/// Helpers pour dériver les URL publiques des fichiers statiques à partir
/// d'une URL d'autorité OIDC ou d'un autre point d'entrée racine.
/// </summary>
public static class FileServerUrlHelpers
{
/// <summary>
/// Dérive la racine publique des fichiers utilisateur en alignant
/// le chemin sur <see cref="Yavsc.Constants.UserFilesPath"/>.
/// </summary>
/// <param name="authorityBaseUrl">
/// URL absolue de base, typiquement l'autorité OIDC de Yavsc.Org.
/// </param>
/// <returns>Une URL absolue pointant vers la racine des fichiers utilisateur.</returns>
public static Uri GetUserFilesBaseUri(Uri authorityBaseUrl)
{
ArgumentNullException.ThrowIfNull(authorityBaseUrl);
if (!authorityBaseUrl.IsAbsoluteUri)
{
throw new ArgumentException(
"The authority base URL must be absolute.",
nameof(authorityBaseUrl));
}
var baseString = authorityBaseUrl.GetLeftPart(UriPartial.Authority);
return new Uri(new Uri(baseString, UriKind.Absolute), EnsureTrailingSlash(Yavsc.Constants.UserFilesPath));
}
/// <summary>
/// Dérive la racine publique des fichiers utilisateur en alignant
/// le chemin sur <see cref="Yavsc.Constants.UserFilesPath"/>.
/// </summary>
/// <param name="authorityBaseUrl">
/// URL absolue de base, typiquement l'autorité OIDC de Yavsc.Org.
/// </param>
/// <returns>Une URL absolue pointant vers la racine des fichiers utilisateur.</returns>
public static Uri GetUserFilesBaseUri(string authorityBaseUrl)
=> GetUserFilesBaseUri(new Uri(authorityBaseUrl, UriKind.Absolute));
/// <summary>
/// Construit l'URL d'un fichier utilisateur à partir de la base d'autorité
/// et d'un chemin relatif sous la racine des fichiers.
/// </summary>
public static Uri GetUserFilesUri(Uri authorityBaseUrl, string relativePath)
{
ArgumentException.ThrowIfNullOrWhiteSpace(relativePath);
var baseUri = GetUserFilesBaseUri(authorityBaseUrl);
return new Uri(baseUri, NormalizeRelativePath(relativePath));
}
/// <summary>
/// Construit l'URL d'un fichier utilisateur à partir de la base d'autorité
/// et d'un chemin relatif sous la racine des fichiers.
/// </summary>
public static Uri GetUserFilesUri(string authorityBaseUrl, string relativePath)
=> GetUserFilesUri(new Uri(authorityBaseUrl, UriKind.Absolute), relativePath);
private static string EnsureTrailingSlash(string path)
=> path.EndsWith("/", StringComparison.Ordinal) ? path : path + "/";
private static string NormalizeRelativePath(string relativePath)
=> relativePath.TrimStart('/');
}

Some files were not shown because too many files have changed in this diff Show more