From a131a6ddf8be479e23dd4dc89c30bff6b513cc1e Mon Sep 17 00:00:00 2001 From: Paul Schneider Date: Sat, 7 Nov 2026 23:38:02 +0000 Subject: [PATCH 01/11] + chqt_regular --- src/PostIt/PostIt/App.axaml | 1 + 1 file changed, 1 insertion(+) diff --git a/src/PostIt/PostIt/App.axaml b/src/PostIt/PostIt/App.axaml index 88801b565..c6f5829ff 100644 --- a/src/PostIt/PostIt/App.axaml +++ b/src/PostIt/PostIt/App.axaml @@ -38,5 +38,6 @@ M17,2.49823144 C18.9339734,2.49823144 20.5017686,4.06602662 20.5017686,6 C20.5017686,7.93397338 18.9339734,9.50176856 17,9.50176856 C15.9700352,9.50176856 15.0439275,9.0571034 14.4031791,8.34927521 L9.84455071,10.9536986 C9.94786118,11.284101 10.0035371,11.6355486 10.0035371,12 C10.0035371,12.3644514 9.94786118,12.715899 9.84455071,13.0463014 L14.4022538,15.6517469 C15.0430358,14.9433244 15.9695393,14.4982314 17,14.4982314 C18.9339734,14.4982314 20.5017686,16.0660262 20.5017686,17.9999996 C20.5017686,19.9339729 18.9339734,21.5017681 17,21.5017681 C15.0660266,21.5017681 13.4982314,19.9339729 13.4982314,17.9999996 C13.4982314,17.6355481 13.5539074,17.2841005 13.6572179,16.9536982 L9.09951477,14.3482526 C8.45873279,15.0566751 7.53222925,15.5017686 6.50176856,15.5017686 C4.56779519,15.5017686 3,13.9339734 3,12 C3,10.0660266 4.56779519,8.49823144 6.50176856,8.49823144 C7.53173336,8.49823144 8.45784104,8.9428966 9.09858948,9.65072479 L13.6572179,7.04630139 C13.5539074,6.71589903 13.4982314,6.36445142 13.4982314,6 C13.4982314,4.06602662 15.0660266,2.49823144 17,2.49823144 Z M17,15.998231 C15.8944537,15.998231 14.9982314,16.8944533 14.9982314,17.9999996 C14.9982314,19.1055458 15.8944537,20.0017681 17,20.0017681 C18.1055463,20.0017681 19.0017686,19.1055458 19.0017686,17.9999996 C19.0017686,16.8944533 18.1055463,15.998231 17,15.998231 Z M6.50176856,9.99823144 C5.39622231,9.99823144 4.5,10.8944537 4.5,12 C4.5,13.1055463 5.39622231,14.0017686 6.50176856,14.0017686 C7.60731481,14.0017686 8.50353713,13.1055463 8.50353713,12 C8.50353713,10.8944537 7.60731481,9.99823144 6.50176856,9.99823144 Z M17,3.99823144 C15.8944537,3.99823144 14.9982314,4.89445375 14.9982314,6 C14.9982314,7.10554625 15.8944537,8.00176856 17,8.00176856 C18.1055463,8.00176856 19.0017686,7.10554625 19.0017686,6 C19.0017686,4.89445375 18.1055463,3.99823144 17,3.99823144 Z M2 14.75C2 16.5449 3.45507 18 5.25 18H5.99921L6 20.7499C6 21.0196 6.08736 21.2822 6.24901 21.4984C6.6625 22.0512 7.44585 22.1642 7.99868 21.7507L10.1239 20.1608L10.5199 18.5768C10.5914 18.2911 10.6965 18.0162 10.8322 17.7578L7.49986 20.2506L7.49879 16.5H5.25C4.2835 16.5 3.5 15.7165 3.5 14.75V6.25C3.5 5.2835 4.2835 4.5 5.25 4.5H18.75C19.7165 4.5 20.5 5.2835 20.5 6.25V10.0946C21.0475 10.2288 21.5671 10.5054 22 10.9246V6.25C22 4.45507 20.5449 3 18.75 3H5.25C3.45507 3 2 4.45507 2 6.25V14.75Z M18.0979 11.6695L12.1955 17.5719C11.8513 17.916 11.6072 18.3472 11.4892 18.8194L11.0315 20.6501C10.8325 21.4462 11.5536 22.1674 12.3497 21.9683L14.1804 21.5106C14.6526 21.3926 15.0838 21.1485 15.4279 20.8043L21.3303 14.9019C22.223 14.0093 22.223 12.5621 21.3303 11.6695C20.4377 10.7768 18.9905 10.7768 18.0979 11.6695Z M24,7.25 C27.1017853,7.25 29.629937,9.70601719 29.7458479,12.7794443 L29.75,13 L37,13 C37.6903559,13 38.25,13.5596441 38.25,14.25 C38.25,14.8972087 37.7581253,15.4295339 37.1278052,15.4935464 L37,15.5 L35.909,15.5 L34.2058308,38.0698451 C34.0385226,40.2866784 32.1910211,42 29.9678833,42 L18.0321167,42 C15.8089789,42 13.9614774,40.2866784 13.7941692,38.0698451 L12.09,15.5 L11,15.5 C10.3527913,15.5 9.8204661,15.0081253 9.75645361,14.3778052 L9.75,14.25 C9.75,13.6027913 10.2418747,13.0704661 10.8721948,13.0064536 L11,13 L18.25,13 C18.25,9.82436269 20.8243627,7.25 24,7.25 Z M33.4021054,15.5 L14.5978946,15.5 L16.2870795,37.8817009 C16.3559711,38.7945146 17.116707,39.5 18.0321167,39.5 L29.9678833,39.5 C30.883293,39.5 31.6440289,38.7945146 31.7129205,37.8817009 L33.4021054,15.5 Z M27.25,20.75 C27.8972087,20.75 28.4295339,21.2418747 28.4935464,21.8721948 L28.5,22 L28.5,33 C28.5,33.6903559 27.9403559,34.25 27.25,34.25 C26.6027913,34.25 26.0704661,33.7581253 26.0064536,33.1278052 L26,33 L26,22 C26,21.3096441 26.5596441,20.75 27.25,20.75 Z M20.75,20.75 C21.3972087,20.75 21.9295339,21.2418747 21.9935464,21.8721948 L22,22 L22,33 C22,33.6903559 21.4403559,34.25 20.75,34.25 C20.1027913,34.25 19.5704661,33.7581253 19.5064536,33.1278052 L19.5,33 L19.5,22 C19.5,21.3096441 20.0596441,20.75 20.75,20.75 Z M24,9.75 C22.2669685,9.75 20.8507541,11.1064548 20.7551448,12.8155761 L20.75,13 L27.25,13 C27.25,11.2050746 25.7949254,9.75 24,9.75 Z + M14.0038862,2.5 C20.3551608,2.5 25.5038862,7.64872538 25.5038862,14 C25.5038862,20.3512746 20.3551608,25.5 14.0038862,25.5 C12.0828262,25.5 10.2289934,25.0277557 8.57453454,24.1400553 L4.06949813,25.4927799 C3.40830889,25.6913248 2.71135661,25.3162775 2.51281166,24.6550883 C2.44236748,24.4204969 2.44239769,24.1703786 2.5128929,23.935823 L3.86597493,19.4333464 C2.97690068,17.777898 2.50388618,15.9226229 2.50388618,14 C2.50388618,7.64872538 7.65261155,2.5 14.0038862,2.5 Z M14.0038862,4 C8.48103868,4 4.00388618,8.4771525 4.00388618,14 C4.00388618,15.7703119 4.46384891,17.4718347 5.32571954,18.9725127 L5.48656853,19.2525809 L4.08316234,23.9225148 L8.75512584,22.5196672 L9.03501121,22.6802549 C10.5348218,23.5407899 12.2350195,24 14.0038862,24 C19.5267337,24 24.0038862,19.5228475 24.0038862,14 C24.0038862,8.4771525 19.5267337,4 14.0038862,4 Z M10.2538862,15.5 L14.7521489,15.5 C15.1663625,15.5 15.5021489,15.8357864 15.5021489,16.25 C15.5021489,16.6296958 15.219995,16.943491 14.8539195,16.9931534 L14.7521489,17 L10.2538862,17 C9.83967261,17 9.50388618,16.6642136 9.50388618,16.25 C9.50388618,15.8703042 9.78604006,15.556509 10.1521156,15.5068466 L10.2538862,15.5 L14.7521489,15.5 L10.2538862,15.5 Z M10.2538862,11 L17.7583662,11 C18.1725798,11 18.5083662,11.3357864 18.5083662,11.75 C18.5083662,12.1296958 18.2262123,12.443491 17.8601368,12.4931534 L17.7583662,12.5 L10.2538862,12.5 C9.83967261,12.5 9.50388618,12.1642136 9.50388618,11.75 C9.50388618,11.3703042 9.78604006,11.056509 10.1521156,11.0068466 L10.2538862,11 L17.7583662,11 L10.2538862,11 Z From f1c23965b2f5d6995e54b0979ad5a25d704feba8 Mon Sep 17 00:00:00 2001 From: Paul Schneider Date: Sun, 8 Nov 2026 02:04:59 +0000 Subject: [PATCH 02/11] Blog edition accessibility --- .vscode/launch.json | 3 +- CHANGELOG.md | 4 + doc/architecture/postit.md | 45 +++- src/PostIt/PostIt.Android/MainActivity.cs | 22 ++ .../PostIt.Android/PlatformBootstrap.cs | 1 + .../PostIt.Android/PostIt.Android.csproj | 2 + .../AndroidMarkdownEditorTestActivity.cs | 241 ++++++++++++++++++ src/PostIt/PostIt.Tests/BlogReaderTests.cs | 3 +- .../PostIt.Tests/MarkdownEditorScrollTests.cs | 200 +++++++++++++++ .../Controls/MarkdownEditorControl.axaml.cs | 45 ++++ src/PostIt/PostIt/Services/Platform.cs | 1 + src/PostIt/PostIt/Views/Blogs/BlogsPage.axaml | 16 +- .../PostIt/Views/Blogs/BlogsPage.axaml.cs | 27 +- .../PostIt/Views/Layout/MainView.axaml.cs | 62 +++++ 14 files changed, 656 insertions(+), 16 deletions(-) create mode 100644 src/PostIt/PostIt.Tests/AndroidMarkdownEditorTestActivity.cs diff --git a/.vscode/launch.json b/.vscode/launch.json index 87cf40dbb..d8a9f1c8c 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -17,8 +17,7 @@ "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", diff --git a/CHANGELOG.md b/CHANGELOG.md index 337e74288..799dd624b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,10 @@ ### Added +* [PostIt.Android] Embed managed assemblies in APKs by default, including Debug builds launched outside the Makefile, to prevent the native startup abort "No assemblies found" when fast-deployment files are absent. +* [PostIt] Remove the redundant "Post detail" heading and its grid row from the blog editor, including the compact layout. +* [PostIt/Android] Combine system-bar/cutout safe-area insets with actual keyboard overlap at the root, instead of replacing Avalonia's automatic safe-area padding with keyboard-only padding. Preserve the toolbar, session banner, attachments and status controls; place article details beside the editor during landscape keyboard input. Only on Android, temporarily hide the title input while editing in compact mode with the keyboard open, restoring it on keyboard closure or focus change without modifying the draft. Verify visible controls outside native system bars, at least three editor lines and the editor's bottom above IME insets. +* [PostIt/Android] Remove the outer blog-page scroll container so the editor, reader and list retain bounded viewports. Keep the editing caret visible after the keyboard resizes the editor; request the native keyboard on a touch tap, not a scroll gesture, without cycling focus or replacing the selection. Add headless regressions and a debug-only device check using a local synthetic article. * [PostIt.Android] Fix the crash when starting a podcast broadcast with camera preview active: detach preview callbacks using the retained surface holder, before deferred native-view destruction, without accessing an already disposed SurfaceView. Add a device regression covering preview teardown followed by local capture. * [PostIt.Android] Keep the screen awake during foreground video playback and release it on pause, stop, completion, error or video teardown. Add a persisted, default-off podcast option to keep the screen awake during camera preview/live capture; release on capture end and allow normal sleep in the background without changing the broadcast service. Include native LibVLC libraries when building with a single runtime identifier (including physical ARM64 phones). * [PostIt/Podcasts] Preview the selected camera before starting a live broadcast, without creating an emission, encoding files or opening the microphone. Release preview on stop, navigation, logout and Android backgrounding, and before starting the actual broadcast. Correct Android portrait orientation for rear and front cameras: subtract the sensor rotation already carried by Camera2's SurfaceTexture matrix, reversing the remaining rotation when that matrix mirrors the front camera (it was turned 90° or upside down); track display changes for both preview and encoded frames, preserving aspect ratio and fixed live stream dimensions. diff --git a/doc/architecture/postit.md b/doc/architecture/postit.md index 9a0ae000e..4e63f1c06 100644 --- a/doc/architecture/postit.md +++ b/doc/architecture/postit.md @@ -12,6 +12,13 @@ ## Surface : un code-base, trois front-ends +Le projet Android active `EmbedAssembliesIntoApk` par défaut, y compris en +Debug : un APK installé directement doit contenir les assemblies .NET, +sans dépendre des fichiers de Fast Deployment sous `files/.__override__`. +Sans elles, le runtime Android abandonne avant de charger l'interface +avec « No assemblies found ». Le Makefile conserve également ce réglage +explicite pour ses commandes de compilation. + ``` ┌────────────────────────� │ PostIt (lib) │ @@ -376,7 +383,8 @@ de modifier cette répartition. La liste et l'article défilent séparément. Lorsque la largeur de la fenêtre atteint ou dépasse sa hauteur, le lecteur ou l'éditeur passe à gauche (deux tiers de la largeur par défaut), et -l'en-tête, la recherche, les commandes et la liste passent à droite. +l'en-tête, la recherche et la liste passent à droite ; les commandes +restent dans la barre de navigation. Le séparateur devient vertical. En portrait, la disposition verticale revient sans recréer les contrôles ni perdre le brouillon. Le seuil utilise les dimensions clientes de la fenêtre, indépendamment @@ -395,6 +403,41 @@ dépasser le viewport pour que les barres automatiques s'activent. Ne pas placer cette grille dans un `StackPanel` vertical ou un `ScrollViewer` de page, qui lui donnerait une hauteur de mesure illimitée. +Après un redimensionnement de la zone de texte (notamment à l'ouverture du +clavier Android avec `AdjustResize`), l'éditeur remet le curseur dans son +viewport après la mise en page, uniquement s'il garde le focus. Un toucher +dans la zone éditable demande aussi le clavier via le pont natif Android, +sans retirer puis redonner le focus ni modifier la sélection. Les autres +plateformes conservent leur gestion habituelle du clavier. + +`MainView` compose les marges de `TopLevel.InsetsManager` (barres système +et découpes) avec le recouvrement réel indiqué par `TopLevel.InputPane`, +car le clavier ne redimensionne pas toujours la fenêtre Android en mode +edge-to-edge. Si `AdjustResize` a déjà réduit la fenêtre, cette réserve +ne soustrait pas une seconde fois la hauteur du clavier. La racine gère +explicitement ces marges et désactive `TopLevel.AutoSafeAreaPadding` pour +éviter deux propriétaires du même padding. Ne pas remplacer les marges +système par un padding contenant uniquement la hauteur du clavier. +En disposition large, tant que le clavier est ouvert et que l'article +garde le focus, son titre et ses pièces jointes passent dans +une colonne à côté du texte. La barre de commandes, la bannière de session +et le statut restent visibles. La disposition habituelle revient à la +fermeture du clavier ou au changement de focus, sans recréer le brouillon. +Sous Android uniquement, le champ du titre est masqué pendant la saisie +compacte avec le clavier ouvert, en portrait comme en paysage ; il réapparaît à la fermeture du clavier +ou quand le focus quitte l'article. Sa valeur n'est jamais effacée. + +En Debug Android, `fr.pschneider.postit.MarkdownEditorTestActivity` ouvre +un billet synthétique local, vérifie au moins trois lignes visibles et +le bas de l'éditeur au-dessus des insets natifs du clavier et les contrôles +en dehors des barres système, +ferme puis rouvre le clavier par toucher sans perte de focus. Le résultat +est écrit dans `files/markdown-editor-test-result.txt`. Ce test nécessite +Android 11 ou plus pour vérifier les insets du clavier ; il ne publie +aucun billet et retire sa page à la fin. +L'extra booléen `landscape=true` force le paysage pendant le test et restaure +l'orientation demandée précédemment à la fin. + ## Navigation Le host de navigation est un `NavigationPage x:Name="NavRoot"` diff --git a/src/PostIt/PostIt.Android/MainActivity.cs b/src/PostIt/PostIt.Android/MainActivity.cs index 0b56b3776..f962761c2 100644 --- a/src/PostIt/PostIt.Android/MainActivity.cs +++ b/src/PostIt/PostIt.Android/MainActivity.cs @@ -44,6 +44,28 @@ public class MainActivity : AvaloniaMainActivity private void OnScreenAwakeChanged() => RunOnUiThread(UpdateScreenAwake); + internal static void ShowSoftKeyboard() + { + if (Current is not { } activity || !IsForeground) + { + global::Android.Util.Log.Warn("PostIt", "Cannot show the keyboard without a foreground activity."); + return; + } + + activity.RunOnUiThread(() => + { + if (activity.CurrentFocus is not { } view + || activity.GetSystemService(InputMethodService) is not global::Android.Views.InputMethods.InputMethodManager inputMethod) + { + global::Android.Util.Log.Warn("PostIt", "Cannot show the keyboard without a focused native view and input method."); + return; + } + + if (!inputMethod.ShowSoftInput(view, global::Android.Views.InputMethods.ShowFlags.Implicit)) + global::Android.Util.Log.Warn("PostIt", "The input method did not accept the keyboard activation request."); + }); + } + private void UpdateScreenAwake() { if (Window is not { } window) return; diff --git a/src/PostIt/PostIt.Android/PlatformBootstrap.cs b/src/PostIt/PostIt.Android/PlatformBootstrap.cs index 9117aea69..30d76aba5 100644 --- a/src/PostIt/PostIt.Android/PlatformBootstrap.cs +++ b/src/PostIt/PostIt.Android/PlatformBootstrap.cs @@ -22,6 +22,7 @@ internal static class PlatformBootstrap Platform.CreateServiceProvider = AndroidServiceProvider.GetOrCreate; Platform.BackgroundChatService = AndroidBackgroundChatService.Instance; + Platform.ShowSoftKeyboard = MainActivity.ShowSoftKeyboard; Platform.TryGetCurrentLocationAsync = AndroidCurrentLocationProvider.TryGetCurrentLocationAsync; Platform.CreateVideoSurface = (player, replay) => new AndroidVideoSurface(player, replay); if (System.OperatingSystem.IsAndroidVersionAtLeast(26)) diff --git a/src/PostIt/PostIt.Android/PostIt.Android.csproj b/src/PostIt/PostIt.Android/PostIt.Android.csproj index a2e97677b..36736de19 100644 --- a/src/PostIt/PostIt.Android/PostIt.Android.csproj +++ b/src/PostIt/PostIt.Android/PostIt.Android.csproj @@ -8,6 +8,7 @@ 1 1.0 apk + true false $(RuntimeIdentifier) @@ -32,6 +33,7 @@ + diff --git a/src/PostIt/PostIt.Tests/AndroidMarkdownEditorTestActivity.cs b/src/PostIt/PostIt.Tests/AndroidMarkdownEditorTestActivity.cs new file mode 100644 index 000000000..02580a7cc --- /dev/null +++ b/src/PostIt/PostIt.Tests/AndroidMarkdownEditorTestActivity.cs @@ -0,0 +1,241 @@ +#if ANDROID +using System; +using System.IO; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using Android.App; +using Android.Content; +using Android.Content.PM; +using Android.OS; +using Android.Views; +using Android.Views.InputMethods; +using Avalonia; +using Avalonia.Controls; +using Avalonia.LogicalTree; +using Avalonia.Threading; +using AvaloniaEdit; +using PostIt.Android; +using PostIt.Controls; +using PostIt.ViewModels; +using PostIt.Views.Blogs; + +namespace PostIt.Tests; + +[Activity(Name = "fr.pschneider.postit.MarkdownEditorTestActivity", Exported = true)] +public sealed class AndroidMarkdownEditorTestActivity : Activity +{ + private string _stage = "startup"; + private ScreenOrientation? _previousOrientation; + protected override async void OnCreate(Bundle? state) + { + base.OnCreate(state); + var result = Path.Combine(FilesDir!.AbsolutePath, "markdown-editor-test-result.txt"); + File.WriteAllText(result, "RUNNING"); + try + { + using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(60)); + await RunAsync(timeout.Token); + File.WriteAllText(result, "PASS\nbounded viewport above IME,at least three visible lines,visible caret,keyboard reopen,retained focus"); + } + catch (Exception ex) + { + File.WriteAllText(result, $"FAIL at {_stage}\n" + ex); + } + finally + { + RunOnUiThread(Finish); + } + } + + private async Task RunAsync(CancellationToken ct) + { + if (!OperatingSystem.IsAndroidVersionAtLeast(30)) + throw new PlatformNotSupportedException("Android 11 required for keyboard visibility assertions."); + StartActivity(new Intent(this, typeof(MainActivity)).AddFlags(ActivityFlags.NewTask)); + _stage = "waiting for main activity"; + await WaitAsync(() => MainActivity.IsForeground && (Avalonia.Application.Current as App)?.View is not null, ct); + var root = ((App)Avalonia.Application.Current!).View!; + if (Intent?.GetBooleanExtra("landscape", false) == true) + { + _previousOrientation = MainActivity.Current!.RequestedOrientation; + MainActivity.Current.RequestedOrientation = ScreenOrientation.Landscape; + await WaitAsync(() => TopLevel.GetTopLevel(root)!.ClientSize.Width > TopLevel.GetTopLevel(root)!.ClientSize.Height, ct); + } + var navigation = root.FindControl("NavRoot")!; + BlogsPage? page = null; + TextEditor? source = null; + var focusLosses = 0; + try + { + await Dispatcher.UIThread.InvokeAsync(async () => + { + page = new BlogsPage + { + DataContext = new BlogsViewModel + { + IsEditing = true, + DraftTitle = "Local keyboard test", + DraftArticle = string.Join("\n", Enumerable.Range(1, 150).Select(i => $"Line {i}: local keyboard test")) + } + }; + await navigation.PushAsync(page, null); + source = page.GetLogicalDescendants().OfType().Single() + .FindControl("SourceEditor")!; + }); + _stage = "waiting for editor layout"; + await WaitAsync(() => source!.TextArea.Bounds.Height > 0, ct); + await Dispatcher.UIThread.InvokeAsync(() => CheckSystemBars(root)); + await Dispatcher.UIThread.InvokeAsync(() => + { + if (!source!.TextArea.Focus()) + throw new InvalidOperationException("Unable to focus the mounted editor."); + source.CaretOffset = source.Document.TextLength; + source.TextArea.Caret.BringCaretToView(); + source.TextArea.LostFocus += (_, _) => focusLosses++; + }); + _stage = "waiting for native input connection"; + await WaitAsync(() => + { + var activity = MainActivity.Current!; + var manager = (InputMethodManager)activity.GetSystemService(InputMethodService)!; + return activity.CurrentFocus is { } view && view.HasWindowFocus + && manager.InvokeIsActive(view) && manager.IsAcceptingText; + }, ct); + _stage = "opening keyboard"; + await TapAsync(source!, root); + await WaitAsync(KeyboardVisible, ct); + await Task.Delay(500, ct); + await Dispatcher.UIThread.InvokeAsync(() => CheckCaret(source!, root)); + var activity = MainActivity.Current!; + await Dispatcher.UIThread.InvokeAsync(() => + { + var manager = (InputMethodManager)activity.GetSystemService(InputMethodService)!; + if (!manager.HideSoftInputFromWindow(activity.CurrentFocus!.WindowToken, HideSoftInputFlags.None)) + throw new InvalidOperationException("Keyboard hide request rejected."); + }); + await WaitAsync(() => !KeyboardVisible(), ct); + await Task.Delay(500, ct); + await Dispatcher.UIThread.InvokeAsync(() => CheckSystemBars(root)); + await TapAsync(source!, root); + _stage = "reopening keyboard"; + await WaitAsync(KeyboardVisible, ct); + await Task.Delay(500, ct); + await Dispatcher.UIThread.InvokeAsync(() => + { + CheckCaret(source!, root); + if (focusLosses != 0) throw new InvalidOperationException($"Editor lost focus {focusLosses} times."); + }); + } + finally + { + if (page is not null) + await Dispatcher.UIThread.InvokeAsync(async () => + { + if (ReferenceEquals(navigation.NavigationStack.LastOrDefault(), page)) + await navigation.PopAsync(); + }); + if (_previousOrientation is { } orientation && MainActivity.Current is { } main) + main.RunOnUiThread(() => main.RequestedOrientation = orientation); + } + } + + private static bool KeyboardVisible() + => OperatingSystem.IsAndroidVersionAtLeast(30) + && MainActivity.Current?.Window?.DecorView?.RootWindowInsets?.IsVisible(WindowInsets.Type.Ime()) == true; + + private static void CheckCaret(TextEditor source, Control root) + { + var area = source.TextArea; + if (!area.IsFocused) throw new InvalidOperationException("Editor is not focused."); + var rect = area.Caret.CalculateCaretRectangle(); + var view = area.TextView; + var bottom = rect.Bottom - view.ScrollOffset.Y; + if (rect.Top - view.ScrollOffset.Y < -1 || bottom > view.Bounds.Height + 1) + throw new InvalidOperationException($"Caret outside viewport: bottom={bottom}, height={view.Bounds.Height}."); + var editorBottom = source.TranslatePoint(new Point(0, source.Bounds.Height), root)!.Value.Y; + if (editorBottom > root.Bounds.Height + 1) + throw new InvalidOperationException($"Editor outside root: bottom={editorBottom}, height={root.Bounds.Height}."); + if (view.Bounds.Height < view.DefaultLineHeight * 3) + throw new InvalidOperationException($"Less than three visible lines: viewport={view.Bounds.Height}, line={view.DefaultLineHeight}."); + if (OperatingSystem.IsAndroidVersionAtLeast(30) && KeyboardVisible()) + { + var activity = MainActivity.Current!; + var decor = activity.Window!.DecorView; + var keyboardTop = decor.Height - decor.RootWindowInsets!.GetInsets(WindowInsets.Type.Ime()).Bottom; + var location = new int[2]; + activity.CurrentFocus!.GetLocationInWindow(location); + var topLevel = TopLevel.GetTopLevel(root)!; + var bottomInWindow = source.TranslatePoint(new Point(0, source.Bounds.Height), topLevel)!.Value.Y + * topLevel.RenderScaling + location[1]; + if (bottomInWindow > keyboardTop + 2) + throw new InvalidOperationException($"Editor hidden by keyboard: bottom={bottomInWindow}, keyboardTop={keyboardTop}."); + } + CheckSystemBars(root); + } + + private static void CheckSystemBars(Control root) + { + if (!OperatingSystem.IsAndroidVersionAtLeast(30)) + throw new PlatformNotSupportedException("Android 11 required for native inset assertions."); + var activity = MainActivity.Current!; + var decor = activity.Window!.DecorView; + var insets = decor.RootWindowInsets!; + var bars = insets.GetInsets(WindowInsets.Type.SystemBars() | WindowInsets.Type.DisplayCutout()); + var location = new int[2]; + activity.CurrentFocus!.GetLocationInWindow(location); + var topLevel = TopLevel.GetTopLevel(root)!; + var navigation = root.FindControl("NavRoot")!; + var banner = root.FindControl("SessionBanner")!; + var top = navigation.TranslatePoint(new Point(), topLevel)!.Value.Y * topLevel.RenderScaling + location[1]; + var bottom = banner.TranslatePoint(new Point(0, banner.Bounds.Height), topLevel)!.Value.Y + * topLevel.RenderScaling + location[1]; + var visibleBottom = decor.Height - bars.Bottom; + if (KeyboardVisible()) + visibleBottom = Math.Min(visibleBottom, decor.Height - insets.GetInsets(WindowInsets.Type.Ime()).Bottom); + if (top < bars.Top - 2 || bottom > visibleBottom + 2 || !banner.IsVisible) + throw new InvalidOperationException($"Controls overlap system bars: top={top}, safeTop={bars.Top}, bottom={bottom}, safeBottom={visibleBottom}, banner={banner.IsVisible}."); + if (navigation.NavigationStack.LastOrDefault() is BlogsPage page) + { + var bar = NavigationPage.GetTopCommandBar(page)!; + var shouldShowTitle = !KeyboardVisible(); + if (!bar.IsVisible || bar.Bounds.Height <= 0 + || page.FindControl("DraftTitleTextBox")?.IsVisible != shouldShowTitle) + throw new InvalidOperationException("Blog controls are unavailable."); + if (page.FindControl("DraftTitleTextBox")?.Text != "Local keyboard test") + throw new InvalidOperationException("The title changed during keyboard layout transitions."); + } + } + + private static async Task TapAsync(TextEditor source, Control root) + { + await Dispatcher.UIThread.InvokeAsync(() => + { + var activity = MainActivity.Current!; + var point = source.TextArea.TranslatePoint(new Point(80, source.TextArea.Bounds.Height / 2), root)!.Value; + var location = new int[2]; + activity.CurrentFocus!.GetLocationInWindow(location); + var scale = TopLevel.GetTopLevel(root)!.RenderScaling; + var x = (float)(point.X * scale + location[0]); + var y = (float)(point.Y * scale + location[1]); + var now = SystemClock.UptimeMillis(); + using var properties = new MotionEvent.PointerProperties { Id = 0, ToolType = MotionEventToolType.Finger }; + using var coordinates = new MotionEvent.PointerCoords { X = x, Y = y, Pressure = 1, Size = 1 }; + using var down = MotionEvent.Obtain(now, now, MotionEventActions.Down, 1, + new[] { properties }, new[] { coordinates }, 0, 0, 1, 1, 0, 0, + InputSourceType.Touchscreen, 0)!; + using var up = MotionEvent.Obtain(now, now + 50, MotionEventActions.Up, 1, + new[] { properties }, new[] { coordinates }, 0, 0, 1, 1, 0, 0, + InputSourceType.Touchscreen, 0)!; + activity.DispatchTouchEvent(down); + activity.DispatchTouchEvent(up); + }); + } + + private static async Task WaitAsync(Func condition, CancellationToken ct) + { + while (!await Dispatcher.UIThread.InvokeAsync(condition)) + await Task.Delay(50, ct); + } +} +#endif diff --git a/src/PostIt/PostIt.Tests/BlogReaderTests.cs b/src/PostIt/PostIt.Tests/BlogReaderTests.cs index d07cf7a30..0b26cf33e 100644 --- a/src/PostIt/PostIt.Tests/BlogReaderTests.cs +++ b/src/PostIt/PostIt.Tests/BlogReaderTests.cs @@ -228,7 +228,6 @@ public class BlogReaderTests { Assert.True(reader.Bounds.Right <= list.Bounds.Left); Assert.Equal(2, Grid.GetColumn(page.BlogsHeaderPanel)); - Assert.Equal(2, Grid.GetColumn(page.BlogsCommandBar)); Assert.Equal(reader.Margin.Top, reader.Bounds.Top); Assert.Equal(page.StatusBar.Bounds.Top - reader.Margin.Bottom, reader.Bounds.Bottom); Assert.Equal(36, page.TranslatePoint(new Point(), nav)!.Value.Y); @@ -237,9 +236,9 @@ public class BlogReaderTests { Assert.True(list.Bounds.Bottom <= reader.Bounds.Top); Assert.Equal(0, Grid.GetColumn(page.BlogsHeaderPanel)); - Assert.Equal(0, Grid.GetColumn(page.BlogsCommandBar)); } + Assert.Same(page.BlogsCommandBar, NavigationPage.GetTopCommandBar(page)); var articleScroll = page.FindControl("ArticleReader")! .GetVisualDescendants().OfType().Single(); Assert.InRange(articleScroll.Viewport.Height, 1, window.ClientSize.Height); diff --git a/src/PostIt/PostIt.Tests/MarkdownEditorScrollTests.cs b/src/PostIt/PostIt.Tests/MarkdownEditorScrollTests.cs index 6cdaa5b5b..f89352b70 100644 --- a/src/PostIt/PostIt.Tests/MarkdownEditorScrollTests.cs +++ b/src/PostIt/PostIt.Tests/MarkdownEditorScrollTests.cs @@ -1,12 +1,17 @@ using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Primitives; +using Avalonia.Headless; using Avalonia.Headless.XUnit; +using Avalonia.Input; using Avalonia.LogicalTree; using Avalonia.Threading; using Avalonia.VisualTree; using AvaloniaEdit; using PostIt.Controls; +using PostIt.Services; +using PostIt.ViewModels; +using PostIt.Views; using PostIt.Views.Blogs; namespace PostIt.Tests; @@ -16,6 +21,201 @@ public class MarkdownEditorScrollTests private static readonly string LongArticle = string.Join("\n\n", Enumerable.Range(1, 100).Select(i => $"Paragraph {i}: article content.")); + [AvaloniaFact] + public async Task Landscape_keyboard_preserves_controls_and_restores_editor_layout() + { + var root = new MainView(); + var page = new BlogsPage { DataContext = new BlogsViewModel { IsEditing = true, DraftArticle = LongArticle } }; + var window = new Window { Width = 800, Height = 400, Content = root }; + try + { + window.Show(); + await root.NavRoot.PushAsync(page, null); + Dispatcher.UIThread.RunJobs(); + window.UpdateLayout(); + var editor = page.ArticleEditor; + var source = editor.FindControl("SourceEditor")!; + source.TextArea.Focus(); + source.CaretOffset = source.Document.TextLength; + root.ApplyKeyboardOcclusion(new Rect(0, 200, 800, 200)); + window.UpdateLayout(); + Dispatcher.UIThread.RunJobs(); + window.UpdateLayout(); + Assert.True(page.DraftTitleTextBox.IsVisible); + Assert.True(page.AttachmentsBorder.IsVisible); + Assert.True(root.SessionBanner.IsVisible); + Assert.Equal(1, Grid.GetColumn(page.DraftTitleTextBox)); + Assert.Equal(1, Grid.GetColumn(page.AttachmentsBorder)); + Assert.True(page.StatusBar.IsVisible); + Assert.Equal(2, Grid.GetColumn(page.StatusBar)); + Assert.Same(page.BlogsCommandBar, NavigationPage.GetTopCommandBar(page)); + Assert.True(source.TextArea.Bounds.Height >= source.TextArea.TextView.DefaultLineHeight * 3); + var bottom = source.TranslatePoint(new Point(0, source.Bounds.Height), window)!.Value.Y; + Assert.InRange(bottom, 1, 200); + var document = source.Document; + root.ApplyKeyboardOcclusion(null); + window.UpdateLayout(); + Dispatcher.UIThread.RunJobs(); + window.UpdateLayout(); + Assert.True(page.DraftTitleTextBox.IsVisible); + Assert.True(page.AttachmentsBorder.IsVisible); + Assert.True(root.SessionBanner.IsVisible); + Assert.Equal(0, Grid.GetColumn(page.DraftTitleTextBox)); + Assert.Same(document, source.Document); + Assert.True(source.TextArea.IsFocused); + + window.Height = 200; + Dispatcher.UIThread.RunJobs(); + window.UpdateLayout(); + root.ApplyKeyboardOcclusion(new Rect(0, 200, 800, 200)); + Assert.Equal(0, root.Padding.Bottom); + } + finally + { + CloseWindow(window, page.ArticleEditor); + } + } + + [AvaloniaFact] + public void Keyboard_padding_preserves_system_bar_insets_and_restores_them() + { + var root = new MainView(); + var window = new Window { Width = 600, Height = 800, Content = root }; + try + { + window.Show(); + Dispatcher.UIThread.RunJobs(); + window.UpdateLayout(); + var safeArea = new Thickness(10, 24, 12, 30); + root.ApplySafeArea(safeArea); + Assert.Equal(safeArea, root.Padding); + root.ApplyKeyboardOcclusion(new Rect(0, 500, 600, 300)); + Assert.Equal(new Thickness(10, 24, 12, 300), root.Padding); + root.ApplySafeArea(new Thickness(20, 26, 22, 32)); + Assert.Equal(new Thickness(20, 26, 22, 300), root.Padding); + root.ApplyKeyboardOcclusion(null); + window.UpdateLayout(); + Assert.Equal(new Thickness(20, 26, 22, 32), root.Padding); + var navigationTop = root.NavRoot.TranslatePoint(new Point(), window)!.Value.Y; + var bannerBottom = root.SessionBanner.TranslatePoint(new Point(0, root.SessionBanner.Bounds.Height), window)!.Value.Y; + Assert.True(navigationTop >= 26); + Assert.True(bannerBottom <= 768); + Assert.True(root.SessionBanner.IsVisible); + } + finally + { + window.Close(); + } + } + + [AvaloniaTheory] + [InlineData(true)] + [InlineData(false)] + public void Resizing_keeps_the_focused_caret_visible_without_changing_selection(bool focused) + { + var editor = new MarkdownEditorControl { MarkdownText = LongArticle }; + var other = new TextBox(); + var panel = new DockPanel(); + DockPanel.SetDock(other, Dock.Top); + panel.Children.Add(other); + panel.Children.Add(editor); + var window = new Window { Width = 600, Height = 500, Content = panel }; + try + { + window.Show(); + Dispatcher.UIThread.RunJobs(); + window.UpdateLayout(); + var source = editor.FindControl("SourceEditor")!; + source.TextArea.Focus(); + source.Select(LongArticle.Length - 20, 10); + source.TextArea.Caret.BringCaretToView(); + Dispatcher.UIThread.RunJobs(); + window.UpdateLayout(); + var selectedText = source.SelectedText; + var caretOffset = source.CaretOffset; + var scroller = FindArticleScroller(editor, false); + if (!focused) + { + other.Focus(); + scroller.ScrollToHome(); + } + + window.Height = 250; + window.UpdateLayout(); + Dispatcher.UIThread.RunJobs(); + window.UpdateLayout(); + + Assert.Equal(selectedText, source.SelectedText); + Assert.Equal(caretOffset, source.CaretOffset); + if (focused) + { + Assert.True(source.TextArea.IsFocused); + var caret = source.TextArea.Caret.CalculateCaretRectangle(); + var view = source.TextArea.TextView; + Assert.InRange(caret.Top - view.ScrollOffset.Y, 0, view.Bounds.Height); + Assert.InRange(caret.Bottom - view.ScrollOffset.Y, 0, view.Bounds.Height); + } + else + { + Assert.True(other.IsFocused); + Assert.Equal(0, scroller.Offset.Y); + } + } + finally + { + CloseWindow(window, editor); + } + } + + [AvaloniaFact] + public void Repeated_touch_requests_keyboard_without_losing_focus_and_read_only_does_not() + { + var editor = new MarkdownEditorControl { MarkdownText = LongArticle }; + var window = new Window { Width = 600, Height = 400, Content = editor }; + var previous = Platform.ShowSoftKeyboard; + var requests = 0; + Platform.ShowSoftKeyboard = () => requests++; + try + { + window.Show(); + Dispatcher.UIThread.RunJobs(); + window.UpdateLayout(); + var source = editor.FindControl("SourceEditor")!; + source.TextArea.Focus(); + var focusLosses = 0; + source.TextArea.LostFocus += (_, _) => focusLosses++; + var point = source.TextArea.TranslatePoint(new Point(60, 20), window)!.Value; + for (var i = 0; i < 2; i++) + { + using var touch = window.TouchBegin(point); + window.TouchEnd(touch, point); + Assert.True(source.TextArea.IsFocused); + Assert.Equal(i + 1, requests); + } + + window.MouseDown(point, MouseButton.Left); + window.MouseUp(point, MouseButton.Left); + Assert.Equal(2, requests); + using (var scrollTouch = window.TouchBegin(point)) + { + var end = point + new Vector(0, -80); + window.TouchMove(scrollTouch, end); + window.TouchEnd(scrollTouch, end); + } + Assert.Equal(2, requests); + source.IsReadOnly = true; + using var readOnlyTouch = window.TouchBegin(point); + window.TouchEnd(readOnlyTouch, point); + Assert.Equal(2, requests); + Assert.Equal(0, focusLosses); + } + finally + { + Platform.ShowSoftKeyboard = previous; + CloseWindow(window, editor); + } + } + [AvaloniaTheory] [InlineData(false)] [InlineData(true)] diff --git a/src/PostIt/PostIt/Controls/MarkdownEditorControl.axaml.cs b/src/PostIt/PostIt/Controls/MarkdownEditorControl.axaml.cs index 2538f7168..89c7126f3 100644 --- a/src/PostIt/PostIt/Controls/MarkdownEditorControl.axaml.cs +++ b/src/PostIt/PostIt/Controls/MarkdownEditorControl.axaml.cs @@ -1,12 +1,19 @@ using System; using Avalonia; using Avalonia.Controls; +using Avalonia.Input; +using Avalonia.Interactivity; +using Avalonia.Threading; +using Avalonia.VisualTree; using AvaloniaEdit.Document; +using PostIt.Services; namespace PostIt.Controls; public partial class MarkdownEditorControl : UserControl { + private IPointer? _touchPointer; + private Point _touchStart; public static readonly StyledProperty MarkdownTextProperty = AvaloniaProperty.Register(nameof(MarkdownText)); @@ -38,6 +45,44 @@ public partial class MarkdownEditorControl : UserControl { InitializeComponent(); PropertyChanged += OnPropertyChanged; + SourceEditor.TextArea.SizeChanged += (_, _) => + Dispatcher.UIThread.Post(KeepCaretVisible, DispatcherPriority.Loaded); + SourceEditor.TextArea.AddHandler(InputElement.PointerPressedEvent, OnEditorPointerPressed, + RoutingStrategies.Tunnel, handledEventsToo: true); + SourceEditor.TextArea.AddHandler(InputElement.PointerReleasedEvent, OnEditorPointerReleased, + RoutingStrategies.Bubble, handledEventsToo: true); + } + + private void KeepCaretVisible() + { + if (SourceEditor.TextArea.IsFocused && SourceEditor.IsEffectivelyVisible + && SourceEditor.TextArea.Bounds.Height > 0) + SourceEditor.TextArea.Caret.BringCaretToView(); + } + + private void OnEditorPointerPressed(object? sender, PointerPressedEventArgs e) + { + if (e.Pointer.Type != PointerType.Touch) + return; + _touchPointer = e.Pointer; + _touchStart = e.GetPosition(SourceEditor.TextArea); + } + + private void OnEditorPointerReleased(object? sender, PointerReleasedEventArgs e) + { + if (!ReferenceEquals(_touchPointer, e.Pointer)) + return; + _touchPointer = null; + var point = e.GetPosition(SourceEditor.TextArea); + var settings = this.GetPlatformSettings() + ?? throw new InvalidOperationException("The editor has no platform input settings."); + var tapSize = settings.GetTapSize(PointerType.Touch); + // AvaloniaEdit changes pointer capture during selection, so its taps may not raise Tapped. + if (new Rect(_touchStart, default(Size)).Inflate(new Thickness(tapSize.Width, tapSize.Height)).Contains(point) + && SourceEditor.TextArea.IsFocused + && !SourceEditor.IsReadOnly + && new Rect(SourceEditor.TextArea.Bounds.Size).Contains(point)) + Platform.ShowSoftKeyboard?.Invoke(); } private void OnPropertyChanged(object? sender, AvaloniaPropertyChangedEventArgs e) diff --git a/src/PostIt/PostIt/Services/Platform.cs b/src/PostIt/PostIt/Services/Platform.cs index c7b717818..9038a82f7 100644 --- a/src/PostIt/PostIt/Services/Platform.cs +++ b/src/PostIt/PostIt/Services/Platform.cs @@ -12,6 +12,7 @@ namespace PostIt.Services; /// public static class Platform { + public static Action? ShowSoftKeyboard { get; set; } public static ScreenAwakeRequests ScreenAwake { get; } = new(); private static bool _isApplicationActive = !OperatingSystem.IsAndroid(); public static event Action? ApplicationActivityChanged; diff --git a/src/PostIt/PostIt/Views/Blogs/BlogsPage.axaml b/src/PostIt/PostIt/Views/Blogs/BlogsPage.axaml index a2116ff31..be9118ffe 100644 --- a/src/PostIt/PostIt/Views/Blogs/BlogsPage.axaml +++ b/src/PostIt/PostIt/Views/Blogs/BlogsPage.axaml @@ -155,7 +155,6 @@ - - @@ -248,18 +246,15 @@ - + @@ -284,6 +280,7 @@ + @@ -335,5 +332,4 @@ Grid.Row="5" DataContext="{Binding ActionStatus}" /> - diff --git a/src/PostIt/PostIt/Views/Blogs/BlogsPage.axaml.cs b/src/PostIt/PostIt/Views/Blogs/BlogsPage.axaml.cs index 9123ca1a9..26eb7177c 100644 --- a/src/PostIt/PostIt/Views/Blogs/BlogsPage.axaml.cs +++ b/src/PostIt/PostIt/Views/Blogs/BlogsPage.axaml.cs @@ -7,6 +7,9 @@ using Avalonia.Layout; using Avalonia.Platform.Storage; using Avalonia.Controls.Primitives; using Avalonia.Media; +using Avalonia.Input; +using Avalonia.Interactivity; +using Avalonia.VisualTree; using CommunityToolkit.Mvvm.Input; using Markdown.Avalonia; @@ -17,11 +20,14 @@ public partial class BlogsPage : ContentPage private static readonly RelayCommand DisabledLinkCommand = new(static _ => { }, static _ => false); private bool? _isWideLayout; + private bool? _isCompactEditor; private ViewModels.BlogsViewModel? _observedViewModel; public BlogsPage() { InitializeComponent(); + AddHandler(InputElement.GotFocusEvent, (_, _) => QueueLayoutUpdate(), RoutingStrategies.Bubble); + AddHandler(InputElement.LostFocusEvent, (_, _) => QueueLayoutUpdate(), RoutingStrategies.Bubble); SizeChanged += (_, _) => Avalonia.Threading.Dispatcher.UIThread.Post(() => { @@ -38,6 +44,9 @@ public partial class BlogsPage : ContentPage UpdateHyperlinkCommand(); } + private void QueueLayoutUpdate() + => Avalonia.Threading.Dispatcher.UIThread.Post(UpdateResponsiveLayout); + private void UpdateResponsiveLayout() { var size = TopLevel.GetTopLevel(this)?.ClientSize ?? Bounds.Size; @@ -46,6 +55,23 @@ public partial class BlogsPage : ContentPage // Use the window size so compacting the navigation bar cannot change the orientation. var isWide = size.Width >= size.Height; + var compact = this.FindAncestorOfType()?.IsSoftKeyboardOpen == true + && ArticleEditor.IsKeyboardFocusWithin && !ArticleEditor.IsPreviewVisible; + var sideBySide = compact && isWide; + if (_isCompactEditor != compact || _isWideLayout != isWide) + { + _isCompactEditor = compact; + DraftTitleTextBox.IsVisible = !compact || !System.OperatingSystem.IsAndroid(); + PostEditor.ColumnDefinitions = new ColumnDefinitions(sideBySide ? "3*,2*" : "*"); + SetArea(ArticleEditor, sideBySide ? 0 : 1, 0, rowSpan: sideBySide ? 3 : 1); + SetArea(DraftTitleTextBox, 0, sideBySide ? 1 : 0); + SetArea(AttachmentsBorder, sideBySide ? 1 : 2, sideBySide ? 1 : 0); + ArticleEditor.SourceEditor.Padding = compact ? new Thickness(2) : new Thickness(5, 5, 5, 15); + PostEditor.Margin = new Thickness(compact ? 4 : 12); + PostEditor.RowSpacing = compact ? 2 : 10; + } + SetArea(StatusBar, sideBySide ? 1 : isWide ? 3 : 5, sideBySide ? 2 : 0, + columnSpan: isWide && !sideBySide ? 3 : 1); if (_isWideLayout == isWide) return; _isWideLayout = isWide; @@ -58,7 +84,6 @@ public partial class BlogsPage : ContentPage SetArea(PostsSplitter, isWide ? 0 : 3, isWide ? 1 : 0, isWide ? 3 : 1); SetArea(PostReader, isWide ? 0 : 4, 0, isWide ? 3 : 1); SetArea(PostEditor, isWide ? 0 : 4, 0, isWide ? 3 : 1); - SetArea(StatusBar, isWide ? 3 : 5, 0, columnSpan: isWide ? 3 : 1); PostsSplitter.ResizeDirection = isWide ? GridResizeDirection.Columns : GridResizeDirection.Rows; PostsSplitter.HorizontalAlignment = isWide ? HorizontalAlignment.Center : HorizontalAlignment.Stretch; PostsSplitter.VerticalAlignment = isWide ? VerticalAlignment.Stretch : VerticalAlignment.Center; diff --git a/src/PostIt/PostIt/Views/Layout/MainView.axaml.cs b/src/PostIt/PostIt/Views/Layout/MainView.axaml.cs index 22bf537c6..9c7a40a80 100644 --- a/src/PostIt/PostIt/Views/Layout/MainView.axaml.cs +++ b/src/PostIt/PostIt/Views/Layout/MainView.axaml.cs @@ -1,13 +1,75 @@ using System; +using Avalonia; using Avalonia.Controls; +using Avalonia.Controls.Platform; namespace PostIt.Views; public partial class MainView : UserControl { + private IInputPane? _inputPane; + private IInsetsManager? _insetsManager; + private Thickness _safeArea; + private Rect? _keyboardRect; + internal bool IsSoftKeyboardOpen { get; private set; } + public MainView() { InitializeComponent(); + TopLevel.SetAutoSafeAreaPadding(this, false); + AttachedToVisualTree += (_, _) => + { + var topLevel = TopLevel.GetTopLevel(this); + _inputPane = topLevel?.InputPane; + _insetsManager = topLevel?.InsetsManager; + if (_insetsManager is not null) + { + _insetsManager.SafeAreaChanged += SafeAreaChanged; + _safeArea = _insetsManager.SafeAreaPadding; + } + if (_inputPane is not null) + { + _inputPane.StateChanged += InputPaneStateChanged; + ApplyKeyboardOcclusion(_inputPane.State == InputPaneState.Open ? _inputPane.OccludedRect : null); + } + ApplyKeyboardOcclusion(_keyboardRect); + }; + DetachedFromVisualTree += (_, _) => + { + if (_inputPane is not null) + _inputPane.StateChanged -= InputPaneStateChanged; + _inputPane = null; + if (_insetsManager is not null) + _insetsManager.SafeAreaChanged -= SafeAreaChanged; + _insetsManager = null; + }; + SizeChanged += (_, _) => ApplyKeyboardOcclusion(_keyboardRect); + } + + private void InputPaneStateChanged(object? sender, InputPaneStateEventArgs e) + => ApplyKeyboardOcclusion(e.NewState == InputPaneState.Open ? e.EndRect : null); + + private void SafeAreaChanged(object? sender, SafeAreaChangedArgs e) + => ApplySafeArea(e.SafeAreaPadding); + + internal void ApplySafeArea(Thickness safeArea) + { + _safeArea = safeArea; + ApplyKeyboardOcclusion(_keyboardRect); + } + + internal void ApplyKeyboardOcclusion(Rect? keyboardRect) + { + _keyboardRect = keyboardRect; + IsSoftKeyboardOpen = keyboardRect is { Height: > 0 }; + var topLevel = TopLevel.GetTopLevel(this); + var bottom = topLevel is null ? null : this.TranslatePoint(new Point(0, Bounds.Height), topLevel); + // Subtract only actual overlap: AdjustResize may already have removed the keyboard area. + var overlap = keyboardRect is { Height: > 0 } rect && bottom is { } point + ? Math.Clamp(point.Y - rect.Top, 0, Bounds.Height) + : 0; + Padding = new Thickness(_safeArea.Left, _safeArea.Top, _safeArea.Right, + Math.Max(_safeArea.Bottom, overlap)); } protected override void OnDataContextChanged(EventArgs e) From 0728d2a3f7c37b91cf72ffe0c035e56d96f77456 Mon Sep 17 00:00:00 2001 From: Paul Schneider Date: Sun, 8 Nov 2026 02:29:09 +0000 Subject: [PATCH 03/11] Allow amateur performer profiles Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- CHANGELOG.md | 1 + ...oviderOngoingRequestsPageViewModelTests.cs | 15 +++++++ .../ProviderOngoingRequestsPageViewModel.cs | 14 ++++++- .../ViewModels/Layout/HomePageViewModel.cs | 8 +++- .../PerformerConfigurationPageViewModel.cs | 4 +- .../ProviderOngoingRequestsPage.axaml | 13 +++--- .../Layout/PerformerConfigurationPage.axaml | 5 ++- .../Workflow/PerformerProfileSettings.cs | 25 ++++++++++- .../Business/EstimateApiController.cs | 28 ++++++++++++- .../accounting/AccountController.cs | 11 ++--- .../Accounting/ManageController.cs | 3 +- .../Contracting/EstimateController.cs | 41 +++++++++++++++++-- src/Yavsc.Org/Views/Estimate/Index.cshtml | 9 +++- src/Yavsc.Org/Views/Manage/SetActivity.cshtml | 4 +- .../Models/Workflow/PerformerProfile.cs | 2 +- src/Yavsc.Server/Services/InvoicingService.cs | 4 ++ .../EstimateApiControllerTests.cs | 24 +++++++++++ src/test/Yavsc.Api.Tests/InvoiceApiTests.cs | 20 +++++++++ .../PerformerDonationSettingsTests.cs | 6 ++- .../PerformerCodeInputValidationTests.cs | 9 ++++ 20 files changed, 217 insertions(+), 29 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 799dd624b..5dbfdd27c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -18,6 +18,7 @@ * [PostIt/Calls] Support direct IPv6 SRTP calls using global, ULA and loopback addresses, shared endpoint validation, IPv6 UDP sockets and bracketed reception URLs. Exclude scoped/link-local, multicast, unspecified and IPv4-mapped addresses; verify real bidirectional IPv6 audio/video, wrong-key rejection and port lifecycle with LibVLC. * [PostIt/Calls] Allow directly assigned public IPv4 addresses for direct SRTP calls, alongside LAN/VPN and loopback addresses. Share unicast validation between interface discovery, media and server signaling; continue rejecting unspecified, link-local, multicast, reserved and IPv6 addresses. Keep explicit address-disclosure consent and no automatic NAT traversal. * [PostIt] Update bundled settings with the default podcast title, camera/microphone preferences and French language selection. +* [Performers] Allow performer profiles without a business registration for amateur use; keep activities available while disabling estimate issuance and new invoicing in the UI and server APIs. ## [1.0.8-rc34] - unstable diff --git a/src/PostIt/PostIt.Tests/ProviderOngoingRequestsPageViewModelTests.cs b/src/PostIt/PostIt.Tests/ProviderOngoingRequestsPageViewModelTests.cs index cfb300316..af5d2fcd5 100644 --- a/src/PostIt/PostIt.Tests/ProviderOngoingRequestsPageViewModelTests.cs +++ b/src/PostIt/PostIt.Tests/ProviderOngoingRequestsPageViewModelTests.cs @@ -156,6 +156,21 @@ public class ProviderOngoingRequestsPageViewModelTests Assert.False(vm.CreateEstimateForSelectedCommand.CanExecute(null)); } + [Fact] + public async Task CreateEstimateForSelectedCommand_is_disabled_for_an_amateur_profile() + { + 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, canIssueEstimates: false); + + await vm.InitializeAsync(); + vm.SelectedQuery = vm.Queries[0]; + + Assert.False(vm.CreateEstimateForSelectedCommand.CanExecute(null)); + } + private sealed class StubProviderApi : IYavscApiClient { public HttpClient Http { get; } = new(); diff --git a/src/PostIt/PostIt/ViewModels/Activity/ProviderOngoingRequestsPageViewModel.cs b/src/PostIt/PostIt/ViewModels/Activity/ProviderOngoingRequestsPageViewModel.cs index 360bf54ad..dee11f39c 100644 --- a/src/PostIt/PostIt/ViewModels/Activity/ProviderOngoingRequestsPageViewModel.cs +++ b/src/PostIt/PostIt/ViewModels/Activity/ProviderOngoingRequestsPageViewModel.cs @@ -27,6 +27,7 @@ public partial class ProviderOngoingRequestsPageViewModel : ViewModelBase, IActi private readonly EstimateApiClient? _estimateClient; private readonly Settings? _settings; private List _allQueries = new(); + public bool CanIssueEstimates { get; } [ObservableProperty] public partial ObservableCollection Queries { get; set; } = new(); @@ -75,11 +76,13 @@ public partial class ProviderOngoingRequestsPageViewModel : ViewModelBase, IActi public ProviderOngoingRequestsPageViewModel( BillingApiClient billingClient, Settings? settings = null, - EstimateApiClient? estimateClient = null) + EstimateApiClient? estimateClient = null, + bool canIssueEstimates = true) { _billingClient = billingClient ?? throw new ArgumentNullException(nameof(billingClient)); _estimateClient = estimateClient; _settings = settings; + CanIssueEstimates = canIssueEstimates; if (_settings is not null) { @@ -225,7 +228,8 @@ public partial class ProviderOngoingRequestsPageViewModel : ViewModelBase, IActi } } - private bool CanCreateEstimateForSelected() => SelectedQuery is not null && _estimateClient is not null; + private bool CanCreateEstimateForSelected() + => SelectedQuery is not null && _estimateClient is not null && CanIssueEstimates; [RelayCommand(CanExecute = nameof(CanCreateEstimateForSelected))] public async Task CreateEstimateForSelectedAsync() @@ -242,6 +246,12 @@ public partial class ProviderOngoingRequestsPageViewModel : ViewModelBase, IActi return; } + if (!CanIssueEstimates) + { + this.SetWarningStatus("Un identifiant d'entreprise est nécessaire pour émettre un devis."); + return; + } + var app = (App?)Application.Current; if (app is null) { diff --git a/src/PostIt/PostIt/ViewModels/Layout/HomePageViewModel.cs b/src/PostIt/PostIt/ViewModels/Layout/HomePageViewModel.cs index c801806d2..ebc49a4af 100644 --- a/src/PostIt/PostIt/ViewModels/Layout/HomePageViewModel.cs +++ b/src/PostIt/PostIt/ViewModels/Layout/HomePageViewModel.cs @@ -2,6 +2,7 @@ using System; using System.Collections.ObjectModel; using System.ComponentModel; using System.Linq; +using System.Net.Http; using System.Threading.Tasks; using Avalonia; using Avalonia.Threading; @@ -9,6 +10,7 @@ using CommunityToolkit.Mvvm.Input; using Microsoft.Extensions.DependencyInjection; using PostIt.Services; using PostIt.ViewModels.Chat; +using Yavsc.Abstract.Workflow; using Yavsc.Abstract.Models.Messaging; using Yavsc.Api.Client; @@ -218,7 +220,11 @@ public class HomePageViewModel : ViewModelBase var estimateClient = app.ServiceProvider?.GetRequiredService(); - var vm = new ProviderOngoingRequestsPageViewModel(billingClient, Settings, estimateClient); + var profileEndpoint = new Uri(new Uri(Api.Settings.ApiUrl.TrimEnd('/') + "/", UriKind.Absolute), "account/performer-profile").ToString(); + var profile = await Api.CallAsync(HttpMethod.Get, profileEndpoint).ConfigureAwait(true); + var vm = new ProviderOngoingRequestsPageViewModel( + billingClient, Settings, estimateClient, + canIssueEstimates: profile?.CanIssueEstimates == true); await vm.InitializeAsync(); await app.PushPageAsync(vm); } diff --git a/src/PostIt/PostIt/ViewModels/PerformerConfigurationPageViewModel.cs b/src/PostIt/PostIt/ViewModels/PerformerConfigurationPageViewModel.cs index 0083a38db..77668bf0d 100644 --- a/src/PostIt/PostIt/ViewModels/PerformerConfigurationPageViewModel.cs +++ b/src/PostIt/PostIt/ViewModels/PerformerConfigurationPageViewModel.cs @@ -44,9 +44,11 @@ public partial class PerformerConfigurationPageViewModel : ViewModelBase [ObservableProperty] public partial string ExerciseCountryCode { get; set; } = "fr"; - [ObservableProperty] + [ObservableProperty, NotifyPropertyChangedFor(nameof(IsAmateur))] public partial string SIREN { get; set; } = string.Empty; + public bool IsAmateur => string.IsNullOrWhiteSpace(SIREN); + [ObservableProperty] public partial string Website { get; set; } = string.Empty; diff --git a/src/PostIt/PostIt/Views/Activity/ProviderOngoingRequestsPage.axaml b/src/PostIt/PostIt/Views/Activity/ProviderOngoingRequestsPage.axaml index 173fe903b..2f41564ff 100644 --- a/src/PostIt/PostIt/Views/Activity/ProviderOngoingRequestsPage.axaml +++ b/src/PostIt/PostIt/Views/Activity/ProviderOngoingRequestsPage.axaml @@ -28,11 +28,14 @@ Opacity="0.7" /> - + + + + + PlaceholderText="SIREN / SIRET (facultatif)"/> + diff --git a/src/Yavsc.Abstract/Workflow/PerformerProfileSettings.cs b/src/Yavsc.Abstract/Workflow/PerformerProfileSettings.cs index cd15c2658..708da2198 100644 --- a/src/Yavsc.Abstract/Workflow/PerformerProfileSettings.cs +++ b/src/Yavsc.Abstract/Workflow/PerformerProfileSettings.cs @@ -1,15 +1,18 @@ #nullable enable using System.ComponentModel.DataAnnotations; +using System.Text.RegularExpressions; +using Yavsc.Models.Workflow; namespace Yavsc.Abstract.Workflow; -public sealed class PerformerProfileSettings +public sealed class PerformerProfileSettings : IValidatableObject { public string PerformerId { get; set; } = string.Empty; public string UserName { get; set; } = string.Empty; public string ExerciseCountryCode { get; set; } = "fr"; public string SIREN { get; set; } = string.Empty; + public bool CanIssueEstimates => !string.IsNullOrWhiteSpace(SIREN); public string WebSite { get; set; } = string.Empty; /// Owner-only PayPal recipient. Null preserves the existing setting; empty disables donations. [MaxLength(127)] @@ -19,4 +22,24 @@ public sealed class PerformerProfileSettings public bool AcceptPublicContact { get; set; } public bool UseGeoLocalizationToReduceDistanceWithClients { get; set; } public List SelectedActivityCodes { get; set; } = new(); + + public IEnumerable Validate(ValidationContext validationContext) + { + var countryCode = PerformerCodeInputValidationCatalog.NormalizeCountryCode( + string.IsNullOrWhiteSpace(ExerciseCountryCode) ? "fr" : ExerciseCountryCode); + var rule = PerformerCodeInputValidationCatalog.GetRule(countryCode); + if (rule is null) + { + yield return new ValidationResult( + "Le pays d'exercice doit etre l'un des suivants: fr, en, pt.", + new[] { nameof(ExerciseCountryCode) }); + yield break; + } + + if (!string.IsNullOrWhiteSpace(SIREN) + && !Regex.IsMatch(SIREN.Trim(), rule.RegularExpression, RegexOptions.CultureInvariant)) + { + yield return new ValidationResult(rule.ErrorMessage, new[] { nameof(SIREN) }); + } + } } diff --git a/src/Yavsc.Api/Controllers/Business/EstimateApiController.cs b/src/Yavsc.Api/Controllers/Business/EstimateApiController.cs index af9c85a8f..c1c4e683f 100644 --- a/src/Yavsc.Api/Controllers/Business/EstimateApiController.cs +++ b/src/Yavsc.Api/Controllers/Business/EstimateApiController.cs @@ -66,7 +66,7 @@ namespace Yavsc.Controllers // PUT: api/Estimate/5 [HttpPut("{id}"), Produces("application/json")] - public IActionResult PutEstimate(long id, [FromBody] Estimate estimate) + public async Task PutEstimate(long id, [FromBody] Estimate estimate) { if (!ModelState.IsValid) @@ -88,6 +88,11 @@ namespace Yavsc.Controllers } } + if (!await CanIssueEstimatesAsync(estimate.OwnerId)) + { + return Conflict(new { Error = "A business registration is required to issue or edit estimates." }); + } + var entry = _context.Attach(estimate); try { @@ -110,7 +115,7 @@ namespace Yavsc.Controllers // POST: api/Estimate [HttpPost, Produces("application/json")] - public IActionResult PostEstimate([FromBody] Estimate estimate) + public async Task PostEstimate([FromBody] Estimate estimate) { var uid = User.GetUserId(); if (estimate.OwnerId == null) estimate.OwnerId = uid; @@ -124,6 +129,11 @@ namespace Yavsc.Controllers } } + if (!await CanIssueEstimatesAsync(estimate.OwnerId)) + { + return Conflict(new { Error = "A business registration is required to issue estimates." }); + } + if (estimate.CommandId != null) { var query = _context.NominativeServiceCommands @@ -334,5 +344,19 @@ namespace Yavsc.Controllers { return _context.Estimates.Count(e => e.Id == id) > 0; } + + private Task CanIssueEstimatesAsync(string? performerId) + { + if (string.IsNullOrWhiteSpace(performerId)) + { + return Task.FromResult(false); + } + + return _context.Performers + .AsNoTracking() + .AnyAsync(profile => profile.PerformerId == performerId + && profile.SIREN != null + && profile.SIREN.Trim() != ""); + } } } diff --git a/src/Yavsc.Api/Controllers/accounting/AccountController.cs b/src/Yavsc.Api/Controllers/accounting/AccountController.cs index bb41168b8..90316a2b4 100644 --- a/src/Yavsc.Api/Controllers/accounting/AccountController.cs +++ b/src/Yavsc.Api/Controllers/accounting/AccountController.cs @@ -616,6 +616,12 @@ namespace Yavsc.WebApi.Controllers return BadRequest(new { error = "Payload is required." }); } + model.SIREN = model.SIREN?.Trim() ?? string.Empty; + if (string.IsNullOrWhiteSpace(model.ExerciseCountryCode)) + { + model.ExerciseCountryCode = "fr"; + } + var uid = User.GetUserId(); if (string.IsNullOrWhiteSpace(uid)) { @@ -652,11 +658,6 @@ namespace Yavsc.WebApi.Controllers return NotFound(); } - if (string.IsNullOrWhiteSpace(model.ExerciseCountryCode)) - { - model.ExerciseCountryCode = "fr"; - } - var profile = await _dbContext.Performers.FirstOrDefaultAsync(p => p.PerformerId == uid); if (profile is null) { diff --git a/src/Yavsc.Org/Controllers/Accounting/ManageController.cs b/src/Yavsc.Org/Controllers/Accounting/ManageController.cs index e3d76169d..8b11f576c 100644 --- a/src/Yavsc.Org/Controllers/Accounting/ManageController.cs +++ b/src/Yavsc.Org/Controllers/Accounting/ManageController.cs @@ -608,6 +608,7 @@ namespace Yavsc.Controllers var uid = user.Id; var postedCountryCode = model.ExerciseCountryCode; model.ExerciseCountryCode = NormalizeCountryCodeOrDefault(model.ExerciseCountryCode); + model.SIREN = model.SIREN?.Trim() ?? string.Empty; // Model binding validated the raw posted payload before entering // the action. If country was empty, we fallback to "fr" above, @@ -622,7 +623,7 @@ namespace Yavsc.Controllers if (ModelState.IsValid) { var isFrenchPerformerCode = string.Equals(model.ExerciseCountryCode, "fr", StringComparison.Ordinal); - if (isFrenchPerformerCode) + if (isFrenchPerformerCode && !string.IsNullOrWhiteSpace(model.SIREN)) { var exSiren = await _dbContext.ExceptionsSIREN.FirstOrDefaultAsync( ex => ex.SIREN == model.SIREN diff --git a/src/Yavsc.Org/Controllers/Contracting/EstimateController.cs b/src/Yavsc.Org/Controllers/Contracting/EstimateController.cs index 5dbd882b4..b2eb2cd8d 100644 --- a/src/Yavsc.Org/Controllers/Contracting/EstimateController.cs +++ b/src/Yavsc.Org/Controllers/Contracting/EstimateController.cs @@ -29,9 +29,10 @@ namespace Yavsc.Controllers // GET: Estimate - public IActionResult Index() + public async Task Index() { var uid = User.FindFirstValue(ClaimTypes.NameIdentifier); + ViewBag.CanIssueEstimates = await CanIssueEstimatesAsync(uid); return View(_context.Estimates.Include(e=>e.Query) .Include(e=>e.Query.PerformerProfile) .Include(e=>e.Query.PerformerProfile.Performer) @@ -73,9 +74,14 @@ namespace Yavsc.Controllers // GET: Estimate/Create [Authorize] - public IActionResult Create() + public async Task Create() { var uid = User.FindFirstValue(ClaimTypes.NameIdentifier); + if (!await CanIssueEstimatesAsync(uid)) + { + return RedirectToAction("SetActivity", "Manage"); + } + IQueryable queries = _context.RdvQueries.Include(q=>q.Location).Where(bq=>bq.PerformerId == uid); //.Select(bq=>new SelectListItem{ Text = bq.Client.UserName, Value = bq.Client.Id }); ViewBag.Clients = queries.Select(q=>q.Client).Distinct(); @@ -93,6 +99,11 @@ namespace Yavsc.Controllers ) { estimate.OwnerId = User.GetUserId(); + if (!await CanIssueEstimatesAsync(estimate.OwnerId)) + { + return RedirectToAction("SetActivity", "Manage"); + } + if (ModelState.IsValid) { _context.Estimates @@ -138,7 +149,7 @@ namespace Yavsc.Controllers // GET: Estimate/Edit/5 - public IActionResult Edit(long? id) + public async Task Edit(long? id) { if (id == null) { @@ -152,6 +163,10 @@ namespace Yavsc.Controllers { return NotFound(); } + if (!await CanIssueEstimatesAsync(estimate.OwnerId)) + { + return RedirectToAction("SetActivity", "Manage"); + } return View(estimate); } @@ -159,11 +174,15 @@ namespace Yavsc.Controllers // POST: Estimate/Edit/5 [HttpPost] [ValidateAntiForgeryToken] - public IActionResult Edit(Estimate estimate) + public async Task Edit(Estimate estimate) { var uid = User.FindFirstValue(ClaimTypes.NameIdentifier); if (estimate.OwnerId!=uid&&estimate.ClientId!=uid ) return NotFound(); + if (!await CanIssueEstimatesAsync(estimate.OwnerId)) + { + return RedirectToAction("SetActivity", "Manage"); + } if (ModelState.IsValid) { _context.Update(estimate); @@ -203,5 +222,19 @@ namespace Yavsc.Controllers _context.SaveChanges(User.GetUserId()); return RedirectToAction("Index"); } + + private Task CanIssueEstimatesAsync(string? performerId) + { + if (string.IsNullOrWhiteSpace(performerId)) + { + return Task.FromResult(false); + } + + return _context.Performers + .AsNoTracking() + .AnyAsync(profile => profile.PerformerId == performerId + && profile.SIREN != null + && profile.SIREN.Trim() != ""); + } } } diff --git a/src/Yavsc.Org/Views/Estimate/Index.cshtml b/src/Yavsc.Org/Views/Estimate/Index.cshtml index 3710eaee4..39dc0508c 100644 --- a/src/Yavsc.Org/Views/Estimate/Index.cshtml +++ b/src/Yavsc.Org/Views/Estimate/Index.cshtml @@ -7,7 +7,14 @@

Index

- Create New + @if ((bool?)ViewBag.CanIssueEstimates == true) + { + Create New + } + else + { + Un identifiant d'entreprise est nécessaire pour émettre ou modifier des devis. + }

diff --git a/src/Yavsc.Org/Views/Manage/SetActivity.cshtml b/src/Yavsc.Org/Views/Manage/SetActivity.cshtml index b096fc21d..afc76f932 100644 --- a/src/Yavsc.Org/Views/Manage/SetActivity.cshtml +++ b/src/Yavsc.Org/Views/Manage/SetActivity.cshtml @@ -84,10 +84,10 @@
- +
- + Sans identifiant, votre profil reste utilisable comme amateur, mais l'émission de devis et la facturation sont désactivées.
diff --git a/src/Yavsc.Server/Models/Workflow/PerformerProfile.cs b/src/Yavsc.Server/Models/Workflow/PerformerProfile.cs index 5b95c91ad..7b4ee15d5 100644 --- a/src/Yavsc.Server/Models/Workflow/PerformerProfile.cs +++ b/src/Yavsc.Server/Models/Workflow/PerformerProfile.cs @@ -28,7 +28,7 @@ namespace Yavsc.Models.Workflow [RegularExpression("^[A-Za-z]{2}$", ErrorMessage = "Country code must be a 2-letter code.")] public string ExerciseCountryCode { get; set; } = "fr"; - [Required,YaStringLength(14),Display(Name="SIREN")] + [YaStringLength(14),Display(Name="Identifiant d'entreprise (SIREN/SIRET)")] public string SIREN { get; set; } public long OrganizationAddressId { get; set; } diff --git a/src/Yavsc.Server/Services/InvoicingService.cs b/src/Yavsc.Server/Services/InvoicingService.cs index bebf81809..ccff48ef9 100644 --- a/src/Yavsc.Server/Services/InvoicingService.cs +++ b/src/Yavsc.Server/Services/InvoicingService.cs @@ -38,6 +38,10 @@ public sealed class InvoicingService(ApplicationDbContext db, IPayPalTransaction RequirePerformer(actorId, command.InvoicePerformerId!, administrator); return await ResponseAsync(command, ct); } + var performerProfile = await db.Performers.AsNoTracking() + .SingleOrDefaultAsync(profile => profile.PerformerId == estimate.OwnerId, ct); + if (string.IsNullOrWhiteSpace(performerProfile?.SIREN)) + throw new InvoiceOperationException(409, "A business registration is required to issue invoices."); if (command.InvoiceEstimateId.HasValue || command.AmountDue.HasValue || command.AmountPaid != 0m) throw new InvoiceOperationException(409, "This command already has an invoice or a balance requiring reconciliation."); if (command.ClientId != estimate.ClientId || command.PerformerId != estimate.OwnerId) diff --git a/src/test/Yavsc.Api.Tests/EstimateApiControllerTests.cs b/src/test/Yavsc.Api.Tests/EstimateApiControllerTests.cs index 568175610..9a2452ca1 100644 --- a/src/test/Yavsc.Api.Tests/EstimateApiControllerTests.cs +++ b/src/test/Yavsc.Api.Tests/EstimateApiControllerTests.cs @@ -152,6 +152,30 @@ public sealed class EstimateApiControllerTests : IClassFixture(); + db.Performers.Single(profile => profile.PerformerId == "alice").SIREN = ""; + db.SaveChanges(); + } + + using var http = NewClient("alice"); + var response = await http.PostAsJsonAsync( + "/api/v1/estimate", + NewEstimatePayload(commandId, clientId: "bob"), + TestContext.Current.CancellationToken); + + Assert.Equal(HttpStatusCode.Conflict, response.StatusCode); + using var checkScope = _fixture.Services.CreateScope(); + var checkDb = checkScope.ServiceProvider.GetRequiredService(); + Assert.Empty(checkDb.Estimates); + Assert.Null(checkDb.RdvQueries.Single(query => query.Id == commandId).ValidationDate); + } + [Fact] public async Task PostEstimate_for_another_owner_is_rejected() { diff --git a/src/test/Yavsc.Api.Tests/InvoiceApiTests.cs b/src/test/Yavsc.Api.Tests/InvoiceApiTests.cs index 4a1c69c52..8719bc341 100644 --- a/src/test/Yavsc.Api.Tests/InvoiceApiTests.cs +++ b/src/test/Yavsc.Api.Tests/InvoiceApiTests.cs @@ -131,6 +131,26 @@ public sealed class InvoiceApiTests(ApiWebServerFixture fixture) : IClassFixture Assert.Null(db.RdvQueries.Single(q => q.Id == commandId).AmountDue); } + [Fact] + public async Task Amateur_performer_cannot_generate_an_invoice() + { + var (estimateId, commandId) = Seed(); + using (var scope = fixture.Services.CreateScope()) + { + var db = scope.ServiceProvider.GetRequiredService(); + db.Performers.Single(profile => profile.PerformerId == "alice").SIREN = ""; + db.SaveChanges(); + } + + using var http = Client(); + var response = await http.PostAsync($"/api/v1/invoices/from-estimate/{estimateId}", null, Ct); + + Assert.Equal(HttpStatusCode.Conflict, response.StatusCode); + using var checkScope = fixture.Services.CreateScope(); + var checkDb = checkScope.ServiceProvider.GetRequiredService(); + Assert.Null(checkDb.RdvQueries.Single(query => query.Id == commandId).AmountDue); + } + [Theory] [InlineData("wrong-signer")] [InlineData("missing-date")] diff --git a/src/test/Yavsc.Api.Tests/PerformerDonationSettingsTests.cs b/src/test/Yavsc.Api.Tests/PerformerDonationSettingsTests.cs index adce4d460..b7672ede1 100644 --- a/src/test/Yavsc.Api.Tests/PerformerDonationSettingsTests.cs +++ b/src/test/Yavsc.Api.Tests/PerformerDonationSettingsTests.cs @@ -55,11 +55,13 @@ public sealed class PerformerDonationSettingsTests(ApiWebServerFixture fixture) var profile = await client.GetFromJsonAsync(Endpoint, Ct); Assert.NotNull(profile); Assert.Equal("", profile.DonationPayPalEmail); + Assert.False(profile.CanIssueEstimates); profile.DonationPayPalEmail = "new@payments.example"; using var response = await client.PutAsJsonAsync(Endpoint, profile, Ct); Assert.Equal(HttpStatusCode.OK, response.StatusCode); - Assert.Equal("new@payments.example", - (await client.GetFromJsonAsync(Endpoint, Ct))?.DonationPayPalEmail); + var saved = await client.GetFromJsonAsync(Endpoint, Ct); + Assert.Equal("new@payments.example", saved?.DonationPayPalEmail); + Assert.False(saved?.CanIssueEstimates); } [Theory] diff --git a/src/test/Yavsc.Org.Tests/NonRegression/PerformerCodeInputValidationTests.cs b/src/test/Yavsc.Org.Tests/NonRegression/PerformerCodeInputValidationTests.cs index 9d418404a..4b934baa2 100644 --- a/src/test/Yavsc.Org.Tests/NonRegression/PerformerCodeInputValidationTests.cs +++ b/src/test/Yavsc.Org.Tests/NonRegression/PerformerCodeInputValidationTests.cs @@ -51,6 +51,15 @@ public class PerformerCodeInputValidationTests Assert.Empty(Validate(pt)); } + [Fact] + public void Validate_accepts_an_empty_business_code_for_amateur_performers() + { + var profile = CreateBaseProfile(); + profile.SIREN = ""; + + Assert.Empty(Validate(profile)); + } + private static PerformerProfile CreateBaseProfile() { return new PerformerProfile From 650e5f5e30ebdb52188d440a52b903060a5d26a8 Mon Sep 17 00:00:00 2001 From: Paul Schneider Date: Sun, 8 Nov 2026 05:02:23 +0000 Subject: [PATCH 04/11] feat: add resource quotas, PayPal subscriptions and paid disk allowances Calculate and enforce configurable resource consumption, expose balances in PostIt and document the rule in CGU. Add confirmed monthly PayPal credits and disk quotas of twice the free default for Discovery and five times for Premium, with payment reconciliation, migrations and regression tests. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- CHANGELOG.md | 3 + INSTALL.md | 166 + contrib/template.appsettings-api.json | 3 + contrib/template.appsettings-blogs.json | 3 + contrib/template.appsettings-org.json | 11 + doc/architecture/postit.md | 34 + src/PostIt/PostIt.Tests/AboutTermsTests.cs | 19 + .../PostIt.Tests/AdministrationAccessTests.cs | 42 +- .../ResourceUsageApiClientTests.cs | 19 + .../ViewModels/AdministrationPageViewModel.cs | 26 +- .../ViewModels/Layout/AboutPageViewModel.cs | 26 +- .../Layout/UserProfilePageViewModel.cs | 48 +- .../PostIt/Views/Layout/AboutPage.axaml | 7 + .../Views/Layout/AdministrationPage.axaml | 18 +- .../PostIt/Views/Layout/UserProfilePage.axaml | 15 +- .../Resources/ResourceUsageSummary.cs | 15 +- .../ResourceUsageApiController.cs | 85 +- .../accounting/AccountController.cs | 2 +- src/Yavsc.Api/Program.cs | 5 +- src/Yavsc.Api/ResourceUsage.http | 14 + src/Yavsc.Api/appsettings-api.json | 3 + .../Controllers/FileSystemApiController.cs | 18 +- src/Yavsc.Blogs/Program.cs | 3 +- src/Yavsc.Blogs/appsettings-blogs.json | 3 + .../Accounting/ManageController.cs | 2 +- src/Yavsc.Org/Controllers/HomeController.cs | 4 + .../ResourceSubscriptionController.cs | 167 + src/Yavsc.Org/Extensions/HostingExtensions.cs | 13 + ...08035037_ResourceSubscriptions.Designer.cs | 5197 ++++++++++++++++ .../20261108035037_ResourceSubscriptions.cs | 107 + ...0261108041224_PremiumDiskQuota.Designer.cs | 5200 ++++++++++++++++ .../20261108041224_PremiumDiskQuota.cs | 29 + ...61108045419_DiscoveryDiskQuota.Designer.cs | 5203 +++++++++++++++++ .../20261108045419_DiscoveryDiskQuota.cs | 29 + .../ApplicationDbContextModelSnapshot.cs | 125 + src/Yavsc.Org/ResourceSubscriptions.http | 38 + src/Yavsc.Org/Services/DiskUsageTracker.cs | 5 +- .../Services/PayPalSubscriptionGateway.cs | 249 + .../Services/ResourceSubscriptionService.cs | 177 + .../ViewModels/ResourceSubscriptionPage.cs | 9 + src/Yavsc.Org/Views/Home/CGU.cshtml | 138 + .../Views/ResourceSubscription/Index.cshtml | 64 + src/Yavsc.Org/Views/Shared/_Layout.cshtml | 2 + src/Yavsc.Org/appsettings-org.json | 11 + src/Yavsc.Server/Helpers/FileSystemHelpers.cs | 22 +- .../Helpers/ResourceUsageCountingStream.cs | 51 + .../Helpers/ResourceUsageCredit.cs | 26 + .../Helpers/ResourceUsageExemptAttribute.cs | 4 + .../Helpers/ResourceUsageService.cs | 98 + .../ResourceUsageTelemetryMiddleware.cs | 88 +- .../Helpers/ResourceUsageTracker.cs | 141 +- .../Models/ApplicationDbContext.cs | 17 + src/Yavsc.Server/Models/ApplicationUser.cs | 11 +- .../Models/Payment/ResourceSubscription.cs | 41 + .../Models/ResourceUsageRecord.cs | 1 + src/Yavsc.Server/Services/LiveProcessor.cs | 7 +- .../Settings/ResourceSubscriptionOptions.cs | 15 + .../Settings/ResourceUsageOptions.cs | 21 + .../Fixtures/ApiWebServerFixture.cs | 5 +- .../Yavsc.Api.Tests/LiveProcessorTests.cs | 23 + .../ResourceUsageApiControllerTests.cs | 65 +- .../Yavsc.Blogs.Tests/FileSystemApiTests.cs | 30 + .../Yavsc.Blogs.Tests/FilterFileNameTests.cs | 39 + .../Fixtures/BlogsWebServerFixture.cs | 3 + .../ResourceSubscriptionControllerTests.cs | 248 + .../Controllers/ResourceUsageTermsTests.cs | 30 + .../PayPalSubscriptionGatewayTests.cs | 208 + .../ResourceSubscriptionTests.cs | 486 ++ .../Yavsc.Server.Tests/ResourceUsageTests.cs | 283 + 69 files changed, 19114 insertions(+), 206 deletions(-) create mode 100644 src/PostIt/PostIt.Tests/AboutTermsTests.cs create mode 100644 src/Yavsc.Api/ResourceUsage.http create mode 100644 src/Yavsc.Org/Controllers/ResourceSubscriptionController.cs create mode 100644 src/Yavsc.Org/Migrations/20261108035037_ResourceSubscriptions.Designer.cs create mode 100644 src/Yavsc.Org/Migrations/20261108035037_ResourceSubscriptions.cs create mode 100644 src/Yavsc.Org/Migrations/20261108041224_PremiumDiskQuota.Designer.cs create mode 100644 src/Yavsc.Org/Migrations/20261108041224_PremiumDiskQuota.cs create mode 100644 src/Yavsc.Org/Migrations/20261108045419_DiscoveryDiskQuota.Designer.cs create mode 100644 src/Yavsc.Org/Migrations/20261108045419_DiscoveryDiskQuota.cs create mode 100644 src/Yavsc.Org/ResourceSubscriptions.http create mode 100644 src/Yavsc.Org/Services/PayPalSubscriptionGateway.cs create mode 100644 src/Yavsc.Org/Services/ResourceSubscriptionService.cs create mode 100644 src/Yavsc.Org/ViewModels/ResourceSubscriptionPage.cs create mode 100644 src/Yavsc.Org/Views/Home/CGU.cshtml create mode 100644 src/Yavsc.Org/Views/ResourceSubscription/Index.cshtml create mode 100644 src/Yavsc.Server/Helpers/ResourceUsageCountingStream.cs create mode 100644 src/Yavsc.Server/Helpers/ResourceUsageCredit.cs create mode 100644 src/Yavsc.Server/Helpers/ResourceUsageExemptAttribute.cs create mode 100644 src/Yavsc.Server/Helpers/ResourceUsageService.cs create mode 100644 src/Yavsc.Server/Models/Payment/ResourceSubscription.cs create mode 100644 src/Yavsc.Server/Settings/ResourceSubscriptionOptions.cs create mode 100644 src/Yavsc.Server/Settings/ResourceUsageOptions.cs create mode 100644 src/test/Yavsc.Org.Tests/Controllers/ResourceSubscriptionControllerTests.cs create mode 100644 src/test/Yavsc.Org.Tests/Controllers/ResourceUsageTermsTests.cs create mode 100644 src/test/Yavsc.Server.Tests/PayPalSubscriptionGatewayTests.cs create mode 100644 src/test/Yavsc.Server.Tests/ResourceSubscriptionTests.cs create mode 100644 src/test/Yavsc.Server.Tests/ResourceUsageTests.cs diff --git a/CHANGELOG.md b/CHANGELOG.md index 5dbfdd27c..4f2cfee0a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,9 @@ ### Added +* [Yavsc/PostIt/PayPal] Add monthly Découverte (EUR 1 excluding VAT) and Premium (EUR 2 excluding VAT) resource subscriptions, charged at EUR 1.20 / EUR 2.40 including 20% VAT. Confirmed monthly PayPal payments erase up to one / three default quotas, carry two thirds of unused monthly credit without expiry, and preserve historical counters. Add persistent idempotent payment credits, refund reconciliation, authenticated Web subscription/cancellation pages, verified REST webhooks, PostIt links and balances, migration and updated CGU. +* [Yavsc/PostIt/Subscriptions] Align new users' free quota with the existing 500 MiB database default; grant twice that standard quota for Discovery (1,000 MiB) and five times for Premium (2,500 MiB) during confirmed paid monthly periods, including their remainder after cancellation. Restore the user's base quota after expiry or refund without deleting files, refuse uploads beyond available space before writing, and expose the effective quota in profile and usage responses. +* [PostIt/API/Blogs/Yavsc.Org] Compute cumulative resource consumption in configurable points per API call, recorded CPU second, MiB transferred and MiB added to storage, with backend-defined defaults, a default 1,000-point limit and per-user overrides. Serialize accounting and known-cost admission across PostgreSQL hosts, count streamed HTTP bodies, reject further consuming operations with HTTP 429, and check personal uploads before writing. Keep usage/session access available, display the indicator and balance in PostIt, and publish linked CGU explaining the rule and after-measurement enforcement. * [PostIt.Android] Embed managed assemblies in APKs by default, including Debug builds launched outside the Makefile, to prevent the native startup abort "No assemblies found" when fast-deployment files are absent. * [PostIt] Remove the redundant "Post detail" heading and its grid row from the blog editor, including the compact layout. * [PostIt/Android] Combine system-bar/cutout safe-area insets with actual keyboard overlap at the root, instead of replacing Avalonia's automatic safe-area padding with keyboard-only padding. Preserve the toolbar, session banner, attachments and status controls; place article details beside the editor during landscape keyboard input. Only on Android, temporarily hide the title input while editing in compact mode with the keyboard open, restoring it on keyboard closure or focus change without modifying the draft. Verify visible controls outside native system bars, at least three editor lines and the editor's bottom above IME insets. diff --git a/INSTALL.md b/INSTALL.md index 24b9567a1..19112f0aa 100644 --- a/INSTALL.md +++ b/INSTALL.md @@ -76,6 +76,172 @@ login callback, updating and uninstallation on Windows with a standard (non-administrator) account. Installer compilation alone does not validate these Windows runtime behaviours. +## Resource consumption and CGU + +Configure the **same** `ResourceUsage` section on Yavsc.Api, Yavsc.Blogs and +Yavsc.Org. API and Blogs must also use the same application database. +All three hosts and configuration templates inherit the backend defaults +from [ResourceUsageOptions](src/Yavsc.Server/Settings/ResourceUsageOptions.cs). +Deploy matching backend versions across hosts. The public CGU renders the +effective coefficients and limit. The default limit is 1,000 points. +The following is an example explicit override, not a duplicate of defaults. +Use the account's immutable user ID (`sub`), not its login, for overrides: + +```json +{ + "ResourceUsage": { + "ApiCallWeight": 0.2, + "CpuSecondWeight": 0.1, + "BandwidthMbWeight": 0.05, + "StorageMbWeight": 0.5, + "DefaultLimit": 1000, + "UserLimits": { + "example-account-id": 20000 + } + } +} +``` + +Environment variables follow ASP.NET's convention, for example +`ResourceUsage__DefaultLimit` and +`ResourceUsage__UserLimits__example-account-id`. Restart all three services +after changing the rule. Invalid weights or limits fail startup. +Existing cumulative `ResourceUsageRecords` are reused, and changing weights +recalculates their gross indicator. Apply the `ResourceSubscriptions` +migration before deploying any of the three hosts: it adds the credit +balance and subscription/payment tables without clearing existing counters. + +Consumption is in **points**, independent of `EstimatedCompensation` and +currency. Counters have no automatic reset. Storage means cumulative +instrumented writes, not current occupancy; the historical CPU counter is +instrumented elapsed processing time, not exhaustive CPU profiling. + +Authenticated HTTP operations are admitted atomically against known costs +(API call and declared request body). Personal-file uploads additionally +check their aggregate storage cost before writing. Response bytes and +unknown-length request bodies are measured through counting streams, and +remaining costs are recorded after execution, including failed requests. +PostgreSQL transaction-scoped advisory locks serialize admission and +accounting for each user across hosts. In-flight operations can exceed the +limit through costs unknown at admission; subsequent operations return +HTTP 429 with `resource_quota_exceeded` Problem Details. No permanent account +suspension or strict running-operation interruption is performed. + +`GET /api/v1/resource-usage/me` returns `Consumption`, `ConsumptionLimit`, +`RemainingConsumption` and `IsQuotaReached`, alongside existing counters. +It also returns `GrossConsumption`, `AppliedCredits` and `CreditBalance`. +`Consumption` is the gross indicator less acquired credits, floored at zero. +`RemainingConsumption` includes both unused free quota and carried credit. +Usage consultation (including the role-protected admin overview), login, +session refresh and the CGU remain accessible without consuming quota. +The quota does not measure local PostIt resources, direct peer calls or +WebSocket traffic. HTTP upload size limits and disk quotas still apply. + +The public page `/Home/CGU` describes the effective rule and default limit +(and the individual limit for a signed-in user). It is linked from the Web +footer and PostIt's **About** page, using the configured authentication +authority. PostIt displays consumption and remaining points in **My profile** +and the administration usage views. + +### Monthly resource subscriptions (PayPal REST) + +The free registration keeps the configured cumulative quota without a +monthly reset. Discovery costs EUR 1 excluding VAT (EUR 1.20 including 20% +VAT) per month; Premium costs EUR 2 excluding VAT (EUR 2.40 including VAT). +Every **confirmed payment** grants up to one / three default quotas, +respectively, with renewal on the UTC monthly anniversary of the PayPal +start date. The pack allowance is captured at subscription creation, not +multiplied by an individual user's quota override. + +At reconciliation, old carried credit is used first; the new allowance +erases remaining net usage. Two thirds of the unused allowance are added +to permanent carried credit, rounded down to eight decimal places. +Old carried credit never loses another third and survives cancellation. +Example: 400 points of usage and 1,000 new points erase 400 and carry +400; an idle Premium month carries 2,000 points. +Counters are never deleted. Pending/failed payments give no credit. +Refunds (including partial refunds) revoke the corresponding award once. + +Discovery grants **twice `Constants.DefaultFSQ`** (1,000 MiB), and Premium +**five times `Constants.DefaultFSQ`** (2,500 MiB) of disk space during each +confirmed, non-reversed paid monthly period. Free registrations use the standard quota. +The reference is the standard free quota (500 MiB), not an individual's +administratively adjusted `DiskQuota`. That base quota is never overwritten. +New user objects now use the existing 500 MiB database default rather than +the former 512 MiB CLR initializer; existing accounts retain their stored quota. +Cancellation retains the disk allowance through the UTC anniversary ending +the paid period; expiry or refund restores the base quota without deleting +existing files. Uploads exceeding available space are refused before writing. +The maximum size of one file and separate podcast limits are unchanged. +Pending/failed payments grant no disk bonus. Apply the +`ResourceSubscriptions`, `PremiumDiskQuota` and `DiscoveryDiskQuota` EF migrations to the shared +database before deploying any host. Profile and usage responses expose the +effective disk quota; usage also exposes `PremiumDiskQuotaUntil` and `DiscoveryDiskQuotaUntil`. +When paid periods overlap, Premium takes precedence until its expiry, then +any still-paid Discovery period applies. + +Configure only **Yavsc.Org** for PayPal subscriptions. API and Blogs need +the migrated shared database and matching resource weights, not PayPal +credentials. Existing Classic donation settings remain unchanged. +Use the existing `PayPal:Mode`, `PayPal:ClientId` and `PayPal:ClientSecret` +REST settings; keep credentials in user-secrets or environment variables. + +```json +{ + "ResourceSubscriptions": { + "DiscoveryPlanId": "P-REPLACEWITHDISCOVERYPLAN", + "PremiumPlanId": "P-REPLACEWITHPREMIUMPLAN", + "WebhookId": "REPLACEWITHWEBHOOKID", + "DiscoveryPriceExcludingTax": 1, + "PremiumPriceExcludingTax": 2, + "VatPercent": 20 + } +} +``` + +Before enabling checkout, create a PayPal subscription product and two +**ACTIVE** billing plans in the same REST app and environment: +one indefinite `REGULAR` cycle with `interval_unit: MONTH`, +`interval_count: 1`, `total_cycles: 0`, and EUR `fixed_price.value` +of **1.20** / **2.40** respectively. These are **already VAT-inclusive** +amounts: do not add PayPal tax, setup fees, trials, quantity support or +shipping fees. Disable billing outstanding balances in the plans +(`auto_bill_outstanding: false`) to avoid bundling missed installments +into an amount that does not match one monthly payment. +Checkout checks the configured plan against its expected TTC amount and +refuses automatic collection of outstanding balances. +Numerically invalid pricing fails startup; missing plan IDs/webhook/ +credentials returns an explicit unavailable error instead of a fake success. + +Register the HTTPS endpoint +`https:///ResourceSubscription/Notify` in that REST app. +Subscribe to `BILLING.SUBSCRIPTION.ACTIVATED`, `UPDATED`, `CANCELLED`, +`SUSPENDED`, `EXPIRED`, `PAYMENT.FAILED`, and `PAYMENT.SALE.COMPLETED`, +`REFUNDED`, `REVERSED` (the lifecycle events use the +`BILLING.SUBSCRIPTION.` prefix). Set the returned webhook ID in configuration. +The server verifies the signature through PayPal, then fetches the bound +subscription and transaction history; it never grants credit from an +unverified webhook or the browser return. Payment IDs and monthly cycles +are unique, and the same per-user PostgreSQL lock serializes usage and awards. +Delayed notifications take effect on the usage measured when reconciled. + +Users manage subscriptions at `/ResourceSubscription`, linked from the Web +footer and PostIt's About/profile pages. A browser Web login may be required +independently of PostIt's session. Create/refresh/cancel require antiforgery +tokens and ownership; the management page remains available at the quota. +**Refresh payments** reconciles missed notifications and historical refunds. +Cancellation is confirmed with PayPal, not merely recorded locally. +Only one non-terminal subscription is allowed per account. +An uncertain creation is retried with its same PayPal request ID for at +most 24 hours; an older unresolved creation requires merchant-side review +before allowing a second checkout. Do not delete that record and retry +without checking PayPal for a possible existing agreement. + +Run a real Sandbox approval, first payment, renewal, repeated webhook, +refund and cancellation before enabling production. The repository tests +use synthetic PayPal transports and do not validate merchant credentials +or PayPal account eligibility. + ## Podcast live broadcasts and replays PostIt Desktop's home page provides **Podcasts : directs et replays**. diff --git a/contrib/template.appsettings-api.json b/contrib/template.appsettings-api.json index afe693a4f..b5562aded 100644 --- a/contrib/template.appsettings-api.json +++ b/contrib/template.appsettings-api.json @@ -1,4 +1,7 @@ { + "ResourceUsage": { + "UserLimits": {} + }, "Site": { "Authority": "https://preprod-yavsc.$DOMAIN", "Audience": ["api"], diff --git a/contrib/template.appsettings-blogs.json b/contrib/template.appsettings-blogs.json index 6f8fa02bc..fa1ebc71c 100644 --- a/contrib/template.appsettings-blogs.json +++ b/contrib/template.appsettings-blogs.json @@ -1,4 +1,7 @@ { + "ResourceUsage": { + "UserLimits": {} + }, "Site": { "Title": "Yavsc Blogs", "Description": "A collection of blogs about software development, technology, and programming.", diff --git a/contrib/template.appsettings-org.json b/contrib/template.appsettings-org.json index c330f5f32..abe88244b 100644 --- a/contrib/template.appsettings-org.json +++ b/contrib/template.appsettings-org.json @@ -1,4 +1,15 @@ { + "ResourceSubscriptions": { + "DiscoveryPlanId": "", + "PremiumPlanId": "", + "WebhookId": "", + "DiscoveryPriceExcludingTax": 1, + "PremiumPriceExcludingTax": 2, + "VatPercent": 20 + }, + "ResourceUsage": { + "UserLimits": {} + }, "Logging": { "LogLevel": { "Default": "Information" diff --git a/doc/architecture/postit.md b/doc/architecture/postit.md index 4e63f1c06..85cb052be 100644 --- a/doc/architecture/postit.md +++ b/doc/architecture/postit.md @@ -99,6 +99,13 @@ de chaque téléphone. ## Administration et profil personnel +Le quota disque renvoyé par le profil est le quota effectif : Découverte donne +deux fois et Premium cinq fois le quota gratuit standard durant la mensualité confirmée payée, +y compris après résiliation jusqu'à son échéance UTC. Ensuite, ou après +remboursement, le quota habituel reprend sans suppression des fichiers. +Les téléversements dépassant l'espace disponible sont refusés avant écriture. +La taille maximale par fichier et les quotas podcast restent inchangés. + L'accueil présente un seul accès **Administration**, visible et exécutable uniquement pour le rôle exact `Administrator`. `SessionStatusViewModel.RefreshAsync` lit les rôles dans `GET account/me` après le rafraîchissement de session ; @@ -119,6 +126,33 @@ indépendamment de la visibilité du bouton dans PostIt. endpoints `account/me` pour lire et enregistrer les informations personnelles. Elle affiche aussi `resource-usage/me`, sans appeler la liste des usages globaux. Une indisponibilité de l'usage n'empêche pas la gestion du profil. +La consommation est chargée avant le profil, pour rester consultable même +si une opération de gestion reçoit un refus de quota. L'administration +charge également les usages avant ses autres outils et les conserve sur +un refus HTTP 429, tant que le rôle administrateur est toujours présent. + +L'indicateur cumulé est exprimé en points : `0,02 × appels API + secondes +CPU enregistrées + 0,1 × Mio transférés + 0,3 × Mio ajoutés au stockage`. +Le profil et les vues d'administration affichent le seuil effectif, le +solde et l'atteinte du quota, indépendamment de l'estimation financière. +La section serveur `ResourceUsage` configure les coefficients et les +seuils individuels ; voir [INSTALL.md](../../INSTALL.md#resource-consumption-and-cgu). +Le contrôle admet les coûts connus puis constate les coûts restants : +il bloque les opérations suivantes, sans interrompre strictement celles +déjà en cours. + +La page **À propos** ouvre les CGU dédiées de PostIt et de Yavsc sur +`Home/CGU` auprès de l'autorité configurée, y compris sans session. +Cette page publique présente les coefficients réellement configurés, +la période cumulée, le seuil et les limites de la mesure. +**Mon profil** et **À propos** proposent aussi un lien vers +`ResourceSubscription` sur cette même autorité. La souscription mensuelle +et la résiliation PayPal utilisent la session Web et des formulaires +antiforgery ; PostIt ne stocke ni identifiant marchand ni secret PayPal. +Le profil affiche la consommation brute, l'usage effacé et le crédit +reporté, en plus de l'indicateur net. Les crédits Découverte/Premium ne +suppriment pas les compteurs : les paiements confirmés sont rapprochés +par Yavsc.Org et leur déduction est appliquée aussi au quota API/Blogs. ### Outils d'administration du site diff --git a/src/PostIt/PostIt.Tests/AboutTermsTests.cs b/src/PostIt/PostIt.Tests/AboutTermsTests.cs new file mode 100644 index 000000000..3b4a1e7c4 --- /dev/null +++ b/src/PostIt/PostIt.Tests/AboutTermsTests.cs @@ -0,0 +1,19 @@ +using PostIt.ViewModels; + +namespace PostIt.Tests; + +public sealed class AboutTermsTests +{ + [Fact] + public void Terms_follow_the_configured_instance_and_changes_to_it() + { + var settings = new Settings(); + settings.Authentication.Authority = "https://first.example/"; + var model = new AboutPageViewModel(settings); + Assert.Equal("https://first.example/Home/CGU", model.TermsUri.AbsoluteUri); + Assert.Equal("https://first.example/ResourceSubscription", model.SubscriptionsUri.AbsoluteUri); + settings.Authentication.Authority = "https://second.example"; + Assert.Equal("https://second.example/Home/CGU", model.TermsUri.AbsoluteUri); + Assert.Equal("https://second.example/ResourceSubscription", model.SubscriptionsUri.AbsoluteUri); + } +} diff --git a/src/PostIt/PostIt.Tests/AdministrationAccessTests.cs b/src/PostIt/PostIt.Tests/AdministrationAccessTests.cs index fc733e3f4..30feb7b6e 100644 --- a/src/PostIt/PostIt.Tests/AdministrationAccessTests.cs +++ b/src/PostIt/PostIt.Tests/AdministrationAccessTests.cs @@ -15,6 +15,32 @@ namespace PostIt.Tests; public class AdministrationAccessTests { + [Fact] + public async Task Profile_quota_failure_keeps_the_consumption_visible_without_enabling_profile_changes() + { + await using var api = new ProfileTransport("Performer") { ExhaustedQuota = true }; + var model = new UserProfilePageViewModel(api, usageClient: api.UsageClient); + await model.RefreshAsync(); + Assert.True(model.ResourceUsage?.IsQuotaReached); + Assert.False(model.IsProfileLoaded); + Assert.False(model.SaveProfileCommand.CanExecute(null)); + Assert.Contains("resource_quota_exceeded", model.StatusMessage); + } + + [Fact] + public async Task Administration_quota_failure_keeps_the_authorized_usage_overview() + { + await using var api = new ProfileTransport("Administrator"); + var session = new SessionStatusViewModel { Api = api }; + await session.RefreshAsync(); + api.ExhaustedQuota = true; + var model = new AdministrationPageViewModel(api, api.UsageClient, session); + await model.RefreshAsync(); + Assert.True(Assert.Single(model.UsageOverview).IsQuotaReached); + Assert.Empty(model.Users); + Assert.Contains("les usages restent consultables", model.StatusMessage); + } + [AvaloniaTheory] [InlineData("Moderator", false)] [InlineData("Administrator", true)] @@ -242,6 +268,7 @@ public class AdministrationAccessTests public Task? PendingProfile { get; set; } public bool FailProfile { get; set; } public bool FailUsage { get; set; } + public bool ExhaustedQuota { get; set; } public bool HideIpAddressInCalls { get; set; } public ResourceUsageApiClient UsageClient => new(this, Settings.ApiUrl); @@ -268,6 +295,8 @@ public class AdministrationAccessTests object result; if (path.EndsWith("/account/me")) { + if (ExhaustedQuota) + throw new HttpRequestException("resource_quota_exceeded", null, System.Net.HttpStatusCode.TooManyRequests); if (FailProfile) throw new HttpRequestException("Profile unavailable"); result = PendingProfile is not null ? await PendingProfile @@ -277,11 +306,22 @@ public class AdministrationAccessTests { if (FailUsage) throw new HttpRequestException("Usage unavailable"); - var usage = new ResourceUsageSummary { UserId = "alice-id", UserName = "alice", ApiCalls = 12m }; + var usage = new ResourceUsageSummary + { + UserId = "alice-id", UserName = "alice", ApiCalls = 12m, + Consumption = ExhaustedQuota ? 10000m : 0.24m, + ConsumptionLimit = 10000m, + RemainingConsumption = ExhaustedQuota ? 0m : 9999.76m, + IsQuotaReached = ExhaustedQuota + }; result = path.EndsWith("/admin") ? new List { usage } : usage; } else if (path.EndsWith("/users")) + { + if (ExhaustedQuota) + throw new HttpRequestException("resource_quota_exceeded", null, System.Net.HttpStatusCode.TooManyRequests); result = new List { new() { UserId = "alice-id", UserName = "alice" } }; + } else throw new InvalidOperationException($"Unexpected endpoint: {path}"); diff --git a/src/PostIt/PostIt.Tests/ResourceUsageApiClientTests.cs b/src/PostIt/PostIt.Tests/ResourceUsageApiClientTests.cs index 407183b77..963577d69 100644 --- a/src/PostIt/PostIt.Tests/ResourceUsageApiClientTests.cs +++ b/src/PostIt/PostIt.Tests/ResourceUsageApiClientTests.cs @@ -7,6 +7,18 @@ namespace PostIt.Tests; public class ResourceUsageApiClientTests { + [Fact] + public async Task Usage_remains_visible_when_the_rest_of_the_profile_is_unavailable() + { + var usage = new ResourceUsageApiClient(new FakeYavscApiClient(), "https://example.invalid/api/v1/"); + var model = new PostIt.ViewModels.UserProfilePageViewModel(null, usageClient: usage); + await model.RefreshAsync(); + Assert.NotNull(model.ResourceUsage); + Assert.Equal(20.65m, model.ResourceUsage.Consumption); + Assert.Null(model.UsageError); + Assert.False(model.IsProfileLoaded); + Assert.False(model.IsBusy); + } [Fact] public async Task GetCurrentAsync_calls_user_usage_endpoint() { @@ -19,6 +31,10 @@ public class ResourceUsageApiClientTests Assert.Equal("GET", fake.LastMethod); Assert.Equal(12.5m, usage.ApiCalls); Assert.Equal(3.2m, usage.CpuSeconds); + Assert.Equal(20.65m, usage.Consumption); + Assert.Equal(10000m, usage.ConsumptionLimit); + Assert.Equal(9979.35m, usage.RemainingConsumption); + Assert.False(usage.IsQuotaReached); } [Fact] @@ -56,6 +72,9 @@ public class ResourceUsageApiClientTests CpuSeconds = 3.2m, BandwidthMb = 18.4m, StorageMb = 51.2m, + Consumption = 20.65m, + ConsumptionLimit = 10000m, + RemainingConsumption = 9979.35m, EstimatedCompensation = 4.9m, Currency = "EUR", RecordedAtUtc = DateTimeOffset.UtcNow diff --git a/src/PostIt/PostIt/ViewModels/AdministrationPageViewModel.cs b/src/PostIt/PostIt/ViewModels/AdministrationPageViewModel.cs index bc6787229..9aef20641 100644 --- a/src/PostIt/PostIt/ViewModels/AdministrationPageViewModel.cs +++ b/src/PostIt/PostIt/ViewModels/AdministrationPageViewModel.cs @@ -96,6 +96,17 @@ public partial class AdministrationPageViewModel : ViewModelBase IsBusy = true; try { + var usage = await _usageClient.GetAdminOverviewAsync().ConfigureAwait(true) + ?? throw new InvalidOperationException("Le serveur a renvoyé une liste d’usages vide."); + if (!_session.IsAdministrator) + { + ClearAdministrationData(); + StatusMessage = "Le rôle Administrator est requis."; + return; + } + foreach (var item in usage) + UsageOverview.Add(item); + var query = SearchText.Trim(); var usersEndpoint = string.IsNullOrWhiteSpace(query) ? new Uri(new Uri(_api.Settings.ApiUrl.TrimEnd('/') + "/", UriKind.Absolute), "users").ToString() @@ -103,11 +114,10 @@ public partial class AdministrationPageViewModel : ViewModelBase var users = await _api.CallAsync>(HttpMethod.Get, usersEndpoint).ConfigureAwait(true) ?? throw new InvalidOperationException("Le serveur a renvoyé une liste d’utilisateurs vide."); - var usage = await _usageClient.GetAdminOverviewAsync().ConfigureAwait(true) - ?? throw new InvalidOperationException("Le serveur a renvoyé une liste d’usages vide."); if (!_session.IsAdministrator) { + ClearAdministrationData(); StatusMessage = "Le rôle Administrator est requis."; return; } @@ -116,8 +126,6 @@ public partial class AdministrationPageViewModel : ViewModelBase { Users.Add(user); } - foreach (var item in usage) - UsageOverview.Add(item); OnPropertyChanged(nameof(FilteredUsers)); OnPropertyChanged(nameof(SelectedUsage)); @@ -125,6 +133,16 @@ public partial class AdministrationPageViewModel : ViewModelBase await LoadToolsAsync(); StatusMessage = Users.Count > 0 ? $"{Users.Count} utilisateur(s) chargé(s)." : "Aucun utilisateur trouvé."; } + catch (HttpRequestException ex) when (ex.StatusCode == System.Net.HttpStatusCode.TooManyRequests) + { + if (!_session.IsAdministrator) + { + ClearAdministrationData(); + StatusMessage = "Le rôle Administrator est requis."; + } + else + StatusMessage = $"Quota insuffisant : les usages restent consultables. {ex.Message}"; + } catch (Exception ex) { ClearAdministrationData(); diff --git a/src/PostIt/PostIt/ViewModels/Layout/AboutPageViewModel.cs b/src/PostIt/PostIt/ViewModels/Layout/AboutPageViewModel.cs index 1082e4828..cf6883e90 100644 --- a/src/PostIt/PostIt/ViewModels/Layout/AboutPageViewModel.cs +++ b/src/PostIt/PostIt/ViewModels/Layout/AboutPageViewModel.cs @@ -17,13 +17,24 @@ public partial class AboutPageViewModel : ViewModelBase public const string RepositoryUrl = "https://forgejo.pschneider.fr/notazof/yavsc"; public const string IssuesUrl = RepositoryUrl + "/issues"; - public AboutPageViewModel() + private readonly Settings? _settings; + + public AboutPageViewModel(Settings? settings = null) { + _settings = settings; Version = ReadVersion(); } public string Version { get; } + public Uri TermsUri => new(new Uri( + (_settings?.Authentication.Authority ?? AuthenticationSettings.DefaultAuthority).TrimEnd('/') + "/"), "Home/CGU"); + public Uri SubscriptionsUri => new(new Uri( + (_settings?.Authentication.Authority ?? AuthenticationSettings.DefaultAuthority).TrimEnd('/') + "/"), "ResourceSubscription"); + + [ObservableProperty] + public partial string? StatusMessage { get; set; } + public string Description { get; } = "PostIt est le client de la plateforme Yavsc : blog, devis, " + "demandes de prestations et fichiers personnels."; @@ -49,13 +60,20 @@ public partial class AboutPageViewModel : ViewModelBase [RelayCommand] private Task OpenIssues() => OpenUrlAsync(IssuesUrl); - private static async Task OpenUrlAsync(string url) + [RelayCommand] + private Task OpenTerms() => OpenUrlAsync(TermsUri.AbsoluteUri); + + [RelayCommand] + private Task OpenSubscriptions() => OpenUrlAsync(SubscriptionsUri.AbsoluteUri); + + private async Task OpenUrlAsync(string url) { + StatusMessage = null; var app = (App)App.Current!; var topLevel = TopLevel.GetTopLevel(app.View); - if (topLevel is not null) + if (topLevel is null || !await topLevel.Launcher.LaunchUriAsync(new Uri(url)).ConfigureAwait(true)) { - await topLevel.Launcher.LaunchUriAsync(new Uri(url)).ConfigureAwait(true); + StatusMessage = "Impossible d'ouvrir le navigateur : " + url; } } diff --git a/src/PostIt/PostIt/ViewModels/Layout/UserProfilePageViewModel.cs b/src/PostIt/PostIt/ViewModels/Layout/UserProfilePageViewModel.cs index 61f071683..9dfa45704 100644 --- a/src/PostIt/PostIt/ViewModels/Layout/UserProfilePageViewModel.cs +++ b/src/PostIt/PostIt/ViewModels/Layout/UserProfilePageViewModel.cs @@ -17,6 +17,9 @@ public partial class UserProfilePageViewModel : ViewModelBase private readonly YavscApiClient? _api; private readonly SessionStatusViewModel? _sessionStatus; private readonly ResourceUsageApiClient? _usageClient; + private readonly AboutPageViewModel _subscriptionLinks; + public IAsyncRelayCommand OpenSubscriptionsCommand => _subscriptionLinks.OpenSubscriptionsCommand; + public string? SubscriptionLinkError => _subscriptionLinks.StatusMessage; [ObservableProperty] public partial ResourceUsageSummary? ResourceUsage { get; set; } @@ -158,6 +161,8 @@ public partial class UserProfilePageViewModel : ViewModelBase _api = api; _sessionStatus = sessionStatus; _usageClient = usageClient; + _subscriptionLinks = new AboutPageViewModel(api?.Settings); + _subscriptionLinks.PropertyChanged += (_, _) => OnPropertyChanged(nameof(SubscriptionLinkError)); } public UserProfilePageViewModel() : this(null, null) { } @@ -167,19 +172,18 @@ public partial class UserProfilePageViewModel : ViewModelBase [RelayCommand] public async Task RefreshAsync() { - if (_api is null) - { - IsProfileLoaded = false; - StatusMessage = "Client API de profil indisponible."; - return; - } - IsBusy = true; IsProfileLoaded = false; ResourceUsage = null; UsageError = null; try { + await LoadUsageAsync(); + if (_api is null) + { + StatusMessage = "Client API de profil indisponible."; + return; + } var me = await _api.CallAsync(HttpMethod.Get, new Uri(new Uri(_api.Settings.ApiUrl.TrimEnd('/') + "/", UriKind.Absolute), "account/me").ToString()).ConfigureAwait(true); if (me is null) { @@ -218,18 +222,6 @@ public partial class UserProfilePageViewModel : ViewModelBase } IsProfileLoaded = true; StatusMessage = "Profil chargé."; - if (_usageClient is not null) - { - try - { - ResourceUsage = await _usageClient.GetCurrentAsync() - ?? throw new InvalidOperationException("Le serveur a renvoyé un usage vide."); - } - catch (Exception ex) - { - UsageError = $"Impossible de charger mon usage : {ex.Message}"; - } - } } catch (Exception ex) { @@ -264,6 +256,24 @@ public partial class UserProfilePageViewModel : ViewModelBase } } + private async Task LoadUsageAsync() + { + if (_usageClient is null) + { + UsageError = "Client API de consommation indisponible."; + return; + } + try + { + ResourceUsage = await _usageClient.GetCurrentAsync() + ?? throw new InvalidOperationException("Le serveur a renvoyé un usage vide."); + } + catch (Exception ex) when (ex is HttpRequestException or JsonException or InvalidOperationException) + { + UsageError = $"Impossible de charger mon usage : {ex.Message}"; + } + } + public ProfileUpdateRequest BuildProfileUpdateRequest() { static string NormalizeField(string? value, string placeholder) diff --git a/src/PostIt/PostIt/Views/Layout/AboutPage.axaml b/src/PostIt/PostIt/Views/Layout/AboutPage.axaml index 5ad594e38..aa8ec5664 100644 --- a/src/PostIt/PostIt/Views/Layout/AboutPage.axaml +++ b/src/PostIt/PostIt/Views/Layout/AboutPage.axaml @@ -34,5 +34,12 @@ + + + } + +

Le premier crédit est accordé après le premier paiement confirmé, puis à chaque mensualité payée à la date anniversaire UTC du début PayPal.

+

Un seul abonnement non résilié par compte. Pour changer de pack, résiliez d'abord le précédent. Un remboursement, même partiel, retire le crédit de la mensualité correspondante.

+

Mes abonnements

+@foreach (var subscription in Model.Subscriptions) +{ +
+

@(subscription.Pack == "Premium" ? "Premium" : "Découverte")

+

État PayPal : @subscription.State. Référence : @subscription.PayPalId

+

Tarif souscrit : @subscription.PriceExcludingTax.ToString("F2") € HT, @subscription.PriceIncludingTax.ToString("F2") € TTC. Crédit mensuel : @subscription.MonthlyPoints points.

+

Début UTC : @subscription.StartsAt?.ToUniversalTime().ToString("u"). Prochain prélèvement UTC : @subscription.NextBillingAt?.ToUniversalTime().ToString("u").

+ @if (subscription.PayPalId is not null && subscription.State is not ("CANCELLED" or "EXPIRED")) + { +
+ + + + } +
+} +
+ + +

CGU de PostIt et de Yavsc

diff --git a/src/Yavsc.Org/Views/Shared/_Layout.cshtml b/src/Yavsc.Org/Views/Shared/_Layout.cshtml index 653ffae0a..be37b3a63 100644 --- a/src/Yavsc.Org/Views/Shared/_Layout.cshtml +++ b/src/Yavsc.Org/Views/Shared/_Layout.cshtml @@ -42,6 +42,8 @@ diff --git a/src/Yavsc.Org/appsettings-org.json b/src/Yavsc.Org/appsettings-org.json index 25e017bfd..4d725f11a 100644 --- a/src/Yavsc.Org/appsettings-org.json +++ b/src/Yavsc.Org/appsettings-org.json @@ -1,4 +1,15 @@ { + "ResourceSubscriptions": { + "DiscoveryPlanId": "", + "PremiumPlanId": "", + "WebhookId": "", + "DiscoveryPriceExcludingTax": 1, + "PremiumPriceExcludingTax": 2, + "VatPercent": 20 + }, + "ResourceUsage": { + "UserLimits": {} + }, "Logging": { "LogLevel": { "Default": "Information", diff --git a/src/Yavsc.Server/Helpers/FileSystemHelpers.cs b/src/Yavsc.Server/Helpers/FileSystemHelpers.cs index 3d903e36f..d2d587f7e 100644 --- a/src/Yavsc.Server/Helpers/FileSystemHelpers.cs +++ b/src/Yavsc.Server/Helpers/FileSystemHelpers.cs @@ -166,6 +166,12 @@ namespace Yavsc.Server.Helpers } public static FileReceivedInfo ReceiveUserFile(this ApplicationUser user, string root, IFormFile f, string destFileName = null) { + var name = AbstractFileSystemHelpers.FilterFileName(destFileName ?? f.FileName); + var destination = new FileInfo(Path.Combine(root, name)); + var replacedBytes = destination.Exists ? destination.Length : 0L; + var available = user.GetEffectiveDiskQuota(DateTimeOffset.UtcNow) - user.DiskUsage + replacedBytes; + if (f.Length > available) + return new FileReceivedInfo(root, name) { QuotaOffense = true }; // f.FileName is parsed by ASP.NET Core from the // Content-Disposition header: it handles unquoted // values and the RFC 5987 filename* parameter that @@ -203,6 +209,7 @@ namespace Yavsc.Server.Helpers // TODO lock user's disk usage for this scope, // this process is not safe at concurrent access. long usage = user.DiskUsage; + var quota = user.GetEffectiveDiskQuota(DateTimeOffset.UtcNow); var item = new FileReceivedInfo (root, AbstractFileSystemHelpers.FilterFileName(destFileName)); @@ -212,8 +219,15 @@ namespace Yavsc.Server.Helpers item.Overridden = true; usage -= fi.Length; } + if (usage >= quota) + { + inputStream.Dispose(); + item.QuotaOffense = true; + return item; + } using (var dest = fi.OpenWrite()) { + dest.SetLength(0); using (inputStream) { const int blen = 1024; @@ -221,16 +235,20 @@ namespace Yavsc.Server.Helpers int len = 0; while (!token.IsCancellationRequested && (len = inputStream.Read(buffer, 0, blen)) > 0) { + if (len > quota - usage) + { + item.QuotaOffense = true; + break; + } dest.Write(buffer, 0, len); usage += len; - if (usage >= user.DiskQuota) break; } user.DiskUsage = usage; dest.Close(); inputStream.Close(); } } - if (usage >= user.DiskQuota) + if (usage > quota) { item.QuotaOffense = true; } diff --git a/src/Yavsc.Server/Helpers/ResourceUsageCountingStream.cs b/src/Yavsc.Server/Helpers/ResourceUsageCountingStream.cs new file mode 100644 index 000000000..926e94352 --- /dev/null +++ b/src/Yavsc.Server/Helpers/ResourceUsageCountingStream.cs @@ -0,0 +1,51 @@ +#nullable enable +namespace Yavsc.Server.Helpers; + +internal sealed class ResourceUsageCountingStream(Stream inner) : Stream +{ + private long _bytesRead; + private long _bytesWritten; + public long BytesRead => Interlocked.Read(ref _bytesRead); + public long BytesWritten => Interlocked.Read(ref _bytesWritten); + public override bool CanRead => inner.CanRead; + public override bool CanSeek => inner.CanSeek; + public override bool CanWrite => inner.CanWrite; + public override long Length => inner.Length; + public override long Position { get => inner.Position; set => inner.Position = value; } + public override void Flush() => inner.Flush(); + public override Task FlushAsync(CancellationToken cancellationToken) => inner.FlushAsync(cancellationToken); + public override long Seek(long offset, SeekOrigin origin) => inner.Seek(offset, origin); + public override void SetLength(long value) => inner.SetLength(value); + + public override int Read(byte[] buffer, int offset, int count) + { + var read = inner.Read(buffer, offset, count); + Interlocked.Add(ref _bytesRead, read); + return read; + } + + public override Task ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) + => ReadAsync(buffer.AsMemory(offset, count), cancellationToken).AsTask(); + + public override async ValueTask ReadAsync(Memory buffer, CancellationToken cancellationToken = default) + { + var read = await inner.ReadAsync(buffer, cancellationToken); + Interlocked.Add(ref _bytesRead, read); + return read; + } + + public override void Write(byte[] buffer, int offset, int count) + { + inner.Write(buffer, offset, count); + Interlocked.Add(ref _bytesWritten, count); + } + + public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) + => WriteAsync(buffer.AsMemory(offset, count), cancellationToken).AsTask(); + + public override async ValueTask WriteAsync(ReadOnlyMemory buffer, CancellationToken cancellationToken = default) + { + await inner.WriteAsync(buffer, cancellationToken); + Interlocked.Add(ref _bytesWritten, buffer.Length); + } +} diff --git a/src/Yavsc.Server/Helpers/ResourceUsageCredit.cs b/src/Yavsc.Server/Helpers/ResourceUsageCredit.cs new file mode 100644 index 000000000..230902fe6 --- /dev/null +++ b/src/Yavsc.Server/Helpers/ResourceUsageCredit.cs @@ -0,0 +1,26 @@ +namespace Yavsc.Server.Helpers; + +public static class ResourceUsageCredit +{ + public static decimal NetConsumption(decimal gross, decimal credits) => Math.Max(0m, gross - credits); + public static decimal Balance(decimal gross, decimal credits) => Math.Max(0m, credits - gross); + + public static decimal MonthlyGrant(decimal gross, decimal existingCredits, decimal allowance) + { + ArgumentOutOfRangeException.ThrowIfNegative(gross); + ArgumentOutOfRangeException.ThrowIfNegative(existingCredits); + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(allowance); + var erased = Math.Min(allowance, NetConsumption(gross, existingCredits)); + // Round down only the carried credit to the persistence precision. + var carried = decimal.Round((allowance - erased) * 2m / 3m, 8, MidpointRounding.ToZero); + return decimal.Round(erased + carried, 8, MidpointRounding.ToZero); + } + + public static int BillingCycle(DateTimeOffset anchor, DateTimeOffset paidAt) + { + if (paidAt < anchor) throw new ArgumentOutOfRangeException(nameof(paidAt)); + var cycle = (paidAt.Year - anchor.Year) * 12 + paidAt.Month - anchor.Month; + if (anchor.AddMonths(cycle) > paidAt) cycle--; + return cycle; + } +} diff --git a/src/Yavsc.Server/Helpers/ResourceUsageExemptAttribute.cs b/src/Yavsc.Server/Helpers/ResourceUsageExemptAttribute.cs new file mode 100644 index 000000000..2f67b668e --- /dev/null +++ b/src/Yavsc.Server/Helpers/ResourceUsageExemptAttribute.cs @@ -0,0 +1,4 @@ +namespace Yavsc.Server.Helpers; + +[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)] +public sealed class ResourceUsageExemptAttribute : Attribute; diff --git a/src/Yavsc.Server/Helpers/ResourceUsageService.cs b/src/Yavsc.Server/Helpers/ResourceUsageService.cs new file mode 100644 index 000000000..10ccdd27e --- /dev/null +++ b/src/Yavsc.Server/Helpers/ResourceUsageService.cs @@ -0,0 +1,98 @@ +#nullable enable +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Options; +using Yavsc.Abstract.Resources; +using Yavsc.Models; +using Yavsc.Settings; + +namespace Yavsc.Server.Helpers; + +public interface IResourceUsageService +{ + Task GetCurrentAsync(string userId, string userName, CancellationToken cancellationToken); + Task> GetOverviewAsync(CancellationToken cancellationToken); + Task TryAdmitAsync(string userId, string userName, decimal apiCalls, decimal bandwidthMb, + long anticipatedStorageBytes, CancellationToken cancellationToken); +} + +public sealed class ResourceUsageService( + ApplicationDbContext dbContext, + IOptions options, + TimeProvider? clock = null) : IResourceUsageService +{ + private readonly ResourceUsageOptions _options = options.Value; + + public async Task GetCurrentAsync( + string userId, string userName, CancellationToken cancellationToken) + { + var record = await ResourceUsageTracker.UpdateAsync(dbContext, userId, userName, + cancellationToken: cancellationToken); + var user = await dbContext.Users.AsNoTracking().SingleOrDefaultAsync(u => u.Id == userId, cancellationToken); + return ToSummary(record ?? throw new InvalidOperationException("Usage initialization failed."), user); + } + + public async Task> GetOverviewAsync(CancellationToken cancellationToken) + { + var records = await dbContext.ResourceUsageRecords.AsNoTracking() + .OrderByDescending(r => r.RecordedAtUtc).ThenByDescending(r => r.Id) + .ToListAsync(cancellationToken); + var ids = records.Select(r => r.UserId).Distinct().ToArray(); + var users = await dbContext.Users.AsNoTracking().Where(u => ids.Contains(u.Id)).ToDictionaryAsync(u => u.Id, cancellationToken); + return records.GroupBy(r => r.UserId).Select(g => ToSummary(g.First(), users.GetValueOrDefault(g.Key))).ToList(); + } + + public async Task TryAdmitAsync( + string userId, string userName, decimal apiCalls, decimal bandwidthMb, + long anticipatedStorageBytes, CancellationToken cancellationToken) + => await ResourceUsageTracker.UpdateAsync(dbContext, userId, userName, + apiCalls: apiCalls, bandwidthMb: bandwidthMb, + policy: _options, anticipatedStorageBytes: anticipatedStorageBytes, + cancellationToken: cancellationToken) is not null; + + private ResourceUsageSummary ToSummary(ResourceUsageRecord record, ApplicationUser? user) + { + var gross = _options.Calculate(record.ApiCalls, record.CpuSeconds, record.BandwidthMb, record.StorageMb); + var consumption = ResourceUsageCredit.NetConsumption(gross, record.CreditPoints); + var limit = _options.GetLimit(record.UserId); + return new ResourceUsageSummary + { + UserId = record.UserId, + UserName = record.UserName, + RecordedAtUtc = new DateTimeOffset(DateTime.SpecifyKind(record.RecordedAtUtc, DateTimeKind.Utc)), + ApiCalls = record.ApiCalls, + CpuSeconds = record.CpuSeconds, + BandwidthMb = record.BandwidthMb, + StorageMb = record.StorageMb, + EstimatedCompensation = record.EstimatedCompensation, + Currency = record.Currency, + Consumption = consumption, + GrossConsumption = gross, + CreditBalance = ResourceUsageCredit.Balance(gross, record.CreditPoints), + AppliedCredits = Math.Min(gross, record.CreditPoints), + ConsumptionLimit = limit, + RemainingConsumption = Math.Max(0m, limit - consumption) + ResourceUsageCredit.Balance(gross, record.CreditPoints), + IsQuotaReached = consumption >= limit, + DiskQuota = user?.GetEffectiveDiskQuota((clock ?? TimeProvider.System).GetUtcNow()), + PremiumDiskQuotaUntil = user?.PremiumDiskQuotaUntil, + DiscoveryDiskQuotaUntil = user?.DiscoveryDiskQuotaUntil + }; + } +} + +public static class ResourceUsageServiceCollectionExtensions +{ + public static IServiceCollection AddResourceUsage(this IServiceCollection services, IConfiguration configuration) + { + services.AddOptions() + .Bind(configuration.GetSection(ResourceUsageOptions.SectionName)) + .Validate(o => o.ApiCallWeight > 0m && o.CpuSecondWeight >= 0m + && o.BandwidthMbWeight >= 0m && o.StorageMbWeight >= 0m, + "ResourceUsage weights must be non-negative and ApiCallWeight must be positive.") + .Validate(o => o.DefaultLimit > 0m && o.UserLimits.All(p => !string.IsNullOrWhiteSpace(p.Key) && p.Value > 0m), + "ResourceUsage limits must be positive and keyed by user ID.") + .ValidateOnStart(); + return services.AddScoped(); + } +} diff --git a/src/Yavsc.Server/Helpers/ResourceUsageTelemetryMiddleware.cs b/src/Yavsc.Server/Helpers/ResourceUsageTelemetryMiddleware.cs index 8b1795167..9e0fd4365 100644 --- a/src/Yavsc.Server/Helpers/ResourceUsageTelemetryMiddleware.cs +++ b/src/Yavsc.Server/Helpers/ResourceUsageTelemetryMiddleware.cs @@ -1,54 +1,86 @@ #nullable enable using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; using Yavsc.Models; namespace Yavsc.Server.Helpers; -public sealed class ResourceUsageTelemetryMiddleware +public sealed class ResourceUsageTelemetryMiddleware( + RequestDelegate next, + IServiceScopeFactory scopeFactory, + ILogger logger) { - private readonly RequestDelegate _next; - private readonly IServiceScopeFactory _scopeFactory; - - public ResourceUsageTelemetryMiddleware( - RequestDelegate next, - IServiceScopeFactory scopeFactory) - { - _next = next; - _scopeFactory = scopeFactory; - } - - public async Task InvokeAsync(HttpContext context) + public async Task InvokeAsync(HttpContext context, IResourceUsageService usage) { var userId = context.User.GetUserId(); - if (string.IsNullOrWhiteSpace(userId)) + if (string.IsNullOrWhiteSpace(userId) || IsExempt(context)) { - await _next(context); + await next(context); return; } var userName = context.User.Identity?.Name ?? userId; var requestBytes = context.Request.ContentLength ?? 0L; + if (!await usage.TryAdmitAsync(userId, userName, 1m, ToMb(requestBytes), 0, + context.RequestAborted)) + { + logger.LogWarning("Resource quota refused a request for user {UserId}", userId); + await WriteQuotaProblemAsync(context); + return; + } + var originalRequest = context.Request.Body; + var originalResponse = context.Response.Body; + using var request = new ResourceUsageCountingStream(originalRequest); + using var response = new ResourceUsageCountingStream(originalResponse); + context.Request.Body = request; + context.Response.Body = response; try { - await _next(context); + await next(context); } finally { - var responseBytes = context.Response.ContentLength ?? 0L; - var totalBytes = requestBytes + responseBytes; - var bandwidthMb = totalBytes <= 0 ? 0m : (decimal)totalBytes / (1024m * 1024m); - - using var scope = _scopeFactory.CreateScope(); + context.Request.Body = originalRequest; + context.Response.Body = originalResponse; + // Known ingress was charged at admission. Count streamed responses + // and unknown-length ingress once, even on failure or cancellation. + var extraBytes = Math.Max(0L, request.BytesRead - requestBytes) + response.BytesWritten; + using var scope = scopeFactory.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); - await ResourceUsageTracker.RecordAsync( - db, - userId, - userName, - apiCalls: 1m, - bandwidthMb: bandwidthMb, - actorUserId: userId); + await ResourceUsageTracker.RecordAsync(db, userId, userName, + bandwidthMb: ToMb(extraBytes), actorUserId: userId); } } + + public static async Task WriteQuotaProblemAsync(HttpContext context) + { + var site = context.RequestServices.GetRequiredService>().Value; + var termsUrl = new Uri(new Uri(site.Authority.TrimEnd('/') + "/"), "Home/CGU").AbsoluteUri; + context.Response.StatusCode = StatusCodes.Status429TooManyRequests; + var problem = new ProblemDetails + { + Status = StatusCodes.Status429TooManyRequests, + Title = "Quota de consommation insuffisant", + Detail = "Cette opération dépasse le quota disponible. Consultez votre consommation ou contactez l'administration.", + Instance = context.Request.Path + }; + problem.Extensions["code"] = "resource_quota_exceeded"; + problem.Extensions["usagePath"] = Constants.APIPrefix + "/" + Constants.ResourceUsagePath + "/me"; + problem.Extensions["termsUrl"] = termsUrl; + problem.Extensions["subscriptionUrl"] = new Uri(new Uri(site.Authority.TrimEnd('/') + "/"), "ResourceSubscription").AbsoluteUri; + await context.Response.WriteAsJsonAsync(problem, + options: null, contentType: "application/problem+json", cancellationToken: context.RequestAborted); + } + + private static decimal ToMb(long bytes) => (decimal)bytes / (1024m * 1024m); + + private static bool IsExempt(HttpContext context) + => context.GetEndpoint()?.Metadata.GetMetadata() is not null + || context.Request.Path.Equals("/login", StringComparison.OrdinalIgnoreCase) + || context.Request.Path.Equals("/refresh", StringComparison.OrdinalIgnoreCase) + || context.Request.Path.Equals("/logout", StringComparison.OrdinalIgnoreCase); } diff --git a/src/Yavsc.Server/Helpers/ResourceUsageTracker.cs b/src/Yavsc.Server/Helpers/ResourceUsageTracker.cs index cad05a699..873dc10c4 100644 --- a/src/Yavsc.Server/Helpers/ResourceUsageTracker.cs +++ b/src/Yavsc.Server/Helpers/ResourceUsageTracker.cs @@ -1,11 +1,14 @@ #nullable enable using Microsoft.EntityFrameworkCore; using Yavsc.Models; +using Yavsc.Settings; namespace Yavsc.Server.Helpers; public static class ResourceUsageTracker { + private static readonly SemaphoreSlim LocalGate = new(1, 1); + public static async Task RecordAsync( ApplicationDbContext dbContext, string userId, @@ -15,55 +18,103 @@ public static class ResourceUsageTracker decimal apiCalls = 0m, decimal bandwidthMb = 0m, string? actorUserId = null, - string currency = Constants.ResourceUsageDefaultCurrency) + string currency = Constants.ResourceUsageDefaultCurrency, + CancellationToken cancellationToken = default) { - if (dbContext is null || string.IsNullOrWhiteSpace(userId)) + await UpdateAsync(dbContext, userId, userName, cpuSeconds, storageBytes, + apiCalls, bandwidthMb, actorUserId, currency, cancellationToken: cancellationToken); + } + + internal static async Task UpdateAsync( + ApplicationDbContext dbContext, string userId, string userName, + decimal cpuSeconds = 0m, long storageBytes = 0, decimal apiCalls = 0m, + decimal bandwidthMb = 0m, string? actorUserId = null, + string currency = Constants.ResourceUsageDefaultCurrency, + ResourceUsageOptions? policy = null, long anticipatedStorageBytes = 0, + CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(dbContext); + ArgumentException.ThrowIfNullOrWhiteSpace(userId); + ArgumentOutOfRangeException.ThrowIfNegative(cpuSeconds); + ArgumentOutOfRangeException.ThrowIfNegative(storageBytes); + ArgumentOutOfRangeException.ThrowIfNegative(apiCalls); + ArgumentOutOfRangeException.ThrowIfNegative(bandwidthMb); + ArgumentOutOfRangeException.ThrowIfNegative(anticipatedStorageBytes); + + return await WithUserLockAsync(dbContext, userId, async () => { - return; - } + var effectiveActor = string.IsNullOrWhiteSpace(actorUserId) ? userId : actorUserId; + var now = DateTime.UtcNow; + var storageMb = (decimal)storageBytes / (1024m * 1024m); + var record = await dbContext.ResourceUsageRecords + .Where(r => r.UserId == userId) + .OrderByDescending(r => r.RecordedAtUtc).ThenByDescending(r => r.Id) + .FirstOrDefaultAsync(cancellationToken); + if (record is not null) + await dbContext.Entry(record).ReloadAsync(cancellationToken); - var effectiveActor = string.IsNullOrWhiteSpace(actorUserId) ? userId : actorUserId; - var now = DateTime.UtcNow; - var storageMb = storageBytes <= 0 ? 0m : (decimal)storageBytes / (1024m * 1024m); - - var record = await dbContext.ResourceUsageRecords - .Where(r => r.UserId == userId) - .OrderByDescending(r => r.RecordedAtUtc) - .FirstOrDefaultAsync(); - - if (record is null) - { - record = new ResourceUsageRecord + if (policy is not null) { - UserId = userId, - UserName = string.IsNullOrWhiteSpace(userName) ? userId : userName, - RecordedAtUtc = now, - ApiCalls = apiCalls, - CpuSeconds = cpuSeconds, - BandwidthMb = bandwidthMb, - StorageMb = storageMb, - EstimatedCompensation = 0m, - Currency = currency, - UserCreated = effectiveActor, - UserModified = effectiveActor, - DateCreated = now, - DateModified = now, - }; - dbContext.ResourceUsageRecords.Add(record); - await dbContext.SaveChangesAsync(effectiveActor); - return; + var gross = record is null ? 0m : + policy.Calculate(record.ApiCalls, record.CpuSeconds, record.BandwidthMb, record.StorageMb); + var current = ResourceUsageCredit.NetConsumption(gross, record?.CreditPoints ?? 0m); + var projected = ResourceUsageCredit.NetConsumption(gross + policy.Calculate(apiCalls, cpuSeconds, bandwidthMb, + storageMb + (decimal)anticipatedStorageBytes / (1024m * 1024m)), record?.CreditPoints ?? 0m); + var limit = policy.GetLimit(userId); + if (current >= limit || projected > limit) return null; + } + + if (record is not null && apiCalls == 0m && cpuSeconds == 0m && bandwidthMb == 0m && storageBytes == 0) + return record; + + if (record is null) + { + record = new ResourceUsageRecord + { + UserId = userId, + UserName = string.IsNullOrWhiteSpace(userName) ? userId : userName, + Currency = currency, + UserCreated = effectiveActor, + DateCreated = now + }; + dbContext.ResourceUsageRecords.Add(record); + } + + record.UserName = string.IsNullOrWhiteSpace(userName) ? record.UserName : userName; + record.RecordedAtUtc = now; + record.ApiCalls += apiCalls; + record.CpuSeconds += cpuSeconds; + record.BandwidthMb += bandwidthMb; + record.StorageMb += storageMb; + record.Currency = string.IsNullOrWhiteSpace(currency) ? record.Currency : currency; + record.DateModified = now; + record.UserModified = effectiveActor; + + await dbContext.SaveChangesAsync(effectiveActor, cancellationToken); + return record; + }, cancellationToken); + } + + public static async Task WithUserLockAsync(ApplicationDbContext dbContext, string userId, + Func> action, CancellationToken cancellationToken) + { + // This lock is shared by accounting and subscription credits on all hosts. + var postgres = dbContext.Database.IsNpgsql(); + if (!postgres) await LocalGate.WaitAsync(cancellationToken); + try + { + await using var transaction = postgres && dbContext.Database.CurrentTransaction is null + ? await dbContext.Database.BeginTransactionAsync(cancellationToken) : null; + if (postgres) + await dbContext.Database.ExecuteSqlInterpolatedAsync( + $"SELECT pg_advisory_xact_lock(hashtextextended({userId}, 781932))", cancellationToken); + var result = await action(); + if (transaction is not null) await transaction.CommitAsync(cancellationToken); + return result; + } + finally + { + if (!postgres) LocalGate.Release(); } - - record.UserName = string.IsNullOrWhiteSpace(userName) ? record.UserName : userName; - record.RecordedAtUtc = now; - record.ApiCalls += apiCalls; - record.CpuSeconds += cpuSeconds; - record.BandwidthMb += bandwidthMb; - record.StorageMb += storageMb; - record.Currency = string.IsNullOrWhiteSpace(currency) ? record.Currency : currency; - record.DateModified = now; - record.UserModified = effectiveActor; - - await dbContext.SaveChangesAsync(effectiveActor); } } diff --git a/src/Yavsc.Server/Models/ApplicationDbContext.cs b/src/Yavsc.Server/Models/ApplicationDbContext.cs index ac4ecaff1..35b26ab73 100644 --- a/src/Yavsc.Server/Models/ApplicationDbContext.cs +++ b/src/Yavsc.Server/Models/ApplicationDbContext.cs @@ -96,6 +96,21 @@ namespace Yavsc.Models entity.HasIndex(r => new { r.UserId, r.RecordedAtUtc }); entity.Property(r => r.Currency).HasMaxLength(8).HasDefaultValue(Constants.ResourceUsageDefaultCurrency); entity.Property(r => r.UserName).HasMaxLength(256); + entity.Property(r => r.CreditPoints).HasPrecision(28, 8).HasDefaultValue(0m); + }); + + builder.Entity(entity => + { + entity.HasIndex(s => s.PayPalId).IsUnique(); + entity.HasIndex(s => s.UserId); + entity.HasOne().WithMany().HasForeignKey(s => s.UserId).OnDelete(DeleteBehavior.Restrict); + entity.Property(s => s.MonthlyPoints).HasPrecision(28, 8); + }); + builder.Entity(entity => + { + entity.HasIndex(p => new { p.SubscriptionId, p.Cycle }).IsUnique(); + entity.HasOne().WithMany().HasForeignKey(p => p.SubscriptionId).OnDelete(DeleteBehavior.Restrict); + entity.Property(p => p.GrantedPoints).HasPrecision(28, 8); }); // Customize the ASP.NET Identity model and override the defaults if needed. @@ -365,6 +380,8 @@ namespace Yavsc.Models public DbSet Estimates { get; set; } public DbSet Signatures { get; set; } public DbSet ResourceUsageRecords { get; set; } + public DbSet ResourceSubscriptions { get; set; } + public DbSet ResourceSubscriptionPayments { get; set; } public DbSet BankStatus { get; set; } public DbSet BalanceImpact { get; set; } diff --git a/src/Yavsc.Server/Models/ApplicationUser.cs b/src/Yavsc.Server/Models/ApplicationUser.cs index b2eb2c458..1f7c95e8b 100644 --- a/src/Yavsc.Server/Models/ApplicationUser.cs +++ b/src/Yavsc.Server/Models/ApplicationUser.cs @@ -93,7 +93,16 @@ namespace Yavsc.Models public virtual List? BankInfo { get; set; } - public long DiskQuota { get; set; } = 512 * 1024 * 1024; + public long DiskQuota { get; set; } = Constants.DefaultFSQ; + [JsonIgnore, System.Text.Json.Serialization.JsonIgnore] + public DateTimeOffset? PremiumDiskQuotaUntil { get; set; } + [JsonIgnore, System.Text.Json.Serialization.JsonIgnore] + public DateTimeOffset? DiscoveryDiskQuotaUntil { get; set; } + + public long GetEffectiveDiskQuota(DateTimeOffset now) + => PremiumDiskQuotaUntil > now ? checked(Constants.DefaultFSQ * 5L) + : DiscoveryDiskQuotaUntil > now ? checked(Constants.DefaultFSQ * 2L) : DiskQuota; + public long DiskUsage { get; set; } = 0; public long MaxFileSize { get; set; } = 512 * 1024 * 1024; diff --git a/src/Yavsc.Server/Models/Payment/ResourceSubscription.cs b/src/Yavsc.Server/Models/Payment/ResourceSubscription.cs new file mode 100644 index 000000000..27a9d342c --- /dev/null +++ b/src/Yavsc.Server/Models/Payment/ResourceSubscription.cs @@ -0,0 +1,41 @@ +#nullable enable +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; + +namespace Yavsc.Models.Payment; + +public sealed class ResourceSubscription +{ + public Guid Id { get; set; } + [MaxLength(450)] + public string UserId { get; set; } = ""; + [MaxLength(32)] + public string Pack { get; set; } = ""; + [MaxLength(64)] + public string PlanId { get; set; } = ""; + [MaxLength(64)] + public string? PayPalId { get; set; } + [MaxLength(32)] + public string State { get; set; } = "CREATING"; + public decimal MonthlyPoints { get; set; } + [Column(TypeName = "numeric(18,2)")] + public decimal PriceExcludingTax { get; set; } + public decimal VatPercent { get; set; } + [Column(TypeName = "numeric(18,2)")] + public decimal PriceIncludingTax { get; set; } + public DateTimeOffset CreatedAt { get; set; } + public DateTimeOffset? StartsAt { get; set; } + public DateTimeOffset? NextBillingAt { get; set; } + public int LastCreditedCycle { get; set; } = -1; +} + +public sealed class ResourceSubscriptionPayment +{ + [MaxLength(64)] + public string Id { get; set; } = ""; + public Guid SubscriptionId { get; set; } + public int Cycle { get; set; } + public DateTimeOffset PaidAt { get; set; } + public decimal GrantedPoints { get; set; } + public bool Reversed { get; set; } +} diff --git a/src/Yavsc.Server/Models/ResourceUsageRecord.cs b/src/Yavsc.Server/Models/ResourceUsageRecord.cs index 4b8a8794d..784283272 100644 --- a/src/Yavsc.Server/Models/ResourceUsageRecord.cs +++ b/src/Yavsc.Server/Models/ResourceUsageRecord.cs @@ -23,6 +23,7 @@ public sealed class ResourceUsageRecord : ITrackedEntity public decimal CpuSeconds { get; set; } public decimal BandwidthMb { get; set; } public decimal StorageMb { get; set; } + public decimal CreditPoints { get; set; } public decimal EstimatedCompensation { get; set; } [Required] diff --git a/src/Yavsc.Server/Services/LiveProcessor.cs b/src/Yavsc.Server/Services/LiveProcessor.cs index 02bc5104d..1c84dea30 100644 --- a/src/Yavsc.Server/Services/LiveProcessor.cs +++ b/src/Yavsc.Server/Services/LiveProcessor.cs @@ -447,13 +447,18 @@ public sealed class LiveProcessor : ILiveProcessor, IDisposable var path = Path.Combine(destDir, Path.GetFileName(fileName)); var oldLength = File.Exists(path) ? new FileInfo(path).Length : 0; var usage = user.DiskUsage - oldLength; + if (usage >= user.GetEffectiveDiskQuota(_clock.GetUtcNow())) + { + await handler.Socket.CloseOutputAsync(WebSocketCloseStatus.PolicyViolation, "Available quota required.", ct); + return false; + } await using var file = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.Read); var buffer = new byte[Constants.WebSocketsMaxBufLen]; while (handler.Socket.State == WebSocketState.Open) { var received = await handler.Socket.ReceiveAsync(new ArraySegment(buffer), ct); if (received.MessageType == WebSocketMessageType.Close) break; - if (received.MessageType != WebSocketMessageType.Binary || usage + received.Count > user.DiskQuota) + if (received.MessageType != WebSocketMessageType.Binary || usage + received.Count > user.GetEffectiveDiskQuota(_clock.GetUtcNow())) { await handler.Socket.CloseOutputAsync(WebSocketCloseStatus.PolicyViolation, "Binary data and available quota required.", ct); return false; diff --git a/src/Yavsc.Server/Settings/ResourceSubscriptionOptions.cs b/src/Yavsc.Server/Settings/ResourceSubscriptionOptions.cs new file mode 100644 index 000000000..f17572cbe --- /dev/null +++ b/src/Yavsc.Server/Settings/ResourceSubscriptionOptions.cs @@ -0,0 +1,15 @@ +#nullable enable +namespace Yavsc.Settings; + +public sealed class ResourceSubscriptionOptions +{ + public const string SectionName = "ResourceSubscriptions"; + public string DiscoveryPlanId { get; set; } = ""; + public string PremiumPlanId { get; set; } = ""; + public string WebhookId { get; set; } = ""; + public decimal DiscoveryPriceExcludingTax { get; set; } = 1m; + public decimal PremiumPriceExcludingTax { get; set; } = 2m; + public decimal VatPercent { get; set; } = 20m; + + public decimal TotalPrice(decimal net) => decimal.Round(net * (1m + VatPercent / 100m), 2, MidpointRounding.AwayFromZero); +} diff --git a/src/Yavsc.Server/Settings/ResourceUsageOptions.cs b/src/Yavsc.Server/Settings/ResourceUsageOptions.cs new file mode 100644 index 000000000..2645e4cca --- /dev/null +++ b/src/Yavsc.Server/Settings/ResourceUsageOptions.cs @@ -0,0 +1,21 @@ +#nullable enable +namespace Yavsc.Settings; + +public sealed class ResourceUsageOptions +{ + public const string SectionName = "ResourceUsage"; + + public decimal ApiCallWeight { get; set; } = 0.2m; + public decimal CpuSecondWeight { get; set; } = 0.1m; + public decimal BandwidthMbWeight { get; set; } = 0.05m; + public decimal StorageMbWeight { get; set; } = 0.5m; + public decimal DefaultLimit { get; set; } = 1000m; + public Dictionary UserLimits { get; set; } = new(); + + public decimal GetLimit(string userId) + => UserLimits.TryGetValue(userId, out var limit) ? limit : DefaultLimit; + + public decimal Calculate(decimal apiCalls, decimal cpuSeconds, decimal bandwidthMb, decimal storageMb) + => apiCalls * ApiCallWeight + cpuSeconds * CpuSecondWeight + + bandwidthMb * BandwidthMbWeight + storageMb * StorageMbWeight; +} diff --git a/src/test/Yavsc.Api.Tests/Fixtures/ApiWebServerFixture.cs b/src/test/Yavsc.Api.Tests/Fixtures/ApiWebServerFixture.cs index 30815c4ec..c6dcd21d9 100644 --- a/src/test/Yavsc.Api.Tests/Fixtures/ApiWebServerFixture.cs +++ b/src/test/Yavsc.Api.Tests/Fixtures/ApiWebServerFixture.cs @@ -21,6 +21,7 @@ using Yavsc.Interface; using Yavsc.Server.Hubs; using Microsoft.AspNetCore.Identity; using Yavsc.Api.Services; +using Yavsc.Server.Helpers; namespace Yavsc.Api.Test.Fixtures; @@ -39,6 +40,7 @@ public sealed class ApiWebServerFixture : WebHostFixture protected override WebApplication BuildApp(WebApplicationBuilder builder) { + builder.Services.AddResourceUsage(builder.Configuration); if (UseNpgsqlProvider()) { var npgsqlConnectionString = EnsureNpgsqlDatabaseCreated(); @@ -76,7 +78,7 @@ public sealed class ApiWebServerFixture : WebHostFixture builder.Services.AddPodcasts(builder.Configuration); builder.Services.Configure(options => options.RootPath = podcastRoot); builder.Services.Configure(_ => { }); - builder.Services.Configure(settings => settings.Authority = "example.test"); + builder.Services.Configure(settings => settings.Authority = "https://example.test"); builder.Services.AddTransient(); builder.Services.AddInvoicing(builder.Configuration); builder.Services.AddSingleton(); @@ -130,6 +132,7 @@ public sealed class ApiWebServerFixture : WebHostFixture app.UseRouting(); app.UseAuthentication(); app.UseAuthorization(); + app.UseMiddleware(); app.MapControllers(); app.MapOpenApi().RequireAuthorization("AdministratorOnly"); diff --git a/src/test/Yavsc.Api.Tests/LiveProcessorTests.cs b/src/test/Yavsc.Api.Tests/LiveProcessorTests.cs index 53b18da8c..85249f13e 100644 --- a/src/test/Yavsc.Api.Tests/LiveProcessorTests.cs +++ b/src/test/Yavsc.Api.Tests/LiveProcessorTests.cs @@ -217,6 +217,29 @@ public sealed class LiveProcessorTests : IDisposable if (Directory.Exists(_root)) Directory.Delete(_root, recursive: true); } + [Theory] + [InlineData(true)] + [InlineData(false)] + public async Task Legacy_stream_uses_paid_premium_quota_and_refuses_growth_after_expiry(bool paid) + { + var clock = new Clock(); + var processor = New(clock: clock); + Directory.CreateDirectory(_root); + var path = Path.Combine(_root, "disk.ts"); + await File.WriteAllBytesAsync(path, new byte[] { 9 }, _ct); + using var socket = new IncomingSocket(new byte[] { 1, 2, 3 }); + var context = new DefaultHttpContext(); + context.Features.Set(socket); + var user = new ApplicationUser + { + UserName = "legacy", DiskQuota = 10, DiskUsage = 100, + PremiumDiskQuotaUntil = clock.Now.AddSeconds(paid ? 1 : -1) + }; + Assert.Equal(paid, await processor.AcceptStream(context, user, _root, "disk.ts")); + Assert.Equal(paid ? new byte[] { 1, 2, 3 } : new byte[] { 9 }, await File.ReadAllBytesAsync(path, _ct)); + Assert.Empty(processor.Casters); + } + private sealed class Clock : TimeProvider { public DateTimeOffset Now { get; set; } = DateTimeOffset.UtcNow; diff --git a/src/test/Yavsc.Api.Tests/ResourceUsageApiControllerTests.cs b/src/test/Yavsc.Api.Tests/ResourceUsageApiControllerTests.cs index 836ab7929..694b8f624 100644 --- a/src/test/Yavsc.Api.Tests/ResourceUsageApiControllerTests.cs +++ b/src/test/Yavsc.Api.Tests/ResourceUsageApiControllerTests.cs @@ -40,6 +40,36 @@ public sealed class ResourceUsageApiControllerTests : IClassFixture(); + var user = new Yavsc.Models.ApplicationUser + { + Id = userId, UserName = userId, NormalizedUserName = userId.ToUpperInvariant(), + Email = $"{userId}@example.test", DiskQuota = 1234L, + PremiumDiskQuotaUntil = premium ? DateTimeOffset.UtcNow.AddDays(1) : null, + DiscoveryDiskQuotaUntil = premium ? null : DateTimeOffset.UtcNow.AddDays(1) + }; + db.Users.Add(user); + await db.SaveChangesAsync(ct); + using var http = NewClient(_fixture, userId); + var profile = await http.GetFromJsonAsync("/api/v1/account/me", ct); + Assert.NotNull(profile); + Assert.Equal(Yavsc.Constants.DefaultFSQ * multiplier, profile.DiskQuota); + user.PremiumDiskQuotaUntil = DateTimeOffset.UtcNow.AddSeconds(-1); + user.DiscoveryDiskQuotaUntil = DateTimeOffset.UtcNow.AddSeconds(-1); + await db.SaveChangesAsync(ct); + profile = await http.GetFromJsonAsync("/api/v1/account/me", ct); + Assert.NotNull(profile); + Assert.Equal(1234L, profile.DiskQuota); + } + [Fact] public async Task GetCurrentUserUsage_persists_snapshot_in_database() { @@ -100,9 +130,9 @@ public sealed class ResourceUsageApiControllerTests : IClassFixture(); var record = await db.ResourceUsageRecords - .SingleAsync(r => r.UserId == "telemetry-user"); + .SingleAsync(r => r.UserId == "quota-consultation-user"); - Assert.True(record.ApiCalls >= 1m); - Assert.True(record.BandwidthMb > 0m); + Assert.Equal(0m, record.ApiCalls); + Assert.Equal(0m, record.BandwidthMb); + } + + [Fact] + public async Task Exhausted_quota_blocks_operations_but_not_usage_consultation() + { + using var scope = _fixture.Services.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + await ResourceUsageTracker.RecordAsync(db, "exhausted-quota-user", "exhausted-quota-user", cpuSeconds: 10000m); + using var http = NewClient(_fixture, "exhausted-quota-user"); + + var refused = await http.GetAsync("/api/v1/notifications/me", TestContext.Current.CancellationToken); + Assert.Equal(HttpStatusCode.TooManyRequests, refused.StatusCode); + Assert.Equal("application/problem+json", refused.Content.Headers.ContentType?.MediaType); + Assert.Contains("resource_quota_exceeded", + await refused.Content.ReadAsStringAsync(TestContext.Current.CancellationToken)); + + var consulted = await http.GetAsync("/api/v1/resource-usage/me", TestContext.Current.CancellationToken); + Assert.Equal(HttpStatusCode.OK, consulted.StatusCode); + var summary = await consulted.Content.ReadFromJsonAsync(TestContext.Current.CancellationToken); + Assert.NotNull(summary); + Assert.Equal(1000m, summary.Consumption); + Assert.Equal(1000m, summary.ConsumptionLimit); + Assert.Equal(0m, summary.RemainingConsumption); + Assert.True(summary.IsQuotaReached); + Assert.Equal(0m, summary.ApiCalls); } [Fact] diff --git a/src/test/Yavsc.Blogs.Tests/FileSystemApiTests.cs b/src/test/Yavsc.Blogs.Tests/FileSystemApiTests.cs index 569e4af3d..0b7d2a9b9 100644 --- a/src/test/Yavsc.Blogs.Tests/FileSystemApiTests.cs +++ b/src/test/Yavsc.Blogs.Tests/FileSystemApiTests.cs @@ -10,6 +10,7 @@ using Yavsc.Models.Blog; using Yavsc.Models.Relationship; using Yavsc.Models.Workflow; using Yavsc.Tests.Shared; +using Yavsc.Server.Helpers; namespace Yavsc.Blogs.Tests; @@ -135,6 +136,35 @@ public sealed class FileSystemApiTests : IClassFixture "Expected the uploaded file on disk under the owner's personal root"); } + [Fact] + public async Task Upload_is_refused_before_writing_when_known_storage_would_exceed_quota() + { + _fixture.ResetDatabase(); + _fixture.SeedUser("storage-quota-user", u => u.DiskQuota = 10_000_000); + using (var scope = _fixture.Services.CreateScope()) + await ResourceUsageTracker.RecordAsync( + scope.ServiceProvider.GetRequiredService(), + "storage-quota-user", "storage-quota-user", cpuSeconds: 9999.8m, + cancellationToken: TestContext.Current.CancellationToken); + + const string fileName = "quota-refused-file.txt"; + using var form = new MultipartFormDataContent(); + form.Add(new ByteArrayContent(new byte[1048576]), "file", fileName); + using var http = NewClient("storage-quota-user"); + using var response = await http.PostAsync("/api/v1/fs", form, TestContext.Current.CancellationToken); + Assert.Equal(HttpStatusCode.TooManyRequests, response.StatusCode); + Assert.Contains("resource_quota_exceeded", + await response.Content.ReadAsStringAsync(TestContext.Current.CancellationToken)); + Assert.False(File.Exists(PhysicalFile(_fixture, "storage-quota-user", fileName))); + using var finalScope = _fixture.Services.CreateScope(); + var db = finalScope.ServiceProvider.GetRequiredService(); + Assert.Empty(db.UploadedFiles.Where(f => f.OwnerId == "storage-quota-user")); + var record = await db.ResourceUsageRecords.SingleAsync( + r => r.UserId == "storage-quota-user", TestContext.Current.CancellationToken); + Assert.Equal(0m, record.ApiCalls); + Assert.Equal(0m, record.StorageMb); + } + /// /// Regression for the "Mes fichiers" page listing nothing: the /// personal-storage tree is keyed by the user's login diff --git a/src/test/Yavsc.Blogs.Tests/FilterFileNameTests.cs b/src/test/Yavsc.Blogs.Tests/FilterFileNameTests.cs index d445c29e4..c97338781 100644 --- a/src/test/Yavsc.Blogs.Tests/FilterFileNameTests.cs +++ b/src/test/Yavsc.Blogs.Tests/FilterFileNameTests.cs @@ -27,6 +27,45 @@ public sealed class FilterFileNameTests Assert.Equal(filtered, AbstractFileSystemHelpers.FilterFileName(filtered)); } + [Theory] + [InlineData(true, 5)] + [InlineData(false, 2)] + public void Paid_upload_accepts_exact_effective_quota_and_refuses_overflow_without_touching_files(bool premium, long multiplier) + { + var root = Path.Combine(Path.GetTempPath(), $"yavsc-disk-{Guid.NewGuid():N}"); + Directory.CreateDirectory(root); + try + { + var limit = Yavsc.Constants.DefaultFSQ * multiplier; + var user = new ApplicationUser + { + DiskQuota = 10L, DiskUsage = limit - 3, + PremiumDiskQuotaUntil = premium ? DateTimeOffset.UtcNow.AddDays(1) : null, + DiscoveryDiskQuotaUntil = premium ? null : DateTimeOffset.UtcNow.AddDays(1) + }; + using var input = new MemoryStream(new byte[] { 1, 2, 3 }); + var received = user.ReceiveUserFile(root, new FormFile(input, 0, 3, "file", "disk.bin") + { + Headers = new HeaderDictionary(), ContentType = "application/octet-stream" + }); + Assert.False(received.QuotaOffense); + Assert.Equal(limit, user.DiskUsage); + using var extra = new MemoryStream(new byte[] { 4 }); + Assert.True(user.ReceiveUserFile(root, new FormFile(extra, 0, 1, "file", "extra.bin")).QuotaOffense); + Assert.False(File.Exists(Path.Combine(root, "extra.bin"))); + user.PremiumDiskQuotaUntil = DateTimeOffset.UtcNow.AddSeconds(-1); + user.DiscoveryDiskQuotaUntil = DateTimeOffset.UtcNow.AddSeconds(-1); + using var replacement = new MemoryStream(new byte[] { 5 }); + Assert.True(user.ReceiveUserFile(root, new FormFile(replacement, 0, 1, "file", "disk.bin")).QuotaOffense); + Assert.Equal(new byte[] { 1, 2, 3 }, File.ReadAllBytes(Path.Combine(root, "disk.bin"))); + Assert.Equal(limit, user.DiskUsage); + } + finally + { + Directory.Delete(root, recursive: true); + } + } + [Fact] public async Task Uploaded_accented_filename_is_accessible_through_static_files() { diff --git a/src/test/Yavsc.Blogs.Tests/Fixtures/BlogsWebServerFixture.cs b/src/test/Yavsc.Blogs.Tests/Fixtures/BlogsWebServerFixture.cs index 1e0dd81f7..7153c07eb 100644 --- a/src/test/Yavsc.Blogs.Tests/Fixtures/BlogsWebServerFixture.cs +++ b/src/test/Yavsc.Blogs.Tests/Fixtures/BlogsWebServerFixture.cs @@ -10,6 +10,7 @@ using Yavsc.Models.Blog; using Yavsc.Models.Relationship; using Yavsc.Services; using Yavsc.Tests.Shared; +using Yavsc.Server.Helpers; using static Yavsc.Constants; namespace Yavsc.Blogs.Tests; @@ -85,6 +86,7 @@ public sealed class BlogsWebServerFixture : WebHostFixture protected override WebApplication BuildApp(WebApplicationBuilder builder) { + builder.Services.AddResourceUsage(builder.Configuration); // Open the shared in-memory connection lazily on the first // fixture construction. Subsequent constructions (xUnit // creates one fixture instance per IClassFixture) reuse @@ -132,6 +134,7 @@ public sealed class BlogsWebServerFixture : WebHostFixture builder.Services.Configure(s => { s.UserFilesRoot = BlogFilesRoot; + s.Authority = "https://example.test"; }); // Real BlogSpotService — same instance the production host diff --git a/src/test/Yavsc.Org.Tests/Controllers/ResourceSubscriptionControllerTests.cs b/src/test/Yavsc.Org.Tests/Controllers/ResourceSubscriptionControllerTests.cs new file mode 100644 index 000000000..d1433d2a4 --- /dev/null +++ b/src/test/Yavsc.Org.Tests/Controllers/ResourceSubscriptionControllerTests.cs @@ -0,0 +1,248 @@ +using System.Net; +using System.Net.Http.Json; +using System.Text.Json; +using System.Text.RegularExpressions; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.TestHost; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Options; +using Yavsc.Models; +using Yavsc.Models.Payment; +using Yavsc.Server.Helpers; +using Yavsc.Settings; +using Yavsc.Web.Services; +using Xunit; + +namespace Yavsc.Org.Tests.Controllers; + +public sealed class ResourceSubscriptionControllerTests : IClassFixture +{ + private readonly Factory _factory; + private static CancellationToken Ct => TestContext.Current.CancellationToken; + + public ResourceSubscriptionControllerTests(Factory factory) + { + _factory = factory; + factory.PayPal.Payments.Clear(); + factory.PayPal.Verified = true; + factory.PayPal.CancelCount = 0; + using var scope = factory.Services.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + db.ResourceSubscriptionPayments.RemoveRange(db.ResourceSubscriptionPayments); + db.ResourceSubscriptions.RemoveRange(db.ResourceSubscriptions); + db.ResourceUsageRecords.RemoveRange(db.ResourceUsageRecords); + if (!db.Users.Any(u => u.Id == "listener")) + db.Users.Add(new ApplicationUser { Id = "listener", UserName = "Listener", Email = "listener@example.test" }); + if (!db.Users.Any(u => u.Id == "author")) + db.Users.Add(new ApplicationUser { Id = "author", UserName = "Author", Email = "author@example.test" }); + db.SaveChanges(); + } + + [Fact] + public async Task Subscription_management_requires_login_and_all_mutations_require_antiforgery() + { + using var anonymous = _factory.CreateClient(new() { AllowAutoRedirect = false }); + using var page = await anonymous.GetAsync("/ResourceSubscription", Ct); + Assert.Equal(HttpStatusCode.Redirect, page.StatusCode); + using var client = _factory.SignedInClient(); + using var create = await client.PostAsync("/ResourceSubscription/Create", new FormUrlEncodedContent( + new Dictionary { ["pack"] = "Discovery" }), Ct); + Assert.Equal(HttpStatusCode.BadRequest, create.StatusCode); + } + + [Fact] + public async Task Exhausted_free_usage_can_still_subscribe_and_browser_return_does_not_award_unpaid_credit() + { + using (var scope = _factory.Services.CreateScope()) + await ResourceUsageTracker.RecordAsync(scope.ServiceProvider.GetRequiredService(), + "listener", "Listener", cpuSeconds: 12000m, cancellationToken: Ct); + using var client = _factory.SignedInClient(); + var html = await client.GetStringAsync("/ResourceSubscription", Ct); + Assert.Contains("1200", html); + Assert.Contains("Premium", html); + var subscription = await StartAsync(client); + Assert.Equal("listener", subscription.UserId); + Assert.Equal(1000m, subscription.MonthlyPoints); + Assert.Equal(1.2m, subscription.PriceIncludingTax); + using var returned = await client.GetAsync($"/ResourceSubscription/Return?id={subscription.Id}", Ct); + Assert.Equal(HttpStatusCode.Redirect, returned.StatusCode); + var usage = await UsageAsync(); + Assert.Equal(1200m, usage.Consumption); + Assert.True(usage.IsQuotaReached); + } + + [Fact] + public async Task Verified_notification_reconciles_payment_once_and_unblocks_without_a_browser_return() + { + using (var scope = _factory.Services.CreateScope()) + await ResourceUsageTracker.RecordAsync(scope.ServiceProvider.GetRequiredService(), + "listener", "Listener", cpuSeconds: 12000m, cancellationToken: Ct); + using var client = _factory.SignedInClient(); + var subscription = await StartAsync(client); + _factory.PayPal.Payments.Add(new("PAY-1", "COMPLETED", 1.2m, "EUR", subscription.CreatedAt)); + using var first = await NotifyAsync(subscription.PayPalId!); + using var repeated = await NotifyAsync(subscription.PayPalId!); + Assert.Equal(HttpStatusCode.NoContent, first.StatusCode); + Assert.Equal(HttpStatusCode.NoContent, repeated.StatusCode); + var usage = await UsageAsync(); + Assert.Equal(200m, usage.Consumption); + Assert.False(usage.IsQuotaReached); + using var verificationScope = _factory.Services.CreateScope(); + Assert.Single(verificationScope.ServiceProvider.GetRequiredService().ResourceSubscriptionPayments); + } + + [Fact] + public async Task Premium_checkout_uses_three_quotas_and_its_own_vat_inclusive_price() + { + using var client = _factory.SignedInClient(); + using var response = await PostAsync(client, "/ResourceSubscription/Create", new() { ["pack"] = "Premium" }); + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + using var scope = _factory.Services.CreateScope(); + var subscription = await scope.ServiceProvider.GetRequiredService().ResourceSubscriptions.SingleAsync(Ct); + Assert.Equal("P-PREMIUM", subscription.PlanId); + Assert.Equal(3000m, subscription.MonthlyPoints); + Assert.Equal(2.4m, subscription.PriceIncludingTax); + } + + [Theory] + [InlineData("[]")] + [InlineData("""{"event_type":"PAYMENT.SALE.COMPLETED","resource":[]}""")] + [InlineData("""{"event_type":"PAYMENT.SALE.REFUNDED","resource":{"sale_id":42}}""")] + [InlineData("""{"event_type":"PAYMENT.SALE.REFUNDED","resource":{"links":{}}}""")] + [InlineData("""{"event_type":"PAYMENT.SALE.REFUNDED","resource":{"links":[{"href":42}]}}""")] + public async Task Malformed_notification_shapes_are_rejected_without_credit(string json) + { + using var client = _factory.CreateClient(); + using var response = await client.PostAsync("/ResourceSubscription/Notify", + new StringContent(json, System.Text.Encoding.UTF8, "application/json"), Ct); + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + Assert.Equal(0m, (await UsageAsync()).CreditBalance); + } + + [Fact] + public async Task Forged_notification_does_not_reconcile_or_grant_a_credit() + { + using var client = _factory.SignedInClient(); + var subscription = await StartAsync(client); + _factory.PayPal.Payments.Add(new("PAY-1", "COMPLETED", 1.2m, "EUR", subscription.CreatedAt)); + _factory.PayPal.Verified = false; + using var notified = await NotifyAsync(subscription.PayPalId!); + Assert.Equal(HttpStatusCode.BadRequest, notified.StatusCode); + Assert.Equal(0m, (await UsageAsync()).CreditBalance); + } + + [Fact] + public async Task Cancellation_is_owned_post_only_and_retains_acquired_credit() + { + using var client = _factory.SignedInClient(); + var subscription = await StartAsync(client); + _factory.PayPal.Payments.Add(new("PAY-1", "COMPLETED", 1.2m, "EUR", subscription.CreatedAt)); + using var notified = await NotifyAsync(subscription.PayPalId!); + Assert.Equal(HttpStatusCode.NoContent, notified.StatusCode); + using var other = _factory.SignedInClient("author"); + using var refused = await PostAsync(other, "/ResourceSubscription/Cancel", new() { ["id"] = subscription.Id.ToString() }); + Assert.Equal(HttpStatusCode.NotFound, refused.StatusCode); + Assert.Equal(0, _factory.PayPal.CancelCount); + using var get = await client.GetAsync($"/ResourceSubscription/Cancel?id={subscription.Id}", Ct); + Assert.NotEqual(HttpStatusCode.OK, get.StatusCode); + using var cancelled = await PostAsync(client, "/ResourceSubscription/Cancel", new() { ["id"] = subscription.Id.ToString() }); + Assert.Equal(HttpStatusCode.Redirect, cancelled.StatusCode); + Assert.Equal(1, _factory.PayPal.CancelCount); + Assert.Equal(666.66666666m, (await UsageAsync()).CreditBalance); + } + + [Fact] + public async Task Refund_notification_finds_the_original_receipt_and_removes_its_credit() + { + using var client = _factory.SignedInClient(); + var subscription = await StartAsync(client); + _factory.PayPal.Payments.Add(new("PAY-1", "COMPLETED", 1.2m, "EUR", subscription.CreatedAt)); + using var first = await NotifyAsync(subscription.PayPalId!); + Assert.Equal(HttpStatusCode.NoContent, first.StatusCode); + _factory.PayPal.Payments[0] = _factory.PayPal.Payments[0] with { State = "REFUNDED" }; + using var notificationClient = _factory.CreateClient(); + using var refund = await notificationClient.PostAsJsonAsync("/ResourceSubscription/Notify", + new { event_type = "PAYMENT.SALE.REFUNDED", resource = new { sale_id = "PAY-1", id = "REFUND-1" } }, Ct); + Assert.Equal(HttpStatusCode.NoContent, refund.StatusCode); + Assert.Equal(0m, (await UsageAsync()).CreditBalance); + } + + private async Task StartAsync(HttpClient client) + { + using var response = await PostAsync(client, "/ResourceSubscription/Create", new() + { + ["pack"] = "Discovery", ["UserId"] = "author", ["Amount"] = "0.01", ["MonthlyPoints"] = "999999" + }); + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.StartsWith("https://www.sandbox.paypal.com/", response.Headers.Location?.ToString()); + using var scope = _factory.Services.CreateScope(); + return await scope.ServiceProvider.GetRequiredService().ResourceSubscriptions.AsNoTracking().SingleAsync(Ct); + } + + private static async Task PostAsync(HttpClient client, string action, Dictionary fields) + { + var html = await client.GetStringAsync("/ResourceSubscription", Ct); + var match = Regex.Match(html, "name=\"__RequestVerificationToken\"[^>]*value=\"([^\"]+)\""); + Assert.True(match.Success); + fields["__RequestVerificationToken"] = WebUtility.HtmlDecode(match.Groups[1].Value); + return await client.PostAsync(action, new FormUrlEncodedContent(fields), Ct); + } + + private async Task UsageAsync() + { + using var scope = _factory.Services.CreateScope(); + return await scope.ServiceProvider.GetRequiredService().GetCurrentAsync("listener", "Listener", Ct); + } + + private async Task NotifyAsync(string paypalId) + { + using var client = _factory.CreateClient(); + return await client.PostAsJsonAsync("/ResourceSubscription/Notify", + new { event_type = "PAYMENT.SALE.COMPLETED", resource = new { billing_agreement_id = paypalId } }, Ct); + } + + public sealed class Factory : PodcastWebTests.Factory + { + public Gateway PayPal { get; } = new(); + protected override void ConfigureWebHost(IWebHostBuilder builder) + { + base.ConfigureWebHost(builder); + builder.ConfigureTestServices(services => + { + services.AddSingleton(PayPal); + services.Configure(o => + { + o.DiscoveryPlanId = "P-DISCOVERY"; + o.PremiumPlanId = "P-PREMIUM"; + o.WebhookId = "WH-TEST"; + }); + }); + } + } + + public sealed class Gateway : IPayPalSubscriptionGateway + { + public bool Verified { get; set; } = true; + public int CancelCount { get; set; } + public List Payments { get; } = []; + private PayPalSubscriptionDetails _remote = null!; + public Task CreateAsync(ResourceSubscription subscription, string returnUrl, string cancelUrl, CancellationToken ct) + { + _remote = new("I-TEST", subscription.Id.ToString("N"), subscription.PlanId, "APPROVAL_PENDING", + subscription.CreatedAt, subscription.CreatedAt.AddMonths(1), "https://www.sandbox.paypal.com/approve"); + return Task.FromResult(_remote); + } + public Task GetAsync(string id, CancellationToken ct) => Task.FromResult(_remote); + public Task> TransactionsAsync(string id, DateTimeOffset from, DateTimeOffset to, CancellationToken ct) + => Task.FromResult>(Payments.ToArray()); + public Task CancelAsync(string id, CancellationToken ct) + { + CancelCount++; + _remote = _remote with { State = "CANCELLED", NextBillingAt = null }; + return Task.CompletedTask; + } + public Task VerifyWebhookAsync(JsonElement notification, IReadOnlyDictionary headers, CancellationToken ct) + => Verified ? Task.CompletedTask : throw new SubscriptionOperationException(400, "Signature invalide."); + } +} diff --git a/src/test/Yavsc.Org.Tests/Controllers/ResourceUsageTermsTests.cs b/src/test/Yavsc.Org.Tests/Controllers/ResourceUsageTermsTests.cs new file mode 100644 index 000000000..6064294ed --- /dev/null +++ b/src/test/Yavsc.Org.Tests/Controllers/ResourceUsageTermsTests.cs @@ -0,0 +1,30 @@ +using System.Net; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Options; +using Yavsc.Settings; +using Xunit; + +namespace Yavsc.Org.Tests.Controllers; + +public sealed class ResourceUsageTermsTests +{ + [Fact] + public async Task Public_terms_describe_the_configured_rule_and_are_linked_from_the_footer() + { + using var factory = new TestWebApplicationFactory(); + var options = factory.Services.GetRequiredService>().Value; + options.DefaultLimit = 12345m; + using var client = factory.CreateClient(); + using var response = await client.GetAsync("/Home/CGU", TestContext.Current.CancellationToken); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + var html = await response.Content.ReadAsStringAsync(TestContext.Current.CancellationToken); + Assert.Contains("12345", html); + Assert.Contains("resource_quota_exceeded", html); + Assert.Contains("I =", html); + Assert.Contains("Home/CGU", html); + Assert.Contains((Yavsc.Constants.DefaultFSQ * 5L).ToString(), html); + Assert.Contains((Yavsc.Constants.DefaultFSQ * 2L).ToString(), html); + Assert.Contains("quota disque", html); + Assert.Contains("Découverte porte le quota disque", html); + } +} diff --git a/src/test/Yavsc.Server.Tests/PayPalSubscriptionGatewayTests.cs b/src/test/Yavsc.Server.Tests/PayPalSubscriptionGatewayTests.cs new file mode 100644 index 000000000..956773020 --- /dev/null +++ b/src/test/Yavsc.Server.Tests/PayPalSubscriptionGatewayTests.cs @@ -0,0 +1,208 @@ +using System.Net; +using System.Net.Http.Json; +using System.Text.Json; +using Microsoft.Extensions.Options; +using Yavsc.Models.Payment; +using Yavsc.Settings; +using Yavsc.Web.Services; + +namespace Yavsc.Server.Tests; + +public sealed class PayPalSubscriptionGatewayTests +{ + private static CancellationToken Ct => TestContext.Current.CancellationToken; + private sealed class Handler : HttpMessageHandler + { + public string PlanCurrency { get; set; } = "EUR"; + public string PlanPrice { get; set; } = "1.20"; + public string Frequency { get; set; } = "MONTH"; + public bool AutoBillOutstanding { get; set; } + public string? RawResponse { get; set; } + public string Verification { get; set; } = "SUCCESS"; + public string ApprovalUrl { get; set; } = "https://www.sandbox.paypal.com/webapps/billing/subscriptions?ba_token=test"; + public string CustomId { get; set; } = ""; + public HttpStatusCode Status { get; set; } = HttpStatusCode.OK; + public List<(string Path, string Body, string? RequestId, string Host)> Requests { get; } = []; + + protected override async Task SendAsync(HttpRequestMessage request, CancellationToken ct) + { + var path = request.RequestUri!.AbsolutePath; + var body = request.Content is null ? "" : await request.Content.ReadAsStringAsync(ct); + Requests.Add((path, body, request.Headers.TryGetValues("PayPal-Request-Id", out var ids) ? ids.Single() : null, request.RequestUri.Host)); + if (Status != HttpStatusCode.OK) return new(Status) { Content = new StringContent("unavailable") }; + if (RawResponse is not null && path != "/v1/oauth2/token") + return new(HttpStatusCode.OK) { Content = new StringContent(RawResponse) }; + object response = path switch + { + "/v1/oauth2/token" => new { access_token = "synthetic-token" }, + "/v1/billing/plans/P-DISCOVERY" => new + { + id = "P-DISCOVERY", status = "ACTIVE", + billing_cycles = new[] { new + { + tenure_type = "REGULAR", total_cycles = 0, + frequency = new { interval_unit = Frequency, interval_count = 1 }, + pricing_scheme = new { fixed_price = new { currency_code = PlanCurrency, value = PlanPrice } } + }}, + payment_preferences = new { auto_bill_outstanding = AutoBillOutstanding, setup_fee = new { value = "0" } } + }, + "/v1/notifications/verify-webhook-signature" => new { verification_status = Verification }, + "/v1/billing/subscriptions/I-TEST/transactions" => new + { + transactions = new[] { new + { + id = "PAY-1", status = "COMPLETED", time = "2026-01-31T12:00:00Z", + amount_with_breakdown = new { gross_amount = new { value = "1.20", currency_code = "EUR" } } + }} + }, + _ => new + { + id = "I-TEST", custom_id = CustomId, plan_id = "P-DISCOVERY", status = "APPROVAL_PENDING", + start_time = "2026-01-31T12:00:00Z", + links = new[] { new { rel = "approve", href = ApprovalUrl } } + } + }; + return new(HttpStatusCode.OK) { Content = JsonContent.Create(response) }; + } + } + + private static PayPalSubscriptionGateway Gateway(HttpClient http, string mode = "sandbox") + => new(http, Options.Create(new PayPalSettings { Mode = mode, ClientId = "test-client", ClientSecret = "test-secret" }), + Options.Create(new ResourceSubscriptionOptions { WebhookId = "test-webhook" })); + + private static ResourceSubscription Subscription() => new() + { + Id = Guid.NewGuid(), UserId = "alice", Pack = "Discovery", PlanId = "P-DISCOVERY", + PriceExcludingTax = 1m, PriceIncludingTax = 1.2m + }; + + [Theory] + [InlineData("sandbox", "api-m.sandbox.paypal.com")] + [InlineData("production", "api-m.paypal.com")] + public async Task Creation_checks_monthly_ttc_plan_and_uses_local_idempotency_reference(string mode, string host) + { + var subscription = Subscription(); + using var handler = new Handler { CustomId = subscription.Id.ToString("N") }; + using var http = new HttpClient(handler); + var result = await Gateway(http, mode).CreateAsync(subscription, "https://site.example/return", "https://site.example/cancel", Ct); + Assert.Equal("I-TEST", result.Id); + var creation = Assert.Single(handler.Requests.Where(r => r.Path == "/v1/billing/subscriptions")); + Assert.Equal(subscription.Id.ToString("N"), creation.RequestId); + Assert.Contains(subscription.Id.ToString("N"), creation.Body); + Assert.Contains("P-DISCOVERY", creation.Body); + Assert.Contains("SUBSCRIBE_NOW", creation.Body); + Assert.All(handler.Requests, r => Assert.Equal(host, r.Host)); + } + + [Theory] + [InlineData("EUR", "1.00", "MONTH")] + [InlineData("USD", "1.20", "MONTH")] + [InlineData("EUR", "1.20", "YEAR")] + public async Task Wrong_plan_price_currency_or_period_is_refused_before_checkout(string currency, string price, string period) + { + using var handler = new Handler { PlanCurrency = currency, PlanPrice = price, Frequency = period }; + using var http = new HttpClient(handler); + var error = await Assert.ThrowsAsync(() => + Gateway(http).CreateAsync(Subscription(), "https://site.example/return", "https://site.example/cancel", Ct)); + Assert.Equal(503, error.StatusCode); + Assert.DoesNotContain(handler.Requests, r => r.Path == "/v1/billing/subscriptions"); + } + + [Fact] + public async Task Automatic_collection_of_outstanding_payments_is_refused_before_checkout() + { + using var handler = new Handler { AutoBillOutstanding = true }; + using var http = new HttpClient(handler); + var error = await Assert.ThrowsAsync(() => + Gateway(http).CreateAsync(Subscription(), "https://site.example/return", "https://site.example/cancel", Ct)); + Assert.Equal(503, error.StatusCode); + Assert.DoesNotContain(handler.Requests, r => r.Path == "/v1/billing/subscriptions"); + } + + [Theory] + [InlineData("""[]""")] + [InlineData("""{"id":"I-TEST","links":{}}""")] + [InlineData("""{"id":"I-TEST","plan_overridden":"false"}""")] + [InlineData("""{"id":"I-TEST","billing_info":[]}""")] + [InlineData("""{"id":"I-TEST","links":[{"rel":"approve","href":"https://www.paypal.com/a"},{"rel":"approve","href":"https://www.paypal.com/b"}]}""")] + public async Task Malformed_subscription_shapes_are_explicit_upstream_errors(string response) + { + using var handler = new Handler { RawResponse = response }; + using var http = new HttpClient(handler); + var error = await Assert.ThrowsAsync(() => Gateway(http).GetAsync("I-TEST", Ct)); + Assert.Equal(502, error.StatusCode); + } + + [Theory] + [InlineData("""{"billing_cycles":{}}""")] + [InlineData("""{"id":"P-DISCOVERY","status":"ACTIVE","billing_cycles":[{"tenure_type":"REGULAR","total_cycles":"0","frequency":{"interval_unit":"MONTH","interval_count":1},"pricing_scheme":{"fixed_price":{"currency_code":"EUR","value":"1.20"}}}],"payment_preferences":{"auto_bill_outstanding":false}}""")] + public async Task Malformed_plan_shapes_are_explicit_upstream_errors(string response) + { + using var handler = new Handler { RawResponse = response }; + using var http = new HttpClient(handler); + var error = await Assert.ThrowsAsync(() => + Gateway(http).CreateAsync(Subscription(), "https://site.example/return", "https://site.example/cancel", Ct)); + Assert.Equal(502, error.StatusCode); + } + + [Fact] + public async Task Approval_redirect_cannot_point_to_an_untrusted_site() + { + using var handler = new Handler { ApprovalUrl = "https://attacker.example/" }; + using var http = new HttpClient(handler); + var error = await Assert.ThrowsAsync(() => Gateway(http).GetAsync("I-TEST", Ct)); + Assert.Equal(502, error.StatusCode); + } + + [Fact] + public async Task Webhook_verification_uses_the_configured_id_and_requires_paypal_success() + { + using var handler = new Handler { Verification = "FAILURE" }; + using var http = new HttpClient(handler); + using var notification = JsonDocument.Parse("""{"id":"WH-TEST","event_type":"PAYMENT.SALE.COMPLETED"}"""); + var headers = new Dictionary + { + ["PAYPAL-AUTH-ALGO"] = "SHA256withRSA", ["PAYPAL-CERT-URL"] = "https://api.paypal.com/cert", + ["PAYPAL-TRANSMISSION-ID"] = "test-transmission", ["PAYPAL-TRANSMISSION-SIG"] = "test-signature", + ["PAYPAL-TRANSMISSION-TIME"] = "2026-01-31T12:00:00Z" + }; + var error = await Assert.ThrowsAsync(() => + Gateway(http).VerifyWebhookAsync(notification.RootElement, headers, Ct)); + Assert.Equal(400, error.StatusCode); + var verification = Assert.Single(handler.Requests.Where(r => r.Path.EndsWith("verify-webhook-signature"))); + Assert.Contains("test-webhook", verification.Body); + Assert.Contains("test-signature", verification.Body); + handler.Verification = "SUCCESS"; + await Gateway(http).VerifyWebhookAsync(notification.RootElement, headers, Ct); + } + + [Fact] + public async Task Transaction_history_is_read_with_bounded_ranges_and_invariant_euro_amounts() + { + using var handler = new Handler(); + using var http = new HttpClient(handler); + var from = new DateTimeOffset(2026, 1, 31, 12, 0, 0, TimeSpan.Zero); + var payments = await Gateway(http).TransactionsAsync("I-TEST", from, from.AddDays(61), Ct); + Assert.Equal(3, handler.Requests.Count(r => r.Path.EndsWith("/transactions"))); + Assert.All(payments, p => Assert.Equal(1.2m, p.Amount)); + Assert.All(payments, p => Assert.Equal("EUR", p.Currency)); + } + + [Fact] + public async Task Http_failure_is_an_explicit_payment_failure_not_a_successful_subscription() + { + using var handler = new Handler { Status = HttpStatusCode.ServiceUnavailable }; + using var http = new HttpClient(handler); + var error = await Assert.ThrowsAsync(() => Gateway(http).GetAsync("I-TEST", Ct)); + Assert.Equal(502, error.StatusCode); + } + + [Fact] + public async Task Invalid_paypal_id_is_refused_without_network_access() + { + using var handler = new Handler(); + using var http = new HttpClient(handler); + await Assert.ThrowsAsync(() => Gateway(http).GetAsync("../other", Ct)); + Assert.Empty(handler.Requests); + } +} diff --git a/src/test/Yavsc.Server.Tests/ResourceSubscriptionTests.cs b/src/test/Yavsc.Server.Tests/ResourceSubscriptionTests.cs new file mode 100644 index 000000000..0539e301a --- /dev/null +++ b/src/test/Yavsc.Server.Tests/ResourceSubscriptionTests.cs @@ -0,0 +1,486 @@ +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Options; +using System.Text.Json; +using Yavsc.Models; +using Yavsc.Models.Payment; +using Yavsc.Server.Helpers; +using Yavsc.Settings; +using Yavsc.Web.Services; + +namespace Yavsc.Server.Tests; + +public sealed class ResourceSubscriptionTests +{ + private static readonly DateTimeOffset Start = new(2026, 1, 31, 12, 0, 0, TimeSpan.Zero); + private static CancellationToken Ct => TestContext.Current.CancellationToken; + + private sealed class Clock : TimeProvider + { + public DateTimeOffset Now { get; set; } = Start; + public override DateTimeOffset GetUtcNow() => Now; + } + + private sealed class Gateway : IPayPalSubscriptionGateway + { + public PayPalSubscriptionDetails Remote { get; set; } = null!; + public List Payments { get; } = []; + public Task GetAsync(string id, CancellationToken ct) => Task.FromResult(Remote); + public Task> TransactionsAsync(string id, DateTimeOffset from, DateTimeOffset to, CancellationToken ct) + => Task.FromResult>(Payments.ToArray()); + public Task CreateAsync(ResourceSubscription subscription, string returnUrl, string cancelUrl, CancellationToken ct) + => throw new NotSupportedException(); + public Task CancelAsync(string id, CancellationToken ct) => throw new NotSupportedException(); + public Task VerifyWebhookAsync(JsonElement notification, IReadOnlyDictionary headers, CancellationToken ct) + => throw new NotSupportedException(); + } + + private static ServiceProvider Provider(Clock clock, Gateway gateway, bool useBackendDefaults = false) + { + var name = Guid.NewGuid().ToString(); + var services = new ServiceCollection(); + services.AddDbContext(o => o.UseInMemoryDatabase(name)); + services.AddResourceUsage(new ConfigurationBuilder().Build()); + if (!useBackendDefaults) + services.Configure(o => + { + o.ApiCallWeight = 0.02m; + o.CpuSecondWeight = 1m; + o.BandwidthMbWeight = 0.1m; + o.StorageMbWeight = 0.3m; + o.DefaultLimit = 10000m; + }); + services.Configure(o => + { + o.DiscoveryPlanId = "P-DISCOVERY"; + o.PremiumPlanId = "P-PREMIUM"; + }); + services.AddSingleton(clock); + services.AddSingleton(gateway); + services.AddScoped(); + return services.BuildServiceProvider(); + } + + private static async Task BeginAsync(IServiceProvider services, Gateway gateway, string pack = "Discovery", decimal gross = 0m) + { + var db = services.GetRequiredService(); + db.Users.Add(new ApplicationUser { Id = "alice", UserName = "Alice", Email = "alice@example.test" }); + await db.SaveChangesAsync(Ct); + await ResourceUsageTracker.RecordAsync(db, "alice", "Alice", cpuSeconds: gross, cancellationToken: Ct); + var service = services.GetRequiredService(); + var subscription = await service.PrepareAsync("alice", pack, Ct); + gateway.Remote = new("I-TEST", subscription.Id.ToString("N"), subscription.PlanId, "ACTIVE", Start, Start.AddMonths(1), null); + await service.BindAsync(subscription, gateway.Remote, Ct); + return subscription; + } + + [Theory] + [InlineData(4000, 0, 10000, 8000)] + [InlineData(15000, 0, 10000, 10000)] + [InlineData(0, 0, 30000, 20000)] + [InlineData(4000, 5000, 30000, 20000)] + public void Monthly_credit_erases_usage_then_carries_two_thirds_of_unused_allowance( + decimal gross, decimal previous, decimal allowance, decimal grant) + => Assert.Equal(grant, ResourceUsageCredit.MonthlyGrant(gross, previous, allowance)); + + [Theory] + [InlineData("Premium", 2.4, 5)] + [InlineData("Discovery", 1.2, 2)] + public async Task Paid_disk_quota_uses_standard_reference_and_survives_cancellation_until_anniversary( + string pack, decimal amount, long multiplier) + { + var clock = new Clock(); + var gateway = new Gateway(); + using var provider = Provider(clock, gateway); + using var scope = provider.CreateScope(); + var subscription = await BeginAsync(scope.ServiceProvider, gateway, pack); + clock.Now = Start.AddMinutes(1); + var db = scope.ServiceProvider.GetRequiredService(); + var user = await db.Users.SingleAsync(Ct); + user.DiskQuota = 1234L; + user.DiskUsage = 5000L; + await db.SaveChangesAsync(Ct); + gateway.Payments.Add(new("PAY-DISK", "COMPLETED", amount, "EUR", Start)); + var service = scope.ServiceProvider.GetRequiredService(); + await service.ReconcileAsync(subscription, Ct); + Assert.Equal(Yavsc.Constants.DefaultFSQ * multiplier, user.GetEffectiveDiskQuota(clock.Now)); + Assert.Equal(Start.AddMonths(1), pack == "Premium" ? user.PremiumDiskQuotaUntil : user.DiscoveryDiskQuotaUntil); + var usage = await scope.ServiceProvider.GetRequiredService().GetCurrentAsync("alice", "Alice", Ct); + Assert.Equal(Yavsc.Constants.DefaultFSQ * multiplier, usage.DiskQuota); + Assert.Equal(user.PremiumDiskQuotaUntil, usage.PremiumDiskQuotaUntil); + Assert.Equal(user.DiscoveryDiskQuotaUntil, usage.DiscoveryDiskQuotaUntil); + gateway.Remote = gateway.Remote with { State = "CANCELLED", NextBillingAt = null }; + await service.ReconcileAsync(subscription, Ct); + Assert.Equal(Yavsc.Constants.DefaultFSQ * multiplier, user.GetEffectiveDiskQuota(Start.AddMonths(1).AddTicks(-1))); + Assert.Equal(1234L, user.GetEffectiveDiskQuota(Start.AddMonths(1))); + Assert.Equal(1234L, user.DiskQuota); + Assert.Equal(5000L, user.DiskUsage); + } + + [Theory] + [InlineData("Discovery", "PENDING", 1.2)] + [InlineData("Discovery", "FAILED", 1.2)] + [InlineData("Premium", "PENDING", 2.4)] + [InlineData("Premium", "FAILED", 2.4)] + public async Task Unpaid_subscriptions_do_not_grant_disk_bonus(string pack, string state, decimal amount) + { + var clock = new Clock(); + var gateway = new Gateway(); + using var provider = Provider(clock, gateway); + using var scope = provider.CreateScope(); + var subscription = await BeginAsync(scope.ServiceProvider, gateway, pack); + clock.Now = Start.AddMinutes(1); + gateway.Payments.Add(new("PAY-DISK", state, amount, "EUR", Start)); + await scope.ServiceProvider.GetRequiredService().ReconcileAsync(subscription, Ct); + var user = await scope.ServiceProvider.GetRequiredService().Users.SingleAsync(Ct); + Assert.Null(user.PremiumDiskQuotaUntil); + Assert.Null(user.DiscoveryDiskQuotaUntil); + Assert.Equal(user.DiskQuota, user.GetEffectiveDiskQuota(clock.Now)); + } + + [Theory] + [InlineData("Premium", 2.4)] + [InlineData("Discovery", 1.2)] + public async Task Refund_revokes_disk_bonus_but_not_another_paid_period(string pack, decimal amount) + { + var clock = new Clock(); + var gateway = new Gateway(); + using var provider = Provider(clock, gateway); + using var scope = provider.CreateScope(); + var subscription = await BeginAsync(scope.ServiceProvider, gateway, pack); + clock.Now = Start.AddMonths(1).AddMinutes(1); + gateway.Payments.Add(new("PAY-1", "COMPLETED", amount, "EUR", Start)); + gateway.Payments.Add(new("PAY-2", "COMPLETED", amount, "EUR", Start.AddMonths(1))); + var service = scope.ServiceProvider.GetRequiredService(); + await service.ReconcileAsync(subscription, Ct); + var user = await scope.ServiceProvider.GetRequiredService().Users.SingleAsync(Ct); + Assert.Equal(Start.AddMonths(2), pack == "Premium" ? user.PremiumDiskQuotaUntil : user.DiscoveryDiskQuotaUntil); + gateway.Payments[0] = gateway.Payments[0] with { State = "REFUNDED" }; + await service.ReconcileAsync(subscription, Ct); + Assert.Equal(Start.AddMonths(2), pack == "Premium" ? user.PremiumDiskQuotaUntil : user.DiscoveryDiskQuotaUntil); + gateway.Payments[1] = gateway.Payments[1] with { State = "PARTIALLY_REFUNDED" }; + await service.ReconcileAsync(subscription, Ct); + Assert.Null(user.PremiumDiskQuotaUntil); + Assert.Null(user.DiscoveryDiskQuotaUntil); + Assert.Equal(user.DiskQuota, user.GetEffectiveDiskQuota(clock.Now)); + } + + [Fact] + public async Task Cached_disk_tracker_refreshes_paid_entitlement_before_admission() + { + using var provider = Provider(new Clock(), new Gateway()); + using var scope = provider.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + db.Users.Add(new ApplicationUser + { + Id = "alice", UserName = "Alice", Email = "alice@example.test", DiskQuota = 10L, DiskUsage = 11L, + PremiumDiskQuotaUntil = DateTimeOffset.UtcNow.AddDays(1) + }); + await db.SaveChangesAsync(Ct); + var tracker = new DiskUsageTracker(Options.Create(new SiteSettings { DUUserListLen = 10 }), db); + Assert.False(tracker.GetSpace("Alice", Yavsc.Constants.DefaultFSQ * 5L)); + using var other = provider.CreateScope(); + var otherDb = other.ServiceProvider.GetRequiredService(); + var user = await otherDb.Users.SingleAsync(Ct); + user.PremiumDiskQuotaUntil = DateTimeOffset.UtcNow.AddSeconds(-1); + await otherDb.SaveChangesAsync(Ct); + Assert.False(tracker.GetSpace("Alice", 1L)); + } + + [Theory] + [InlineData("Discovery", 1.2, 1000, 3000)] + [InlineData("Premium", 2.4, 3000, 1000)] + public async Task Current_backend_defaults_give_one_or_three_thousand_monthly_points( + string pack, decimal amount, decimal monthlyPoints, decimal remainingUsage) + { + var clock = new Clock(); + var gateway = new Gateway(); + using var provider = Provider(clock, gateway, useBackendDefaults: true); + using var scope = provider.CreateScope(); + var subscription = await BeginAsync(scope.ServiceProvider, gateway, pack, 40000m); + Assert.Equal(monthlyPoints, subscription.MonthlyPoints); + gateway.Payments.Add(new("PAY-DEFAULT", "COMPLETED", amount, "EUR", Start)); + clock.Now = Start.AddMinutes(1); + await scope.ServiceProvider.GetRequiredService().ReconcileAsync(subscription, Ct); + var usage = await scope.ServiceProvider.GetRequiredService().GetCurrentAsync("alice", "Alice", Ct); + Assert.Equal(4000m, usage.GrossConsumption); + Assert.Equal(remainingUsage, usage.Consumption); + Assert.Equal(1000m, usage.ConsumptionLimit); + Assert.Equal(0m, usage.RemainingConsumption); + } + + [Fact] + public void Overlapping_paid_periods_fall_back_from_premium_to_discovery_then_base_quota() + { + var user = new ApplicationUser + { + PremiumDiskQuotaUntil = Start.AddDays(1), + DiscoveryDiskQuotaUntil = Start.AddDays(2) + }; + Assert.Equal(Yavsc.Constants.DefaultFSQ * 5L, user.GetEffectiveDiskQuota(Start)); + Assert.Equal(Yavsc.Constants.DefaultFSQ * 2L, user.GetEffectiveDiskQuota(Start.AddDays(1))); + Assert.Equal(Yavsc.Constants.DefaultFSQ, user.GetEffectiveDiskQuota(Start.AddDays(2))); + } + + [Fact] + public void Free_disk_quota_matches_the_standard_database_default() + { + var user = new ApplicationUser(); + Assert.Equal(Yavsc.Constants.DefaultFSQ, user.DiskQuota); + Assert.Equal(Yavsc.Constants.DefaultFSQ, user.GetEffectiveDiskQuota(Start)); + } + + [Fact] + public void Carried_credit_is_rounded_down_at_database_precision() + => Assert.Equal(6666.66666666m, ResourceUsageCredit.MonthlyGrant(0m, 0m, 10000m)); + + [Theory] + [InlineData("2026-02-28T00:00:00Z", 1)] + [InlineData("2026-03-30T23:59:59Z", 1)] + [InlineData("2026-03-31T00:00:00Z", 2)] + [InlineData("2027-01-31T00:00:00Z", 12)] + public void Monthly_anniversaries_do_not_drift_after_a_short_month(string paidAt, int expected) + => Assert.Equal(expected, ResourceUsageCredit.BillingCycle( + new DateTimeOffset(Start.UtcDateTime.Date, TimeSpan.Zero), DateTimeOffset.Parse(paidAt))); + + [Fact] + public async Task First_payment_preserves_counters_erases_usage_and_repeated_notifications_do_not_duplicate_credit() + { + var clock = new Clock(); + var gateway = new Gateway(); + using var provider = Provider(clock, gateway); + using var scope = provider.CreateScope(); + var subscription = await BeginAsync(scope.ServiceProvider, gateway, gross: 4000m); + gateway.Payments.Add(new("PAY-1", "COMPLETED", 1.2m, "EUR", Start)); + clock.Now = Start.AddMinutes(1); + var service = scope.ServiceProvider.GetRequiredService(); + await service.ReconcileAsync(subscription, Ct); + await service.ReconcileAsync(subscription, Ct); + var usage = await scope.ServiceProvider.GetRequiredService().GetCurrentAsync("alice", "Alice", Ct); + Assert.Equal(4000m, usage.CpuSeconds); + Assert.Equal(4000m, usage.GrossConsumption); + Assert.Equal(0m, usage.Consumption); + Assert.Equal(4000m, usage.CreditBalance); + Assert.Equal(14000m, usage.RemainingConsumption); + Assert.Single(scope.ServiceProvider.GetRequiredService().ResourceSubscriptionPayments); + } + + [Fact] + public async Task Premium_gives_three_default_quotas_not_three_individual_overrides() + { + var gateway = new Gateway(); + using var provider = Provider(new Clock { Now = Start.AddMinutes(1) }, gateway); + using var scope = provider.CreateScope(); + scope.ServiceProvider.GetRequiredService>().Value.UserLimits["alice"] = 15000m; + var subscription = await BeginAsync(scope.ServiceProvider, gateway, "Premium", 35000m); + gateway.Payments.Add(new("PAY-1", "COMPLETED", 2.4m, "EUR", Start.AddMinutes(1))); + await scope.ServiceProvider.GetRequiredService().ReconcileAsync(subscription, Ct); + var usage = await scope.ServiceProvider.GetRequiredService().GetCurrentAsync("alice", "Alice", Ct); + Assert.Equal(30000m, subscription.MonthlyPoints); + Assert.Equal(2m, subscription.PriceExcludingTax); + Assert.Equal(2.4m, subscription.PriceIncludingTax); + Assert.Equal(5000m, usage.Consumption); + Assert.Equal(10000m, usage.RemainingConsumption); + } + + [Fact] + public async Task Old_carry_is_not_reduced_again_and_remains_spendable_after_cancellation() + { + var clock = new Clock(); + var gateway = new Gateway(); + using var provider = Provider(clock, gateway); + using var scope = provider.CreateScope(); + var subscription = await BeginAsync(scope.ServiceProvider, gateway, gross: 4000m); + var service = scope.ServiceProvider.GetRequiredService(); + gateway.Payments.Add(new("PAY-1", "COMPLETED", 1.2m, "EUR", Start)); + clock.Now = Start.AddDays(1); + await service.ReconcileAsync(subscription, Ct); + gateway.Payments.Add(new("PAY-2", "COMPLETED", 1.2m, "EUR", Start.AddMonths(1))); + clock.Now = Start.AddMonths(1).AddMinutes(1); + gateway.Remote = gateway.Remote with { State = "CANCELLED", NextBillingAt = null }; + await service.ReconcileAsync(subscription, Ct); + var usageService = scope.ServiceProvider.GetRequiredService(); + var usage = await usageService.GetCurrentAsync("alice", "Alice", Ct); + Assert.Equal(10666.66666666m, usage.CreditBalance); + Assert.Equal("CANCELLED", subscription.State); + await ResourceUsageTracker.RecordAsync(scope.ServiceProvider.GetRequiredService(), + "alice", "Alice", cpuSeconds: 5000m, cancellationToken: Ct); + usage = await usageService.GetCurrentAsync("alice", "Alice", Ct); + Assert.Equal(5666.66666666m, usage.CreditBalance); + Assert.Equal(0m, usage.Consumption); + } + + [Theory] + [InlineData("PENDING")] + [InlineData("FAILED")] + [InlineData("DECLINED")] + public async Task Approval_and_unpaid_months_never_grant_points(string state) + { + var clock = new Clock(); + var gateway = new Gateway(); + using var provider = Provider(clock, gateway); + using var scope = provider.CreateScope(); + var subscription = await BeginAsync(scope.ServiceProvider, gateway, gross: 12000m); + gateway.Payments.Add(new("PAY-1", state, 1.2m, "EUR", Start)); + clock.Now = Start.AddMinutes(1); + await scope.ServiceProvider.GetRequiredService().ReconcileAsync(subscription, Ct); + var usage = await scope.ServiceProvider.GetRequiredService().GetCurrentAsync("alice", "Alice", Ct); + Assert.Equal(12000m, usage.Consumption); + Assert.True(usage.IsQuotaReached); + Assert.Equal(0m, usage.CreditBalance); + } + + [Theory] + [InlineData("REFUNDED")] + [InlineData("PARTIALLY_REFUNDED")] + [InlineData("FAILED")] + public async Task Reversal_removes_the_awarded_credit_once_without_deleting_history(string state) + { + var clock = new Clock(); + var gateway = new Gateway(); + using var provider = Provider(clock, gateway); + using var scope = provider.CreateScope(); + var subscription = await BeginAsync(scope.ServiceProvider, gateway, gross: 12000m); + gateway.Payments.Add(new("PAY-1", "COMPLETED", 1.2m, "EUR", Start)); + clock.Now = Start.AddMinutes(1); + var service = scope.ServiceProvider.GetRequiredService(); + await service.ReconcileAsync(subscription, Ct); + gateway.Payments[0] = gateway.Payments[0] with { State = state }; + await service.ReconcileAsync(subscription, Ct); + await service.ReconcileAsync(subscription, Ct); + var usage = await scope.ServiceProvider.GetRequiredService().GetCurrentAsync("alice", "Alice", Ct); + Assert.Equal(12000m, usage.Consumption); + Assert.True(usage.IsQuotaReached); + Assert.True(Assert.Single(scope.ServiceProvider.GetRequiredService().ResourceSubscriptionPayments).Reversed); + } + + [Fact] + public async Task A_payment_unblocks_a_user_without_changing_the_free_limit() + { + var clock = new Clock(); + var gateway = new Gateway(); + using var provider = Provider(clock, gateway); + using var scope = provider.CreateScope(); + var subscription = await BeginAsync(scope.ServiceProvider, gateway, gross: 12000m); + var usage = scope.ServiceProvider.GetRequiredService(); + Assert.False(await usage.TryAdmitAsync("alice", "Alice", 1m, 0m, 0, Ct)); + gateway.Payments.Add(new("PAY-1", "COMPLETED", 1.2m, "EUR", Start)); + clock.Now = Start.AddMinutes(1); + await scope.ServiceProvider.GetRequiredService().ReconcileAsync(subscription, Ct); + Assert.True(await usage.TryAdmitAsync("alice", "Alice", 1m, 0m, 0, Ct)); + Assert.Equal(10000m, (await usage.GetCurrentAsync("alice", "Alice", Ct)).ConsumptionLimit); + } + + [Theory] + [InlineData("USD", 1.2)] + [InlineData("EUR", 1)] + public async Task Wrong_currency_or_net_instead_of_gross_price_does_not_grant_credit(string currency, decimal amount) + { + var clock = new Clock(); + var gateway = new Gateway(); + using var provider = Provider(clock, gateway); + using var scope = provider.CreateScope(); + var subscription = await BeginAsync(scope.ServiceProvider, gateway); + gateway.Payments.Add(new("PAY-1", "COMPLETED", amount, currency, Start)); + clock.Now = Start.AddMinutes(1); + var error = await Assert.ThrowsAsync(() => + scope.ServiceProvider.GetRequiredService().ReconcileAsync(subscription, Ct)); + Assert.Equal(409, error.StatusCode); + Assert.Empty(scope.ServiceProvider.GetRequiredService().ResourceSubscriptionPayments); + } + + [Fact] + public async Task Another_custom_account_or_plan_cannot_be_bound() + { + var gateway = new Gateway(); + using var provider = Provider(new Clock(), gateway); + using var scope = provider.CreateScope(); + var subscription = await BeginAsync(scope.ServiceProvider, gateway); + var service = scope.ServiceProvider.GetRequiredService(); + await Assert.ThrowsAsync(() => + service.BindAsync(subscription, gateway.Remote with { CustomId = Guid.NewGuid().ToString("N") }, Ct)); + await Assert.ThrowsAsync(() => + service.BindAsync(subscription, gateway.Remote with { PlanId = "P-OTHER" }, Ct)); + } + + [Fact] + public async Task Concurrent_notifications_in_distinct_scopes_award_the_same_payment_once() + { + var clock = new Clock(); + var gateway = new Gateway(); + using var provider = Provider(clock, gateway); + using var initialScope = provider.CreateScope(); + await BeginAsync(initialScope.ServiceProvider, gateway, gross: 4000m); + gateway.Payments.Add(new("PAY-1", "COMPLETED", 1.2m, "EUR", Start)); + clock.Now = Start.AddMinutes(1); + using var firstScope = provider.CreateScope(); + using var secondScope = provider.CreateScope(); + var first = firstScope.ServiceProvider.GetRequiredService(); + var second = secondScope.ServiceProvider.GetRequiredService(); + var firstSubscription = Assert.Single(await first.GetAllAsync("alice", Ct)); + var secondSubscription = Assert.Single(await second.GetAllAsync("alice", Ct)); + await Task.WhenAll( + Task.Run(() => first.ReconcileAsync(firstSubscription, Ct), Ct), + Task.Run(() => second.ReconcileAsync(secondSubscription, Ct), Ct)); + using var verificationScope = provider.CreateScope(); + var db = verificationScope.ServiceProvider.GetRequiredService(); + Assert.Single(db.ResourceSubscriptionPayments); + Assert.Equal(8000m, (await db.ResourceUsageRecords.SingleAsync(Ct)).CreditPoints); + } + + [Fact] + public async Task An_older_pending_payment_can_complete_after_a_more_recent_month_without_double_credit() + { + var clock = new Clock(); + var gateway = new Gateway(); + using var provider = Provider(clock, gateway); + using var scope = provider.CreateScope(); + var subscription = await BeginAsync(scope.ServiceProvider, gateway, gross: 12000m); + gateway.Payments.Add(new("PAY-1", "PENDING", 1.2m, "EUR", Start)); + gateway.Payments.Add(new("PAY-2", "COMPLETED", 1.2m, "EUR", Start.AddMonths(1))); + clock.Now = Start.AddMonths(1).AddMinutes(1); + var service = scope.ServiceProvider.GetRequiredService(); + await service.ReconcileAsync(subscription, Ct); + gateway.Payments[0] = gateway.Payments[0] with { State = "COMPLETED" }; + await service.ReconcileAsync(subscription, Ct); + await service.ReconcileAsync(subscription, Ct); + var db = scope.ServiceProvider.GetRequiredService(); + Assert.Equal(2, await db.ResourceSubscriptionPayments.CountAsync(Ct)); + Assert.Equal(1, subscription.LastCreditedCycle); + Assert.Equal(17333.33333333m, (await db.ResourceUsageRecords.SingleAsync(Ct)).CreditPoints); + } + + [Fact] + public async Task Two_different_payment_ids_in_the_same_month_do_not_award_two_credits() + { + var clock = new Clock(); + var gateway = new Gateway(); + using var provider = Provider(clock, gateway); + using var scope = provider.CreateScope(); + var subscription = await BeginAsync(scope.ServiceProvider, gateway); + gateway.Payments.Add(new("PAY-1", "COMPLETED", 1.2m, "EUR", Start)); + clock.Now = Start.AddMinutes(1); + var service = scope.ServiceProvider.GetRequiredService(); + await service.ReconcileAsync(subscription, Ct); + gateway.Payments.Add(new("PAY-2", "COMPLETED", 1.2m, "EUR", Start)); + var error = await Assert.ThrowsAsync(() => service.ReconcileAsync(subscription, Ct)); + Assert.Equal(409, error.StatusCode); + var db = scope.ServiceProvider.GetRequiredService(); + Assert.Single(db.ResourceSubscriptionPayments); + Assert.Equal(6666.66666666m, (await db.ResourceUsageRecords.SingleAsync(Ct)).CreditPoints); + } + + [Fact] + public async Task Preparing_the_same_pack_is_idempotent_and_changing_pack_requires_cancellation() + { + var gateway = new Gateway(); + using var provider = Provider(new Clock(), gateway); + using var scope = provider.CreateScope(); + var subscription = await BeginAsync(scope.ServiceProvider, gateway); + var service = scope.ServiceProvider.GetRequiredService(); + Assert.Equal(subscription.Id, (await service.PrepareAsync("alice", "Discovery", Ct)).Id); + await Assert.ThrowsAsync(() => service.PrepareAsync("alice", "Premium", Ct)); + await Assert.ThrowsAsync(() => service.PrepareAsync("alice", "unknown", Ct)); + } +} diff --git a/src/test/Yavsc.Server.Tests/ResourceUsageTests.cs b/src/test/Yavsc.Server.Tests/ResourceUsageTests.cs new file mode 100644 index 000000000..7cbd30f67 --- /dev/null +++ b/src/test/Yavsc.Server.Tests/ResourceUsageTests.cs @@ -0,0 +1,283 @@ +using System.Security.Claims; +using Microsoft.AspNetCore.Http; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging.Abstractions; +using Microsoft.Extensions.Options; +using Yavsc.Models; +using Yavsc.Server.Helpers; +using Yavsc.Settings; + +namespace Yavsc.Server.Tests; + +public sealed class ResourceUsageTests +{ + private static ServiceProvider NewProvider(Action? configure = null) + { + var services = new ServiceCollection(); + var databaseName = Guid.NewGuid().ToString(); + services.AddLogging(); + services.AddDbContext(o => o.UseInMemoryDatabase(databaseName)); + services.AddResourceUsage(new ConfigurationBuilder().Build()); + services.Configure(o => + { + o.ApiCallWeight = 0.02m; + o.CpuSecondWeight = 1m; + o.BandwidthMbWeight = 0.1m; + o.StorageMbWeight = 0.3m; + o.DefaultLimit = 10000m; + }); + services.Configure(o => o.Authority = "https://instance.example"); + if (configure is not null) services.Configure(configure); + return services.BuildServiceProvider(); + } + + private static DefaultHttpContext NewContext(IServiceProvider services) + => new() + { + RequestServices = services, + User = new ClaimsPrincipal(new ClaimsIdentity([new Claim("sub", "alice")], "Bearer")), + Response = { Body = new MemoryStream() } + }; + + [Fact] + public void Configured_formula_uses_exact_decimal_points() + { + var rule = new ResourceUsageOptions + { + ApiCallWeight = 0.2m, CpuSecondWeight = 0.1m, + BandwidthMbWeight = 0.05m, StorageMbWeight = 0.5m, DefaultLimit = 1000m + }; + Assert.Equal(29.34m, rule.Calculate(12.5m, 3.2m, 18.4m, 51.2m)); + Assert.Equal(0m, rule.Calculate(0m, 0m, 0m, 0m)); + Assert.Equal(0.002m, rule.Calculate(0.01m, 0m, 0m, 0m)); + Assert.Equal(1000m, rule.GetLimit("unknown-user")); + } + + [Fact] + public async Task Summary_uses_latest_snapshot_and_individual_limit_without_summing_snapshots() + { + using var provider = NewProvider(o => o.UserLimits["alice"] = 100m); + using var scope = provider.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + db.ResourceUsageRecords.AddRange( + new ResourceUsageRecord { UserId = "alice", UserName = "old", CpuSeconds = 500m, RecordedAtUtc = DateTime.UtcNow.AddDays(-1) }, + new ResourceUsageRecord { UserId = "alice", UserName = "alice", ApiCalls = 10m, CpuSeconds = 3m, BandwidthMb = 2m, StorageMb = 4m }); + await db.SaveChangesAsync(); + var usage = scope.ServiceProvider.GetRequiredService(); + var summary = await usage.GetCurrentAsync("alice", "alice", TestContext.Current.CancellationToken); + Assert.Equal(4.6m, summary.Consumption); + Assert.Equal(100m, summary.ConsumptionLimit); + Assert.Equal(95.4m, summary.RemainingConsumption); + Assert.False(summary.IsQuotaReached); + var overview = await usage.GetOverviewAsync(TestContext.Current.CancellationToken); + Assert.Single(overview); + Assert.Equal(summary.Consumption, overview[0].Consumption); + } + + [Fact] + public async Task Concurrent_admissions_allow_exact_limit_without_lost_updates_or_duplicate_snapshots() + { + using var provider = NewProvider(o => o.DefaultLimit = 0.04m); + var results = await Task.WhenAll(Enumerable.Range(0, 20).Select(async _ => + { + using var scope = provider.CreateScope(); + return await scope.ServiceProvider.GetRequiredService() + .TryAdmitAsync("alice", "alice", 1m, 0m, 0, TestContext.Current.CancellationToken); + })); + Assert.Equal(2, results.Count(accepted => accepted)); + using var finalScope = provider.CreateScope(); + var db = finalScope.ServiceProvider.GetRequiredService(); + var record = Assert.Single(await db.ResourceUsageRecords.ToListAsync(TestContext.Current.CancellationToken)); + Assert.Equal(2m, record.ApiCalls); + var summary = await finalScope.ServiceProvider.GetRequiredService() + .GetCurrentAsync("alice", "alice", TestContext.Current.CancellationToken); + Assert.True(summary.IsQuotaReached); + Assert.Equal(0m, summary.RemainingConsumption); + } + + [Fact] + public async Task Concurrent_accounting_preserves_all_resource_deltas() + { + using var provider = NewProvider(); + await Task.WhenAll(Enumerable.Range(0, 20).Select(async _ => + { + using var scope = provider.CreateScope(); + await ResourceUsageTracker.RecordAsync( + scope.ServiceProvider.GetRequiredService(), + "alice", "alice", cpuSeconds: 0.1m, apiCalls: 1m, + storageBytes: 1048576, bandwidthMb: 0.5m); + })); + using var finalScope = provider.CreateScope(); + var record = Assert.Single(await finalScope.ServiceProvider.GetRequiredService() + .ResourceUsageRecords.ToListAsync(TestContext.Current.CancellationToken)); + Assert.Equal(20m, record.ApiCalls); + Assert.Equal(2m, record.CpuSeconds); + Assert.Equal(20m, record.StorageMb); + Assert.Equal(10m, record.BandwidthMb); + } + + [Fact] + public async Task Known_ingress_or_storage_cost_is_refused_before_consumption() + { + using var provider = NewProvider(o => o.DefaultLimit = 0.11m); + using var scope = provider.CreateScope(); + var usage = scope.ServiceProvider.GetRequiredService(); + Assert.False(await usage.TryAdmitAsync("alice", "alice", 1m, 1m, 0, TestContext.Current.CancellationToken)); + Assert.False(await usage.TryAdmitAsync("alice", "alice", 0m, 0m, 1048576, TestContext.Current.CancellationToken)); + Assert.Empty(await scope.ServiceProvider.GetRequiredService() + .ResourceUsageRecords.ToListAsync(TestContext.Current.CancellationToken)); + } + + [Fact] + public async Task Observed_cost_can_exceed_limit_then_new_operations_are_refused_until_limit_is_increased() + { + using var provider = NewProvider(o => o.DefaultLimit = 1m); + using var scope = provider.CreateScope(); + var usage = scope.ServiceProvider.GetRequiredService(); + Assert.True(await usage.TryAdmitAsync("alice", "alice", 1m, 0m, 0, TestContext.Current.CancellationToken)); + await ResourceUsageTracker.RecordAsync(scope.ServiceProvider.GetRequiredService(), + "alice", "alice", cpuSeconds: 2m, cancellationToken: TestContext.Current.CancellationToken); + Assert.False(await usage.TryAdmitAsync("alice", "alice", 1m, 0m, 0, TestContext.Current.CancellationToken)); + var summary = await usage.GetCurrentAsync("alice", "alice", TestContext.Current.CancellationToken); + Assert.Equal(2.02m, summary.Consumption); + Assert.Equal(0m, summary.RemainingConsumption); + Assert.True(summary.IsQuotaReached); + + var raised = new ResourceUsageService(scope.ServiceProvider.GetRequiredService(), + Options.Create(new ResourceUsageOptions + { + DefaultLimit = 3m, ApiCallWeight = 0.02m, CpuSecondWeight = 1m, + BandwidthMbWeight = 0.1m, StorageMbWeight = 0.3m + })); + Assert.True(await raised.TryAdmitAsync("alice", "alice", 1m, 0m, 0, TestContext.Current.CancellationToken)); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task Middleware_counts_streamed_bodies_once_with_or_without_declared_ingress(bool declared) + { + using var provider = NewProvider(); + using var scope = provider.CreateScope(); + var context = NewContext(scope.ServiceProvider); + using var originalRequest = new MemoryStream(new byte[1048576]); + using var originalResponse = new MemoryStream(); + context.Request.Body = originalRequest; + context.Response.Body = originalResponse; + if (declared) context.Request.ContentLength = 1048576; + var middleware = new ResourceUsageTelemetryMiddleware( + async ctx => + { + await ctx.Request.Body.CopyToAsync(Stream.Null); + await ctx.Response.BodyWriter.WriteAsync(new byte[2 * 1048576]); + }, + provider.GetRequiredService(), + NullLogger.Instance); + await middleware.InvokeAsync(context, scope.ServiceProvider.GetRequiredService()); + Assert.Same(originalRequest, context.Request.Body); + Assert.Same(originalResponse, context.Response.Body); + Assert.True(originalRequest.CanRead); + Assert.True(originalResponse.CanWrite); + var summary = await scope.ServiceProvider.GetRequiredService() + .GetCurrentAsync("alice", "alice", TestContext.Current.CancellationToken); + Assert.Equal(1m, summary.ApiCalls); + Assert.Equal(3m, summary.BandwidthMb); + Assert.Equal(0.32m, summary.Consumption); + } + + [Fact] + public async Task Failed_execution_is_accounted_and_original_streams_are_restored() + { + using var provider = NewProvider(); + using var scope = provider.CreateScope(); + var context = NewContext(scope.ServiceProvider); + var originalResponse = context.Response.Body; + var middleware = new ResourceUsageTelemetryMiddleware( + async ctx => + { + await ctx.Response.Body.WriteAsync(new byte[1048576]); + throw new InvalidOperationException("Expected test failure"); + }, provider.GetRequiredService(), + NullLogger.Instance); + await Assert.ThrowsAsync(() => + middleware.InvokeAsync(context, scope.ServiceProvider.GetRequiredService())); + Assert.Same(originalResponse, context.Response.Body); + var summary = await scope.ServiceProvider.GetRequiredService() + .GetCurrentAsync("alice", "alice", TestContext.Current.CancellationToken); + Assert.Equal(0.12m, summary.Consumption); + } + + [Theory] + [InlineData("/login", false)] + [InlineData("/refresh", false)] + [InlineData("/logout", false)] + [InlineData("/api/v1/resource-usage/me", true)] + public async Task Exempt_endpoints_remain_available_without_consumption(string path, bool metadata) + { + using var provider = NewProvider(o => o.DefaultLimit = 0.01m); + using var scope = provider.CreateScope(); + var context = NewContext(scope.ServiceProvider); + context.Request.Path = path; + if (metadata) + context.SetEndpoint(new Endpoint(_ => Task.CompletedTask, + new EndpointMetadataCollection(new ResourceUsageExemptAttribute()), "usage")); + var ran = false; + var middleware = new ResourceUsageTelemetryMiddleware( + _ => { ran = true; return Task.CompletedTask; }, + provider.GetRequiredService(), + NullLogger.Instance); + await middleware.InvokeAsync(context, scope.ServiceProvider.GetRequiredService()); + Assert.True(ran); + Assert.Empty(await scope.ServiceProvider.GetRequiredService() + .ResourceUsageRecords.ToListAsync(TestContext.Current.CancellationToken)); + } + + [Fact] + public async Task Rejected_request_returns_problem_details_without_running_or_charging() + { + using var provider = NewProvider(o => o.DefaultLimit = 0.01m); + using var scope = provider.CreateScope(); + var context = NewContext(scope.ServiceProvider); + var middleware = new ResourceUsageTelemetryMiddleware( + _ => throw new InvalidOperationException("Must not run"), + provider.GetRequiredService(), + NullLogger.Instance); + await middleware.InvokeAsync(context, scope.ServiceProvider.GetRequiredService()); + Assert.Equal(429, context.Response.StatusCode); + Assert.StartsWith("application/problem+json", context.Response.ContentType); + context.Response.Body.Position = 0; + using var reader = new StreamReader(context.Response.Body); + var payload = await reader.ReadToEndAsync(TestContext.Current.CancellationToken); + Assert.Contains("resource_quota_exceeded", payload); + Assert.Contains("https://instance.example/Home/CGU", payload); + Assert.Empty(await scope.ServiceProvider.GetRequiredService() + .ResourceUsageRecords.ToListAsync(TestContext.Current.CancellationToken)); + } + + [Fact] + public async Task Negative_counter_deltas_are_explicitly_rejected() + { + using var provider = NewProvider(); + using var scope = provider.CreateScope(); + await Assert.ThrowsAsync(() => + ResourceUsageTracker.RecordAsync(scope.ServiceProvider.GetRequiredService(), + "alice", "alice", cpuSeconds: -1m, cancellationToken: TestContext.Current.CancellationToken)); + } + + [Theory] + [InlineData("ResourceUsage:ApiCallWeight", "0")] + [InlineData("ResourceUsage:BandwidthMbWeight", "-1")] + [InlineData("ResourceUsage:DefaultLimit", "0")] + [InlineData("ResourceUsage:UserLimits:alice", "-1")] + public void Invalid_configuration_is_rejected(string key, string value) + { + var configuration = new ConfigurationBuilder() + .AddInMemoryCollection(new Dictionary { [key] = value }).Build(); + var services = new ServiceCollection().AddResourceUsage(configuration); + using var provider = services.BuildServiceProvider(); + Assert.Throws(() => + provider.GetRequiredService>().Value); + } +} From ed8f41bd4a2b3495bbd457637349fe1da9a10c95 Mon Sep 17 00:00:00 2001 From: Paul Schneider Date: Sun, 8 Nov 2026 05:40:08 +0000 Subject: [PATCH 05/11] feat: refund tracked storage usage on deletion and replacement Persist per-file storage receipts, preserve refundability on rename, account for PDF replacements and permit deletion at the consumption limit. Update CGU, installation documentation and regression tests. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- CHANGELOG.md | 2 + INSTALL.md | 10 +- doc/architecture/postit.md | 8 +- .../Business/FrontOfficeApiController.cs | 12 +- .../Controllers/FileSystemApiController.cs | 54 +- ...2221_RefundableResourceStorage.Designer.cs | 5221 +++++++++++++++++ ...0261108052221_RefundableResourceStorage.cs | 34 + .../ApplicationDbContextModelSnapshot.cs | 18 + src/Yavsc.Org/Views/Home/CGU.cshtml | 6 +- .../Helpers/ResourceUsageReliefAttribute.cs | 4 + .../ResourceUsageTelemetryMiddleware.cs | 9 +- .../Helpers/ResourceUsageTracker.cs | 152 +- .../Models/ApplicationDbContext.cs | 2 + .../Models/ResourceStorageRecord.cs | 13 + .../Yavsc.Blogs.Tests/FileSystemApiTests.cs | 73 + .../Controllers/ResourceUsageTermsTests.cs | 3 + .../Yavsc.Server.Tests/ResourceUsageTests.cs | 86 + 17 files changed, 5639 insertions(+), 68 deletions(-) create mode 100644 src/Yavsc.Org/Migrations/20261108052221_RefundableResourceStorage.Designer.cs create mode 100644 src/Yavsc.Org/Migrations/20261108052221_RefundableResourceStorage.cs create mode 100644 src/Yavsc.Server/Helpers/ResourceUsageReliefAttribute.cs create mode 100644 src/Yavsc.Server/Models/ResourceStorageRecord.cs diff --git a/CHANGELOG.md b/CHANGELOG.md index 4f2cfee0a..8d06395a7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,8 @@ ### Added +* [Yavsc/API/Blogs/PostIt] Refund tracked storage points when personal files are deleted or replaced, and when generated PDFs are replaced. Persist per-file accounting receipts, preserve them on rename, reject refunds for untracked legacy files, and allow deletion at the consumption limit without refunding API/CPU/transfer costs. Update CGU and installation instructions. + * [Yavsc/PostIt/PayPal] Add monthly Découverte (EUR 1 excluding VAT) and Premium (EUR 2 excluding VAT) resource subscriptions, charged at EUR 1.20 / EUR 2.40 including 20% VAT. Confirmed monthly PayPal payments erase up to one / three default quotas, carry two thirds of unused monthly credit without expiry, and preserve historical counters. Add persistent idempotent payment credits, refund reconciliation, authenticated Web subscription/cancellation pages, verified REST webhooks, PostIt links and balances, migration and updated CGU. * [Yavsc/PostIt/Subscriptions] Align new users' free quota with the existing 500 MiB database default; grant twice that standard quota for Discovery (1,000 MiB) and five times for Premium (2,500 MiB) during confirmed paid monthly periods, including their remainder after cancellation. Restore the user's base quota after expiry or refund without deleting files, refuse uploads beyond available space before writing, and expose the effective quota in profile and usage responses. * [PostIt/API/Blogs/Yavsc.Org] Compute cumulative resource consumption in configurable points per API call, recorded CPU second, MiB transferred and MiB added to storage, with backend-defined defaults, a default 1,000-point limit and per-user overrides. Serialize accounting and known-cost admission across PostgreSQL hosts, count streamed HTTP bodies, reject further consuming operations with HTTP 429, and check personal uploads before writing. Keep usage/session access available, display the indicator and balance in PostIt, and publish linked CGU explaining the rule and after-measurement enforcement. diff --git a/INSTALL.md b/INSTALL.md index 19112f0aa..b143e7226 100644 --- a/INSTALL.md +++ b/INSTALL.md @@ -113,7 +113,15 @@ balance and subscription/payment tables without clearing existing counters. Consumption is in **points**, independent of `EstimatedCompensation` and currency. Counters have no automatic reset. Storage means cumulative -instrumented writes, not current occupancy; the historical CPU counter is +instrumented writes less individually tracked bytes removed or replaced, +not total filesystem occupancy. Replacements refund their tracked previous +size and charge the new size. Legacy files without an individual receipt +receive no refund; storage counters never become negative. Deletion remains +available at the consumption limit, but API/transfer/CPU costs are not refunded. +Apply the `RefundableResourceStorage` migration before deployment; its empty +receipt table deliberately does not infer provenance from historical counters. +Renames preserve receipts and repeated PDF generation replaces the previous +tracked volume rather than charging the whole file again. The historical CPU counter is instrumented elapsed processing time, not exhaustive CPU profiling. Authenticated HTTP operations are admitted atomically against known costs diff --git a/doc/architecture/postit.md b/doc/architecture/postit.md index 85cb052be..baa2331e8 100644 --- a/doc/architecture/postit.md +++ b/doc/architecture/postit.md @@ -131,8 +131,12 @@ si une opération de gestion reçoit un refus de quota. L'administration charge également les usages avant ses autres outils et les conserve sur un refus HTTP 429, tant que le rôle administrateur est toujours présent. -L'indicateur cumulé est exprimé en points : `0,02 × appels API + secondes -CPU enregistrées + 0,1 × Mio transférés + 0,3 × Mio ajoutés au stockage`. +L'indicateur est exprimé en points selon les coefficients effectifs du +backend, présentés dans les CGU. Le stockage correspond aux volumes +instrumentés ajoutés, moins les volumes individuellement suivis supprimés +ou remplacés. Les anciens fichiers sans suivi ne sont pas remboursés. +La suppression reste disponible au seuil ; CPU, appels API et transferts +ne sont pas remboursés. Les renommages conservent le suivi individuel. Le profil et les vues d'administration affichent le seuil effectif, le solde et l'atteinte du quota, indépendamment de l'estimation financière. La section serveur `ResourceUsage` configure les coefficients et les diff --git a/src/Yavsc.Api/Controllers/Business/FrontOfficeApiController.cs b/src/Yavsc.Api/Controllers/Business/FrontOfficeApiController.cs index 51ea6a2c4..c43130d42 100644 --- a/src/Yavsc.Api/Controllers/Business/FrontOfficeApiController.cs +++ b/src/Yavsc.Api/Controllers/Business/FrontOfficeApiController.cs @@ -159,7 +159,6 @@ namespace Yavsc.ApiControllers uid, User.Identity?.Name ?? uid, cpuSeconds: (decimal)stopwatch.Elapsed.TotalSeconds, - storageBytes: fo.Length, actorUserId: uid); return File(fo.OpenRead(), "application/pdf"); @@ -185,12 +184,21 @@ namespace Yavsc.ApiControllers uid, User.Identity?.Name ?? uid, cpuSeconds: (decimal)stopwatch.Elapsed.TotalSeconds, - storageBytes: renderedPdf?.Length ?? 0, actorUserId: uid); logger.LogError(ex, "estimate {QueryId}: TeX/PDF render failed", queryId); return Problem("TeX render failed: " + ex.Message); } + finally + { + if (renderedPdf is not null) + { + renderedPdf.Refresh(); + if (renderedPdf.Exists) + await ResourceUsageTracker.RecordStorageAsync(dbContext, uid, User.Identity?.Name ?? uid, + "pdf/" + renderedPdf.FullName, renderedPdf.Length, CancellationToken.None); + } + } } // Loads the estimate linked to a query with the navigation the diff --git a/src/Yavsc.Blogs/Controllers/FileSystemApiController.cs b/src/Yavsc.Blogs/Controllers/FileSystemApiController.cs index c05864ae2..7b92d8a42 100644 --- a/src/Yavsc.Blogs/Controllers/FileSystemApiController.cs +++ b/src/Yavsc.Blogs/Controllers/FileSystemApiController.cs @@ -98,6 +98,13 @@ namespace Yavsc.Blogs.Controllers return $"{subdir.TrimStart('/')}/{fileName}"; } + static string StoragePath(string relativePath) + { + var root = Path.GetPathRoot(Path.GetFullPath("."))!; + return "personal/" + Path.GetRelativePath(root, + Path.GetFullPath(Path.Combine(root, relativePath.TrimStart('/', '\\')))).Replace('\\', '/'); + } + [HttpPost("{*subdir}")] public async Task Post([FromServices] IResourceUsageService usage, [ValidRemoteUserFilePath] string subdir="", CancellationToken cancellationToken = default) @@ -105,7 +112,15 @@ namespace Yavsc.Blogs.Controllers if (!ModelState.IsValid) return new BadRequestObjectResult(ModelState); var uid = User.GetUserId(); var form = await Request.ReadFormAsync(cancellationToken); - var anticipatedBytes = form.Files.Sum(f => f.Length); + var anticipatedBytes = 0L; + foreach (var file in form.Files) + { + var path = StoragePath(RelPath(subdir, AbstractFileSystemHelpers.FilterFileName(file.FileName))); + var previous = await dbContext.ResourceStorageRecords.AsNoTracking() + .Where(r => r.UserId == uid && r.Path == path) + .Select(r => r.Bytes).SingleOrDefaultAsync(cancellationToken); + anticipatedBytes = checked(anticipatedBytes + Math.Max(0L, file.Length - previous)); + } if (!await usage.TryAdmitAsync(uid, User.Identity?.Name ?? uid, 0m, 0m, anticipatedBytes, cancellationToken)) { @@ -136,6 +151,8 @@ namespace Yavsc.Blogs.Controllers foreach (var f in form.Files) { + var path = Path.Combine(destDir, AbstractFileSystemHelpers.FilterFileName(f.FileName)); + var oldLength = System.IO.File.Exists(path) ? new FileInfo(path).Length : 0L; var item = user.ReceiveUserFile(destDir, f); if (!item.QuotaOffense) { @@ -170,12 +187,10 @@ namespace Yavsc.Blogs.Controllers item.ContentType = f.ContentType; } - await ResourceUsageTracker.RecordAsync( - dbContext, - uid, - user.UserName, - storageBytes: item.Length, - actorUserId: uid); + var newLength = System.IO.File.Exists(path) ? new FileInfo(path).Length : 0L; + if (!item.QuotaOffense || newLength != oldLength) + await ResourceUsageTracker.RecordStorageAsync(dbContext, uid, user.UserName, + StoragePath(RelPath(subdir, item.FileName)), newLength, CancellationToken.None); received.Add(item); _logger.LogInformation($"Received '{item.FileName}'."); @@ -259,22 +274,24 @@ namespace Yavsc.Blogs.Controllers [HttpPost] [Route("/api/fsc/mvftd")] [Authorize()] - public IActionResult MoveFile([FromBody] RenameFileQuery query) + public async Task MoveFile([FromBody] RenameFileQuery query) { if (!ModelState.IsValid) return new BadRequestObjectResult(ModelState); - var uid = User.FindFirstValue(ClaimTypes.NameIdentifier); + var uid = User.GetUserId(); var user = dbContext.Users.Single( u => u.Id == uid ); var info = user.MoveUserFileToDir(query.Id, query.To, siteSettings); if (!info.Done) return new BadRequestObjectResult(info); + await ResourceUsageTracker.MoveStorageAsync(dbContext, uid, StoragePath(query.Id), + StoragePath(Path.Combine(query.To ?? "", Path.GetFileName(query.Id))), CancellationToken.None); return Ok(new { moved = query.Id }); } [HttpPost] [Route("/api/fsc/mvf")] [Authorize()] - public IActionResult RenameFile([FromBody] RenameFileQuery query) + public async Task RenameFile([FromBody] RenameFileQuery query) { if (!ModelState.IsValid) { var idvr = new ValidRemoteUserFilePathAttribute(); @@ -282,23 +299,30 @@ namespace Yavsc.Blogs.Controllers return this.BadRequest(new { id = idvr.IsValid(query.Id), to = idvr.IsValid(query.To), errors = ModelState }); } _logger.LogInformation($"Valid move query: {query.Id} => {query.To}"); - var uid = User.FindFirstValue(ClaimTypes.NameIdentifier); + var uid = User.GetUserId(); var user = dbContext.Users.Single( u => u.Id == uid ); try { - if (Config.UserFilesOptions.FileProvider.GetFileInfo(Path.Combine(user.UserName, query.Id)).Exists) + var destination = query.To; + var root = Path.Combine(siteSettings.UserFilesRoot, user.UserName); + if (System.IO.File.Exists(Path.Combine(root, query.Id))) { var result = user.MoveUserFile(query.Id, query.To, siteSettings); if (!result.Done) return new BadRequestObjectResult(result); } else { + var dir = new DirectoryInfo(Path.Combine(root, query.To)); + if (dir.Exists) destination = Path.Combine(query.To, dir.Name); var result = user.MoveUserDir(query.Id, query.To, siteSettings); if (!result.Done) return new BadRequestObjectResult(result); } + await ResourceUsageTracker.MoveStorageAsync(dbContext, uid, StoragePath(query.Id), + StoragePath(destination), CancellationToken.None); } catch (Exception ex) { + _logger.LogError(ex, "Failed to rename user file {Path} for {UserId}", query.Id, uid); return new BadRequestObjectResult( new FsOperationInfo { Done = false, @@ -310,7 +334,8 @@ namespace Yavsc.Blogs.Controllers } [HttpDelete("{*id}")] - public IActionResult RemoveDirOrFile ([ValidRemoteUserFilePath] string id) + [ResourceUsageRelief] + public async Task RemoveDirOrFile ([ValidRemoteUserFilePath] string id) { if (!ModelState.IsValid) return new BadRequestObjectResult(ModelState); @@ -322,10 +347,13 @@ namespace Yavsc.Blogs.Controllers var result = user.DeleteUserDirOrFile(id, siteSettings); if (!result.Done) return new BadRequestObjectResult(result); + await ResourceUsageTracker.RecordStorageAsync(dbContext, user.Id, user.UserName, + StoragePath(id), 0L, CancellationToken.None); } catch (Exception ex) { + _logger.LogError(ex, "Failed to delete user file {Path} for {UserId}", id, user.Id); return new BadRequestObjectResult( new FsOperationInfo { Done = false, diff --git a/src/Yavsc.Org/Migrations/20261108052221_RefundableResourceStorage.Designer.cs b/src/Yavsc.Org/Migrations/20261108052221_RefundableResourceStorage.Designer.cs new file mode 100644 index 000000000..d82952854 --- /dev/null +++ b/src/Yavsc.Org/Migrations/20261108052221_RefundableResourceStorage.Designer.cs @@ -0,0 +1,5221 @@ +// +using System; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; +using Yavsc.Models; + +#nullable disable + +namespace Yavsc.Migrations +{ + [DbContext(typeof(ApplicationDbContext))] + [Migration("20261108052221_RefundableResourceStorage")] + partial class RefundableResourceStorage + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "10.0.13") + .HasAnnotation("Relational:MaxIdentifierLength", 63); + + NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); + + modelBuilder.Entity("IdentityServer8.EntityFramework.Entities.ApiResource", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityAlwaysColumn(b.Property("Id")); + + b.Property("AllowedAccessTokenSigningAlgorithms") + .HasColumnType("text"); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Description") + .HasColumnType("text"); + + b.Property("DisplayName") + .HasColumnType("text"); + + b.Property("Enabled") + .HasColumnType("boolean"); + + b.Property("LastAccessed") + .HasColumnType("timestamp with time zone"); + + b.Property("Name") + .HasColumnType("text"); + + b.Property("NonEditable") + .HasColumnType("boolean"); + + b.Property("ShowInDiscoveryDocument") + .HasColumnType("boolean"); + + b.Property("Updated") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.ToTable("ApiResources"); + }); + + modelBuilder.Entity("IdentityServer8.EntityFramework.Entities.ApiResourceClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ApiResourceId") + .HasColumnType("integer"); + + b.Property("ApiResourceId1") + .HasColumnType("integer"); + + b.Property("Type") + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("ApiResourceId"); + + b.HasIndex("ApiResourceId1"); + + b.ToTable("ApiResourceClaims"); + }); + + modelBuilder.Entity("IdentityServer8.EntityFramework.Entities.ApiResourceProperty", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ApiResourceId") + .HasColumnType("integer"); + + b.Property("ApiResourceId1") + .HasColumnType("integer"); + + b.Property("Key") + .HasColumnType("text"); + + b.Property("Value") + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("ApiResourceId"); + + b.HasIndex("ApiResourceId1"); + + b.ToTable("ApiResourceProperties"); + }); + + modelBuilder.Entity("IdentityServer8.EntityFramework.Entities.ApiResourceScope", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ApiResourceId") + .HasColumnType("integer"); + + b.Property("ApiResourceId1") + .HasColumnType("integer"); + + b.Property("Scope") + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("ApiResourceId"); + + b.HasIndex("ApiResourceId1"); + + b.ToTable("ApiResourceScopes"); + }); + + modelBuilder.Entity("IdentityServer8.EntityFramework.Entities.ApiResourceSecret", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ApiResourceId") + .HasColumnType("integer"); + + b.Property("ApiResourceId1") + .HasColumnType("integer"); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Description") + .HasColumnType("text"); + + b.Property("Expiration") + .HasColumnType("timestamp with time zone"); + + b.Property("Type") + .HasColumnType("text"); + + b.Property("Value") + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("ApiResourceId"); + + b.HasIndex("ApiResourceId1"); + + b.ToTable("ApiResourceSecrets"); + }); + + modelBuilder.Entity("IdentityServer8.EntityFramework.Entities.ApiScope", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityAlwaysColumn(b.Property("Id")); + + b.Property("Description") + .HasColumnType("text"); + + b.Property("DisplayName") + .HasColumnType("text"); + + b.Property("Emphasize") + .HasColumnType("boolean"); + + b.Property("Enabled") + .HasColumnType("boolean"); + + b.Property("Name") + .HasColumnType("text"); + + b.Property("Required") + .HasColumnType("boolean"); + + b.Property("ShowInDiscoveryDocument") + .HasColumnType("boolean"); + + b.HasKey("Id"); + + b.ToTable("ApiScopes"); + }); + + modelBuilder.Entity("IdentityServer8.EntityFramework.Entities.ApiScopeClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ScopeId") + .HasColumnType("integer"); + + b.Property("ScopeId1") + .HasColumnType("integer"); + + b.Property("Type") + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("ScopeId"); + + b.HasIndex("ScopeId1"); + + b.ToTable("ApiScopeClaims"); + }); + + modelBuilder.Entity("IdentityServer8.EntityFramework.Entities.ApiScopeProperty", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Key") + .HasColumnType("text"); + + b.Property("ScopeId") + .HasColumnType("integer"); + + b.Property("ScopeId1") + .HasColumnType("integer"); + + b.Property("Value") + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("ScopeId"); + + b.HasIndex("ScopeId1"); + + b.ToTable("ApiScopeProperties"); + }); + + modelBuilder.Entity("IdentityServer8.EntityFramework.Entities.Client", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityAlwaysColumn(b.Property("Id")); + + b.Property("AbsoluteRefreshTokenLifetime") + .HasColumnType("integer"); + + b.Property("AccessTokenLifetime") + .HasColumnType("integer"); + + b.Property("AccessTokenType") + .HasColumnType("integer"); + + b.Property("AllowAccessTokensViaBrowser") + .HasColumnType("boolean"); + + b.Property("AllowOfflineAccess") + .HasColumnType("boolean"); + + b.Property("AllowPlainTextPkce") + .HasColumnType("boolean"); + + b.Property("AllowRememberConsent") + .HasColumnType("boolean"); + + b.Property("AllowedIdentityTokenSigningAlgorithms") + .HasColumnType("text"); + + b.Property("AlwaysIncludeUserClaimsInIdToken") + .HasColumnType("boolean"); + + b.Property("AlwaysSendClientClaims") + .HasColumnType("boolean"); + + b.Property("AuthorizationCodeLifetime") + .HasColumnType("integer"); + + b.Property("BackChannelLogoutSessionRequired") + .HasColumnType("boolean"); + + b.Property("BackChannelLogoutUri") + .HasColumnType("text"); + + b.Property("ClientClaimsPrefix") + .HasColumnType("text"); + + b.Property("ClientId") + .HasColumnType("text"); + + b.Property("ClientName") + .HasColumnType("text"); + + b.Property("ClientUri") + .HasColumnType("text"); + + b.Property("ConsentLifetime") + .HasColumnType("integer"); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Description") + .HasColumnType("text"); + + b.Property("DeviceCodeLifetime") + .HasColumnType("integer"); + + b.Property("EnableLocalLogin") + .HasColumnType("boolean"); + + b.Property("Enabled") + .HasColumnType("boolean"); + + b.Property("FrontChannelLogoutSessionRequired") + .HasColumnType("boolean"); + + b.Property("FrontChannelLogoutUri") + .HasColumnType("text"); + + b.Property("IdentityTokenLifetime") + .HasColumnType("integer"); + + b.Property("IncludeJwtId") + .HasColumnType("boolean"); + + b.Property("LastAccessed") + .HasColumnType("timestamp with time zone"); + + b.Property("LogoUri") + .HasColumnType("text"); + + b.Property("NonEditable") + .HasColumnType("boolean"); + + b.Property("PairWiseSubjectSalt") + .HasColumnType("text"); + + b.Property("ProtocolType") + .HasColumnType("text"); + + b.Property("RefreshTokenExpiration") + .HasColumnType("integer"); + + b.Property("RefreshTokenUsage") + .HasColumnType("integer"); + + b.Property("RequireClientSecret") + .HasColumnType("boolean"); + + b.Property("RequireConsent") + .HasColumnType("boolean"); + + b.Property("RequirePkce") + .HasColumnType("boolean"); + + b.Property("RequireRequestObject") + .HasColumnType("boolean"); + + b.Property("SlidingRefreshTokenLifetime") + .HasColumnType("integer"); + + b.Property("UpdateAccessTokenClaimsOnRefresh") + .HasColumnType("boolean"); + + b.Property("Updated") + .HasColumnType("timestamp with time zone"); + + b.Property("UserCodeType") + .HasColumnType("text"); + + b.Property("UserSsoLifetime") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.ToTable("Clients"); + }); + + modelBuilder.Entity("IdentityServer8.EntityFramework.Entities.ClientClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityAlwaysColumn(b.Property("Id")); + + b.Property("ClientId") + .HasColumnType("integer"); + + b.Property("Type") + .HasColumnType("text"); + + b.Property("Value") + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("ClientId"); + + b.ToTable("ClientClaims"); + }); + + modelBuilder.Entity("IdentityServer8.EntityFramework.Entities.ClientCorsOrigin", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityAlwaysColumn(b.Property("Id")); + + b.Property("ClientId") + .HasColumnType("integer"); + + b.Property("ClientId1") + .HasColumnType("integer"); + + b.Property("Origin") + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("ClientId"); + + b.HasIndex("ClientId1"); + + b.ToTable("ClientCorsOrigins"); + }); + + modelBuilder.Entity("IdentityServer8.EntityFramework.Entities.ClientGrantType", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityAlwaysColumn(b.Property("Id")); + + b.Property("ClientId") + .HasColumnType("integer"); + + b.Property("GrantType") + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("ClientId"); + + b.ToTable("ClientGrantTypes"); + }); + + modelBuilder.Entity("IdentityServer8.EntityFramework.Entities.ClientIdPRestriction", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityAlwaysColumn(b.Property("Id")); + + b.Property("ClientId") + .HasColumnType("integer"); + + b.Property("ClientId1") + .HasColumnType("integer"); + + b.Property("Provider") + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("ClientId"); + + b.HasIndex("ClientId1"); + + b.ToTable("ClientIdPRestrictions"); + }); + + modelBuilder.Entity("IdentityServer8.EntityFramework.Entities.ClientPostLogoutRedirectUri", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityAlwaysColumn(b.Property("Id")); + + b.Property("ClientId") + .HasColumnType("integer"); + + b.Property("ClientId1") + .HasColumnType("integer"); + + b.Property("PostLogoutRedirectUri") + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("ClientId"); + + b.HasIndex("ClientId1"); + + b.ToTable("ClientPostLogoutRedirectUris"); + }); + + modelBuilder.Entity("IdentityServer8.EntityFramework.Entities.ClientProperty", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityAlwaysColumn(b.Property("Id")); + + b.Property("ClientId") + .HasColumnType("integer"); + + b.Property("ClientId1") + .HasColumnType("integer"); + + b.Property("Key") + .HasColumnType("text"); + + b.Property("Value") + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("ClientId"); + + b.HasIndex("ClientId1"); + + b.ToTable("ClientProperties"); + }); + + modelBuilder.Entity("IdentityServer8.EntityFramework.Entities.ClientRedirectUri", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityAlwaysColumn(b.Property("Id")); + + b.Property("ClientId") + .HasColumnType("integer"); + + b.Property("RedirectUri") + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("ClientId"); + + b.ToTable("ClientRedirectUris"); + }); + + modelBuilder.Entity("IdentityServer8.EntityFramework.Entities.ClientScope", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityAlwaysColumn(b.Property("Id")); + + b.Property("ClientId") + .HasColumnType("integer"); + + b.Property("Scope") + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("ClientId"); + + b.ToTable("ClientScopes"); + }); + + modelBuilder.Entity("IdentityServer8.EntityFramework.Entities.ClientSecret", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityAlwaysColumn(b.Property("Id")); + + b.Property("ClientId") + .HasColumnType("integer"); + + b.Property("ClientId1") + .HasColumnType("integer"); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Description") + .HasColumnType("text"); + + b.Property("Expiration") + .HasColumnType("timestamp with time zone"); + + b.Property("Type") + .HasColumnType("text"); + + b.Property("Value") + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("ClientId"); + + b.HasIndex("ClientId1"); + + b.ToTable("ClientSecrets"); + }); + + modelBuilder.Entity("IdentityServer8.EntityFramework.Entities.DeviceFlowCodes", b => + { + b.Property("UserCode") + .HasColumnType("text"); + + b.Property("DeviceCode") + .HasColumnType("text"); + + b.Property("ClientId") + .HasColumnType("text"); + + b.Property("CreationTime") + .HasColumnType("timestamp with time zone"); + + b.Property("Data") + .HasColumnType("text"); + + b.Property("Description") + .HasColumnType("text"); + + b.Property("Expiration") + .HasColumnType("timestamp with time zone"); + + b.Property("SessionId") + .HasColumnType("text"); + + b.Property("SubjectId") + .HasColumnType("text"); + + b.HasKey("UserCode", "DeviceCode"); + + b.ToTable("DeviceFlowCodes"); + }); + + modelBuilder.Entity("IdentityServer8.EntityFramework.Entities.IdentityResource", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Description") + .HasColumnType("text"); + + b.Property("DisplayName") + .HasColumnType("text"); + + b.Property("Emphasize") + .HasColumnType("boolean"); + + b.Property("Enabled") + .HasColumnType("boolean"); + + b.Property("Name") + .HasColumnType("text"); + + b.Property("NonEditable") + .HasColumnType("boolean"); + + b.Property("Required") + .HasColumnType("boolean"); + + b.Property("ShowInDiscoveryDocument") + .HasColumnType("boolean"); + + b.Property("Updated") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.ToTable("IdentityResources"); + }); + + modelBuilder.Entity("IdentityServer8.EntityFramework.Entities.IdentityResourceClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("IdentityResourceId") + .HasColumnType("integer"); + + b.Property("Type") + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("IdentityResourceId"); + + b.ToTable("IdentityResourceClaims"); + }); + + modelBuilder.Entity("IdentityServer8.EntityFramework.Entities.IdentityResourceProperty", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("IdentityResourceId") + .HasColumnType("integer"); + + b.Property("Key") + .HasColumnType("text"); + + b.Property("Value") + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("IdentityResourceId"); + + b.ToTable("IdentityResourceProperties"); + }); + + modelBuilder.Entity("IdentityServer8.EntityFramework.Entities.PersistedGrant", b => + { + b.Property("Key") + .HasColumnType("text"); + + b.Property("ClientId") + .HasColumnType("text"); + + b.Property("ConsumedTime") + .HasColumnType("timestamp with time zone"); + + b.Property("CreationTime") + .HasColumnType("timestamp with time zone"); + + b.Property("Data") + .HasColumnType("text"); + + b.Property("Description") + .HasColumnType("text"); + + b.Property("Expiration") + .HasColumnType("timestamp with time zone"); + + b.Property("SessionId") + .HasColumnType("text"); + + b.Property("SubjectId") + .HasColumnType("text"); + + b.Property("Type") + .HasColumnType("text"); + + b.HasKey("Key"); + + b.ToTable("PersistedGrants"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b => + { + b.Property("Id") + .HasColumnType("text"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("text"); + + b.Property("Name") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("NormalizedName") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedName") + .IsUnique() + .HasDatabaseName("RoleNameIndex"); + + b.ToTable("AspNetRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("text"); + + b.Property("ClaimValue") + .HasColumnType("text"); + + b.Property("RoleId") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetRoleClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("text"); + + b.Property("ClaimValue") + .HasColumnType("text"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.Property("LoginProvider") + .HasColumnType("text"); + + b.Property("ProviderKey") + .HasColumnType("text"); + + b.Property("ProviderDisplayName") + .HasColumnType("text"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("LoginProvider", "ProviderKey"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserLogins", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.Property("UserId") + .HasColumnType("text"); + + b.Property("RoleId") + .HasColumnType("text"); + + b.HasKey("UserId", "RoleId"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetUserRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.Property("UserId") + .HasColumnType("text"); + + b.Property("LoginProvider") + .HasColumnType("text"); + + b.Property("Name") + .HasColumnType("text"); + + b.Property("Value") + .HasColumnType("text"); + + b.HasKey("UserId", "LoginProvider", "Name"); + + b.ToTable("AspNetUserTokens", (string)null); + }); + + modelBuilder.Entity("Yavsc.Abstract.Identity.ClientProviderInfo", b => + { + b.Property("UserId") + .HasColumnType("text"); + + b.Property("Avatar") + .HasColumnType("text"); + + b.Property("BillingAddressId") + .HasColumnType("bigint"); + + b.Property("EMail") + .HasColumnType("text"); + + b.Property("Phone") + .HasColumnType("text"); + + b.Property("UserName") + .HasColumnType("text"); + + b.HasKey("UserId"); + + b.ToTable("ClientProviderInfo"); + }); + + modelBuilder.Entity("Yavsc.Abstract.Models.Messaging.Notification", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Target") + .HasMaxLength(512) + .HasColumnType("character varying(512)"); + + b.Property("body") + .IsRequired() + .HasMaxLength(512) + .HasColumnType("character varying(512)"); + + b.Property("click_action") + .IsRequired() + .HasMaxLength(512) + .HasColumnType("character varying(512)"); + + b.Property("color") + .HasMaxLength(512) + .HasColumnType("character varying(512)"); + + b.Property("icon") + .ValueGeneratedOnAdd() + .HasMaxLength(512) + .HasColumnType("character varying(512)") + .HasDefaultValue("exclam"); + + b.Property("sound") + .HasMaxLength(512) + .HasColumnType("character varying(512)"); + + b.Property("tag") + .HasMaxLength(512) + .HasColumnType("character varying(512)"); + + b.Property("title") + .IsRequired() + .HasMaxLength(1024) + .HasColumnType("character varying(1024)"); + + b.HasKey("Id"); + + b.ToTable("Notification"); + }); + + modelBuilder.Entity("Yavsc.Models.Access.Ban", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("DateCreated") + .HasColumnType("timestamp with time zone"); + + b.Property("DateModified") + .HasColumnType("timestamp with time zone"); + + b.Property("Reason") + .IsRequired() + .HasColumnType("text"); + + b.Property("TargetId") + .IsRequired() + .HasColumnType("text"); + + b.Property("UserCreated") + .HasColumnType("text"); + + b.Property("UserModified") + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("TargetId"); + + b.ToTable("Ban"); + }); + + modelBuilder.Entity("Yavsc.Models.Access.BlackListed", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("OwnerId") + .IsRequired() + .HasColumnType("text"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("OwnerId"); + + b.HasIndex("UserId"); + + b.ToTable("BlackListed"); + }); + + modelBuilder.Entity("Yavsc.Models.Access.CircleAuthorizationToBlogPost", b => + { + b.Property("CircleId") + .HasColumnType("bigint"); + + b.Property("BlogPostId") + .HasColumnType("bigint"); + + b.HasKey("CircleId", "BlogPostId"); + + b.HasIndex("BlogPostId"); + + b.ToTable("CircleAuthorizationToBlogPost"); + }); + + modelBuilder.Entity("Yavsc.Models.Access.CircleAuthorizationToFile", b => + { + b.Property("CircleId") + .HasColumnType("bigint"); + + b.Property("Path") + .HasColumnType("text"); + + b.Property("OwnerId") + .HasColumnType("text"); + + b.Property("Access") + .HasColumnType("smallint"); + + b.HasKey("CircleId", "Path", "OwnerId"); + + b.HasIndex("OwnerId"); + + b.ToTable("CircleAuthorizationToFile"); + }); + + modelBuilder.Entity("Yavsc.Models.AccountBalance", b => + { + b.Property("UserId") + .HasColumnType("text"); + + b.Property("ContactCredits") + .HasColumnType("bigint"); + + b.Property("Credits") + .HasColumnType("numeric"); + + b.HasKey("UserId"); + + b.ToTable("BankStatus"); + }); + + modelBuilder.Entity("Yavsc.Models.ApplicationUser", b => + { + b.Property("Id") + .HasColumnType("text"); + + b.Property("AccessFailedCount") + .HasColumnType("integer"); + + b.Property("AllowMonthlyEmail") + .HasColumnType("boolean"); + + b.Property("Avatar") + .ValueGeneratedOnAdd() + .HasMaxLength(512) + .HasColumnType("character varying(512)") + .HasDefaultValue("/images/Users/icon_user.png"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("text"); + + b.Property("DedicatedGoogleCalendar") + .HasMaxLength(512) + .HasColumnType("character varying(512)"); + + b.Property("DiscoveryDiskQuotaUntil") + .HasColumnType("timestamp with time zone"); + + b.Property("DiskQuota") + .ValueGeneratedOnAdd() + .HasColumnType("bigint") + .HasDefaultValue(524288000L); + + b.Property("DiskUsage") + .HasColumnType("bigint"); + + b.Property("Email") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("EmailConfirmed") + .HasColumnType("boolean"); + + b.Property("FullName") + .HasMaxLength(512) + .HasColumnType("character varying(512)"); + + b.Property("HideIpAddressInCalls") + .HasColumnType("boolean"); + + b.Property("LockoutEnabled") + .HasColumnType("boolean"); + + b.Property("LockoutEnd") + .HasColumnType("timestamp with time zone"); + + b.Property("MaxFileSize") + .HasColumnType("bigint"); + + b.Property("NormalizedEmail") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("NormalizedUserName") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("PasswordHash") + .HasColumnType("text"); + + b.Property("PhoneNumber") + .HasColumnType("text"); + + b.Property("PhoneNumberConfirmed") + .HasColumnType("boolean"); + + b.Property("PostalAddressId") + .HasColumnType("bigint"); + + b.Property("PremiumDiskQuotaUntil") + .HasColumnType("timestamp with time zone"); + + b.Property("SecurityStamp") + .HasColumnType("text"); + + b.Property("TwoFactorEnabled") + .HasColumnType("boolean"); + + b.Property("UserName") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Id"); + + b.HasAlternateKey("Email"); + + b.HasIndex("NormalizedEmail") + .HasDatabaseName("EmailIndex"); + + b.HasIndex("NormalizedUserName") + .IsUnique() + .HasDatabaseName("UserNameIndex"); + + b.HasIndex("PostalAddressId"); + + b.ToTable("AspNetUsers", (string)null); + }); + + modelBuilder.Entity("Yavsc.Models.BalanceImpact", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("BalanceId") + .IsRequired() + .HasColumnType("text"); + + b.Property("ExecDate") + .HasColumnType("timestamp with time zone"); + + b.Property("Impact") + .HasColumnType("numeric"); + + b.Property("Reason") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("BalanceId"); + + b.ToTable("BalanceImpact"); + }); + + modelBuilder.Entity("Yavsc.Models.Bank.BankIdentity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("AccountNumber") + .IsRequired() + .HasColumnType("text"); + + b.Property("BIC") + .IsRequired() + .HasColumnType("text"); + + b.Property("BankCode") + .IsRequired() + .HasColumnType("text"); + + b.Property("BankedKey") + .HasColumnType("integer"); + + b.Property("IBAN") + .IsRequired() + .HasColumnType("text"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("text"); + + b.Property("WicketCode") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("BankIdentity"); + }); + + modelBuilder.Entity("Yavsc.Models.Billing.CommandLine", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Count") + .HasColumnType("integer"); + + b.Property("Currency") + .HasColumnType("text"); + + b.Property("Description") + .IsRequired() + .HasMaxLength(512) + .HasColumnType("character varying(512)"); + + b.Property("EstimateId") + .HasColumnType("bigint"); + + b.Property("EstimateTemplateId") + .HasColumnType("bigint"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("UnitaryCost") + .HasColumnType("numeric"); + + b.HasKey("Id"); + + b.HasIndex("EstimateId"); + + b.HasIndex("EstimateTemplateId"); + + b.ToTable("CommandLine"); + }); + + modelBuilder.Entity("Yavsc.Models.Billing.Estimate", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("AttachedFilesString") + .IsRequired() + .HasColumnType("text"); + + b.Property("AttachedGraphicsString") + .IsRequired() + .HasColumnType("text"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("text"); + + b.Property("ClientValidationDate") + .HasColumnType("timestamp with time zone"); + + b.Property("CommandId") + .HasColumnType("bigint"); + + b.Property("CommandType") + .IsRequired() + .HasColumnType("text"); + + b.Property("Description") + .IsRequired() + .HasColumnType("text"); + + b.Property("OwnerId") + .IsRequired() + .HasColumnType("text"); + + b.Property("ProviderValidationDate") + .HasColumnType("timestamp with time zone"); + + b.Property("Title") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("ClientId"); + + b.HasIndex("CommandId"); + + b.HasIndex("OwnerId"); + + b.ToTable("Estimates"); + }); + + modelBuilder.Entity("Yavsc.Models.Billing.EstimateAttachedFile", b => + { + b.Property("FileId") + .HasColumnType("bigint"); + + b.Property("EstimateId") + .HasColumnType("bigint"); + + b.HasKey("FileId", "EstimateId"); + + b.HasIndex("EstimateId"); + + b.ToTable("EstimateAttachedFiles"); + }); + + modelBuilder.Entity("Yavsc.Models.Billing.EstimateTemplate", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Description") + .HasColumnType("text"); + + b.Property("OwnerId") + .IsRequired() + .HasColumnType("text"); + + b.Property("Title") + .HasColumnType("text"); + + b.HasKey("Id"); + + b.ToTable("EstimateTemplates"); + }); + + modelBuilder.Entity("Yavsc.Models.Billing.ExceptionSIREN", b => + { + b.Property("SIREN") + .HasColumnType("text"); + + b.HasKey("SIREN"); + + b.ToTable("ExceptionsSIREN"); + }); + + modelBuilder.Entity("Yavsc.Models.Billing.InvoicePayment", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Amount") + .HasColumnType("numeric"); + + b.Property("CommandId") + .HasColumnType("bigint"); + + b.Property("Currency") + .IsRequired() + .HasMaxLength(3) + .HasColumnType("character varying(3)"); + + b.Property("ReceivedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("RecordedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("RecordedBy") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("character varying(450)"); + + b.Property("Reference") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("ReferenceScope") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("character varying(450)"); + + b.Property("Source") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("character varying(16)"); + + b.HasKey("Id"); + + b.HasIndex("CommandId"); + + b.HasIndex("Source", "ReferenceScope", "Reference") + .IsUnique(); + + b.ToTable("InvoicePayments"); + }); + + modelBuilder.Entity("Yavsc.Models.Billing.NominativeServiceCommand", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ActivityCode") + .IsRequired() + .HasColumnType("text"); + + b.Property("AmountDue") + .HasColumnType("numeric"); + + b.Property("AmountPaid") + .ValueGeneratedOnAdd() + .HasColumnType("numeric") + .HasDefaultValue(0m); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("text"); + + b.Property("Consent") + .HasColumnType("boolean"); + + b.Property("DateCreated") + .HasColumnType("timestamp with time zone"); + + b.Property("DateModified") + .HasColumnType("timestamp with time zone"); + + b.Property("Description") + .IsRequired() + .HasColumnType("text"); + + b.Property("Discriminator") + .IsRequired() + .HasMaxLength(34) + .HasColumnType("character varying(34)"); + + b.Property("InvoiceClientId") + .HasColumnType("text"); + + b.Property("InvoiceCurrency") + .HasMaxLength(3) + .HasColumnType("character varying(3)"); + + b.Property("InvoiceEstimateId") + .HasColumnType("bigint"); + + b.Property("InvoiceLinesJson") + .HasColumnType("text"); + + b.Property("InvoicePerformerId") + .HasColumnType("text"); + + b.Property("InvoicedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("PaymentId") + .HasColumnType("text"); + + b.Property("PaymentRevision") + .IsConcurrencyToken() + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasDefaultValue(new Guid("00000000-0000-0000-0000-000000000000")); + + b.Property("PerformerId") + .IsRequired() + .HasColumnType("text"); + + b.Property("Provisional") + .HasColumnType("numeric"); + + b.Property("Status") + .HasColumnType("integer"); + + b.Property("UserCreated") + .IsRequired() + .HasColumnType("text"); + + b.Property("UserModified") + .IsRequired() + .HasColumnType("text"); + + b.Property("ValidationDate") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("ActivityCode"); + + b.HasIndex("ClientId"); + + b.HasIndex("InvoiceEstimateId") + .IsUnique(); + + b.HasIndex("PaymentId"); + + b.HasIndex("PerformerId"); + + b.ToTable("NominativeServiceCommands"); + + b.HasDiscriminator("Discriminator").HasValue("NominativeServiceCommand"); + + b.UseTphMappingStrategy(); + }); + + modelBuilder.Entity("Yavsc.Models.Billing.QueryAttachedFile", b => + { + b.Property("FileId") + .HasColumnType("bigint"); + + b.Property("CommandId") + .HasColumnType("bigint"); + + b.HasKey("FileId", "CommandId"); + + b.HasIndex("CommandId"); + + b.ToTable("QueryAttachedFiles"); + }); + + modelBuilder.Entity("Yavsc.Models.Billing.Signature", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CapturedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("CoordinateMax") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(10000); + + b.Property("EstimateId") + .HasColumnType("bigint"); + + b.Property("SignerId") + .IsRequired() + .HasColumnType("text"); + + b.PrimitiveCollection("Strokes") + .IsRequired() + .HasColumnType("integer[]"); + + b.Property("Type") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("SignerId"); + + b.HasIndex("EstimateId", "Type") + .IsUnique(); + + b.ToTable("Signatures"); + }); + + modelBuilder.Entity("Yavsc.Models.Blog.BlogAttachedFile", b => + { + b.Property("FileId") + .HasColumnType("bigint"); + + b.Property("PostId") + .HasColumnType("bigint"); + + b.HasKey("FileId", "PostId"); + + b.HasIndex("PostId"); + + b.ToTable("BlogAttachedFiles"); + }); + + modelBuilder.Entity("Yavsc.Models.Blog.BlogPost", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Article") + .HasMaxLength(56224) + .HasColumnType("character varying(56224)"); + + b.Property("AuthorId") + .HasColumnType("text"); + + b.Property("DateCreated") + .HasColumnType("timestamp with time zone"); + + b.Property("DateModified") + .HasColumnType("timestamp with time zone"); + + b.Property("Photo") + .HasMaxLength(1024) + .HasColumnType("character varying(1024)"); + + b.Property("Title") + .IsRequired() + .HasMaxLength(1024) + .HasColumnType("character varying(1024)"); + + b.Property("UserCreated") + .HasColumnType("text"); + + b.Property("UserModified") + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("AuthorId"); + + b.ToTable("BlogSpot"); + }); + + modelBuilder.Entity("Yavsc.Models.Blog.BlogTag", b => + { + b.Property("PostId") + .HasColumnType("bigint"); + + b.Property("TagId") + .HasColumnType("bigint"); + + b.HasKey("PostId", "TagId"); + + b.HasIndex("TagId"); + + b.ToTable("BlogTag"); + }); + + modelBuilder.Entity("Yavsc.Models.Blog.Comment", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Article") + .IsRequired() + .HasColumnType("text"); + + b.Property("AuthorId") + .IsRequired() + .HasColumnType("text"); + + b.Property("DateCreated") + .HasColumnType("timestamp with time zone"); + + b.Property("DateModified") + .HasColumnType("timestamp with time zone"); + + b.Property("ParentId") + .HasColumnType("bigint"); + + b.Property("ReceiverId") + .HasColumnType("bigint"); + + b.Property("UserCreated") + .IsRequired() + .HasColumnType("text"); + + b.Property("UserModified") + .IsRequired() + .HasColumnType("text"); + + b.Property("Visible") + .HasColumnType("boolean"); + + b.HasKey("Id"); + + b.HasIndex("AuthorId"); + + b.HasIndex("ParentId"); + + b.HasIndex("ReceiverId"); + + b.ToTable("Comment"); + }); + + modelBuilder.Entity("Yavsc.Models.Blog.UploadedFile", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ContentType") + .IsRequired() + .HasColumnType("text"); + + b.Property("Length") + .HasColumnType("bigint"); + + b.Property("OwnerId") + .HasColumnType("text"); + + b.Property("Path") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("OwnerId"); + + b.ToTable("UploadedFiles"); + }); + + modelBuilder.Entity("Yavsc.Models.BlogSpotPublication", b => + { + b.Property("PostId") + .HasColumnType("bigint"); + + b.HasKey("PostId"); + + b.ToTable("blogSpotPublications"); + }); + + modelBuilder.Entity("Yavsc.Models.Calendar.Schedule", b => + { + b.Property("OwnerId") + .HasColumnType("text"); + + b.HasKey("OwnerId"); + + b.ToTable("Schedule"); + }); + + modelBuilder.Entity("Yavsc.Models.Calendar.ScheduledEvent", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("PeriodEnd") + .HasColumnType("timestamp with time zone"); + + b.Property("PeriodStart") + .HasColumnType("timestamp with time zone"); + + b.Property("Reccurence") + .HasColumnType("integer"); + + b.Property("ScheduleOwnerId") + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("ScheduleOwnerId"); + + b.HasIndex("PeriodStart", "PeriodEnd"); + + b.ToTable("ScheduledEvent"); + }); + + modelBuilder.Entity("Yavsc.Models.Chat.ChatConnection", b => + { + b.Property("ConnectionId") + .HasColumnType("text"); + + b.Property("ApplicationUserId") + .IsRequired() + .HasColumnType("text"); + + b.Property("Connected") + .HasColumnType("boolean"); + + b.Property("UserAgent") + .HasColumnType("text"); + + b.HasKey("ConnectionId"); + + b.HasIndex("ApplicationUserId"); + + b.ToTable("ChatConnection"); + }); + + modelBuilder.Entity("Yavsc.Models.Chat.ChatRoom", b => + { + b.Property("Name") + .HasColumnType("text"); + + b.Property("DateCreated") + .HasColumnType("timestamp with time zone"); + + b.Property("DateModified") + .HasColumnType("timestamp with time zone"); + + b.Property("LatestJoinPart") + .HasColumnType("timestamp with time zone"); + + b.Property("OwnerId") + .HasColumnType("text"); + + b.Property("Topic") + .HasColumnType("text"); + + b.Property("UserCreated") + .HasColumnType("text"); + + b.Property("UserModified") + .HasColumnType("text"); + + b.HasKey("Name"); + + b.HasIndex("OwnerId"); + + b.ToTable("ChatRoom"); + }); + + modelBuilder.Entity("Yavsc.Models.Chat.ChatRoomAccess", b => + { + b.Property("ChannelName") + .HasColumnType("text"); + + b.Property("UserId") + .HasColumnType("text"); + + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Level") + .HasColumnType("integer"); + + b.HasKey("ChannelName", "UserId"); + + b.HasIndex("UserId"); + + b.ToTable("ChatRoomAccess"); + }); + + modelBuilder.Entity("Yavsc.Models.Cratie.Option", b => + { + b.Property("Code") + .HasColumnType("text"); + + b.Property("CodeScrutin") + .HasColumnType("text"); + + b.Property("DateCreated") + .HasColumnType("timestamp with time zone"); + + b.Property("DateModified") + .HasColumnType("timestamp with time zone"); + + b.Property("Description") + .HasColumnType("text"); + + b.Property("UserCreated") + .HasColumnType("text"); + + b.Property("UserModified") + .HasColumnType("text"); + + b.HasKey("Code", "CodeScrutin"); + + b.ToTable("Option"); + }); + + modelBuilder.Entity("Yavsc.Models.Drawing.Color", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Blue") + .HasColumnType("smallint"); + + b.Property("Green") + .HasColumnType("smallint"); + + b.Property("Name") + .HasColumnType("text"); + + b.Property("Red") + .HasColumnType("smallint"); + + b.HasKey("Id"); + + b.ToTable("Color"); + }); + + modelBuilder.Entity("Yavsc.Models.Haircut.BrusherProfile", b => + { + b.Property("UserId") + .HasColumnType("text"); + + b.Property("ActionDistance") + .HasColumnType("integer"); + + b.Property("CarePrice") + .HasColumnType("numeric"); + + b.Property("FlatFeeDiscount") + .HasColumnType("numeric"); + + b.Property("HalfBalayagePrice") + .HasColumnType("numeric"); + + b.Property("HalfBrushingPrice") + .HasColumnType("numeric"); + + b.Property("HalfColorPrice") + .HasColumnType("numeric"); + + b.Property("HalfDefrisPrice") + .HasColumnType("numeric"); + + b.Property("HalfFoldingPrice") + .HasColumnType("numeric"); + + b.Property("HalfMechPrice") + .HasColumnType("numeric"); + + b.Property("HalfMultiColorPrice") + .HasColumnType("numeric"); + + b.Property("HalfPermanentPrice") + .HasColumnType("numeric"); + + b.Property("KidCutPrice") + .HasColumnType("numeric"); + + b.Property("LongBalayagePrice") + .HasColumnType("numeric"); + + b.Property("LongBrushingPrice") + .HasColumnType("numeric"); + + b.Property("LongColorPrice") + .HasColumnType("numeric"); + + b.Property("LongDefrisPrice") + .HasColumnType("numeric"); + + b.Property("LongFoldingPrice") + .HasColumnType("numeric"); + + b.Property("LongMechPrice") + .HasColumnType("numeric"); + + b.Property("LongMultiColorPrice") + .HasColumnType("numeric"); + + b.Property("LongPermanentPrice") + .HasColumnType("numeric"); + + b.Property("ManBrushPrice") + .HasColumnType("numeric"); + + b.Property("ManCutPrice") + .HasColumnType("numeric"); + + b.Property("ScheduleOwnerId") + .HasColumnType("text"); + + b.Property("ShampooPrice") + .HasColumnType("numeric"); + + b.Property("ShortBalayagePrice") + .HasColumnType("numeric"); + + b.Property("ShortBrushingPrice") + .HasColumnType("numeric"); + + b.Property("ShortColorPrice") + .HasColumnType("numeric"); + + b.Property("ShortDefrisPrice") + .HasColumnType("numeric"); + + b.Property("ShortFoldingPrice") + .HasColumnType("numeric"); + + b.Property("ShortMechPrice") + .HasColumnType("numeric"); + + b.Property("ShortMultiColorPrice") + .HasColumnType("numeric"); + + b.Property("ShortPermanentPrice") + .HasColumnType("numeric"); + + b.Property("WomenHalfCutPrice") + .HasColumnType("numeric"); + + b.Property("WomenLongCutPrice") + .HasColumnType("numeric"); + + b.Property("WomenShortCutPrice") + .HasColumnType("numeric"); + + b.HasKey("UserId"); + + b.HasIndex("ScheduleOwnerId"); + + b.ToTable("BrusherProfile"); + }); + + modelBuilder.Entity("Yavsc.Models.Haircut.HairPrestation", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Cares") + .HasColumnType("boolean"); + + b.Property("Cut") + .HasColumnType("boolean"); + + b.Property("Dressing") + .HasColumnType("integer"); + + b.Property("Gender") + .HasColumnType("integer"); + + b.Property("Length") + .HasColumnType("integer"); + + b.Property("Shampoo") + .HasColumnType("boolean"); + + b.Property("Tech") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.ToTable("HairPrestation"); + }); + + modelBuilder.Entity("Yavsc.Models.Haircut.HairPrestationCollectionItem", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("PrestationId") + .HasColumnType("bigint"); + + b.Property("QueryId") + .HasColumnType("bigint"); + + b.HasKey("Id"); + + b.HasIndex("PrestationId"); + + b.HasIndex("QueryId"); + + b.ToTable("HairPrestationCollectionItem"); + }); + + modelBuilder.Entity("Yavsc.Models.Haircut.HairTaint", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Brand") + .HasColumnType("text"); + + b.Property("ColorId") + .HasColumnType("bigint"); + + b.HasKey("Id"); + + b.HasIndex("ColorId"); + + b.ToTable("HairTaint"); + }); + + modelBuilder.Entity("Yavsc.Models.Haircut.HairTaintInstance", b => + { + b.Property("TaintId") + .HasColumnType("bigint"); + + b.Property("PrestationId") + .HasColumnType("bigint"); + + b.HasKey("TaintId", "PrestationId"); + + b.HasIndex("PrestationId"); + + b.ToTable("HairTaintInstance"); + }); + + modelBuilder.Entity("Yavsc.Models.IT.Evolution.Feature", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Description") + .HasColumnType("text"); + + b.Property("ShortName") + .HasColumnType("text"); + + b.Property("Status") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.ToTable("Feature"); + }); + + modelBuilder.Entity("Yavsc.Models.IT.Fixing.Bug", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Description") + .IsRequired() + .HasMaxLength(10240) + .HasColumnType("character varying(10240)"); + + b.Property("FeatureId") + .HasColumnType("bigint"); + + b.Property("Status") + .HasColumnType("integer"); + + b.Property("Title") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("FeatureId"); + + b.ToTable("Bug"); + }); + + modelBuilder.Entity("Yavsc.Models.Identity.DeviceDeclaration", b => + { + b.Property("DeviceId") + .HasColumnType("text"); + + b.Property("DeclarationDate") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("LOCALTIMESTAMP"); + + b.Property("DeviceOwnerId") + .IsRequired() + .HasColumnType("text"); + + b.Property("LatestActivityUpdate") + .HasColumnType("timestamp with time zone"); + + b.Property("Model") + .IsRequired() + .HasColumnType("text"); + + b.Property("Platform") + .IsRequired() + .HasColumnType("text"); + + b.Property("Version") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("DeviceId"); + + b.HasIndex("DeviceOwnerId"); + + b.ToTable("DeviceDeclaration"); + }); + + modelBuilder.Entity("Yavsc.Models.Kyc.DeclarationFlag", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("DeclarationId") + .HasColumnType("bigint"); + + b.Property("MatchExcerpt") + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("PatternId") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("DeclarationId"); + + b.HasIndex("PatternId"); + + b.ToTable("DeclarationFlag"); + }); + + modelBuilder.Entity("Yavsc.Models.Kyc.ModerationLog", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Action") + .HasColumnType("integer"); + + b.Property("DeclarationId") + .HasColumnType("bigint"); + + b.Property("ModeratorId") + .HasColumnType("text"); + + b.Property("ScoreDelta") + .HasColumnType("integer"); + + b.Property("Timestamp") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("DeclarationId"); + + b.HasIndex("ModeratorId"); + + b.HasIndex("Timestamp"); + + b.ToTable("ModerationLogs", t => + { + t.HasCheckConstraint("CK_ModerationLog_Immutable", "1=1"); + }); + }); + + modelBuilder.Entity("Yavsc.Models.Kyc.RegexAlertPattern", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Description") + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("IsActive") + .HasColumnType("boolean"); + + b.Property("Pattern") + .IsRequired() + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.Property("Severity") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("IsActive"); + + b.ToTable("RegexAlertPatterns"); + }); + + modelBuilder.Entity("Yavsc.Models.Kyc.TrustDeclaration", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Content") + .IsRequired() + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.Property("DeclarantTokenId") + .HasColumnType("uuid"); + + b.Property("ScoreDelta") + .HasColumnType("integer"); + + b.Property("Sentiment") + .HasColumnType("integer"); + + b.Property("Status") + .HasColumnType("integer"); + + b.Property("SubmittedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("TrustTokenId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("Status"); + + b.HasIndex("SubmittedAt"); + + b.HasIndex("TrustTokenId"); + + b.ToTable("TrustDeclarations"); + }); + + modelBuilder.Entity("Yavsc.Models.Kyc.TrustToken", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("TokenHash") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("TokenSource") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("character varying(32)"); + + b.Property("TrustScore") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("TokenHash") + .IsUnique(); + + b.ToTable("TrustTokens"); + }); + + modelBuilder.Entity("Yavsc.Models.Market.Product", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Depth") + .HasColumnType("numeric"); + + b.Property("Description") + .HasColumnType("text"); + + b.Property("Height") + .HasColumnType("numeric"); + + b.Property("Name") + .HasColumnType("text"); + + b.Property("Price") + .HasColumnType("numeric"); + + b.Property("Public") + .HasColumnType("boolean"); + + b.Property("Weight") + .HasColumnType("numeric"); + + b.Property("Width") + .HasColumnType("numeric"); + + b.HasKey("Id"); + + b.ToTable("Products"); + }); + + modelBuilder.Entity("Yavsc.Models.Market.Service", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ContextId") + .HasColumnType("text"); + + b.Property("Description") + .HasColumnType("text"); + + b.Property("Name") + .HasColumnType("text"); + + b.Property("Public") + .HasColumnType("boolean"); + + b.HasKey("Id"); + + b.HasIndex("ContextId"); + + b.ToTable("Services"); + }); + + modelBuilder.Entity("Yavsc.Models.Messaging.Announce", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("For") + .HasColumnType("smallint"); + + b.Property("Message") + .HasColumnType("text"); + + b.Property("OwnerId") + .HasColumnType("text"); + + b.Property("Sender") + .HasColumnType("text"); + + b.Property("Topic") + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("OwnerId"); + + b.ToTable("Announce"); + }); + + modelBuilder.Entity("Yavsc.Models.Messaging.DismissClicked", b => + { + b.Property("UserId") + .HasColumnType("text"); + + b.Property("NotificationId") + .HasColumnType("bigint"); + + b.HasKey("UserId", "NotificationId"); + + b.HasIndex("NotificationId"); + + b.ToTable("DismissClicked"); + }); + + modelBuilder.Entity("Yavsc.Models.Musical.Instrument", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Name") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)"); + + b.HasKey("Id"); + + b.ToTable("Instrument"); + }); + + modelBuilder.Entity("Yavsc.Models.Musical.InstrumentRating", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("InstrumentId") + .HasColumnType("bigint"); + + b.Property("OwnerId") + .IsRequired() + .HasColumnType("text"); + + b.Property("Rate") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasAlternateKey("InstrumentId", "OwnerId"); + + b.HasIndex("OwnerId"); + + b.ToTable("InstrumentRating"); + }); + + modelBuilder.Entity("Yavsc.Models.Musical.MusicalPreference", b => + { + b.Property("OwnerProfileId") + .HasColumnType("text"); + + b.Property("DjSettingsUserId") + .HasColumnType("text"); + + b.Property("MusicLoverSettingsUserId") + .HasColumnType("text"); + + b.Property("Rate") + .HasColumnType("integer"); + + b.Property("TendencyId") + .HasColumnType("bigint"); + + b.HasKey("OwnerProfileId"); + + b.HasIndex("DjSettingsUserId"); + + b.HasIndex("MusicLoverSettingsUserId"); + + b.HasIndex("TendencyId"); + + b.ToTable("MusicalPreference"); + }); + + modelBuilder.Entity("Yavsc.Models.Musical.MusicalTendency", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Name") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)"); + + b.HasKey("Id"); + + b.ToTable("MusicalTendency"); + }); + + modelBuilder.Entity("Yavsc.Models.Musical.Profiles.DjSettings", b => + { + b.Property("UserId") + .HasColumnType("text"); + + b.Property("SoundCloudId") + .HasColumnType("text"); + + b.HasKey("UserId"); + + b.ToTable("DjSettings"); + }); + + modelBuilder.Entity("Yavsc.Models.Musical.Profiles.Instrumentation", b => + { + b.Property("InstrumentId") + .HasColumnType("bigint"); + + b.Property("UserId") + .HasColumnType("text"); + + b.HasKey("InstrumentId", "UserId"); + + b.HasIndex("UserId"); + + b.ToTable("Instrumentation"); + }); + + modelBuilder.Entity("Yavsc.Models.Musical.Profiles.MusicLoverSettings", b => + { + b.Property("UserId") + .HasColumnType("text"); + + b.HasKey("UserId"); + + b.ToTable("MusicLoverSettings"); + }); + + modelBuilder.Entity("Yavsc.Models.Payment.PayPalPayment", b => + { + b.Property("CreationToken") + .HasColumnType("text"); + + b.Property("DateCreated") + .HasColumnType("timestamp with time zone"); + + b.Property("DateModified") + .HasColumnType("timestamp with time zone"); + + b.Property("ExecutorId") + .IsRequired() + .HasColumnType("text"); + + b.Property("OrderReference") + .HasColumnType("text"); + + b.Property("PaypalPayerId") + .HasColumnType("text"); + + b.Property("State") + .HasColumnType("text"); + + b.Property("UserCreated") + .HasColumnType("text"); + + b.Property("UserModified") + .HasColumnType("text"); + + b.HasKey("CreationToken"); + + b.HasIndex("ExecutorId"); + + b.ToTable("PayPalPayment"); + }); + + modelBuilder.Entity("Yavsc.Models.Payment.PerformerDonation", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("Amount") + .HasColumnType("numeric(18,2)"); + + b.Property("CheckoutToken") + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("CompletedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("Currency") + .IsRequired() + .HasMaxLength(3) + .HasColumnType("character varying(3)"); + + b.Property("DonorId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("character varying(450)"); + + b.Property("PerformerId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("character varying(450)"); + + b.Property("RecipientEmail") + .IsRequired() + .HasMaxLength(127) + .HasColumnType("character varying(127)"); + + b.Property("Revision") + .IsConcurrencyToken() + .HasColumnType("uuid"); + + b.Property("State") + .HasColumnType("integer"); + + b.Property("TransactionId") + .HasMaxLength(32) + .HasColumnType("character varying(32)"); + + b.HasKey("Id"); + + b.HasIndex("CheckoutToken") + .IsUnique(); + + b.HasIndex("DonorId"); + + b.HasIndex("PerformerId"); + + b.HasIndex("TransactionId") + .IsUnique(); + + b.ToTable("PerformerDonations"); + }); + + modelBuilder.Entity("Yavsc.Models.Payment.ResourceSubscription", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("LastCreditedCycle") + .HasColumnType("integer"); + + b.Property("MonthlyPoints") + .HasPrecision(28, 8) + .HasColumnType("numeric(28,8)"); + + b.Property("NextBillingAt") + .HasColumnType("timestamp with time zone"); + + b.Property("Pack") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("character varying(32)"); + + b.Property("PayPalId") + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("PlanId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("PriceExcludingTax") + .HasColumnType("numeric(18,2)"); + + b.Property("PriceIncludingTax") + .HasColumnType("numeric(18,2)"); + + b.Property("StartsAt") + .HasColumnType("timestamp with time zone"); + + b.Property("State") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("character varying(32)"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("character varying(450)"); + + b.Property("VatPercent") + .HasColumnType("numeric"); + + b.HasKey("Id"); + + b.HasIndex("PayPalId") + .IsUnique(); + + b.HasIndex("UserId"); + + b.ToTable("ResourceSubscriptions"); + }); + + modelBuilder.Entity("Yavsc.Models.Payment.ResourceSubscriptionPayment", b => + { + b.Property("Id") + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("Cycle") + .HasColumnType("integer"); + + b.Property("GrantedPoints") + .HasPrecision(28, 8) + .HasColumnType("numeric(28,8)"); + + b.Property("PaidAt") + .HasColumnType("timestamp with time zone"); + + b.Property("Reversed") + .HasColumnType("boolean"); + + b.Property("SubscriptionId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("SubscriptionId", "Cycle") + .IsUnique(); + + b.ToTable("ResourceSubscriptionPayments"); + }); + + modelBuilder.Entity("Yavsc.Models.Relationship.Circle", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ApplicationUserId") + .HasColumnType("text"); + + b.Property("Name") + .IsRequired() + .HasColumnType("text"); + + b.Property("OwnerId") + .IsRequired() + .HasColumnType("text"); + + b.Property("Public") + .HasColumnType("boolean"); + + b.HasKey("Id"); + + b.HasIndex("ApplicationUserId"); + + b.ToTable("Circle"); + }); + + modelBuilder.Entity("Yavsc.Models.Relationship.CircleMember", b => + { + b.Property("MemberId") + .HasColumnType("text"); + + b.Property("CircleId") + .HasColumnType("bigint"); + + b.HasKey("MemberId", "CircleId"); + + b.HasIndex("CircleId"); + + b.ToTable("CircleMembers"); + }); + + modelBuilder.Entity("Yavsc.Models.Relationship.Contact", b => + { + b.Property("OwnerId") + .HasColumnType("text"); + + b.Property("UserId") + .HasColumnType("text"); + + b.Property("AddressId") + .HasColumnType("bigint"); + + b.Property("ApplicationUserId") + .HasColumnType("text"); + + b.Property("EMail") + .HasColumnType("text"); + + b.Property("Name") + .HasColumnType("text"); + + b.HasKey("OwnerId", "UserId"); + + b.HasIndex("AddressId"); + + b.HasIndex("ApplicationUserId"); + + b.ToTable("Contact"); + }); + + modelBuilder.Entity("Yavsc.Models.Relationship.HyperLink", b => + { + b.Property("HRef") + .HasColumnType("text"); + + b.Property("Method") + .HasColumnType("text"); + + b.Property("BrusherProfileUserId") + .HasColumnType("text"); + + b.Property("ContentType") + .HasColumnType("text"); + + b.Property("PayPalPaymentCreationToken") + .HasColumnType("text"); + + b.Property("Rel") + .HasColumnType("text"); + + b.HasKey("HRef", "Method"); + + b.HasIndex("BrusherProfileUserId"); + + b.HasIndex("PayPalPaymentCreationToken"); + + b.ToTable("HyperLink"); + }); + + modelBuilder.Entity("Yavsc.Models.Relationship.Location", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Address") + .IsRequired() + .HasMaxLength(512) + .HasColumnType("character varying(512)"); + + b.Property("Latitude") + .HasColumnType("double precision"); + + b.Property("Longitude") + .HasColumnType("double precision"); + + b.HasKey("Id"); + + b.ToTable("Locations"); + }); + + modelBuilder.Entity("Yavsc.Models.Relationship.PostalAddress", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("City") + .HasColumnType("text"); + + b.Property("Country") + .HasColumnType("text"); + + b.Property("PostalCode") + .HasColumnType("text"); + + b.Property("Province") + .HasColumnType("text"); + + b.Property("State") + .HasColumnType("text"); + + b.Property("Street1") + .HasColumnType("text"); + + b.Property("Street2") + .HasColumnType("text"); + + b.HasKey("Id"); + + b.ToTable("PostalAddress"); + }); + + modelBuilder.Entity("Yavsc.Models.Relationship.Tag", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Name") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.ToTable("Tags"); + }); + + modelBuilder.Entity("Yavsc.Models.ResourceStorageRecord", b => + { + b.Property("UserId") + .HasMaxLength(450) + .HasColumnType("character varying(450)"); + + b.Property("Path") + .HasMaxLength(1024) + .HasColumnType("character varying(1024)"); + + b.Property("Bytes") + .HasColumnType("bigint"); + + b.HasKey("UserId", "Path"); + + b.ToTable("ResourceStorageRecords"); + }); + + modelBuilder.Entity("Yavsc.Models.ResourceUsageRecord", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ApiCalls") + .HasColumnType("numeric"); + + b.Property("BandwidthMb") + .HasColumnType("numeric"); + + b.Property("CpuSeconds") + .HasColumnType("numeric"); + + b.Property("CreditPoints") + .ValueGeneratedOnAdd() + .HasPrecision(28, 8) + .HasColumnType("numeric(28,8)") + .HasDefaultValue(0m); + + b.Property("Currency") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(8) + .HasColumnType("character varying(8)") + .HasDefaultValue("EUR"); + + b.Property("DateCreated") + .HasColumnType("timestamp with time zone"); + + b.Property("DateModified") + .HasColumnType("timestamp with time zone"); + + b.Property("EstimatedCompensation") + .HasColumnType("numeric"); + + b.Property("RecordedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("StorageMb") + .HasColumnType("numeric"); + + b.Property("UserCreated") + .HasColumnType("text"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("UserModified") + .HasColumnType("text"); + + b.Property("UserName") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Id"); + + b.HasIndex("UserId", "RecordedAtUtc"); + + b.ToTable("ResourceUsageRecords"); + }); + + modelBuilder.Entity("Yavsc.Models.Skill", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Name") + .HasColumnType("text"); + + b.Property("Rate") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.ToTable("SiteSkills"); + }); + + modelBuilder.Entity("Yavsc.Models.Streaming.LiveFlow", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("DifferedFileName") + .HasColumnType("text"); + + b.Property("MediaType") + .HasColumnType("text"); + + b.Property("OwnerId") + .IsRequired() + .HasColumnType("text"); + + b.Property("Pitch") + .HasColumnType("text"); + + b.Property("PlannedDurationMinutes") + .HasColumnType("integer"); + + b.Property("PodcastDeleted") + .HasColumnType("boolean"); + + b.Property("PodcastId") + .HasColumnType("uuid"); + + b.Property("PreparedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("PublicAnnouncement") + .HasMaxLength(1023) + .HasColumnType("character varying(1023)"); + + b.Property("ScheduledStartAt") + .HasColumnType("timestamp with time zone"); + + b.Property("SequenceNumber") + .HasColumnType("integer"); + + b.Property("StartedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("Title") + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("OwnerId"); + + b.HasIndex("PodcastId") + .IsUnique(); + + b.ToTable("LiveFlow"); + }); + + modelBuilder.Entity("Yavsc.Models.Workflow.Activity", b => + { + b.Property("Code") + .HasColumnType("text"); + + b.Property("DateCreated") + .HasColumnType("timestamp with time zone"); + + b.Property("DateModified") + .HasColumnType("timestamp with time zone"); + + b.Property("Description") + .HasColumnType("text"); + + b.Property("Hidden") + .HasColumnType("boolean"); + + b.Property("Moderated") + .HasColumnType("boolean"); + + b.Property("ModeratorGroupName") + .HasColumnType("text"); + + b.Property("Name") + .IsRequired() + .HasColumnType("text"); + + b.Property("ParentCode") + .HasColumnType("text"); + + b.Property("Photo") + .HasColumnType("text"); + + b.Property("Rate") + .HasColumnType("integer"); + + b.Property("SettingsClassName") + .HasColumnType("text"); + + b.Property("UserCreated") + .HasColumnType("text"); + + b.Property("UserModified") + .HasColumnType("text"); + + b.HasKey("Code"); + + b.HasIndex("ParentCode"); + + b.ToTable("Activities"); + }); + + modelBuilder.Entity("Yavsc.Models.Workflow.CoWorking", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("FormationSettingsUserId") + .HasColumnType("text"); + + b.Property("PerformerId") + .HasColumnType("text"); + + b.Property("WorkingForId") + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("FormationSettingsUserId"); + + b.HasIndex("PerformerId"); + + b.HasIndex("WorkingForId"); + + b.ToTable("CoWorking"); + }); + + modelBuilder.Entity("Yavsc.Models.Workflow.CommandForm", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ActionName") + .HasColumnType("text"); + + b.Property("ActivityCode") + .IsRequired() + .HasColumnType("text"); + + b.Property("Title") + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("ActivityCode"); + + b.ToTable("CommandForm"); + }); + + modelBuilder.Entity("Yavsc.Models.Workflow.Country", b => + { + b.Property("Code") + .HasMaxLength(2) + .HasColumnType("character varying(2)"); + + b.Property("DisplayName") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.HasKey("Code"); + + b.ToTable("Countries"); + + b.HasData( + new + { + Code = "fr", + DisplayName = "France" + }, + new + { + Code = "en", + DisplayName = "England" + }, + new + { + Code = "pt", + DisplayName = "Portugal" + }); + }); + + modelBuilder.Entity("Yavsc.Models.Workflow.DictionnaireMetier", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("DomaineActiviteCode") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("Langue") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + b.Property("Nom") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.HasKey("Id"); + + b.HasIndex("DomaineActiviteCode", "Langue", "Nom") + .IsUnique(); + + b.ToTable("DictionnaireMetier"); + }); + + modelBuilder.Entity("Yavsc.Models.Workflow.PerformerCodeInputValidation", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CountryCode") + .IsRequired() + .HasMaxLength(2) + .HasColumnType("character varying(2)"); + + b.Property("ErrorMessage") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("RegularExpression") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Id"); + + b.HasIndex("CountryCode"); + + b.ToTable("PerformerCodeInputValidations"); + + b.HasData( + new + { + Id = 1L, + CountryCode = "fr", + ErrorMessage = "Le code FR doit contenir entre 9 et 14 chiffres.", + RegularExpression = "^[0-9]{9,14}$" + }, + new + { + Id = 2L, + CountryCode = "en", + ErrorMessage = "Le code EN doit contenir entre 8 et 14 caracteres alphanumeriques.", + RegularExpression = "^[A-Za-z0-9]{8,14}$" + }, + new + { + Id = 3L, + CountryCode = "pt", + ErrorMessage = "Le code PT doit contenir exactement 9 chiffres.", + RegularExpression = "^[0-9]{9}$" + }); + }); + + modelBuilder.Entity("Yavsc.Models.Workflow.PerformerProfile", b => + { + b.Property("PerformerId") + .HasColumnType("text"); + + b.Property("AcceptNotifications") + .HasColumnType("boolean"); + + b.Property("AcceptPublicContact") + .HasColumnType("boolean"); + + b.Property("Active") + .HasColumnType("boolean"); + + b.Property("DonationPayPalEmail") + .HasMaxLength(127) + .HasColumnType("character varying(127)"); + + b.Property("ExerciseCountryCode") + .IsRequired() + .HasColumnType("text"); + + b.Property("MaxDailyCost") + .HasColumnType("integer"); + + b.Property("MinDailyCost") + .HasColumnType("integer"); + + b.Property("OrganizationAddressId") + .HasColumnType("bigint"); + + b.Property("Rate") + .HasColumnType("integer"); + + b.Property("SIREN") + .IsRequired() + .HasColumnType("text"); + + b.Property("UseGeoLocalizationToReduceDistanceWithClients") + .HasColumnType("boolean"); + + b.Property("WebSite") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("PerformerId"); + + b.HasIndex("OrganizationAddressId"); + + b.ToTable("Performers"); + }); + + modelBuilder.Entity("Yavsc.Models.Workflow.Profiles.FormationSettings", b => + { + b.Property("UserId") + .HasColumnType("text"); + + b.Property("DisplayName") + .HasColumnType("text"); + + b.HasKey("UserId"); + + b.ToTable("FormationSettings"); + }); + + modelBuilder.Entity("Yavsc.Models.Workflow.TermeMetier", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("DateSoumission") + .HasColumnType("timestamp with time zone"); + + b.Property("DateValidation") + .HasColumnType("timestamp with time zone"); + + b.Property("Definition") + .IsRequired() + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.Property("DictionnaireMetierId") + .HasColumnType("bigint"); + + b.Property("Langue") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + b.Property("Mot") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("ProposeParId") + .HasMaxLength(450) + .HasColumnType("character varying(450)"); + + b.Property("StatutValidation") + .HasColumnType("integer"); + + b.Property("ValideParId") + .HasMaxLength(450) + .HasColumnType("character varying(450)"); + + b.HasKey("Id"); + + b.HasIndex("ProposeParId"); + + b.HasIndex("ValideParId"); + + b.HasIndex("DictionnaireMetierId", "Langue", "Mot") + .IsUnique(); + + b.ToTable("TermeMetier"); + }); + + modelBuilder.Entity("Yavsc.Models.Workflow.UserActivity", b => + { + b.Property("DoesCode") + .HasColumnType("text"); + + b.Property("UserId") + .HasColumnType("text"); + + b.Property("Weight") + .HasColumnType("integer"); + + b.HasKey("DoesCode", "UserId"); + + b.HasIndex("UserId"); + + b.ToTable("UserActivities"); + }); + + modelBuilder.Entity("Yavsc.Server.Models.Calendar.Period", b => + { + b.Property("Start") + .HasColumnType("timestamp with time zone"); + + b.Property("End") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Start", "End"); + + b.ToTable("Period"); + }); + + modelBuilder.Entity("Yavsc.Server.Models.EMailing.MailingTemplate", b => + { + b.Property("Id") + .HasColumnType("text"); + + b.Property("Body") + .HasMaxLength(65536) + .HasColumnType("character varying(65536)"); + + b.Property("DateCreated") + .HasColumnType("timestamp with time zone"); + + b.Property("DateModified") + .HasColumnType("timestamp with time zone"); + + b.Property("ReplyToAddress") + .HasColumnType("text"); + + b.Property("ToSend") + .HasColumnType("integer"); + + b.Property("Topic") + .HasColumnType("text"); + + b.Property("UserCreated") + .HasColumnType("text"); + + b.Property("UserModified") + .HasColumnType("text"); + + b.HasKey("Id"); + + b.ToTable("MailingTemplate"); + }); + + modelBuilder.Entity("Yavsc.Server.Models.IT.ProjectBuildConfiguration", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Name") + .IsRequired() + .HasColumnType("text"); + + b.Property("ProjectId") + .HasColumnType("bigint"); + + b.HasKey("Id"); + + b.HasIndex("ProjectId"); + + b.ToTable("ProjectBuildConfiguration"); + }); + + modelBuilder.Entity("Yavsc.Server.Models.IT.SourceCode.GitRepositoryReference", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Branch") + .HasColumnType("text"); + + b.Property("OwnerId") + .HasColumnType("text"); + + b.Property("Path") + .IsRequired() + .HasColumnType("text"); + + b.Property("Url") + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("OwnerId"); + + b.ToTable("GitRepositoryReference"); + }); + + modelBuilder.Entity("Yavsc.Models.Haircut.HairCutQuery", b => + { + b.HasBaseType("Yavsc.Models.Billing.NominativeServiceCommand"); + + b.Property("AdditionalInfo") + .IsRequired() + .HasColumnType("text"); + + b.Property("EventDate") + .HasColumnType("timestamp with time zone"); + + b.Property("LocationId") + .HasColumnType("bigint"); + + b.Property("PrestationId") + .HasColumnType("bigint"); + + b.Property("SelectedProfileUserId") + .HasColumnType("text"); + + b.HasIndex("LocationId"); + + b.HasIndex("PrestationId"); + + b.HasIndex("SelectedProfileUserId"); + + b.HasDiscriminator().HasValue("HairCutQuery"); + }); + + modelBuilder.Entity("Yavsc.Models.Haircut.HairMultiCutQuery", b => + { + b.HasBaseType("Yavsc.Models.Billing.NominativeServiceCommand"); + + b.Property("EventDate") + .HasColumnType("timestamp with time zone"); + + b.Property("LocationId") + .HasColumnType("bigint"); + + b.HasIndex("LocationId"); + + b.ToTable("NominativeServiceCommands", t => + { + t.Property("EventDate") + .HasColumnName("HairMultiCutQuery_EventDate"); + + t.Property("LocationId") + .HasColumnName("HairMultiCutQuery_LocationId"); + }); + + b.HasDiscriminator().HasValue("HairMultiCutQuery"); + }); + + modelBuilder.Entity("Yavsc.Models.Workflow.RdvQuery", b => + { + b.HasBaseType("Yavsc.Models.Billing.NominativeServiceCommand"); + + b.Property("EventDate") + .HasColumnType("timestamp with time zone"); + + b.Property("LocationId") + .HasColumnType("bigint"); + + b.Property("LocationType") + .HasColumnType("integer"); + + b.Property("Reason") + .IsRequired() + .HasColumnType("text"); + + b.HasIndex("LocationId"); + + b.ToTable("NominativeServiceCommands", t => + { + t.Property("EventDate") + .HasColumnName("RdvQuery_EventDate"); + + t.Property("LocationId") + .HasColumnName("RdvQuery_LocationId"); + }); + + b.HasDiscriminator().HasValue("RdvQuery"); + }); + + modelBuilder.Entity("Yavsc.Server.Models.IT.Project", b => + { + b.HasBaseType("Yavsc.Models.Billing.NominativeServiceCommand"); + + b.Property("GitId") + .HasColumnType("bigint"); + + b.Property("Name") + .IsRequired() + .HasColumnType("text"); + + b.Property("OwnerId") + .HasColumnType("text"); + + b.Property("Version") + .HasColumnType("text"); + + b.HasIndex("GitId"); + + b.HasDiscriminator().HasValue("Project"); + }); + + modelBuilder.Entity("IdentityServer8.EntityFramework.Entities.ApiResourceClaim", b => + { + b.HasOne("IdentityServer8.EntityFramework.Entities.ApiResource", null) + .WithMany("UserClaims") + .HasForeignKey("ApiResourceId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("IdentityServer8.EntityFramework.Entities.ApiResource", "ApiResource") + .WithMany() + .HasForeignKey("ApiResourceId1"); + + b.Navigation("ApiResource"); + }); + + modelBuilder.Entity("IdentityServer8.EntityFramework.Entities.ApiResourceProperty", b => + { + b.HasOne("IdentityServer8.EntityFramework.Entities.ApiResource", null) + .WithMany("Properties") + .HasForeignKey("ApiResourceId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("IdentityServer8.EntityFramework.Entities.ApiResource", "ApiResource") + .WithMany() + .HasForeignKey("ApiResourceId1"); + + b.Navigation("ApiResource"); + }); + + modelBuilder.Entity("IdentityServer8.EntityFramework.Entities.ApiResourceScope", b => + { + b.HasOne("IdentityServer8.EntityFramework.Entities.ApiResource", null) + .WithMany("Scopes") + .HasForeignKey("ApiResourceId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("IdentityServer8.EntityFramework.Entities.ApiResource", "ApiResource") + .WithMany() + .HasForeignKey("ApiResourceId1"); + + b.Navigation("ApiResource"); + }); + + modelBuilder.Entity("IdentityServer8.EntityFramework.Entities.ApiResourceSecret", b => + { + b.HasOne("IdentityServer8.EntityFramework.Entities.ApiResource", null) + .WithMany("Secrets") + .HasForeignKey("ApiResourceId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("IdentityServer8.EntityFramework.Entities.ApiResource", "ApiResource") + .WithMany() + .HasForeignKey("ApiResourceId1"); + + b.Navigation("ApiResource"); + }); + + modelBuilder.Entity("IdentityServer8.EntityFramework.Entities.ApiScopeClaim", b => + { + b.HasOne("IdentityServer8.EntityFramework.Entities.ApiScope", null) + .WithMany("UserClaims") + .HasForeignKey("ScopeId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("IdentityServer8.EntityFramework.Entities.ApiScope", "Scope") + .WithMany() + .HasForeignKey("ScopeId1"); + + b.Navigation("Scope"); + }); + + modelBuilder.Entity("IdentityServer8.EntityFramework.Entities.ApiScopeProperty", b => + { + b.HasOne("IdentityServer8.EntityFramework.Entities.ApiScope", null) + .WithMany("Properties") + .HasForeignKey("ScopeId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("IdentityServer8.EntityFramework.Entities.ApiScope", "Scope") + .WithMany() + .HasForeignKey("ScopeId1"); + + b.Navigation("Scope"); + }); + + modelBuilder.Entity("IdentityServer8.EntityFramework.Entities.ClientClaim", b => + { + b.HasOne("IdentityServer8.EntityFramework.Entities.Client", "Client") + .WithMany("Claims") + .HasForeignKey("ClientId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Client"); + }); + + modelBuilder.Entity("IdentityServer8.EntityFramework.Entities.ClientCorsOrigin", b => + { + b.HasOne("IdentityServer8.EntityFramework.Entities.Client", null) + .WithMany("AllowedCorsOrigins") + .HasForeignKey("ClientId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("IdentityServer8.EntityFramework.Entities.Client", "Client") + .WithMany() + .HasForeignKey("ClientId1"); + + b.Navigation("Client"); + }); + + modelBuilder.Entity("IdentityServer8.EntityFramework.Entities.ClientGrantType", b => + { + b.HasOne("IdentityServer8.EntityFramework.Entities.Client", "Client") + .WithMany("AllowedGrantTypes") + .HasForeignKey("ClientId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Client"); + }); + + modelBuilder.Entity("IdentityServer8.EntityFramework.Entities.ClientIdPRestriction", b => + { + b.HasOne("IdentityServer8.EntityFramework.Entities.Client", null) + .WithMany("IdentityProviderRestrictions") + .HasForeignKey("ClientId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("IdentityServer8.EntityFramework.Entities.Client", "Client") + .WithMany() + .HasForeignKey("ClientId1"); + + b.Navigation("Client"); + }); + + modelBuilder.Entity("IdentityServer8.EntityFramework.Entities.ClientPostLogoutRedirectUri", b => + { + b.HasOne("IdentityServer8.EntityFramework.Entities.Client", null) + .WithMany("PostLogoutRedirectUris") + .HasForeignKey("ClientId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("IdentityServer8.EntityFramework.Entities.Client", "Client") + .WithMany() + .HasForeignKey("ClientId1"); + + b.Navigation("Client"); + }); + + modelBuilder.Entity("IdentityServer8.EntityFramework.Entities.ClientProperty", b => + { + b.HasOne("IdentityServer8.EntityFramework.Entities.Client", null) + .WithMany("Properties") + .HasForeignKey("ClientId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("IdentityServer8.EntityFramework.Entities.Client", "Client") + .WithMany() + .HasForeignKey("ClientId1"); + + b.Navigation("Client"); + }); + + modelBuilder.Entity("IdentityServer8.EntityFramework.Entities.ClientRedirectUri", b => + { + b.HasOne("IdentityServer8.EntityFramework.Entities.Client", "Client") + .WithMany("RedirectUris") + .HasForeignKey("ClientId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Client"); + }); + + modelBuilder.Entity("IdentityServer8.EntityFramework.Entities.ClientScope", b => + { + b.HasOne("IdentityServer8.EntityFramework.Entities.Client", "Client") + .WithMany("AllowedScopes") + .HasForeignKey("ClientId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Client"); + }); + + modelBuilder.Entity("IdentityServer8.EntityFramework.Entities.ClientSecret", b => + { + b.HasOne("IdentityServer8.EntityFramework.Entities.Client", null) + .WithMany("ClientSecrets") + .HasForeignKey("ClientId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("IdentityServer8.EntityFramework.Entities.Client", "Client") + .WithMany() + .HasForeignKey("ClientId1"); + + b.Navigation("Client"); + }); + + modelBuilder.Entity("IdentityServer8.EntityFramework.Entities.IdentityResourceClaim", b => + { + b.HasOne("IdentityServer8.EntityFramework.Entities.IdentityResource", "IdentityResource") + .WithMany("UserClaims") + .HasForeignKey("IdentityResourceId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("IdentityResource"); + }); + + modelBuilder.Entity("IdentityServer8.EntityFramework.Entities.IdentityResourceProperty", b => + { + b.HasOne("IdentityServer8.EntityFramework.Entities.IdentityResource", "IdentityResource") + .WithMany("Properties") + .HasForeignKey("IdentityResourceId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("IdentityResource"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.HasOne("Yavsc.Models.ApplicationUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.HasOne("Yavsc.Models.ApplicationUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Yavsc.Models.ApplicationUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.HasOne("Yavsc.Models.ApplicationUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Yavsc.Models.Access.Ban", b => + { + b.HasOne("Yavsc.Models.ApplicationUser", "TargetUser") + .WithMany() + .HasForeignKey("TargetId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("TargetUser"); + }); + + modelBuilder.Entity("Yavsc.Models.Access.BlackListed", b => + { + b.HasOne("Yavsc.Models.ApplicationUser", "Owner") + .WithMany("BlackList") + .HasForeignKey("OwnerId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Yavsc.Models.ApplicationUser", "User") + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Owner"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Yavsc.Models.Access.CircleAuthorizationToBlogPost", b => + { + b.HasOne("Yavsc.Models.Blog.BlogPost", "Target") + .WithMany("ACL") + .HasForeignKey("BlogPostId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Yavsc.Models.Relationship.Circle", "Allowed") + .WithMany() + .HasForeignKey("CircleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Allowed"); + + b.Navigation("Target"); + }); + + modelBuilder.Entity("Yavsc.Models.Access.CircleAuthorizationToFile", b => + { + b.HasOne("Yavsc.Models.Relationship.Circle", "Allowed") + .WithMany() + .HasForeignKey("CircleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Yavsc.Models.ApplicationUser", "Owner") + .WithMany() + .HasForeignKey("OwnerId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Allowed"); + + b.Navigation("Owner"); + }); + + modelBuilder.Entity("Yavsc.Models.AccountBalance", b => + { + b.HasOne("Yavsc.Models.ApplicationUser", "Owner") + .WithOne("AccountBalance") + .HasForeignKey("Yavsc.Models.AccountBalance", "UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Owner"); + }); + + modelBuilder.Entity("Yavsc.Models.ApplicationUser", b => + { + b.HasOne("Yavsc.Models.Relationship.Location", "PostalAddress") + .WithMany() + .HasForeignKey("PostalAddressId"); + + b.Navigation("PostalAddress"); + }); + + modelBuilder.Entity("Yavsc.Models.BalanceImpact", b => + { + b.HasOne("Yavsc.Models.AccountBalance", "Balance") + .WithMany() + .HasForeignKey("BalanceId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Balance"); + }); + + modelBuilder.Entity("Yavsc.Models.Bank.BankIdentity", b => + { + b.HasOne("Yavsc.Models.ApplicationUser", "User") + .WithMany("BankInfo") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Yavsc.Models.Billing.CommandLine", b => + { + b.HasOne("Yavsc.Models.Billing.Estimate", null) + .WithMany("Bill") + .HasForeignKey("EstimateId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Yavsc.Models.Billing.EstimateTemplate", null) + .WithMany("Bill") + .HasForeignKey("EstimateTemplateId"); + }); + + modelBuilder.Entity("Yavsc.Models.Billing.Estimate", b => + { + b.HasOne("Yavsc.Models.ApplicationUser", "Client") + .WithMany() + .HasForeignKey("ClientId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Yavsc.Models.Billing.NominativeServiceCommand", "Query") + .WithMany() + .HasForeignKey("CommandId"); + + b.HasOne("Yavsc.Models.Workflow.PerformerProfile", "Owner") + .WithMany() + .HasForeignKey("OwnerId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Client"); + + b.Navigation("Owner"); + + b.Navigation("Query"); + }); + + modelBuilder.Entity("Yavsc.Models.Billing.EstimateAttachedFile", b => + { + b.HasOne("Yavsc.Models.Billing.Estimate", "Estimate") + .WithMany() + .HasForeignKey("EstimateId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Yavsc.Models.Blog.UploadedFile", "File") + .WithMany() + .HasForeignKey("FileId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Estimate"); + + b.Navigation("File"); + }); + + modelBuilder.Entity("Yavsc.Models.Billing.InvoicePayment", b => + { + b.HasOne("Yavsc.Models.Billing.NominativeServiceCommand", "Command") + .WithMany() + .HasForeignKey("CommandId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Command"); + }); + + modelBuilder.Entity("Yavsc.Models.Billing.NominativeServiceCommand", b => + { + b.HasOne("Yavsc.Models.Workflow.Activity", "Context") + .WithMany() + .HasForeignKey("ActivityCode") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Yavsc.Models.ApplicationUser", "Client") + .WithMany() + .HasForeignKey("ClientId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Yavsc.Models.Billing.Estimate", null) + .WithMany() + .HasForeignKey("InvoiceEstimateId") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("Yavsc.Models.Payment.PayPalPayment", "Regularization") + .WithMany() + .HasForeignKey("PaymentId"); + + b.HasOne("Yavsc.Models.Workflow.PerformerProfile", "PerformerProfile") + .WithMany() + .HasForeignKey("PerformerId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Client"); + + b.Navigation("Context"); + + b.Navigation("PerformerProfile"); + + b.Navigation("Regularization"); + }); + + modelBuilder.Entity("Yavsc.Models.Billing.QueryAttachedFile", b => + { + b.HasOne("Yavsc.Models.Billing.NominativeServiceCommand", "Command") + .WithMany() + .HasForeignKey("CommandId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Yavsc.Models.Blog.UploadedFile", "File") + .WithMany() + .HasForeignKey("FileId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Command"); + + b.Navigation("File"); + }); + + modelBuilder.Entity("Yavsc.Models.Billing.Signature", b => + { + b.HasOne("Yavsc.Models.Billing.Estimate", "Estimate") + .WithMany("Signatures") + .HasForeignKey("EstimateId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Yavsc.Models.ApplicationUser", "Signer") + .WithMany() + .HasForeignKey("SignerId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Estimate"); + + b.Navigation("Signer"); + }); + + modelBuilder.Entity("Yavsc.Models.Blog.BlogAttachedFile", b => + { + b.HasOne("Yavsc.Models.Blog.UploadedFile", "File") + .WithMany() + .HasForeignKey("FileId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Yavsc.Models.Blog.BlogPost", "Post") + .WithMany() + .HasForeignKey("PostId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("File"); + + b.Navigation("Post"); + }); + + modelBuilder.Entity("Yavsc.Models.Blog.BlogPost", b => + { + b.HasOne("Yavsc.Models.ApplicationUser", "Author") + .WithMany("Posts") + .HasForeignKey("AuthorId") + .OnDelete(DeleteBehavior.Restrict); + + b.Navigation("Author"); + }); + + modelBuilder.Entity("Yavsc.Models.Blog.BlogTag", b => + { + b.HasOne("Yavsc.Models.Blog.BlogPost", "Post") + .WithMany("Tags") + .HasForeignKey("PostId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Yavsc.Models.Relationship.Tag", "Tag") + .WithMany() + .HasForeignKey("TagId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Post"); + + b.Navigation("Tag"); + }); + + modelBuilder.Entity("Yavsc.Models.Blog.Comment", b => + { + b.HasOne("Yavsc.Models.ApplicationUser", "Author") + .WithMany("BlogComments") + .HasForeignKey("AuthorId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("Yavsc.Models.Blog.Comment", "Parent") + .WithMany("Children") + .HasForeignKey("ParentId"); + + b.HasOne("Yavsc.Models.Blog.BlogPost", "Post") + .WithMany("Comments") + .HasForeignKey("ReceiverId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Author"); + + b.Navigation("Parent"); + + b.Navigation("Post"); + }); + + modelBuilder.Entity("Yavsc.Models.Blog.UploadedFile", b => + { + b.HasOne("Yavsc.Models.ApplicationUser", "Owner") + .WithMany() + .HasForeignKey("OwnerId"); + + b.Navigation("Owner"); + }); + + modelBuilder.Entity("Yavsc.Models.BlogSpotPublication", b => + { + b.HasOne("Yavsc.Models.Blog.BlogPost", "Post") + .WithOne("Publication") + .HasForeignKey("Yavsc.Models.BlogSpotPublication", "PostId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Post"); + }); + + modelBuilder.Entity("Yavsc.Models.Calendar.Schedule", b => + { + b.HasOne("Yavsc.Models.ApplicationUser", "Owner") + .WithMany() + .HasForeignKey("OwnerId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Owner"); + }); + + modelBuilder.Entity("Yavsc.Models.Calendar.ScheduledEvent", b => + { + b.HasOne("Yavsc.Models.Calendar.Schedule", null) + .WithMany("Events") + .HasForeignKey("ScheduleOwnerId"); + + b.HasOne("Yavsc.Server.Models.Calendar.Period", "Period") + .WithMany() + .HasForeignKey("PeriodStart", "PeriodEnd"); + + b.Navigation("Period"); + }); + + modelBuilder.Entity("Yavsc.Models.Chat.ChatConnection", b => + { + b.HasOne("Yavsc.Models.ApplicationUser", "Owner") + .WithMany("Connections") + .HasForeignKey("ApplicationUserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Owner"); + }); + + modelBuilder.Entity("Yavsc.Models.Chat.ChatRoom", b => + { + b.HasOne("Yavsc.Models.ApplicationUser", "Owner") + .WithMany("Rooms") + .HasForeignKey("OwnerId"); + + b.Navigation("Owner"); + }); + + modelBuilder.Entity("Yavsc.Models.Chat.ChatRoomAccess", b => + { + b.HasOne("Yavsc.Models.Chat.ChatRoom", "Room") + .WithMany("Moderation") + .HasForeignKey("ChannelName") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Yavsc.Models.ApplicationUser", "User") + .WithMany("RoomAccess") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Room"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Yavsc.Models.Haircut.BrusherProfile", b => + { + b.HasOne("Yavsc.Models.Calendar.Schedule", "Schedule") + .WithMany() + .HasForeignKey("ScheduleOwnerId"); + + b.HasOne("Yavsc.Models.Workflow.PerformerProfile", "BaseProfile") + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("BaseProfile"); + + b.Navigation("Schedule"); + }); + + modelBuilder.Entity("Yavsc.Models.Haircut.HairPrestationCollectionItem", b => + { + b.HasOne("Yavsc.Models.Haircut.HairPrestation", "Prestation") + .WithMany() + .HasForeignKey("PrestationId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Yavsc.Models.Haircut.HairMultiCutQuery", "Query") + .WithMany("Prestations") + .HasForeignKey("QueryId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Prestation"); + + b.Navigation("Query"); + }); + + modelBuilder.Entity("Yavsc.Models.Haircut.HairTaint", b => + { + b.HasOne("Yavsc.Models.Drawing.Color", "Color") + .WithMany() + .HasForeignKey("ColorId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Color"); + }); + + modelBuilder.Entity("Yavsc.Models.Haircut.HairTaintInstance", b => + { + b.HasOne("Yavsc.Models.Haircut.HairPrestation", "Prestation") + .WithMany("Taints") + .HasForeignKey("PrestationId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Yavsc.Models.Haircut.HairTaint", "Taint") + .WithMany() + .HasForeignKey("TaintId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Prestation"); + + b.Navigation("Taint"); + }); + + modelBuilder.Entity("Yavsc.Models.IT.Fixing.Bug", b => + { + b.HasOne("Yavsc.Models.IT.Evolution.Feature", "False") + .WithMany() + .HasForeignKey("FeatureId"); + + b.Navigation("False"); + }); + + modelBuilder.Entity("Yavsc.Models.Identity.DeviceDeclaration", b => + { + b.HasOne("Yavsc.Models.ApplicationUser", "DeviceOwner") + .WithMany("DeviceDeclaration") + .HasForeignKey("DeviceOwnerId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("DeviceOwner"); + }); + + modelBuilder.Entity("Yavsc.Models.Kyc.DeclarationFlag", b => + { + b.HasOne("Yavsc.Models.Kyc.TrustDeclaration", "Declaration") + .WithMany("Flags") + .HasForeignKey("DeclarationId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Yavsc.Models.Kyc.RegexAlertPattern", "Pattern") + .WithMany() + .HasForeignKey("PatternId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Declaration"); + + b.Navigation("Pattern"); + }); + + modelBuilder.Entity("Yavsc.Models.Kyc.ModerationLog", b => + { + b.HasOne("Yavsc.Models.Kyc.TrustDeclaration", "Declaration") + .WithMany() + .HasForeignKey("DeclarationId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Declaration"); + }); + + modelBuilder.Entity("Yavsc.Models.Kyc.TrustDeclaration", b => + { + b.HasOne("Yavsc.Models.Kyc.TrustToken", "Subject") + .WithMany("Declarations") + .HasForeignKey("TrustTokenId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Subject"); + }); + + modelBuilder.Entity("Yavsc.Models.Market.Service", b => + { + b.HasOne("Yavsc.Models.Workflow.Activity", "Context") + .WithMany("Services") + .HasForeignKey("ContextId"); + + b.Navigation("Context"); + }); + + modelBuilder.Entity("Yavsc.Models.Messaging.Announce", b => + { + b.HasOne("Yavsc.Models.ApplicationUser", "Owner") + .WithMany() + .HasForeignKey("OwnerId"); + + b.Navigation("Owner"); + }); + + modelBuilder.Entity("Yavsc.Models.Messaging.DismissClicked", b => + { + b.HasOne("Yavsc.Abstract.Models.Messaging.Notification", "Notified") + .WithMany() + .HasForeignKey("NotificationId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Yavsc.Models.ApplicationUser", "User") + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Notified"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Yavsc.Models.Musical.InstrumentRating", b => + { + b.HasOne("Yavsc.Models.Musical.Instrument", "Instrument") + .WithMany() + .HasForeignKey("InstrumentId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Yavsc.Models.Workflow.PerformerProfile", "Profile") + .WithMany() + .HasForeignKey("OwnerId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Instrument"); + + b.Navigation("Profile"); + }); + + modelBuilder.Entity("Yavsc.Models.Musical.MusicalPreference", b => + { + b.HasOne("Yavsc.Models.Musical.Profiles.DjSettings", null) + .WithMany("SoundColor") + .HasForeignKey("DjSettingsUserId"); + + b.HasOne("Yavsc.Models.Musical.Profiles.MusicLoverSettings", null) + .WithMany("SoundColor") + .HasForeignKey("MusicLoverSettingsUserId"); + + b.HasOne("Yavsc.Models.Musical.MusicalTendency", "MusicalTendency") + .WithMany() + .HasForeignKey("TendencyId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("MusicalTendency"); + }); + + modelBuilder.Entity("Yavsc.Models.Musical.Profiles.Instrumentation", b => + { + b.HasOne("Yavsc.Models.Musical.Instrument", "Tool") + .WithMany() + .HasForeignKey("InstrumentId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Yavsc.Models.Workflow.PerformerProfile", "User") + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Tool"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Yavsc.Models.Payment.PayPalPayment", b => + { + b.HasOne("Yavsc.Models.ApplicationUser", "Executor") + .WithMany() + .HasForeignKey("ExecutorId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Executor"); + }); + + modelBuilder.Entity("Yavsc.Models.Payment.PerformerDonation", b => + { + b.HasOne("Yavsc.Models.ApplicationUser", null) + .WithMany() + .HasForeignKey("DonorId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("Yavsc.Models.Workflow.PerformerProfile", null) + .WithMany() + .HasForeignKey("PerformerId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("Yavsc.Models.Payment.ResourceSubscription", b => + { + b.HasOne("Yavsc.Models.ApplicationUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("Yavsc.Models.Payment.ResourceSubscriptionPayment", b => + { + b.HasOne("Yavsc.Models.Payment.ResourceSubscription", null) + .WithMany() + .HasForeignKey("SubscriptionId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("Yavsc.Models.Relationship.Circle", b => + { + b.HasOne("Yavsc.Models.ApplicationUser", null) + .WithMany("Circles") + .HasForeignKey("ApplicationUserId"); + }); + + modelBuilder.Entity("Yavsc.Models.Relationship.CircleMember", b => + { + b.HasOne("Yavsc.Models.Relationship.Circle", "Circle") + .WithMany("Members") + .HasForeignKey("CircleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Yavsc.Models.ApplicationUser", "Member") + .WithMany("Membership") + .HasForeignKey("MemberId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Circle"); + + b.Navigation("Member"); + }); + + modelBuilder.Entity("Yavsc.Models.Relationship.Contact", b => + { + b.HasOne("Yavsc.Models.Relationship.PostalAddress", "PostalAddress") + .WithMany() + .HasForeignKey("AddressId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Yavsc.Models.ApplicationUser", null) + .WithMany("Book") + .HasForeignKey("ApplicationUserId"); + + b.Navigation("PostalAddress"); + }); + + modelBuilder.Entity("Yavsc.Models.Relationship.HyperLink", b => + { + b.HasOne("Yavsc.Models.Haircut.BrusherProfile", null) + .WithMany("Links") + .HasForeignKey("BrusherProfileUserId"); + + b.HasOne("Yavsc.Models.Payment.PayPalPayment", null) + .WithMany("Links") + .HasForeignKey("PayPalPaymentCreationToken"); + }); + + modelBuilder.Entity("Yavsc.Models.Streaming.LiveFlow", b => + { + b.HasOne("Yavsc.Models.ApplicationUser", "Owner") + .WithMany() + .HasForeignKey("OwnerId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Owner"); + }); + + modelBuilder.Entity("Yavsc.Models.Workflow.Activity", b => + { + b.HasOne("Yavsc.Models.Workflow.Activity", "Parent") + .WithMany("Children") + .HasForeignKey("ParentCode"); + + b.Navigation("Parent"); + }); + + modelBuilder.Entity("Yavsc.Models.Workflow.CoWorking", b => + { + b.HasOne("Yavsc.Models.Workflow.Profiles.FormationSettings", null) + .WithMany("CoWorking") + .HasForeignKey("FormationSettingsUserId"); + + b.HasOne("Yavsc.Models.Workflow.PerformerProfile", "Performer") + .WithMany() + .HasForeignKey("PerformerId"); + + b.HasOne("Yavsc.Models.ApplicationUser", "WorkingFor") + .WithMany() + .HasForeignKey("WorkingForId"); + + b.Navigation("Performer"); + + b.Navigation("WorkingFor"); + }); + + modelBuilder.Entity("Yavsc.Models.Workflow.CommandForm", b => + { + b.HasOne("Yavsc.Models.Workflow.Activity", "Context") + .WithMany("Forms") + .HasForeignKey("ActivityCode") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Context"); + }); + + modelBuilder.Entity("Yavsc.Models.Workflow.DictionnaireMetier", b => + { + b.HasOne("Yavsc.Models.Workflow.Activity", "DomaineActivite") + .WithMany() + .HasForeignKey("DomaineActiviteCode") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("DomaineActivite"); + }); + + modelBuilder.Entity("Yavsc.Models.Workflow.PerformerCodeInputValidation", b => + { + b.HasOne("Yavsc.Models.Workflow.Country", "Country") + .WithMany() + .HasForeignKey("CountryCode") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Country"); + }); + + modelBuilder.Entity("Yavsc.Models.Workflow.PerformerProfile", b => + { + b.HasOne("Yavsc.Models.Relationship.Location", "OrganizationAddress") + .WithMany() + .HasForeignKey("OrganizationAddressId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Yavsc.Models.ApplicationUser", "Performer") + .WithMany() + .HasForeignKey("PerformerId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("OrganizationAddress"); + + b.Navigation("Performer"); + }); + + modelBuilder.Entity("Yavsc.Models.Workflow.TermeMetier", b => + { + b.HasOne("Yavsc.Models.Workflow.DictionnaireMetier", "DictionnaireMetier") + .WithMany("Termes") + .HasForeignKey("DictionnaireMetierId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Yavsc.Models.ApplicationUser", "ProposePar") + .WithMany() + .HasForeignKey("ProposeParId"); + + b.HasOne("Yavsc.Models.ApplicationUser", "ValidePar") + .WithMany() + .HasForeignKey("ValideParId"); + + b.Navigation("DictionnaireMetier"); + + b.Navigation("ProposePar"); + + b.Navigation("ValidePar"); + }); + + modelBuilder.Entity("Yavsc.Models.Workflow.UserActivity", b => + { + b.HasOne("Yavsc.Models.Workflow.Activity", "Does") + .WithMany() + .HasForeignKey("DoesCode") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Yavsc.Models.Workflow.PerformerProfile", "User") + .WithMany("Activity") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Does"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Yavsc.Server.Models.IT.ProjectBuildConfiguration", b => + { + b.HasOne("Yavsc.Server.Models.IT.Project", "TargetProject") + .WithMany("Configurations") + .HasForeignKey("ProjectId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("TargetProject"); + }); + + modelBuilder.Entity("Yavsc.Server.Models.IT.SourceCode.GitRepositoryReference", b => + { + b.HasOne("Yavsc.Models.ApplicationUser", "Owner") + .WithMany() + .HasForeignKey("OwnerId"); + + b.Navigation("Owner"); + }); + + modelBuilder.Entity("Yavsc.Models.Haircut.HairCutQuery", b => + { + b.HasOne("Yavsc.Models.Relationship.Location", "Location") + .WithMany() + .HasForeignKey("LocationId"); + + b.HasOne("Yavsc.Models.Haircut.HairPrestation", "Prestation") + .WithMany() + .HasForeignKey("PrestationId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Yavsc.Models.Haircut.BrusherProfile", "SelectedProfile") + .WithMany() + .HasForeignKey("SelectedProfileUserId"); + + b.Navigation("Location"); + + b.Navigation("Prestation"); + + b.Navigation("SelectedProfile"); + }); + + modelBuilder.Entity("Yavsc.Models.Haircut.HairMultiCutQuery", b => + { + b.HasOne("Yavsc.Models.Relationship.Location", "Location") + .WithMany() + .HasForeignKey("LocationId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Location"); + }); + + modelBuilder.Entity("Yavsc.Models.Workflow.RdvQuery", b => + { + b.HasOne("Yavsc.Models.Relationship.Location", "Location") + .WithMany() + .HasForeignKey("LocationId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Location"); + }); + + modelBuilder.Entity("Yavsc.Server.Models.IT.Project", b => + { + b.HasOne("Yavsc.Server.Models.IT.SourceCode.GitRepositoryReference", "Repository") + .WithMany() + .HasForeignKey("GitId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Repository"); + }); + + modelBuilder.Entity("IdentityServer8.EntityFramework.Entities.ApiResource", b => + { + b.Navigation("Properties"); + + b.Navigation("Scopes"); + + b.Navigation("Secrets"); + + b.Navigation("UserClaims"); + }); + + modelBuilder.Entity("IdentityServer8.EntityFramework.Entities.ApiScope", b => + { + b.Navigation("Properties"); + + b.Navigation("UserClaims"); + }); + + modelBuilder.Entity("IdentityServer8.EntityFramework.Entities.Client", b => + { + b.Navigation("AllowedCorsOrigins"); + + b.Navigation("AllowedGrantTypes"); + + b.Navigation("AllowedScopes"); + + b.Navigation("Claims"); + + b.Navigation("ClientSecrets"); + + b.Navigation("IdentityProviderRestrictions"); + + b.Navigation("PostLogoutRedirectUris"); + + b.Navigation("Properties"); + + b.Navigation("RedirectUris"); + }); + + modelBuilder.Entity("IdentityServer8.EntityFramework.Entities.IdentityResource", b => + { + b.Navigation("Properties"); + + b.Navigation("UserClaims"); + }); + + modelBuilder.Entity("Yavsc.Models.ApplicationUser", b => + { + b.Navigation("AccountBalance"); + + b.Navigation("BankInfo"); + + b.Navigation("BlackList"); + + b.Navigation("BlogComments"); + + b.Navigation("Book"); + + b.Navigation("Circles"); + + b.Navigation("Connections"); + + b.Navigation("DeviceDeclaration"); + + b.Navigation("Membership"); + + b.Navigation("Posts"); + + b.Navigation("RoomAccess"); + + b.Navigation("Rooms"); + }); + + modelBuilder.Entity("Yavsc.Models.Billing.Estimate", b => + { + b.Navigation("Bill"); + + b.Navigation("Signatures"); + }); + + modelBuilder.Entity("Yavsc.Models.Billing.EstimateTemplate", b => + { + b.Navigation("Bill"); + }); + + modelBuilder.Entity("Yavsc.Models.Blog.BlogPost", b => + { + b.Navigation("ACL"); + + b.Navigation("Comments"); + + b.Navigation("Publication") + .IsRequired(); + + b.Navigation("Tags"); + }); + + modelBuilder.Entity("Yavsc.Models.Blog.Comment", b => + { + b.Navigation("Children"); + }); + + modelBuilder.Entity("Yavsc.Models.Calendar.Schedule", b => + { + b.Navigation("Events"); + }); + + modelBuilder.Entity("Yavsc.Models.Chat.ChatRoom", b => + { + b.Navigation("Moderation"); + }); + + modelBuilder.Entity("Yavsc.Models.Haircut.BrusherProfile", b => + { + b.Navigation("Links"); + }); + + modelBuilder.Entity("Yavsc.Models.Haircut.HairPrestation", b => + { + b.Navigation("Taints"); + }); + + modelBuilder.Entity("Yavsc.Models.Kyc.TrustDeclaration", b => + { + b.Navigation("Flags"); + }); + + modelBuilder.Entity("Yavsc.Models.Kyc.TrustToken", b => + { + b.Navigation("Declarations"); + }); + + modelBuilder.Entity("Yavsc.Models.Musical.Profiles.DjSettings", b => + { + b.Navigation("SoundColor"); + }); + + modelBuilder.Entity("Yavsc.Models.Musical.Profiles.MusicLoverSettings", b => + { + b.Navigation("SoundColor"); + }); + + modelBuilder.Entity("Yavsc.Models.Payment.PayPalPayment", b => + { + b.Navigation("Links"); + }); + + modelBuilder.Entity("Yavsc.Models.Relationship.Circle", b => + { + b.Navigation("Members"); + }); + + modelBuilder.Entity("Yavsc.Models.Workflow.Activity", b => + { + b.Navigation("Children"); + + b.Navigation("Forms"); + + b.Navigation("Services"); + }); + + modelBuilder.Entity("Yavsc.Models.Workflow.DictionnaireMetier", b => + { + b.Navigation("Termes"); + }); + + modelBuilder.Entity("Yavsc.Models.Workflow.PerformerProfile", b => + { + b.Navigation("Activity"); + }); + + modelBuilder.Entity("Yavsc.Models.Workflow.Profiles.FormationSettings", b => + { + b.Navigation("CoWorking"); + }); + + modelBuilder.Entity("Yavsc.Models.Haircut.HairMultiCutQuery", b => + { + b.Navigation("Prestations"); + }); + + modelBuilder.Entity("Yavsc.Server.Models.IT.Project", b => + { + b.Navigation("Configurations"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/Yavsc.Org/Migrations/20261108052221_RefundableResourceStorage.cs b/src/Yavsc.Org/Migrations/20261108052221_RefundableResourceStorage.cs new file mode 100644 index 000000000..367ec16a0 --- /dev/null +++ b/src/Yavsc.Org/Migrations/20261108052221_RefundableResourceStorage.cs @@ -0,0 +1,34 @@ +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Yavsc.Migrations +{ + /// + public partial class RefundableResourceStorage : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "ResourceStorageRecords", + columns: table => new + { + UserId = table.Column(type: "character varying(450)", maxLength: 450, nullable: false), + Path = table.Column(type: "character varying(1024)", maxLength: 1024, nullable: false), + Bytes = table.Column(type: "bigint", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_ResourceStorageRecords", x => new { x.UserId, x.Path }); + }); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "ResourceStorageRecords"); + } + } +} diff --git a/src/Yavsc.Org/Migrations/ApplicationDbContextModelSnapshot.cs b/src/Yavsc.Org/Migrations/ApplicationDbContextModelSnapshot.cs index f65103aa0..c800698c7 100644 --- a/src/Yavsc.Org/Migrations/ApplicationDbContextModelSnapshot.cs +++ b/src/Yavsc.Org/Migrations/ApplicationDbContextModelSnapshot.cs @@ -3081,6 +3081,24 @@ namespace Yavsc.Migrations b.ToTable("Tags"); }); + modelBuilder.Entity("Yavsc.Models.ResourceStorageRecord", b => + { + b.Property("UserId") + .HasMaxLength(450) + .HasColumnType("character varying(450)"); + + b.Property("Path") + .HasMaxLength(1024) + .HasColumnType("character varying(1024)"); + + b.Property("Bytes") + .HasColumnType("bigint"); + + b.HasKey("UserId", "Path"); + + b.ToTable("ResourceStorageRecords"); + }); + modelBuilder.Entity("Yavsc.Models.ResourceUsageRecord", b => { b.Property("Id") diff --git a/src/Yavsc.Org/Views/Home/CGU.cshtml b/src/Yavsc.Org/Views/Home/CGU.cshtml index 7e3c2bb75..384a6725f 100644 --- a/src/Yavsc.Org/Views/Home/CGU.cshtml +++ b/src/Yavsc.Org/Views/Home/CGU.cshtml @@ -36,7 +36,10 @@
  • Le stockage est le volume cumulé ajouté par les opérations instrumentées (fichiers personnels et génération de PDF), - pas l'espace disque actuellement occupé : suppression et remplacement ne remboursent pas de points. + diminué des volumes comptabilisés supprimés ou remplacés : ces opérations remboursent les points de stockage associés. + Un remplacement rembourse l'ancien volume suivi puis comptabilise le nouveau. + Les anciens fichiers sans suivi individuel ne donnent pas de remboursement ; le compteur de stockage ne devient jamais négatif. + Les points d'appels API, de CPU et de transfert ne sont pas remboursés.
  • Le compteur historique « CPU » contient les durées enregistrées par les traitements instrumentés, @@ -44,6 +47,7 @@ Les ressources locales de PostIt, les appels directs entre appareils et le trafic WebSocket ne sont pas mesurés par cet indicateur HTTP.
  • +

    La suppression de fichiers reste autorisée même lorsque le seuil de consommation est atteint, afin de libérer du stockage.

    Le calcul utilise les valeurs décimales non arrondies ; l'arrondi de l'affichage ne décide pas du blocage. Cet indicateur n'est ni un prix, ni une facture, ni une estimation de compensation financière. diff --git a/src/Yavsc.Server/Helpers/ResourceUsageReliefAttribute.cs b/src/Yavsc.Server/Helpers/ResourceUsageReliefAttribute.cs new file mode 100644 index 000000000..116caf505 --- /dev/null +++ b/src/Yavsc.Server/Helpers/ResourceUsageReliefAttribute.cs @@ -0,0 +1,4 @@ +namespace Yavsc.Server.Helpers; + +[AttributeUsage(AttributeTargets.Method)] +public sealed class ResourceUsageReliefAttribute : Attribute; diff --git a/src/Yavsc.Server/Helpers/ResourceUsageTelemetryMiddleware.cs b/src/Yavsc.Server/Helpers/ResourceUsageTelemetryMiddleware.cs index 9e0fd4365..289e659f2 100644 --- a/src/Yavsc.Server/Helpers/ResourceUsageTelemetryMiddleware.cs +++ b/src/Yavsc.Server/Helpers/ResourceUsageTelemetryMiddleware.cs @@ -24,7 +24,14 @@ public sealed class ResourceUsageTelemetryMiddleware( var userName = context.User.Identity?.Name ?? userId; var requestBytes = context.Request.ContentLength ?? 0L; - if (!await usage.TryAdmitAsync(userId, userName, 1m, ToMb(requestBytes), 0, + var relief = context.GetEndpoint()?.Metadata.GetMetadata() is not null; + if (relief) + { + using var admissionScope = scopeFactory.CreateScope(); + await ResourceUsageTracker.RecordAsync(admissionScope.ServiceProvider.GetRequiredService(), + userId, userName, apiCalls: 1m, bandwidthMb: ToMb(requestBytes), actorUserId: userId); + } + else if (!await usage.TryAdmitAsync(userId, userName, 1m, ToMb(requestBytes), 0, context.RequestAborted)) { logger.LogWarning("Resource quota refused a request for user {UserId}", userId); diff --git a/src/Yavsc.Server/Helpers/ResourceUsageTracker.cs b/src/Yavsc.Server/Helpers/ResourceUsageTracker.cs index 873dc10c4..a83837a96 100644 --- a/src/Yavsc.Server/Helpers/ResourceUsageTracker.cs +++ b/src/Yavsc.Server/Helpers/ResourceUsageTracker.cs @@ -9,6 +9,55 @@ public static class ResourceUsageTracker { private static readonly SemaphoreSlim LocalGate = new(1, 1); + public static Task RecordStorageAsync(ApplicationDbContext db, string userId, string userName, + string path, long bytes, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(db); + ArgumentException.ThrowIfNullOrWhiteSpace(userId); + ArgumentException.ThrowIfNullOrWhiteSpace(path); + ArgumentOutOfRangeException.ThrowIfNegative(bytes); + return WithUserLockAsync(db, userId, async () => + { + var stored = await db.ResourceStorageRecords.FindAsync([userId, path], cancellationToken); + if (stored is not null) await db.Entry(stored).ReloadAsync(cancellationToken); + var delta = bytes - (stored?.Bytes ?? 0L); + if (stored is null && bytes > 0) + db.ResourceStorageRecords.Add(new ResourceStorageRecord { UserId = userId, Path = path, Bytes = bytes }); + else if (stored is not null) + { + if (bytes == 0) db.ResourceStorageRecords.Remove(stored); + else stored.Bytes = bytes; + } + await UpdateCoreAsync(db, userId, userName, 0m, delta, 0m, 0m, + userId, Constants.ResourceUsageDefaultCurrency, null, 0, cancellationToken); + await db.SaveChangesAsync(userId, cancellationToken); + return true; + }, cancellationToken); + } + + public static Task MoveStorageAsync(ApplicationDbContext db, string userId, string from, string to, + CancellationToken cancellationToken = default) + => WithUserLockAsync(db, userId, async () => + { + ArgumentException.ThrowIfNullOrWhiteSpace(from); + ArgumentException.ThrowIfNullOrWhiteSpace(to); + if (from == to) return true; + var records = await db.ResourceStorageRecords.Where(r => r.UserId == userId + && (r.Path == from || r.Path.StartsWith(from + "/"))).ToListAsync(cancellationToken); + foreach (var record in records) + { + db.ResourceStorageRecords.Remove(record); + db.ResourceStorageRecords.Add(new ResourceStorageRecord + { + UserId = userId, + Path = to + record.Path.Substring(from.Length), + Bytes = record.Bytes + }); + } + await db.SaveChangesAsync(userId, cancellationToken); + return true; + }, cancellationToken); + public static async Task RecordAsync( ApplicationDbContext dbContext, string userId, @@ -42,57 +91,64 @@ public static class ResourceUsageTracker ArgumentOutOfRangeException.ThrowIfNegative(anticipatedStorageBytes); return await WithUserLockAsync(dbContext, userId, async () => + await UpdateCoreAsync(dbContext, userId, userName, cpuSeconds, storageBytes, apiCalls, + bandwidthMb, actorUserId, currency, policy, anticipatedStorageBytes, cancellationToken), cancellationToken); + } + + private static async Task UpdateCoreAsync(ApplicationDbContext dbContext, + string userId, string userName, decimal cpuSeconds, long storageBytes, decimal apiCalls, + decimal bandwidthMb, string? actorUserId, string currency, ResourceUsageOptions? policy, + long anticipatedStorageBytes, CancellationToken cancellationToken) + { + var effectiveActor = string.IsNullOrWhiteSpace(actorUserId) ? userId : actorUserId; + var now = DateTime.UtcNow; + var storageMb = (decimal)storageBytes / (1024m * 1024m); + var record = await dbContext.ResourceUsageRecords + .Where(r => r.UserId == userId) + .OrderByDescending(r => r.RecordedAtUtc).ThenByDescending(r => r.Id) + .FirstOrDefaultAsync(cancellationToken); + if (record is not null) + await dbContext.Entry(record).ReloadAsync(cancellationToken); + + if (policy is not null) { - var effectiveActor = string.IsNullOrWhiteSpace(actorUserId) ? userId : actorUserId; - var now = DateTime.UtcNow; - var storageMb = (decimal)storageBytes / (1024m * 1024m); - var record = await dbContext.ResourceUsageRecords - .Where(r => r.UserId == userId) - .OrderByDescending(r => r.RecordedAtUtc).ThenByDescending(r => r.Id) - .FirstOrDefaultAsync(cancellationToken); - if (record is not null) - await dbContext.Entry(record).ReloadAsync(cancellationToken); + var gross = record is null ? 0m : + policy.Calculate(record.ApiCalls, record.CpuSeconds, record.BandwidthMb, record.StorageMb); + var current = ResourceUsageCredit.NetConsumption(gross, record?.CreditPoints ?? 0m); + var projected = ResourceUsageCredit.NetConsumption(gross + policy.Calculate(apiCalls, cpuSeconds, bandwidthMb, + storageMb + (decimal)anticipatedStorageBytes / (1024m * 1024m)), record?.CreditPoints ?? 0m); + var limit = policy.GetLimit(userId); + if (current >= limit || projected > limit) return null; + } - if (policy is not null) - { - var gross = record is null ? 0m : - policy.Calculate(record.ApiCalls, record.CpuSeconds, record.BandwidthMb, record.StorageMb); - var current = ResourceUsageCredit.NetConsumption(gross, record?.CreditPoints ?? 0m); - var projected = ResourceUsageCredit.NetConsumption(gross + policy.Calculate(apiCalls, cpuSeconds, bandwidthMb, - storageMb + (decimal)anticipatedStorageBytes / (1024m * 1024m)), record?.CreditPoints ?? 0m); - var limit = policy.GetLimit(userId); - if (current >= limit || projected > limit) return null; - } - - if (record is not null && apiCalls == 0m && cpuSeconds == 0m && bandwidthMb == 0m && storageBytes == 0) - return record; - - if (record is null) - { - record = new ResourceUsageRecord - { - UserId = userId, - UserName = string.IsNullOrWhiteSpace(userName) ? userId : userName, - Currency = currency, - UserCreated = effectiveActor, - DateCreated = now - }; - dbContext.ResourceUsageRecords.Add(record); - } - - record.UserName = string.IsNullOrWhiteSpace(userName) ? record.UserName : userName; - record.RecordedAtUtc = now; - record.ApiCalls += apiCalls; - record.CpuSeconds += cpuSeconds; - record.BandwidthMb += bandwidthMb; - record.StorageMb += storageMb; - record.Currency = string.IsNullOrWhiteSpace(currency) ? record.Currency : currency; - record.DateModified = now; - record.UserModified = effectiveActor; - - await dbContext.SaveChangesAsync(effectiveActor, cancellationToken); + if (record is not null && apiCalls == 0m && cpuSeconds == 0m && bandwidthMb == 0m && storageBytes == 0) return record; - }, cancellationToken); + + if (record is null) + { + record = new ResourceUsageRecord + { + UserId = userId, + UserName = string.IsNullOrWhiteSpace(userName) ? userId : userName, + Currency = currency, + UserCreated = effectiveActor, + DateCreated = now + }; + dbContext.ResourceUsageRecords.Add(record); + } + + record.UserName = string.IsNullOrWhiteSpace(userName) ? record.UserName : userName; + record.RecordedAtUtc = now; + record.ApiCalls += apiCalls; + record.CpuSeconds += cpuSeconds; + record.BandwidthMb += bandwidthMb; + record.StorageMb = Math.Max(0m, record.StorageMb + storageMb); + record.Currency = string.IsNullOrWhiteSpace(currency) ? record.Currency : currency; + record.DateModified = now; + record.UserModified = effectiveActor; + + await dbContext.SaveChangesAsync(effectiveActor, cancellationToken); + return record; } public static async Task WithUserLockAsync(ApplicationDbContext dbContext, string userId, diff --git a/src/Yavsc.Server/Models/ApplicationDbContext.cs b/src/Yavsc.Server/Models/ApplicationDbContext.cs index 35b26ab73..ffd728d0d 100644 --- a/src/Yavsc.Server/Models/ApplicationDbContext.cs +++ b/src/Yavsc.Server/Models/ApplicationDbContext.cs @@ -145,6 +145,7 @@ namespace Yavsc.Models builder.Entity().HasMany(c => c.Connections); builder.Entity().Property(u => u.Avatar).HasDefaultValue(Constants.DefaultAvatar); builder.Entity().Property(u => u.DiskQuota).HasDefaultValue(Constants.DefaultFSQ); + builder.Entity().HasKey(r => new { r.UserId, r.Path }); builder.Entity().HasAlternateKey(u => u.Email); builder.Entity().HasOne(bl => bl.User); builder.Entity().HasOne(bl => bl.Owner); @@ -380,6 +381,7 @@ namespace Yavsc.Models public DbSet Estimates { get; set; } public DbSet Signatures { get; set; } public DbSet ResourceUsageRecords { get; set; } + public DbSet ResourceStorageRecords { get; set; } public DbSet ResourceSubscriptions { get; set; } public DbSet ResourceSubscriptionPayments { get; set; } public DbSet BankStatus { get; set; } diff --git a/src/Yavsc.Server/Models/ResourceStorageRecord.cs b/src/Yavsc.Server/Models/ResourceStorageRecord.cs new file mode 100644 index 000000000..1742793f8 --- /dev/null +++ b/src/Yavsc.Server/Models/ResourceStorageRecord.cs @@ -0,0 +1,13 @@ +#nullable enable +using System.ComponentModel.DataAnnotations; + +namespace Yavsc.Models; + +public sealed class ResourceStorageRecord +{ + [MaxLength(450)] + public string UserId { get; set; } = ""; + [MaxLength(1024)] + public string Path { get; set; } = ""; + public long Bytes { get; set; } +} diff --git a/src/test/Yavsc.Blogs.Tests/FileSystemApiTests.cs b/src/test/Yavsc.Blogs.Tests/FileSystemApiTests.cs index 0b7d2a9b9..3b88e8d8b 100644 --- a/src/test/Yavsc.Blogs.Tests/FileSystemApiTests.cs +++ b/src/test/Yavsc.Blogs.Tests/FileSystemApiTests.cs @@ -136,6 +136,79 @@ public sealed class FileSystemApiTests : IClassFixture "Expected the uploaded file on disk under the owner's personal root"); } + [Fact] + public async Task Same_size_replacement_is_admitted_near_the_limit_and_renaming_keeps_refundability() + { + _fixture.ResetDatabase(); + const string owner = "storage-replacement"; + _fixture.SeedUser(owner, u => u.DiskQuota = 10_000_000); + using var http = NewClient(owner); + var ct = TestContext.Current.CancellationToken; + async Task Upload() + { + using var form = new MultipartFormDataContent(); + form.Add(new ByteArrayContent(new byte[1048576]), "file", "original.bin"); + using var response = await http.PostAsync("/api/v1/fs", form, ct); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + await Upload(); + using (var scope = _fixture.Services.CreateScope()) + { + var policy = scope.ServiceProvider.GetRequiredService>().Value; + var cpu = (policy.DefaultLimit - policy.StorageMbWeight * 1.5m) / policy.CpuSecondWeight; + await ResourceUsageTracker.RecordAsync(scope.ServiceProvider.GetRequiredService(), + owner, owner, cpuSeconds: cpu, cancellationToken: ct); + } + await Upload(); + using var moved = await http.PostAsync("/api/fsc/mvf", + new StringContent("""{"id":"original.bin","to":"renamed.bin"}""", System.Text.Encoding.UTF8, "application/json"), ct); + Assert.Equal(HttpStatusCode.OK, moved.StatusCode); + using var deleted = await http.DeleteAsync("/api/v1/fs/renamed.bin", ct); + Assert.Equal(HttpStatusCode.OK, deleted.StatusCode); + using var verify = _fixture.Services.CreateScope(); + var db = verify.ServiceProvider.GetRequiredService(); + Assert.Equal(0m, (await db.ResourceUsageRecords.SingleAsync(r => r.UserId == owner, ct)).StorageMb); + Assert.Empty(await db.ResourceStorageRecords.Where(r => r.UserId == owner).ToListAsync(ct)); + } + + [Fact] + public async Task Replacement_and_deletion_refund_tracked_storage_but_not_a_legacy_file() + { + _fixture.ResetDatabase(); + const string owner = "storage-refunds"; + _fixture.SeedUser(owner, u => u.DiskQuota = 10_000_000); + using var http = NewClient(owner); + var ct = TestContext.Current.CancellationToken; + async Task Upload(int length) + { + using var form = new MultipartFormDataContent(); + form.Add(new ByteArrayContent(new byte[length]), "file", "refunded.bin"); + using var response = await http.PostAsync("/api/v1/fs", form, ct); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + await Upload(2 * 1048576); + await Upload(1048576); + using (var scope = _fixture.Services.CreateScope()) + { + var db = scope.ServiceProvider.GetRequiredService(); + Assert.Equal(1m, (await db.ResourceUsageRecords.SingleAsync(r => r.UserId == owner, ct)).StorageMb); + Assert.Equal(1048576L, (await db.ResourceStorageRecords.SingleAsync(r => r.UserId == owner, ct)).Bytes); + await ResourceUsageTracker.RecordAsync(db, owner, owner, cpuSeconds: 20000m, cancellationToken: ct); + } + using var deleted = await http.DeleteAsync("/api/v1/fs/refunded.bin", ct); + Assert.Equal(HttpStatusCode.OK, deleted.StatusCode); + Assert.False(File.Exists(PhysicalFile(_fixture, owner, "refunded.bin"))); + WritePhysicalFile(_fixture, owner, "legacy.bin", new byte[1048576]); + using var legacy = await http.DeleteAsync("/api/v1/fs/legacy.bin", ct); + Assert.Equal(HttpStatusCode.OK, legacy.StatusCode); + using var verify = _fixture.Services.CreateScope(); + var final = verify.ServiceProvider.GetRequiredService(); + var usage = await final.ResourceUsageRecords.SingleAsync(r => r.UserId == owner, ct); + Assert.Equal(0m, usage.StorageMb); + Assert.Equal(20000m, usage.CpuSeconds); + Assert.Empty(await final.ResourceStorageRecords.Where(r => r.UserId == owner).ToListAsync(ct)); + } + [Fact] public async Task Upload_is_refused_before_writing_when_known_storage_would_exceed_quota() { diff --git a/src/test/Yavsc.Org.Tests/Controllers/ResourceUsageTermsTests.cs b/src/test/Yavsc.Org.Tests/Controllers/ResourceUsageTermsTests.cs index 6064294ed..eb1fdee75 100644 --- a/src/test/Yavsc.Org.Tests/Controllers/ResourceUsageTermsTests.cs +++ b/src/test/Yavsc.Org.Tests/Controllers/ResourceUsageTermsTests.cs @@ -26,5 +26,8 @@ public sealed class ResourceUsageTermsTests Assert.Contains((Yavsc.Constants.DefaultFSQ * 2L).ToString(), html); Assert.Contains("quota disque", html); Assert.Contains("Découverte porte le quota disque", html); + Assert.Contains("remboursent les points de stockage", html); + Assert.Contains("suppression de fichiers reste autorisée", html); + Assert.DoesNotContain("ne remboursent pas de points", html); } } diff --git a/src/test/Yavsc.Server.Tests/ResourceUsageTests.cs b/src/test/Yavsc.Server.Tests/ResourceUsageTests.cs index 7cbd30f67..73b2b3549 100644 --- a/src/test/Yavsc.Server.Tests/ResourceUsageTests.cs +++ b/src/test/Yavsc.Server.Tests/ResourceUsageTests.cs @@ -256,6 +256,92 @@ public sealed class ResourceUsageTests .ResourceUsageRecords.ToListAsync(TestContext.Current.CancellationToken)); } + [Fact] + public async Task Tracked_storage_replacement_and_deletion_refund_only_their_original_volume() + { + using var provider = NewProvider(); + using var scope = provider.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + var ct = TestContext.Current.CancellationToken; + await ResourceUsageTracker.RecordAsync(db, "alice", "alice", cpuSeconds: 5m, storageBytes: 1048576, cancellationToken: ct); + await ResourceUsageTracker.RecordStorageAsync(db, "alice", "alice", "personal/file", 2 * 1048576, ct); + await ResourceUsageTracker.RecordStorageAsync(db, "alice", "alice", "personal/file", 1048576, ct); + var record = await db.ResourceUsageRecords.SingleAsync(ct); + Assert.Equal(2m, record.StorageMb); + var usage = scope.ServiceProvider.GetRequiredService(); + Assert.Equal(5.6m, (await usage.GetCurrentAsync("alice", "alice", ct)).Consumption); + await ResourceUsageTracker.RecordStorageAsync(db, "alice", "alice", "personal/legacy", 0, ct); + Assert.Equal(2m, record.StorageMb); + await ResourceUsageTracker.RecordStorageAsync(db, "alice", "alice", "personal/file", 0, ct); + await ResourceUsageTracker.RecordStorageAsync(db, "alice", "alice", "personal/file", 0, ct); + Assert.Equal(1m, record.StorageMb); + Assert.Equal(5m, record.CpuSeconds); + Assert.Equal(5.3m, (await usage.GetCurrentAsync("alice", "alice", ct)).Consumption); + Assert.Empty(await db.ResourceStorageRecords.ToListAsync(ct)); + } + + [Fact] + public async Task Concurrent_deletions_do_not_refund_the_same_receipt_twice() + { + using var provider = NewProvider(); + var ct = TestContext.Current.CancellationToken; + using (var setup = provider.CreateScope()) + { + var db = setup.ServiceProvider.GetRequiredService(); + await ResourceUsageTracker.RecordStorageAsync(db, "alice", "alice", "file", 1048576, ct); + await ResourceUsageTracker.RecordAsync(db, "alice", "alice", storageBytes: 1048576, cancellationToken: ct); + } + await Task.WhenAll(Enumerable.Range(0, 5).Select(async _ => + { + using var scope = provider.CreateScope(); + await ResourceUsageTracker.RecordStorageAsync(scope.ServiceProvider.GetRequiredService(), + "alice", "alice", "file", 0, ct); + })); + using var verify = provider.CreateScope(); + Assert.Equal(1m, (await verify.ServiceProvider.GetRequiredService() + .ResourceUsageRecords.SingleAsync(ct)).StorageMb); + } + + [Fact] + public async Task Repeated_pdf_storage_accounting_is_idempotent_and_renamed_files_remain_refundable() + { + using var provider = NewProvider(); + using var scope = provider.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + var ct = TestContext.Current.CancellationToken; + await ResourceUsageTracker.RecordStorageAsync(db, "alice", "alice", "pdf/file", 1048576, ct); + await ResourceUsageTracker.RecordStorageAsync(db, "alice", "alice", "pdf/file", 1048576, ct); + await ResourceUsageTracker.MoveStorageAsync(db, "alice", "pdf", "renamed", ct); + Assert.Equal("renamed/file", (await db.ResourceStorageRecords.SingleAsync(ct)).Path); + await ResourceUsageTracker.RecordStorageAsync(db, "alice", "alice", "renamed/file", 0, ct); + Assert.Equal(0m, (await db.ResourceUsageRecords.SingleAsync(ct)).StorageMb); + } + + [Fact] + public async Task Relief_request_runs_at_the_limit_but_still_counts_api_and_transfer_costs() + { + using var provider = NewProvider(o => o.DefaultLimit = 0.01m); + using var scope = provider.CreateScope(); + var context = NewContext(scope.ServiceProvider); + context.SetEndpoint(new Endpoint(_ => Task.CompletedTask, + new EndpointMetadataCollection(new ResourceUsageReliefAttribute()), "delete")); + var ran = false; + var middleware = new ResourceUsageTelemetryMiddleware( + async ctx => + { + ran = true; + await ctx.Response.Body.WriteAsync(new byte[1048576], TestContext.Current.CancellationToken); + }, + provider.GetRequiredService(), + NullLogger.Instance); + await middleware.InvokeAsync(context, scope.ServiceProvider.GetRequiredService()); + Assert.True(ran); + var record = await scope.ServiceProvider.GetRequiredService() + .ResourceUsageRecords.SingleAsync(TestContext.Current.CancellationToken); + Assert.Equal(1m, record.ApiCalls); + Assert.Equal(1m, record.BandwidthMb); + } + [Fact] public async Task Negative_counter_deltas_are_explicitly_rejected() { From 97b350be2d7fe380e669672fd2109e3a19cc3024 Mon Sep 17 00:00:00 2001 From: Paul Schneider Date: Sun, 8 Nov 2026 05:44:39 +0000 Subject: [PATCH 06/11] Owner and admin link to --- src/Yavsc.Org/Views/Home/Privacy.cshtml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Yavsc.Org/Views/Home/Privacy.cshtml b/src/Yavsc.Org/Views/Home/Privacy.cshtml index a9a6e7cf4..a967c2acd 100644 --- a/src/Yavsc.Org/Views/Home/Privacy.cshtml +++ b/src/Yavsc.Org/Views/Home/Privacy.cshtml @@ -8,7 +8,7 @@ À aucun moment, aucune adresse postale, aucune adresse e-mail ni aucun numéro de téléphone ne sont transmis à personne. Seul le système - et son link:Contact[possesseur] ont accès + son [possesseur ou l'administration](/Home/Contact) ont accès à ces informations. De plus, le droit de retrait est permanent From b157dce4e46a40f90e7cd377b8c5620704876a7a Mon Sep 17 00:00:00 2001 From: Paul Schneider Date: Sun, 8 Nov 2026 07:43:15 +0000 Subject: [PATCH 07/11] Add OBS podcast ingestion and account withdrawal privacy controls Support scoped RTMPS publishing through MediaMTX, authenticated replay, resource accounting and PostIt activation/revocation. Close withdrawn accounts, erase managed files and purge eligible payment residues after one year. Include migrations, documentation and regression tests. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- CHANGELOG.md | 4 + INSTALL.md | 138 +- contrib/mediamtx-podcasts.yml | 26 + .../PostIt.Tests/AdministrationToolsTests.cs | 27 + .../PostIt.Tests/PodcastScheduleTests.cs | 104 +- .../AdministrationPageViewModel.Tools.cs | 11 + .../ViewModels/AdministrationPageViewModel.cs | 1 + .../ViewModels/PodcastsPageViewModel.cs | 86 +- .../Views/Layout/AdministrationPage.axaml | 3 + .../PostIt/Views/Video/PodcastsPage.axaml | 16 + .../PaymentResiduePurgeResult.cs | 5 + src/Yavsc.Abstract/Streaming/Podcast.cs | 21 + .../AdministrationApiClient.cs | 2 + src/Yavsc.Api.Client/PodcastApiClient.cs | 9 + src/Yavsc.Api/Administration.http | 6 + .../SiteAdministrationApiController.cs | 7 + .../Controllers/Musical/PodcastController.cs | 6 +- .../Musical/PodcastObsController.cs | 57 + src/Yavsc.Api/Podcast.http | 15 + src/Yavsc.Api/Program.cs | 1 + ...ministrationServiceCollectionExtensions.cs | 3 + src/Yavsc.Api/Services/PodcastObsOptions.cs | 33 + src/Yavsc.Api/Services/PodcastObsRelay.cs | 62 + src/Yavsc.Api/Services/PodcastObsService.cs | 158 + src/Yavsc.Api/Services/PodcastObsWorker.cs | 267 + .../Services/PodcastScheduleService.cs | 52 +- .../PodcastServiceCollectionExtensions.cs | 5 + src/Yavsc.Blogs/Program.cs | 1 + .../Accounting/AccountController.cs | 40 +- src/Yavsc.Org/Extensions/HostingExtensions.cs | 5 + ...261108061011_AccountWithdrawal.Designer.cs | 5228 ++++++++++++++++ .../20261108061011_AccountWithdrawal.cs | 43 + ...1108073234_PodcastObsIngestion.Designer.cs | 5242 +++++++++++++++++ .../20261108073234_PodcastObsIngestion.cs | 61 + .../ApplicationDbContextModelSnapshot.cs | 23 +- .../Services/AccountWithdrawalService.cs | 208 + .../Services/PaymentResiduePurgeWorker.cs | 38 + .../Services/ResourceSubscriptionService.cs | 10 + src/Yavsc.Org/Views/Account/Delete.cshtml | 9 +- src/Yavsc.Org/Views/Home/Privacy.cshtml | 122 +- .../Helpers/PaymentResidueService.cs | 72 + .../Helpers/ResourceUsageTracker.cs | 36 +- .../Helpers/WithdrawnAccountMiddleware.cs | 24 + .../Models/ApplicationDbContext.cs | 3 +- src/Yavsc.Server/Models/ApplicationUser.cs | 4 + src/Yavsc.Server/Models/Messaging/LiveFlow.cs | 8 + src/Yavsc.Server/Services/ProfileService.cs | 4 +- src/test/Yavsc.Api.Tests/PodcastObsTests.cs | 348 ++ .../Yavsc.Api.Tests/PodcastScheduleTests.cs | 9 + .../SiteAdministrationApiTests.cs | 20 +- .../ResourceSubscriptionControllerTests.cs | 15 + .../Controllers/ResourceUsageTermsTests.cs | 19 + .../AccountWithdrawalTests.cs | 298 + .../Yavsc.Server.Tests/ResourceUsageTests.cs | 31 + 54 files changed, 12996 insertions(+), 50 deletions(-) create mode 100644 contrib/mediamtx-podcasts.yml create mode 100644 src/Yavsc.Abstract/Administration/PaymentResiduePurgeResult.cs create mode 100644 src/Yavsc.Api/Controllers/Musical/PodcastObsController.cs create mode 100644 src/Yavsc.Api/Services/PodcastObsOptions.cs create mode 100644 src/Yavsc.Api/Services/PodcastObsRelay.cs create mode 100644 src/Yavsc.Api/Services/PodcastObsService.cs create mode 100644 src/Yavsc.Api/Services/PodcastObsWorker.cs create mode 100644 src/Yavsc.Org/Migrations/20261108061011_AccountWithdrawal.Designer.cs create mode 100644 src/Yavsc.Org/Migrations/20261108061011_AccountWithdrawal.cs create mode 100644 src/Yavsc.Org/Migrations/20261108073234_PodcastObsIngestion.Designer.cs create mode 100644 src/Yavsc.Org/Migrations/20261108073234_PodcastObsIngestion.cs create mode 100644 src/Yavsc.Org/Services/AccountWithdrawalService.cs create mode 100644 src/Yavsc.Org/Services/PaymentResiduePurgeWorker.cs create mode 100644 src/Yavsc.Server/Helpers/PaymentResidueService.cs create mode 100644 src/Yavsc.Server/Helpers/WithdrawnAccountMiddleware.cs create mode 100644 src/test/Yavsc.Api.Tests/PodcastObsTests.cs create mode 100644 src/test/Yavsc.Server.Tests/AccountWithdrawalTests.cs diff --git a/CHANGELOG.md b/CHANGELOG.md index 8d06395a7..2f6e2084a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,10 @@ ### Added +* [Podcasts/OBS/PostIt] Add opt-in MediaMTX RTMPS ingestion for programmed emissions, activated explicitly from PostIt with one-time scoped, expiring and revocable keys. Start on publisher connection, remux H.264/AAC into the existing authenticated segments and MP4 replay workflow, bound concurrency/duration/buffering, enforce consumption and effective disk quotas, account storage with deletion refunds, and report owner-only ingest errors. Add relay configuration, installation instructions and real synthetic RTMP/RTMPS-to-replay regressions, including active revocation. + +* [Yavsc/PostIt/Privacy] Close and pseudonymize withdrawn accounts, cancel PayPal subscriptions before confirming withdrawal, erase managed personal files, avatars and podcasts, and reject old sessions across hosts. Purge eligible technical payment residues one year after effective withdrawal automatically and through a confirmed administrator-only PostIt action; preserve accounting records separately. Clarify the privacy policy, recipients, third-party integrations, withdrawal failures and deployment responsibilities. Make the unique email constraint mutable to support pseudonymization without deleting accounting identities. + * [Yavsc/API/Blogs/PostIt] Refund tracked storage points when personal files are deleted or replaced, and when generated PDFs are replaced. Persist per-file accounting receipts, preserve them on rename, reject refunds for untracked legacy files, and allow deletion at the consumption limit without refunding API/CPU/transfer costs. Update CGU and installation instructions. * [Yavsc/PostIt/PayPal] Add monthly Découverte (EUR 1 excluding VAT) and Premium (EUR 2 excluding VAT) resource subscriptions, charged at EUR 1.20 / EUR 2.40 including 20% VAT. Confirmed monthly PayPal payments erase up to one / three default quotas, carry two thirds of unused monthly credit without expiry, and preserve historical counters. Add persistent idempotent payment credits, refund reconciliation, authenticated Web subscription/cancellation pages, verified REST webhooks, PostIt links and balances, migration and updated CGU. diff --git a/INSTALL.md b/INSTALL.md index b143e7226..4987ef501 100644 --- a/INSTALL.md +++ b/INSTALL.md @@ -78,6 +78,42 @@ these Windows runtime behaviours. ## Resource consumption and CGU +### Account withdrawal and payment retention + +Apply the `AccountWithdrawal` migration before deploying all three hosts. It adds +withdrawal timestamps and replaces the immutable alternate email key with a +required unique email index, preserving uniqueness while allowing pseudonymization. +Do not run the withdrawal flow until every host uses the matching backend. + +Yavsc.Org must have write/delete access to the same managed volumes as API/Blogs: +`Site:UserFilesRoot`, `Site:Avatars` and `Podcast:RootPath`. +Use absolute paths shared across processes; defaults relative to application +directories are not shared automatically. Accounting files under `Site:Bills` +are not erased by withdrawal. Symbolic links in managed user directories are +refused rather than followed. + +The account is blocked before cancellation/erasure, and withdrawal is only +confirmed when these operations and pseudonymization succeed. On an explicit +failure, an administrator must fix the cause and retry the existing administrative +withdrawal action. Ensure no live upload/encoding operation is still writing to +the user's volumes during withdrawal; drain such operations before retrying. + +The Org hosted worker purges eligible technical payment records at startup and +checks at most every minute, with an earlier wake-up for a known anniversary. +Monitor errors and service availability: scheduled processing +cannot ensure an exact wall-clock deletion while the host is stopped. At least +one Org instance must run, and an external operations process must enforce the +one-year retention deadline during prolonged downtime. PostIt administrators can +also confirm and run `POST /api/v1/administration/payment-residues/purge`. +The report counts accounts, subscriptions, monthly payments, donations and legacy +PayPal payments. Active accounts and unfinished withdrawals are never purged. +No new subscription credits may be granted after withdrawal begins. + +Invoice payments, invoices and other legal accounting records are excluded. +Define and publish the actual accounting, logs and backup retention policy for +the deployment, verify configured providers and international-transfer safeguards, +and prevent withdrawn data from being reactivated by backup restoration. + Configure the **same** `ResourceUsage` section on Yavsc.Api, Yavsc.Blogs and Yavsc.Org. API and Blogs must also use the same application database. All three hosts and configuration templates inherit the backend defaults @@ -252,6 +288,100 @@ or PayPal account eligibility. ## Podcast live broadcasts and replays +### OBS Studio for planned emissions + +Deploy MediaMTX **v1.21.3** beside the **single Yavsc.Api media instance** and +FFmpeg on that API host. The generated configuration in +[`contrib/mediamtx-podcasts.yml`](contrib/mediamtx-podcasts.yml) enables only the +OBS publishing paths, RTMPS for publishers and private RTMP/control listeners. +Adjust its `authHTTPAddress` to the API's internal HTTP listener; this listener +must accept the local authentication callback without redirecting it to HTTPS. +Alternatively, use an internal HTTPS URL with a valid certificate. +Install the RTMPS TLS certificate and key at the configured paths. Keep the +control API and internal RTMP ports on loopback (or an isolated authenticated network), +never on the public Internet. Do not enable anonymous HLS/RTMP reads on the relay. +MediaMTX must not record independent copies: Yavsc owns storage and retention. + +Apply the `PodcastObsIngestion` migration on the shared database. Configure +`Podcast:Obs` on **Yavsc.Api only**, for example: + +```json +{ + "Podcast": { + "Obs": { + "Enabled": true, + "ServerUrl": "rtmps://obs.example.org:1936", + "RelayApiUrl": "http://127.0.0.1:9997/", + "RelayReadUrl": "rtmp://127.0.0.1:1935/", + "RelayUser": "yavsc", + "ActivationMinutes": 30, + "MaxDurationMinutes": 120, + "MaxConcurrentBroadcasts": 2 + } + } +} +``` + +Set `Podcast__Obs__RelayPassword` through the deployment's secret mechanism to +a random password of at least 32 characters. It authenticates Yavsc's private +reader/control client, not OBS users. Keep process arguments and credentials +accessible only to the service administrator. The public RTMPS URL must have +no `/live` suffix: the stream key includes the full `obs/` path. +Plain RTMP for the public OBS URL requires the explicit `AllowUnencryptedRtmp: true` option and should +only be used for local testing or inside a VPN. Limit publisher network bitrate +at the relay/network level as well as configuring OBS; application quotas are +checked on completed media segments, not on every incoming RTMP packet. + +In PostIt: + +1. Prepare an emission and select it. +2. Choose **Activer OBS / renouveler la cle**. +3. In OBS, select **Parametres > Stream > Service : Personnalise**, then copy + the displayed server and stream key. Use **H.264 video**, **AAC audio**, + a **2-second keyframe interval** and a bitrate producing segments below 8 MiB. +4. Start streaming in OBS before the activation expires. The actual emission + starts when the publisher connects, even if the scheduled date is later. + No camera capture in PostIt is required; PostIt may be closed afterwards. +5. Stop OBS or choose **Revoquer OBS et arreter le diffuseur** in PostIt. + Committed segments remain available and the normal MP4 worker prepares replay. + +Keys are scoped to one emission, stored only as SHA-256 hashes, displayed once, +rotated on each activation and erased after completion. PostIt never persists +them; navigation/logout clears the displayed key but does not revoke a running +external emission. Revocation is available at the consumption limit. +After disconnect, restart or timeout, the emission ends rather than silently +resuming under a new publisher: prepare a new emission for another broadcast. + +The worker polls the authenticated relay once a second and starts bounded FFmpeg +remuxing tasks. It rejects ended, deleted, revoked or withdrawn accounts and caps +concurrent captures and duration (the lower of planned duration and configured +maximum). MediaMTX also receives a session expiry from authentication, so the +publisher is disconnected at that maximum lifetime even if the API stops. +Committed segments are charged as transferred and stored MiB under the same +consumption rule; their storage receipts are refunded on podcast deletion. +OBS storage counts towards the user's effective disk quota and the existing +podcast media limits. Pending capture files are monitored and bounded; enforcement +can overshoot by one polling interval of incoming data. Processing errors are +reported in the owner-only OBS status endpoint, without exposing keys or FFmpeg +diagnostics. Monitor scan/cleanup failures and do not restore old activation keys +from backups. A prolonged relay/API outage requires operational intervention. + +The normal API listens/authenticates playback; OBS stream credentials never grant +listener access. If the relay is separately hosted, include it in the deployment's +privacy/provider information. + +For the real media regression, set `YAVSC_TEST_MEDIAMTX` to the installed MediaMTX +v1.21.3 executable and run: + +```bash +dotnet test --project src/test/Yavsc.Api.Tests/Yavsc.Api.Tests.csproj --filter-class '*PodcastObsTests' +``` + +The test launches loopback-only listeners, generates synthetic H.264/AAC media +with FFmpeg, verifies RTMP/RTMPS authentication, revocation during streaming, +AAC audio, HLS segments, MP4 replay and refund, +then stops its own processes and removes its temporary files. + PostIt Desktop's home page provides **Podcasts : directs et replays**. Install LibVLC 3 with the `livehttp`, MPEG-TS, x264 and AAC plugins on the Desktop machine. Windows capture uses DirectShow; Linux uses V4L2 and the @@ -274,7 +404,8 @@ replays; only the broadcaster can upload, complete or delete their podcast. Media is not anonymous and no access token is included in a playback URL. Configure Yavsc.Api's `Podcast` section (or environment variables such as -`Podcast__RootPath`). No database migration is needed. Install **FFmpeg 5+ +`Podcast__RootPath`). The base media store needs no database migration; +planned emissions and OBS require their migrations documented above. Install **FFmpeg 5+ on the API server** (with `concatf`, MPEG-TS, MP4 and AAC bitstream-filter support; for Debian/Ubuntu: `apt-get install ffmpeg`). The API runtime stage in the main Dockerfile includes it. Only stream-copy remuxing is performed, @@ -305,7 +436,10 @@ Defaults allow 8 MiB per segment (also the HTTP endpoint's hard limit), 1 GiB retained per owner, 7,200 segments per episode and 100 episodes per owner. At the target two-second segment duration, this is roughly four hours per episode; the byte quota can be reached earlier. Podcast quotas are -separate from the legacy user-files `DiskQuota`. Deleting an ended podcast +separate from the legacy user-files `DiskQuota` for native HTTP capture. +OBS source segments also count towards the user's effective disk quota and +instrumented consumption; the additional MP4 is counted only by `MaxOwnerBytes`. +Deleting an ended podcast releases its podcast quota. Reverse proxies must allow an 8 MiB PUT body and forward Authorization, Range and Content-Range on every API request/response. The retained MPEG-TS **and** the additional MP4 count toward `MaxOwnerBytes`. diff --git a/contrib/mediamtx-podcasts.yml b/contrib/mediamtx-podcasts.yml new file mode 100644 index 000000000..cc7aa2740 --- /dev/null +++ b/contrib/mediamtx-podcasts.yml @@ -0,0 +1,26 @@ +# MediaMTX v1.21.3. Run beside the single Yavsc.Api media host. +# Replace the auth URL port and TLS certificate paths for the deployment. +logLevel: warn +authMethod: http +authHTTPAddress: http://127.0.0.1:5103/api/v1/podcasts/relay/auth +authHTTPExclude: [] +api: true +apiAddress: 127.0.0.1:9997 +rtsp: false +rtmp: true +rtmpEncryption: optional +rtmpAddress: 127.0.0.1:1935 +rtmpsAddress: :1936 +rtmpServerKey: /etc/yavsc/obs/server.key +rtmpServerCert: /etc/yavsc/obs/server.crt +hls: false +webrtc: false +srt: false +playback: false +pathDefaults: + source: publisher + overridePublisher: false + maxReaders: 1 + record: false +paths: + "~^obs/[0-9a-f]{32}$": diff --git a/src/PostIt/PostIt.Tests/AdministrationToolsTests.cs b/src/PostIt/PostIt.Tests/AdministrationToolsTests.cs index 8b03dda89..4c9501a3f 100644 --- a/src/PostIt/PostIt.Tests/AdministrationToolsTests.cs +++ b/src/PostIt/PostIt.Tests/AdministrationToolsTests.cs @@ -15,6 +15,31 @@ namespace PostIt.Tests; public class AdministrationToolsTests { + [Fact] + public async Task Payment_purge_requires_confirmation_reports_counts_and_clears_on_logout() + { + await using var profile = new AdministrationAccessTests.ProfileTransport("Administrator"); + var session = new SessionStatusViewModel { Api = profile }; + await session.RefreshAsync(); + await using var transport = new AdminTransport(); + var vm = new AdministrationPageViewModel(null, session: session, + administrationClient: new AdministrationApiClient(transport, () => "https://example.invalid/api/v1")); + await vm.PurgePaymentResiduesCommand.ExecuteAsync(null); + Assert.Empty(transport.Paths); + vm.ConfirmDestructiveAction = true; + await vm.PurgePaymentResiduesCommand.ExecuteAsync(null); + Assert.Contains("POST https://example.invalid/api/v1/administration/payment-residues/purge", transport.Paths); + Assert.Contains("2 compte(s)", vm.PaymentPurgeReport); + Assert.False(vm.ConfirmDestructiveAction); + session.Api = null; + session.Refresh(); + transport.Paths.Clear(); + vm.ConfirmDestructiveAction = true; + await vm.PurgePaymentResiduesCommand.ExecuteAsync(null); + Assert.Empty(transport.Paths); + Assert.Empty(vm.PaymentPurgeReport); + } + [AvaloniaTheory] [InlineData(400, 800)] [InlineData(800, 400)] @@ -207,6 +232,8 @@ public class AdministrationToolsTests : await PendingSecret.Task; else if (typeof(T) == typeof(ImportResult)) result = new ImportResult(0, 0, 0); + else if (typeof(T) == typeof(PaymentResiduePurgeResult)) + result = new PaymentResiduePurgeResult(2, 3, 4, 1, 1); else throw new NotSupportedException(typeof(T).Name); return JsonSerializer.Deserialize(JsonSerializer.Serialize(result))!; diff --git a/src/PostIt/PostIt.Tests/PodcastScheduleTests.cs b/src/PostIt/PostIt.Tests/PodcastScheduleTests.cs index 16101c420..9a55ff3fc 100644 --- a/src/PostIt/PostIt.Tests/PodcastScheduleTests.cs +++ b/src/PostIt/PostIt.Tests/PodcastScheduleTests.cs @@ -9,6 +9,78 @@ namespace PostIt.Tests; public sealed class PodcastScheduleTests { + [AvaloniaFact] + public async Task Late_obs_credentials_are_not_displayed_after_selection_changes_or_navigation() + { + var path = Path.Combine(Path.GetTempPath(), $"postit-obs-late-{Guid.NewGuid():N}.json"); + var store = new TokenStore(path); + store.Save(new RefreshTokenRecord("test-access", "test-refresh", DateTimeOffset.UtcNow.AddHours(1), null)); + try + { + await using var api = new ScheduleApi(store, path + ".settings"); + var session = new SessionStatusViewModel { Api = api }; + session.Refresh(); + var vm = new PodcastsPageViewModel(new PodcastApiClient(api, () => "https://api.example/"), api, session); + await vm.ActivateAsync(); + vm.SelectedPodcast = api.Plan; + api.PendingActivation = new(TaskCreationOptions.RunContinuationsAsynchronously); + var activation = vm.ActivateObsCommand.ExecuteAsync(null); + vm.SelectedPodcast = api.Plan with { Id = Guid.NewGuid() }; + vm.SelectedPodcast = api.Plan; + api.PendingActivation.SetResult(new("rtmps://obs.example:1936", "secret", DateTimeOffset.UtcNow.AddMinutes(30))); + await activation; + Assert.Empty(vm.ObsStreamKey); + api.PendingActivation = new(TaskCreationOptions.RunContinuationsAsynchronously); + activation = vm.ActivateObsCommand.ExecuteAsync(null); + await vm.DeactivateAsync(); + api.PendingActivation.SetResult(new("rtmps://obs.example:1936", "secret", DateTimeOffset.UtcNow.AddMinutes(30))); + await activation; + Assert.Empty(vm.ObsStreamKey); + } + finally { File.Delete(path); File.Delete(path + ".settings"); } + } + + [AvaloniaFact] + public async Task Obs_activation_is_owned_displays_credentials_and_clears_them_on_navigation_and_revocation() + { + var path = Path.Combine(Path.GetTempPath(), $"postit-obs-{Guid.NewGuid():N}.json"); + var store = new TokenStore(path); + store.Save(new RefreshTokenRecord("test-access", "test-refresh", DateTimeOffset.UtcNow.AddHours(1), null)); + try + { + await using var api = new ScheduleApi(store, path + ".settings"); + var session = new SessionStatusViewModel { Api = api }; + session.Refresh(); + var vm = new PodcastsPageViewModel(new PodcastApiClient(api, () => "https://api.example/"), api, session); + await vm.ActivateAsync(); + vm.SelectedPodcast = api.Plan; + Assert.True(vm.ActivateObsCommand.CanExecute(null)); + await vm.ActivateObsCommand.ExecuteAsync(null); + Assert.Equal("rtmps://obs.example:1936", vm.ObsServerUrl); + Assert.Equal("obs/stream-secret", vm.ObsStreamKey); + Assert.False(vm.IsBroadcasting); + api.Settings.Save(); + Assert.DoesNotContain("stream-secret", await File.ReadAllTextAsync(path + ".settings")); + vm.SelectedPodcast = api.Plan with { Id = Guid.NewGuid(), OwnerId = "other" }; + Assert.Empty(vm.ObsStreamKey); + Assert.False(vm.ActivateObsCommand.CanExecute(null)); + vm.SelectedPodcast = api.Plan; + await vm.ActivateObsCommand.ExecuteAsync(null); + await vm.DeactivateAsync(); + Assert.Empty(vm.ObsStreamKey); + Assert.True(api.ObsEnabled); + await vm.ActivateAsync(); + vm.SelectedPodcast = api.Plan; + await vm.ActivateObsCommand.ExecuteAsync(null); + await vm.DeactivateObsCommand.ExecuteAsync(null); + Assert.False(api.ObsEnabled); + Assert.Empty(vm.ObsStreamKey); + Assert.EndsWith("/obs", api.RevokedPath); + await vm.DeactivateAsync(); + } + finally { File.Delete(path); File.Delete(path + ".settings"); } + } + [AvaloniaFact] public async Task Preparation_and_editing_send_schedule_and_optional_announcement_without_capture() { @@ -62,18 +134,33 @@ public sealed class PodcastScheduleTests finally { File.Delete(tokenPath); File.Delete(tokenPath + ".settings"); } } - private sealed class ScheduleApi(TokenStore store, string settingsPath) : YavscApiClient(new Settings(settingsPath), store) + private sealed class ScheduleApi(TokenStore store, string settingsPath) + : YavscApiClient(new Settings(settingsPath), store), IYavscApiClient { public PodcastResponse Plan { get; private set; } = new(Guid.NewGuid(), "Concert", "owner", "Owner", - DateTimeOffset.UtcNow, DateTimeOffset.UtcNow, PodcastState.Planned, 0, 0, 0); + DateTimeOffset.UtcNow, DateTimeOffset.UtcNow, PodcastState.Planned, 0, 0, 0) { FlowId = 1 }; + public bool ObsEnabled { get; private set; } + public string? RevokedPath { get; private set; } public PreparePodcastRequest? Saved { get; set; } public string? SavedPath { get; private set; } public HttpMethod? SavedMethod { get; private set; } + public TaskCompletionSource? PendingActivation { get; set; } - public override Task CallAsync(HttpMethod method, string path, object? body = null, CancellationToken ct = default) + public override async Task CallAsync(HttpMethod method, string path, object? body = null, CancellationToken ct = default) { object response; if (path.EndsWith("/account/me", StringComparison.Ordinal)) response = new Me { UserId = "owner" }; + else if (path.EndsWith("/obs", StringComparison.Ordinal)) + { + if (method == HttpMethod.Post) + { + ObsEnabled = true; + response = PendingActivation is null + ? new PodcastObsCredentials("rtmps://obs.example:1936", "obs/stream-secret", DateTimeOffset.UtcNow.AddMinutes(30)) + : await PendingActivation.Task; + } + else response = new PodcastObsStatus(ObsEnabled, DateTimeOffset.UtcNow.AddMinutes(30), null); + } else if (method == HttpMethod.Get) response = new List { Plan }; else { @@ -87,7 +174,16 @@ public sealed class PodcastScheduleTests }; response = Plan; } - return Task.FromResult((T)response); + return (T)response; + } + + Task IYavscApiClient.CallAsync(HttpMethod method, string path, object? body, CancellationToken ct) + { + Assert.Equal(HttpMethod.Delete, method); + Assert.EndsWith("/obs", path); + ObsEnabled = false; + RevokedPath = path; + return Task.CompletedTask; } } } diff --git a/src/PostIt/PostIt/ViewModels/AdministrationPageViewModel.Tools.cs b/src/PostIt/PostIt/ViewModels/AdministrationPageViewModel.Tools.cs index b87cbeccc..78486904c 100644 --- a/src/PostIt/PostIt/ViewModels/AdministrationPageViewModel.Tools.cs +++ b/src/PostIt/PostIt/ViewModels/AdministrationPageViewModel.Tools.cs @@ -113,6 +113,17 @@ public partial class AdministrationPageViewModel throw new InvalidOperationException("Cochez la confirmation avant cette opération destructive."); } + [RelayCommand] + private Task PurgePaymentResiduesAsync() => RunOperationAsync(async client => + { + RequireConfirmation(); + var result = await client.PurgePaymentResiduesAsync(); + RequireAccess(); + PaymentPurgeReport = $"{result.Users} compte(s), {result.Subscriptions} abonnement(s), {result.Payments} mensualité(s), {result.Donations} don(s), {result.LegacyPayments} paiement(s) historique(s) purgés."; + }); + + [ObservableProperty] public partial string PaymentPurgeReport { get; set; } = ""; + partial void OnSelectedClientChanged(AdministrationClient? value) { ClientFields = AdministrationFieldViewModel.From(value?.Settings ?? new ClientSettings()); diff --git a/src/PostIt/PostIt/ViewModels/AdministrationPageViewModel.cs b/src/PostIt/PostIt/ViewModels/AdministrationPageViewModel.cs index 9aef20641..9f9d5c9c8 100644 --- a/src/PostIt/PostIt/ViewModels/AdministrationPageViewModel.cs +++ b/src/PostIt/PostIt/ViewModels/AdministrationPageViewModel.cs @@ -156,6 +156,7 @@ public partial class AdministrationPageViewModel : ViewModelBase private void ClearAdministrationData() { + PaymentPurgeReport = ""; Users.Clear(); UsageOverview.Clear(); SelectedUser = null; diff --git a/src/PostIt/PostIt/ViewModels/PodcastsPageViewModel.cs b/src/PostIt/PostIt/ViewModels/PodcastsPageViewModel.cs index 62f297563..26307ed10 100644 --- a/src/PostIt/PostIt/ViewModels/PodcastsPageViewModel.cs +++ b/src/PostIt/PostIt/ViewModels/PodcastsPageViewModel.cs @@ -35,6 +35,11 @@ public partial class PodcastsPageViewModel : ViewModelBase private Control? _capturePreview; private bool _restoringPreferences; private bool _keepScreenOnDuringCapture; + private Guid? _obsPodcastId; + private int _obsVersion; + [ObservableProperty] public partial string ObsServerUrl { get; set; } = ""; + [ObservableProperty] public partial string ObsStreamKey { get; set; } = ""; + [ObservableProperty] public partial string ObsStatus { get; set; } = ""; private IDisposable? _screenAwake; public bool SupportsCaptureScreenAwake => OperatingSystem.IsAndroid(); public bool KeepScreenOnDuringCapture @@ -165,6 +170,7 @@ public partial class PodcastsPageViewModel : ViewModelBase set { if (!SetProperty(ref _selected, value)) return; + if (_obsPodcastId != value?.Id) ClearObsCredentials(); if (value is { State: PodcastState.Planned } && value.OwnerId == _ownerId) { _title = value.Title; @@ -192,6 +198,8 @@ public partial class PodcastsPageViewModel : ViewModelBase public IAsyncRelayCommand FinishCommand { get; } public IAsyncRelayCommand DeleteCommand { get; } public IAsyncRelayCommand RetryReplayCommand { get; } + public IAsyncRelayCommand ActivateObsCommand { get; } + public IAsyncRelayCommand DeactivateObsCommand { get; } public override bool CanNavigateNext { get => false; protected set { } } public override bool CanNavigatePrevious { get => !IsBroadcasting; protected set { } } @@ -201,6 +209,12 @@ public partial class PodcastsPageViewModel : ViewModelBase _api = api; _session = session; RefreshCommand = new AsyncRelayCommand(RefreshAsync, () => !IsBusy); + ActivateObsCommand = new AsyncRelayCommand(ActivateObsAsync, + () => !IsBusy && !IsCapturing && _session.IsLoggedIn + && SelectedPodcast is { State: PodcastState.Planned } p && p.OwnerId == _ownerId); + DeactivateObsCommand = new AsyncRelayCommand(DeactivateObsAsync, + () => !IsBusy && !IsBroadcasting && _session.IsLoggedIn + && SelectedPodcast is { FlowId: not null } p && p.OwnerId == _ownerId); DetectDevicesCommand = new RelayCommand(DetectDevices, () => CanBroadcast && !IsCapturing && !IsBusy); PreviewCommand = new AsyncRelayCommand(StartPreviewAsync, () => CanBroadcast && !IsCapturing && !IsBusy && _session.IsLoggedIn && SelectedCamera is not null); @@ -273,6 +287,8 @@ public partial class PodcastsPageViewModel : ViewModelBase FinishCommand.NotifyCanExecuteChanged(); DeleteCommand.NotifyCanExecuteChanged(); RetryReplayCommand.NotifyCanExecuteChanged(); + ActivateObsCommand.NotifyCanExecuteChanged(); + DeactivateObsCommand.NotifyCanExecuteChanged(); OnPropertyChanged(nameof(CanNavigatePrevious)); } @@ -282,10 +298,18 @@ public partial class PodcastsPageViewModel : ViewModelBase try { var profileUrl = new Uri(new Uri(_api.Settings.ApiUrl.TrimEnd('/') + "/"), "account/me"); - _ownerId = (await _api.CallAsync(HttpMethod.Get, profileUrl.AbsoluteUri)).UserId; + var ownerId = (await _api.CallAsync(HttpMethod.Get, profileUrl.AbsoluteUri)).UserId; + if (_ownerId != ownerId) ClearObsCredentials(); + _ownerId = ownerId; var podcasts = await _client.ListAsync(); Podcasts.Clear(); foreach (var podcast in podcasts) Podcasts.Add(podcast); + if (SelectedPodcast is { FlowId: not null } selected && selected.OwnerId == _ownerId) + { + var obs = await _client.ObsStatusAsync(selected.Id); + ObsStatus = obs.Error ?? (obs.Enabled ? "Entree OBS activee. Le direct commence a la connexion du diffuseur." : "Entree OBS desactivee."); + if (!obs.Enabled) ClearObsCredentials(clearStatus: false); + } Status = "Directs et replays reserves aux utilisateurs connectes."; } catch (Exception ex) { Status = $"Chargement impossible : {ex.Message}"; } @@ -322,6 +346,8 @@ public partial class PodcastsPageViewModel : ViewModelBase public async Task ActivateAsync() { + _session.LogoutCompleted -= ClearObsOnLogout; + _session.LogoutCompleted += ClearObsOnLogout; _restoringPreferences = true; try { @@ -343,11 +369,69 @@ public partial class PodcastsPageViewModel : ViewModelBase public async Task DeactivateAsync() { + _session.LogoutCompleted -= ClearObsOnLogout; + ClearObsCredentials(); _pageCancellation.Cancel(); await StopPreviewAsync(); if (_broadcaster is not null) await StopAsync(); } + private void ClearObsOnLogout() + { + ClearObsCredentials(); + _ownerId = null; + SelectedPodcast = null; + UpdateCommands(); + } + + private void ClearObsCredentials(bool clearStatus = true) + { + ObsServerUrl = ""; + ObsStreamKey = ""; + _obsPodcastId = null; + _obsVersion++; + if (clearStatus) ObsStatus = ""; + } + + private async Task ActivateObsAsync() + { + IsBusy = true; + try + { + var podcast = SelectedPodcast ?? throw new InvalidOperationException("Selectionnez une emission programmee."); + var owner = _ownerId; + ClearObsCredentials(); + var version = _obsVersion; + var token = _pageCancellation.Token; + var credentials = await _client.ActivateObsAsync(podcast.Id, token); + token.ThrowIfCancellationRequested(); + if (_obsVersion != version || !_session.IsLoggedIn || _ownerId != owner || SelectedPodcast?.Id != podcast.Id) + throw new InvalidOperationException("La session ou l'emission a change ; les identifiants OBS ne seront pas affiches."); + _obsPodcastId = podcast.Id; + ObsServerUrl = credentials.ServerUrl; + ObsStreamKey = credentials.StreamKey; + ObsStatus = $"Connectez OBS avant {credentials.ExpiresAt.ToLocalTime():g}. Cette cle remplace toute cle precedente."; + } + + catch (Exception ex) { Status = $"Activation OBS impossible : {ex.Message}"; } + finally { IsBusy = false; } + } + + private async Task DeactivateObsAsync() + { + IsBusy = true; + try + { + var podcast = SelectedPodcast ?? throw new InvalidOperationException("Selectionnez une emission."); + await _client.DeactivateObsAsync(podcast.Id); + ClearObsCredentials(); + ObsStatus = "Cle revoquee et diffuseur deconnecte. Le replay est finalise apres l'arret de la reception."; + await RefreshAsync(); + } + catch (Exception ex) { Status = $"Desactivation OBS impossible : {ex.Message}"; } + finally { IsBusy = false; } + } + private void DetectDevices() { _restoringPreferences = true; diff --git a/src/PostIt/PostIt/Views/Layout/AdministrationPage.axaml b/src/PostIt/PostIt/Views/Layout/AdministrationPage.axaml index a7f4a0c5a..08d367d17 100644 --- a/src/PostIt/PostIt/Views/Layout/AdministrationPage.axaml +++ b/src/PostIt/PostIt/Views/Layout/AdministrationPage.axaml @@ -77,6 +77,9 @@ TextWrapping="Wrap"/> +

    public static System.Func? CreateBrowser { get; set; } = - () => new CustomSchemeBrowser(CustomScheme); + () => null; /// /// Optional platform hook used by the shared billing form to request a diff --git a/src/PostIt/PostIt/ViewModels/Settings/AuthenticationSettings.cs b/src/PostIt/PostIt/ViewModels/Settings/AuthenticationSettings.cs index 3c23187e4..08ff45364 100644 --- a/src/PostIt/PostIt/ViewModels/Settings/AuthenticationSettings.cs +++ b/src/PostIt/PostIt/ViewModels/Settings/AuthenticationSettings.cs @@ -17,6 +17,8 @@ public partial class AuthenticationSettings : ObservableObject /// in PostIt.Android/Properties/AndroidManifest.xml must match. /// public const string AndroidRedirectUri = "android://postit-signin"; + public const string BrowserRedirectUri = "https://postit.pschneider.fr/callback"; + public const string DefaultAuthority = "https://yavsc.pschneider.fr"; diff --git a/src/PostIt/PostIt/ViewModels/Settings/Settings.cs b/src/PostIt/PostIt/ViewModels/Settings/Settings.cs index 260c1f93b..430419483 100644 --- a/src/PostIt/PostIt/ViewModels/Settings/Settings.cs +++ b/src/PostIt/PostIt/ViewModels/Settings/Settings.cs @@ -450,7 +450,7 @@ public partial class Settings : ViewModelBase this.Authentication.ClientId = string.IsNullOrWhiteSpace(settings.Authentication.ClientId) ? AuthenticationSettings.DefaultClientId : settings.Authentication.ClientId; this.Authentication.RedirectUri = string.IsNullOrWhiteSpace(settings.Authentication.RedirectUri) ? - AuthenticationSettings.DesktopRedirectUri : settings.Authentication.RedirectUri; + AuthenticationSettings.BrowserRedirectUri : settings.Authentication.RedirectUri; if (settings.Authentication.Scopes is null || settings.Authentication.Scopes.Length == 0) { this.Authentication.Scopes = AuthenticationSettings.DefaultScopes; @@ -513,7 +513,7 @@ public partial class Settings : ViewModelBase { Authority = AuthenticationSettings.DefaultAuthority, ClientId = AuthenticationSettings.DefaultClientId, - RedirectUri = AuthenticationSettings.DesktopRedirectUri, + RedirectUri = AuthenticationSettings.BrowserRedirectUri, Scopes = AuthenticationSettings.DefaultScopes }; this.DarkMode = false; diff --git a/src/Yavsc.Server/Helpers/ResourceUsageTelemetryMiddleware.cs b/src/Yavsc.Server/Helpers/ResourceUsageTelemetryMiddleware.cs index 289e659f2..aa2f91b9e 100644 --- a/src/Yavsc.Server/Helpers/ResourceUsageTelemetryMiddleware.cs +++ b/src/Yavsc.Server/Helpers/ResourceUsageTelemetryMiddleware.cs @@ -31,6 +31,13 @@ public sealed class ResourceUsageTelemetryMiddleware( await ResourceUsageTracker.RecordAsync(admissionScope.ServiceProvider.GetRequiredService(), userId, userName, apiCalls: 1m, bandwidthMb: ToMb(requestBytes), actorUserId: userId); } + else if (context.User.IsInMsRole("Administrator")) + { + using var admissionScope = scopeFactory.CreateScope(); + await ResourceUsageTracker.RecordAsync(admissionScope.ServiceProvider.GetRequiredService(), + userId, userName, apiCalls: 1m, bandwidthMb: ToMb(requestBytes), actorUserId: userId, + cancellationToken: context.RequestAborted); + } else if (!await usage.TryAdmitAsync(userId, userName, 1m, ToMb(requestBytes), 0, context.RequestAborted)) { diff --git a/src/test/Yavsc.Server.Tests/ResourceUsageTests.cs b/src/test/Yavsc.Server.Tests/ResourceUsageTests.cs index e0d37db87..a6c006d7d 100644 --- a/src/test/Yavsc.Server.Tests/ResourceUsageTests.cs +++ b/src/test/Yavsc.Server.Tests/ResourceUsageTests.cs @@ -287,6 +287,31 @@ public sealed class ResourceUsageTests .ResourceUsageRecords.ToListAsync(TestContext.Current.CancellationToken)); } + [Fact] + public async Task Administrator_request_bypasses_quota_rejection_and_remains_accounted() + { + using var provider = NewProvider(o => o.DefaultLimit = 0.01m); + using var scope = provider.CreateScope(); + var context = NewContext(scope.ServiceProvider); + context.User.AddIdentity(new ClaimsIdentity([ + new Claim("http://schemas.microsoft.com/ws/2008/06/identity/claims/role", "Administrator") + ], "Bearer")); + var ran = false; + var middleware = new ResourceUsageTelemetryMiddleware( + _ => { ran = true; return Task.CompletedTask; }, + provider.GetRequiredService(), + NullLogger.Instance); + + await middleware.InvokeAsync(context, scope.ServiceProvider.GetRequiredService()); + + Assert.True(ran); + Assert.Equal(StatusCodes.Status200OK, context.Response.StatusCode); + var summary = await scope.ServiceProvider.GetRequiredService() + .GetCurrentAsync("alice", "alice", TestContext.Current.CancellationToken); + Assert.Equal(1m, summary.ApiCalls); + Assert.True(summary.IsQuotaReached); + } + [Fact] public async Task Tracked_storage_replacement_and_deletion_refund_only_their_original_volume() {