Mediascherm: paneel Controle bibliotheek (read-check in gewone taal, stand van de schakelaars)

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-17 23:36:05 +01:00
co-authored by Claude Sonnet 5.5
parent 30599c60ee
commit e1f2abf004
16 changed files with 237 additions and 6 deletions
@@ -79,3 +79,4 @@ Kept while Bryan is away (2026-11-17): no questions to him, a most probable assu
| 48 | **Step A (write-through) mirrors the whole module after each change** (2026-11-17). | Simplest consistent form: the same verified copier runs for the `hero` module after every saved change, one at a time, only with `Media:Library:DualWrite` on (default off); a failure never fails the Hero request. At this size (a few dozen photos) a full mirror is cheap and cannot drift from the copy. | Per-change incremental writes: more code, more ways to drift. | `IMediaLibrarySync`, `MediaLibrarySync`, `HeroImageService.SyncLibraryAsync` |
| 49 | **Compact tiles in the clean-up and the delete confirmation** (product owner request, 2026-11-17). | `PhotoSelectionList` has a third layout `compact` (3/4/6/8 columns, square small thumbnails, name and a short usage line on one truncated line each, full name, date, size and usage in the tooltip; checkbox chip, whole-tile select, select all and the bulk bar unchanged). The clean-up dialog uses it. The "places that lose the photo" list in the second step of `DeleteDialog` is a read-only compact grid of the same kind. `PurgeDialog` shows no photo list (only a count), so it is unchanged; the library tiles and the ImagePicker are unchanged. | Long row lists again in the dialogs (much scrolling, little overview). | `PhotoSelectionList.tsx` (`layout="compact"`), `CleanupDialog.tsx`, `DeleteDialog.tsx` (`delete-places`) |
| 50 | **Step C reads the library screen's data from the library tables, not the hero admin** (2026-11-17). | The read switch (`off`/`compare`/`on`) changes where the library screen gets photos, trash and uses; the hero's admin and public endpoints keep their own tables because they need the variants, which move in phase 3. Thumbnails come from the hero. `compare` only logs and reports (`GET media-library/read-check`); `on` falls back to the hero's tables when the library cannot be read. | Serve the hero admin from the library too: needs the variants (and cut sets) in the library tables first. | `HeroMediaUsageProvider`, `IMediaLibraryReader`, `MediaLibraryReader`, `MediaReadComparer` |
| 51 | **"Controle bibliotheek" panel in the library screen** (SLS-Main for Bryan, 2026-11-17). | A small panel under the storage meter, for administrators (the whole screen is admin only), asks `GET media-library/read-check` only when its button is clicked and says in plain words (nl/en) whether the library tables match each module or lists the differences, plus the state of the three switches (copy, write-through, reading off/compare/on; the response now carries `copyOnStartup` and `dualWrite`). It changes nothing. Always shown, not only on test. | Show it only when the read switch is not off: Bryan could then not check before switching. | `LibraryCheck.tsx`, `MediaLibraryController.ReadCheck`, `IMediaLibrarySwitchState` |
@@ -0,0 +1,70 @@
import { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { CheckCircle2, ListChecks, TriangleAlert } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { useReadCheck } from '../services/hooks';
/**
* "Library check": a small panel for administrators that compares the library's own tables with the modules (the hero) in
* plain words and shows the state of the migration switches (copy, write-through, reading). It only asks the server when the
* button is clicked; it changes nothing.
*/
export function LibraryCheck() {
const { t } = useTranslation();
const [asked, setAsked] = useState(false);
const check = useReadCheck(asked);
return (
<section className="space-y-2 rounded-md border p-3" aria-labelledby="library-check-title" data-testid="library-check">
<div className="flex flex-wrap items-center justify-between gap-2">
<h2 id="library-check-title" className="text-sm font-medium">
{t('media.check.title')}
</h2>
<Button type="button" variant="outline" size="sm" disabled={check.isFetching} onClick={() => (asked ? void check.refetch() : setAsked(true))} data-testid="library-check-run">
<ListChecks className="mr-1.5 size-4" aria-hidden="true" />
{check.isFetching ? t('media.check.running') : t('media.check.run')}
</Button>
</div>
<p className="text-xs text-muted-foreground">{t('media.check.hint')}</p>
{check.isError && (
<p role="alert" className="text-sm text-destructive" data-testid="library-check-error">
{t('media.check.error')}
</p>
)}
{check.data && (
<div className="space-y-2" role="status" data-testid="library-check-result">
<p className="text-sm" data-testid="library-check-switches">
{t('media.check.switches', {
copy: check.data.copyOnStartup ? t('media.check.on') : t('media.check.off'),
write: check.data.dualWrite ? t('media.check.on') : t('media.check.off'),
read: t(`media.check.read.${check.data.mode}`),
})}
</p>
{check.data.modules.length === 0 && <p className="text-sm text-muted-foreground">{t('media.check.noModules')}</p>}
{check.data.modules.map((module) => (
<div key={module.module} data-testid={`library-check-${module.module}`}>
{module.matches ? (
<p className="flex items-center gap-2 text-sm text-green-700 dark:text-green-400">
<CheckCircle2 className="size-4 shrink-0" aria-hidden="true" />
{t('media.check.matches', { module: t(`media.module.${module.module}`, { defaultValue: module.module }), photos: module.photos, uses: module.uses })}
</p>
) : (
<div className="space-y-1">
<p className="flex items-center gap-2 text-sm font-medium text-destructive">
<TriangleAlert className="size-4 shrink-0" aria-hidden="true" />
{t('media.check.differs', { module: t(`media.module.${module.module}`, { defaultValue: module.module }), count: module.differences.length })}
</p>
<ul className="list-disc space-y-0.5 pl-6 text-xs" data-testid={`library-check-${module.module}-differences`}>
{module.differences.map((difference) => (
<li key={difference}>{difference}</li>
))}
</ul>
</div>
)}
</div>
))}
</div>
)}
</section>
);
}
@@ -1,5 +1,5 @@
import { http, HttpResponse } from 'msw';
import type { MediaCleanupPreviewDto, MediaLibraryDto, MediaPhotoDto, MediaStorageDto, MediaTrashRequest, MediaTrashResponse } from '@/features/media/services/types';
import type { MediaCleanupPreviewDto, MediaLibraryDto, MediaPhotoDto, MediaReadCheckResponse, MediaStorageDto, MediaTrashRequest, MediaTrashResponse } from '@/features/media/services/types';
const daysAgo = (days: number) => new Date(Date.now() - days * 86_400_000).toISOString();
@@ -81,6 +81,9 @@ export const mediaHandlers = [
...mediaTrashHandlers,
http.get('*/media-library/photos', () => HttpResponse.json({ photos: seedPhotos(), modules: ['hero'] } satisfies MediaLibraryDto)),
http.get('*/media-library/storage', () => HttpResponse.json(seedStorage())),
http.get('*/media-library/read-check', () =>
HttpResponse.json({ mode: 'off', modules: [{ module: 'hero', mode: 'off', photos: 3, uses: 2, matches: true, differences: [] }], copyOnStartup: false, dualWrite: false } satisfies MediaReadCheckResponse),
),
http.get('*/media-library/cleanup-preview', ({ request }) => {
const url = new URL(request.url);
const days = Number(url.searchParams.get('days') ?? 7);
@@ -339,6 +339,52 @@ describe('MediaLibraryPage', () => {
expect(within(dialog).getByTestId('cleanup-confirm')).toBeInTheDocument();
});
it('checks the library against the hero in plain words, with the state of the switches, only when asked', async () => {
let calls = 0;
server.use(
http.get('*/media-library/read-check', () => {
calls += 1;
return HttpResponse.json({ mode: 'compare', modules: [{ module: 'hero', mode: 'compare', photos: 11, uses: 8, matches: true, differences: [] }], copyOnStartup: true, dualWrite: true });
}),
);
renderPage();
await screen.findByTestId('photo-selection-list');
expect(calls).toBe(0);
expect(screen.queryByTestId('library-check-result')).not.toBeInTheDocument();
await userEvent.click(screen.getByTestId('library-check-run'));
expect(await screen.findByTestId('library-check-hero')).toHaveTextContent('De bibliotheek komt overeen met Hero (11 foto');
expect(screen.getByTestId('library-check-switches')).toHaveTextContent('kopie bij het opstarten: aan; schrijven naar de bibliotheek: aan; lezen uit de bibliotheek: vergelijken (alleen loggen)');
expect(calls).toBe(1);
});
it('lists the differences when the library does not match', async () => {
server.use(
http.get('*/media-library/read-check', () =>
HttpResponse.json({ mode: 'off', modules: [{ module: 'hero', mode: 'off', photos: 3, uses: 2, matches: false, differences: ['photo 1 is missing in the library', 'use 2 differs'] }], copyOnStartup: false, dualWrite: false }),
),
);
renderPage();
await screen.findByTestId('photo-selection-list');
await userEvent.click(screen.getByTestId('library-check-run'));
expect(await screen.findByTestId('library-check-hero')).toHaveTextContent('De bibliotheek wijkt af van Hero: 2 verschillen.');
expect(within(screen.getByTestId('library-check-hero-differences')).getAllByRole('listitem')).toHaveLength(2);
expect(screen.getByTestId('library-check-switches')).toHaveTextContent('kopie bij het opstarten: uit; schrijven naar de bibliotheek: uit; lezen uit de bibliotheek: uit');
});
it('says so when the check cannot be run', async () => {
server.use(http.get('*/media-library/read-check', () => new HttpResponse(null, { status: 500 })));
renderPage();
await screen.findByTestId('photo-selection-list');
await userEvent.click(screen.getByTestId('library-check-run'));
expect(await screen.findByTestId('library-check-error')).toHaveTextContent('De controle kon niet worden uitgevoerd.');
});
it('shows an error when the library cannot be loaded', async () => {
server.use(http.get('*/media-library/photos', () => new HttpResponse(null, { status: 500 })));
renderPage();
@@ -7,6 +7,7 @@ import { CleanupDialog } from '../components/CleanupDialog';
import { DeleteDialog } from '../components/DeleteDialog';
import { PurgeDialog } from '../components/PurgeDialog';
import { PhotoSelectionList, type PhotoUse } from '../components/PhotoSelectionList';
import { LibraryCheck } from '../components/LibraryCheck';
import { StorageMeter } from '../components/StorageMeter';
import { useLayoutPreference } from '../lib/layoutPreference';
import { emptySelection, prune, type Selection } from '../lib/selection';
@@ -90,6 +91,7 @@ export function MediaLibraryPage() {
</div>
{storage.data && <StorageMeter storage={storage.data} />}
<LibraryCheck />
<div className="flex gap-2" role="group" aria-label={t('media.view.label')}>
{(['library', 'trash'] as const).map((value) => (
+12 -1
View File
@@ -1,6 +1,6 @@
import { keepPreviousData, useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { api } from '@/lib/api-client';
import type { MediaCleanupPreviewDto, MediaLibraryDto, MediaPurgeRequest, MediaStorageDto, MediaTrashRequest, MediaTrashResponse } from './types';
import type { MediaCleanupPreviewDto, MediaLibraryDto, MediaPurgeRequest, MediaReadCheckResponse, MediaStorageDto, MediaTrashRequest, MediaTrashResponse } from './types';
export const MEDIA_KEY = ['media-library'];
@@ -22,6 +22,17 @@ export function useMediaStorage() {
});
}
/** Compares the library tables with the modules and tells the state of the migration switches. Only asked for when the person clicks. */
export function useReadCheck(enabled: boolean) {
return useQuery<MediaReadCheckResponse, Error>({
queryKey: [...MEDIA_KEY, 'read-check'],
queryFn: () => api.get<MediaReadCheckResponse>('/api/v1/media-library/read-check'),
enabled,
staleTime: 0,
gcTime: 0,
});
}
/** What a clean-up with these settings would select. A preview: nothing is deleted. */
export function useCleanupPreview(days: number, onlyUnused: boolean, enabled: boolean) {
return useQuery<MediaCleanupPreviewDto, Error>({
@@ -29,6 +29,23 @@ export interface MediaLibraryDto {
export type MediaStorageLevel = 'ok' | 'warning' | 'full';
export interface MediaReadCheckModuleDto {
module: string;
mode: string;
photos: number;
uses: number;
matches: boolean;
differences: string[];
}
/** The check of the library tables against the modules, plus the state of the migration switches. */
export interface MediaReadCheckResponse {
mode: 'off' | 'compare' | 'on';
modules: MediaReadCheckModuleDto[];
copyOnStartup: boolean;
dualWrite: boolean;
}
export interface MediaStorageDto {
usedBytes: number;
/** 0 means no limit. */
@@ -902,6 +902,25 @@
"irreversible": "This cannot be undone.",
"partial_one": "{{count}} photo could not be deleted. The rest was deleted for good.",
"partial_other": "{{count}} photos could not be deleted. The rest was deleted for good."
},
"check": {
"title": "Library check",
"run": "Check",
"running": "Checking…",
"hint": "Compares the library’s tables with the hero and shows the state of the switches. Nothing is changed.",
"error": "The check could not be run.",
"switches": "State of the switches: copy at start-up: {{copy}}; writing to the library: {{write}}; reading from the library: {{read}}.",
"on": "on",
"off": "off",
"read": {
"off": "off",
"compare": "compare (log only)",
"on": "on"
},
"noModules": "Nothing to check.",
"matches": "The library matches {{module}} ({{photos}} photos, {{uses}} places).",
"differs_one": "The library differs from {{module}}: {{count}} difference.",
"differs_other": "The library differs from {{module}}: {{count}} differences."
}
}
}
@@ -902,6 +902,25 @@
"irreversible": "Dit kan niet ongedaan worden gemaakt.",
"partial_one": "{{count}} foto kon niet worden verwijderd. De rest is definitief verwijderd.",
"partial_other": "{{count}} foto's konden niet worden verwijderd. De rest is definitief verwijderd."
},
"check": {
"title": "Controle bibliotheek",
"run": "Controleren",
"running": "Bezig met controleren…",
"hint": "Vergelijkt de tabellen van de bibliotheek met de Hero en toont de stand van de schakelaars. Er wordt niets gewijzigd.",
"error": "De controle kon niet worden uitgevoerd.",
"switches": "Stand van de schakelaars: kopie bij het opstarten: {{copy}}; schrijven naar de bibliotheek: {{write}}; lezen uit de bibliotheek: {{read}}.",
"on": "aan",
"off": "uit",
"read": {
"off": "uit",
"compare": "vergelijken (alleen loggen)",
"on": "aan"
},
"noModules": "Geen onderdelen om te controleren.",
"matches": "De bibliotheek komt overeen met {{module}} ({{photos}} foto’s, {{uses}} plekken).",
"differs_one": "De bibliotheek wijkt af van {{module}}: {{count}} verschil.",
"differs_other": "De bibliotheek wijkt af van {{module}}: {{count}} verschillen."
}
}
}
+8
View File
@@ -1306,6 +1306,14 @@
},
"MediaReadCheckResponse": {
"properties": {
"copyOnStartup": {
"default": false,
"type": "boolean"
},
"dualWrite": {
"default": false,
"type": "boolean"
},
"mode": {
"type": "string"
},
@@ -113,11 +113,15 @@ public class MediaLibraryControllerTests
verifier.CheckAsync(Arg.Any<CancellationToken>()).Returns(new MediaReadCheck("hero", MediaReadMode.Compare, 3, 2, ["photo x is missing in the library"]));
var reader = Substitute.For<IMediaLibraryReader>();
reader.Mode.Returns(MediaReadMode.Compare);
var switches = Substitute.For<IMediaLibrarySwitchState>();
switches.Current.Returns(new MediaLibrarySwitches(true, true, MediaReadMode.Compare));
var result = await new MediaLibraryController(library, new Clock(), null, [verifier], reader).ReadCheck(CancellationToken.None);
var result = await new MediaLibraryController(library, new Clock(), null, [verifier], reader, switches).ReadCheck(CancellationToken.None);
var response = result.Should().BeOfType<OkObjectResult>().Subject.Value.Should().BeOfType<MediaReadCheckResponse>().Subject;
response.Mode.Should().Be("compare");
response.CopyOnStartup.Should().BeTrue();
response.DualWrite.Should().BeTrue();
response.Modules.Should().ContainSingle().Which.Should().Match<MediaReadCheckDto>(m => m.Module == "hero" && m.Photos == 3 && m.Uses == 2 && !m.Matches && m.Differences.Count == 1);
}
@@ -89,6 +89,7 @@ public static class ServiceCollectionExtensions
services.TryAddScoped<Media.Library.IMediaLibraryService, Media.Library.MediaLibraryService>();
services.TryAddScoped<Media.Library.IMediaLibrarySync, Media.Library.NoMediaLibrarySync>();
services.TryAddScoped<Media.Library.IMediaLibraryReader, Media.Library.NoMediaLibraryReader>();
services.TryAddSingleton<Media.Library.IMediaLibrarySwitchState, Media.Library.NoMediaLibrarySwitchState>();
services.TryAddSingleton(sp =>
new ResetCooldown(sp.GetRequiredService<TimeProvider>(), TimeSpan.FromMinutes(sp.GetRequiredService<IOptions<PasswordResetSettings>>().Value.CooldownMinutes)));
services.AddScoped<IPasswordResetService, PasswordResetService>();
@@ -23,7 +23,10 @@ public sealed record MediaPhotoDto(
/// <summary>The result of comparing a module's own tables with the library tables (read switch, phase 2 step C).</summary>
public sealed record MediaReadCheckDto(string Module, string Mode, int Photos, int Uses, bool Matches, IReadOnlyList<string> Differences);
public sealed record MediaReadCheckResponse(string Mode, IReadOnlyList<MediaReadCheckDto> Modules);
/// <param name="Mode">The read switch: off, compare or on.</param>
/// <param name="CopyOnStartup">The copy switch (start-up copy into the library tables).</param>
/// <param name="DualWrite">The write-through switch.</param>
public sealed record MediaReadCheckResponse(string Mode, IReadOnlyList<MediaReadCheckDto> Modules, bool CopyOnStartup = false, bool DualWrite = false);
public sealed record MediaLibraryDto(IReadOnlyList<MediaPhotoDto> Photos, IReadOnlyList<string> Modules);
@@ -54,7 +57,7 @@ public sealed record MediaTrashResponse(IReadOnlyList<MediaUseResultDto> Results
[ApiController]
[Route("media-library")]
[Authorize(Policy = "AdminOnly")]
public class MediaLibraryController(IMediaLibraryService library, TimeProvider time, MediaStorageUsage? storage = null, IEnumerable<IMediaReadVerifier>? verifiers = null, IMediaLibraryReader? reader = null) : ControllerBase
public class MediaLibraryController(IMediaLibraryService library, TimeProvider time, MediaStorageUsage? storage = null, IEnumerable<IMediaReadVerifier>? verifiers = null, IMediaLibraryReader? reader = null, IMediaLibrarySwitchState? switches = null) : ControllerBase
{
/// <summary>
/// Compares what each module holds with what the library's own tables hold and lists every difference. Read-only; works
@@ -71,7 +74,8 @@ public class MediaLibraryController(IMediaLibraryService library, TimeProvider t
results.Add(new MediaReadCheckDto(check.Module, check.Mode.ToString().ToLowerInvariant(), check.Photos, check.Uses, check.Matches, check.Differences.Take(50).ToList()));
}
return Ok(new MediaReadCheckResponse((reader?.Mode ?? MediaReadMode.Off).ToString().ToLowerInvariant(), results));
var state = switches?.Current ?? new MediaLibrarySwitches(false, false, reader?.Mode ?? MediaReadMode.Off);
return Ok(new MediaReadCheckResponse(state.ReadFromLibrary.ToString().ToLowerInvariant(), results, state.CopyOnStartup, state.DualWrite));
}
[HttpGet("photos")]
@@ -33,6 +33,21 @@ public sealed class NoMediaLibraryReader : IMediaLibraryReader
public Task<IReadOnlyList<MediaUseSnapshot>> ListUsesAsync(string module, CancellationToken cancellationToken) => Task.FromResult<IReadOnlyList<MediaUseSnapshot>>([]);
}
/// <summary>The current state of the migration switches (for the check in the library screen).</summary>
public sealed record MediaLibrarySwitches(bool CopyOnStartup, bool DualWrite, MediaReadMode ReadFromLibrary);
/// <summary>Tells the current state of the migration switches.</summary>
public interface IMediaLibrarySwitchState
{
MediaLibrarySwitches Current { get; }
}
/// <summary>The default: no library tables, so every switch is off.</summary>
public sealed class NoMediaLibrarySwitchState : IMediaLibrarySwitchState
{
public MediaLibrarySwitches Current => new(false, false, MediaReadMode.Off);
}
/// <summary>What a comparison of a module's own tables with the library tables found. <c>Differences</c> is empty when they agree.</summary>
public sealed record MediaReadCheck(string Module, MediaReadMode Mode, int Photos, int Uses, IReadOnlyList<string> Differences)
{
@@ -40,6 +40,7 @@ public class MediaModule : IModule
services.AddScoped<MediaLibraryCopier>();
services.Replace(ServiceDescriptor.Scoped<IMediaLibrarySync, MediaLibrarySync>());
services.Replace(ServiceDescriptor.Scoped<IMediaLibraryReader, MediaLibraryReader>());
services.Replace(ServiceDescriptor.Singleton<IMediaLibrarySwitchState, MediaLibrarySwitchState>());
services.AddHostedService<MediaLibraryCopyService>();
}
@@ -0,0 +1,10 @@
using Microsoft.Extensions.Options;
using SlpModularCms.Core.Media.Library;
namespace SlpModularCms.Modules.Media.Services;
/// <summary>The migration switches as configured right now (read from the options on every call).</summary>
public sealed class MediaLibrarySwitchState(IOptionsMonitor<MediaLibraryOptions> options) : IMediaLibrarySwitchState
{
public MediaLibrarySwitches Current => new(options.CurrentValue.CopyOnStartup, options.CurrentValue.DualWrite, options.CurrentValue.ReadFromLibrary);
}