diff --git a/aidlc-docs/features/media-library/assumptions-and-open-questions.md b/aidlc-docs/features/media-library/assumptions-and-open-questions.md index 4e6fa63..6e4b948 100644 --- a/aidlc-docs/features/media-library/assumptions-and-open-questions.md +++ b/aidlc-docs/features/media-library/assumptions-and-open-questions.md @@ -4,34 +4,34 @@ Kept while Bryan is away (2026-11-17): no questions to him, a most probable assu | # | Question | Assumption made | If Bryan chooses differently | Where | |---|---|---|---|---| -| 1 | Which **uses** (places and ratios) exist? | Hero `wide` (3:2) and `tall` (2:3), ASF shoot-page **mosaic** tiles (a small fixed set of ratios per page, to be listed by the ASF session), **masonry** (natural ratio, no crop), **thumb** (library thumbnails, 1:1 or natural). A use is `(module, place, ratio set)`. | Other ratios only add rows to the use definitions; a free-form ratio per tile would need a ratio editor and more variants per photo. | Application design section 4 (`MediaUseDefinition`) | -| 2 | **Several formats/variants per photo**: who decides the set? | The **use** decides the ratios and widths (as `VariantPlanner` does for Hero); the library never cuts a fixed set per photo. Formats stay WebP and AVIF as today. | A fixed set per photo costs more disk and CPU on the Pi and cuts variants nobody uses. | `VariantPlanner`, application design section 4 | +| 1 | Which **uses** (places and ratios) exist? **[Confirmed by Bryan "as designed", 2026-11-17]** | Hero `wide` (3:2) and `tall` (2:3), ASF shoot-page **mosaic** tiles (a small fixed set of ratios per page, to be listed by the ASF session), **masonry** (natural ratio, no crop), **thumb** (library thumbnails, 1:1 or natural). A use is `(module, place, ratio set)`. | Other ratios only add rows to the use definitions; a free-form ratio per tile would need a ratio editor and more variants per photo. | Application design section 4 (`MediaUseDefinition`) | +| 2 | **Several formats/variants per photo**: who decides the set? **[Confirmed by Bryan "as designed", 2026-11-17]** | The **use** decides the ratios and widths (as `VariantPlanner` does for Hero); the library never cuts a fixed set per photo. Formats stay WebP and AVIF as today. | A fixed set per photo costs more disk and CPU on the Pi and cuts variants nobody uses. | `VariantPlanner`, application design section 4 | | 3 | The **7-day automatic clean-up** of unattached Hero images until the library is built. **[Decided by Bryan, 2026-11-17, second round: see "Decisions of the second round"]** | **Built (2026-11-17, safe: default unchanged)**: the setting `Media:AutoCleanupUnattached` exists, default `true` (today's behaviour); set `Media__AutoCleanupUnattached=false` per host to keep every upload. Plan: switch it off (default `false`) once the library screen and delete are accepted by Bryan. Switch it off behind a setting (`Media:AutoCleanupUnattached`, default `true` until the library screen exists, then default `false`), so nothing is lost silently once the library can show and delete photos. Retired-file removal (after a replaced set) stays: that is housekeeping of generated files, not a person's photos. | Keep it on until phase C; or switch off now (risk: unused uploads pile up with no screen to remove them). | `HeroMediaCleanup`, `MediaOptions` | | 4 | **Rights per module**: who may see, use and delete which photos? **[Decided by Bryan, 2026-11-17, second round: see "Decisions of the second round"]** | One shared library for Owner and Administrator (like Hero and Offerings). No per-module visibility yet. | Per-module visibility needs an owner field on a photo and a filter; the contract has room for it (`ModuleKey` on a use). | `[Authorize(Policy = "AdminOnly")]`, `MediaUse.Module` | -| 5 | **Public addresses**: per module (`/media//...`) or a shared path? | Keep `/media/{area}/{setHash}/{name}`; `area` stays the module (`hero`; a gallery would use `gallery`). The set hash still comes from the original's hash plus the crops of that **use**. A photo used in two modules is two sets (two addresses), cached separately. | A shared path would change addresses and golden files: not allowed without alignment. | `MediaPaths`, `MediaEndpoint` | -| 6 | **Usage register**: do modules report, or does the library keep it centrally? | Modules report: `IMediaUsageProvider` per module answers "where is this photo used" and "detach this photo" from the module's own data. Computed, never copied, so it cannot go stale. The library warns when a module has no provider. | A central register table keeps the answer fast but must be kept in step on every module save (risk of drift); can be added later as a cache. | Application design section 3, `IMediaUsageProvider` | +| 5 | **Public addresses**: per module (`/media//...`) or a shared path? **[Confirmed by Bryan "as designed", 2026-11-17]** | Keep `/media/{area}/{setHash}/{name}`; `area` stays the module (`hero`; a gallery would use `gallery`). The set hash still comes from the original's hash plus the crops of that **use**. A photo used in two modules is two sets (two addresses), cached separately. | A shared path would change addresses and golden files: not allowed without alignment. | `MediaPaths`, `MediaEndpoint` | +| 6 | **Usage register**: do modules report, or does the library keep it centrally? **[Confirmed by Bryan "as designed", 2026-11-17]** | Modules report: `IMediaUsageProvider` per module answers "where is this photo used" and "detach this photo" from the module's own data. Computed, never copied, so it cannot go stale. The library warns when a module has no provider. | A central register table keeps the answer fast but must be kept in step on every module save (risk of drift); can be added later as a cache. | Application design section 3, `IMediaUsageProvider` | | 7 | **What counts as "unused"** in the clean-up? **[Decided by Bryan, 2026-11-17, second round: see "Decisions of the second round"]** | A photo is unused when **no provider** reports a use. A photo used only by an inactive or unpublished slide still counts as used (it is in a slide). | Treating an inactive slide as unused would delete photos a person may want to switch on again; stricter would be safer than looser. | `MediaUsageService` | | 8 | **Clean-up default period** and slider range. **[Decided by Bryan, 2026-11-17, second round: see "Decisions of the second round"]** | Default 7 days, slider 1 to 365 days, step 1; "Only unused photos" on. The period is measured from the upload date. | Measured from last use, or another range: a one-line change in the filter. | Clean-up component, `CleanupSelection` | -| 9 | **Storage limit and warning**. | Limit = existing `Media:MaxTotalBytes` (2 GB, decided by Bryan, Hero assumption 12). Warning at 80 percent (amber) and at 100 percent (red, uploads refused with a clear message). Used bytes = originals plus all variants, cached 60 s. | Another threshold or limit: configuration only. | `MediaOptions`, `MediaStorageUsage` | +| 9 | **Storage limit and warning**. **[Confirmed by Bryan "as designed", 2026-11-17]** | Limit = existing `Media:MaxTotalBytes` (2 GB, decided by Bryan, Hero assumption 12). Warning at 80 percent (amber) and at 100 percent (red, uploads refused with a clear message). Used bytes = originals plus all variants, cached 60 s. | Another threshold or limit: configuration only. | `MediaOptions`, `MediaStorageUsage` | | 10 | **Delete of a photo that is in use**. **[Decided by Bryan, 2026-11-17, second round: see "Decisions of the second round"]** | Not possible from Clean-up (those rows are not selectable); possible from the library after a second confirmation that names the uses; the module detaches it first (Hero: the slide loses its image and is unpublished until a new one is chosen, as today). | Block deleting in-use photos completely: the extra confirmation path is removed. | `IMediaUsageProvider.DetachAsync`, library screen | -| 11 | **Shared upload service**: does Hero's upload move into the library? | In phase A Hero keeps its own upload endpoint; the library also lists those photos. In phase B both call one upload service in Core. | Moving Hero upload earlier gives a single path sooner but touches Hero before the data model exists. | `HeroImageService`, `MediaUploadGuard` | +| 11 | **Shared upload service**: does Hero's upload move into the library? **[Confirmed by Bryan "as designed", 2026-11-17]** | In phase A Hero keeps its own upload endpoint; the library also lists those photos. In phase B both call one upload service in Core. | Moving Hero upload earlier gives a single path sooner but touches Hero before the data model exists. | `HeroImageService`, `MediaUploadGuard` | | 12 | **Trash delay** (deleted photos recoverable for a while)? **[Decided by Bryan, 2026-11-17, second round: see "Decisions of the second round"]** | No trash in phase A: the confirmation naming the count is the safety. A 7-day trash can be added in phase B (a `DeletedAt` and the existing retired-file mechanism). | Trash from the start: reuse `HeroRetiredFile` logic generalised in Core; about 1 day extra. | `HeroRetiredFile`, application design section 5 | | 13 | **Migration of existing `HeroImages`** (phase C). **[Decided by Bryan, 2026-11-17, second round: see "Decisions of the second round"]** | Expand then contract: new `MediaAsset` and `MediaUse` tables are filled from `HeroImages` and `HeroSlides` with the **same ids, hashes and set hashes**; Hero reads the library; old columns are dropped in a later release. Needs a back-up and alignment: **not built**. | A one-step move is smaller but cannot be rolled back; or no migration at all and the library keeps reading through Hero (the provider approach) until the gallery module needs own tables. | Requirements section 9, application design section 6 | -| 14 | **Crop per use**: data per use or per photo? | A use owns its crop (focus x, y and zoom per ratio); the photo owns the default focus new uses start from. The set hash of a use is `SetHash(originalSha256, crops of that use)` exactly as today, so existing Hero addresses are unchanged. | Crop per photo only (today's model) cannot serve a mosaic with several tiles of the same photo. | `MediaPaths.SetHash`, `MediaUse` | -| 15 | **Selection range** with shift-click and "select all": across pages or the loaded page? | The loaded list (the clean-up list is loaded fully, the library list incrementally; "select all" says how many are loaded and offers "select all N" for a filtered list). | Strictly the current page: simpler, less useful for a clean-up of hundreds. | Selection component | -| 16 | **Deleting files from the store** when a photo is deleted. | The original and the set directories of that photo are deleted through `IMediaStore` after the database rows; a set shared with another use (same hash) is kept until no use references it. | Soft delete first (see 12). | `IMediaStore.DeleteSetAsync`, `HeroRepository.GetReferencedSetHashesAsync` | +| 14 | **Crop per use**: data per use or per photo? **[Confirmed by Bryan "as designed", 2026-11-17]** | A use owns its crop (focus x, y and zoom per ratio); the photo owns the default focus new uses start from. The set hash of a use is `SetHash(originalSha256, crops of that use)` exactly as today, so existing Hero addresses are unchanged. | Crop per photo only (today's model) cannot serve a mosaic with several tiles of the same photo. | `MediaPaths.SetHash`, `MediaUse` | +| 15 | **Selection range** with shift-click and "select all": across pages or the loaded page? **[Confirmed by Bryan "as designed", 2026-11-17]** | The loaded list (the clean-up list is loaded fully, the library list incrementally; "select all" says how many are loaded and offers "select all N" for a filtered list). | Strictly the current page: simpler, less useful for a clean-up of hundreds. | Selection component | +| 16 | **Deleting files from the store** when a photo is deleted. **[Confirmed by Bryan "as designed", 2026-11-17]** | The original and the set directories of that photo are deleted through `IMediaStore` after the database rows; a set shared with another use (same hash) is kept until no use references it. | Soft delete first (see 12). | `IMediaStore.DeleteSetAsync`, `HeroRepository.GetReferencedSetHashesAsync` | | 17 | **Language of the screen**: nl and en like the rest of the admin. | Yes, `media.*` keys in both files; terms: "Mediabibliotheek", "Opruimen", "Alleen ongebruikte foto's". | Dutch only: remove one file. | `frontend/src/i18n/locales` | | 18 | **Phase A built (2026-11-17, on assumptions)**: what is in the first step? | Read-only only: the usage contract (`IMediaUsageProvider`, `MediaLibraryService`, pure `CleanupSelection`), the Hero provider and the selection components in the frontend (`PhotoSelectionList`, `BulkActionBar`, selection rules). **No endpoint, no screen, no delete, no migration, no address change yet.** | Wire the screen and endpoints next (list, storage, clean-up preview) and then delete (needs a Hero delete path and Bryan's check of assumptions 3, 7 and 10). | `Core/Media/Library`, `Modules.Hero/Services/HeroMediaUsageProvider.cs`, `frontend/src/features/media` | -| 19 | The **position** of a slide in "Hero, slide 3". | Rank by `SortOrder` within its hero, counting slides that are switched off, 1-based; a slide that is off still counts as a use and is shown "(uit/off)". | Count only active slides, or show the slide's title instead. | `HeroMediaUsageProvider.ListUsesAsync` | -| 20 | The **thumbnail** of a Hero photo in the library. | The smallest published WebP variant of the current set; none yet (a grey "no preview") while the set is not cut. | Use the full-frame preview (`full-*.webp`), which shows the whole picture instead of the wide crop. | `HeroMediaUsageProvider.Thumbnail` | +| 19 | The **position** of a slide in "Hero, slide 3". **[Confirmed by Bryan "as designed", 2026-11-17]** | Rank by `SortOrder` within its hero, counting slides that are switched off, 1-based; a slide that is off still counts as a use and is shown "(uit/off)". | Count only active slides, or show the slide's title instead. | `HeroMediaUsageProvider.ListUsesAsync` | +| 20 | The **thumbnail** of a Hero photo in the library. **[Confirmed by Bryan "as designed", 2026-11-17]** | The smallest published WebP variant of the current set; none yet (a grey "no preview") while the set is not cut. | Use the full-frame preview (`full-*.webp`), which shows the whole picture instead of the wide crop. | `HeroMediaUsageProvider.Thumbnail` | | 21 | A **name** for a photo. **[Decided by Bryan, 2026-11-17, second round: see "Decisions of the second round"]** | Photos have no file name today (`HeroImage` does not store it), so the library shows a neutral label (date and size); a name field comes with the library's own tables (phase B). | Store the original file name at upload now (a small Hero migration, additive). | `PhotoItem.name`, phase B | | 22 | **Select all** and ranges with photos that cannot be selected (in use during a clean-up). | They are skipped by "select all" and by shift-ranges; the header box shows "some" when only part is selected. | Include them but refuse at confirmation. | `PhotoSelectionList`, `selection.ts` | | 23 | Where does Hero **list all photos** (performance)? | In memory, newest first, as the rest of the Hero repository does (a few dozen photos; the MySQL provider has limits with Guid lists). Paging comes with the screen when the count grows. | Server-side paging by `CreatedAt` (needs an index). | `HeroRepository.GetAllImagesReadOnlyAsync` | | 24 | **Tile ratios of the ASF mosaic** (assumption 1). | **Answered by the ASF session (2026-11-17, from its code)**: the mosaic shows at most 4 tiles per shoot page, from 2 photos up (layouts for 2, 3, 4). The tile shape is fixed per page by the photo count and order, not chosen per photo: **large** (photo 1) 2x2, desktop about 1:1 (max about 656x632), phone 4:3; **wide** (photo 2 with 3 or 4 photos) 2x1, desktop about 2.2:1 (max about 656x300), phone 3:2; **small** (photos 3 and 4 with 4 photos) 1x1, about 1.04:1 (max about 312x300), phone 1:1. With 2 photos: two large side by side. All object-fit cover (a crop). Widths: large and wide up to about 656 px, small about 312 px; phone half width about 175-300, full width about 350-600; retina variants 480, 640, 960, 1280. **Masonry** (portfolio): natural ratio only, no crop (rounding below half a row of 1/40 of the column width); 1, 2 or 3 columns, column width up to about 427 px; thumb now 800 px wide with the height following the ratio, variants about 480 and 800; the lightbox uses a separate `full`. Used in the design as uses `mosaic-large`, `mosaic-wide`, `mosaic-small` (each with a focus point and a desktop and phone shape) and `masonry` (no crop). | Each answer only adds use definitions. A ratio per photo (not per tile shape) would need a ratio editor. | Application design section 4 | | 25 | **Use definitions in code** (built 2026-11-17, pure data, nothing consumes them yet). | `MediaUseDefinition` (ratios with widths, or natural) and `GalleryUses` for the ASF needs: `mosaic-large` (`tilelarge` 1:1, `tilelargem` 4:3), `mosaic-wide` (`tilewide` 11:5, `tilewidem` 3:2), `mosaic-small` (`tilesmall` 26:25, `tilesmallm` 1:1), `masonry` (`natural`, no crop). Ratio names are letters only (2 to 10) to fit the address allow-list, so a phone shape is a name with an `m` suffix. Widths: large and wide 480, 640, 960, 1280 (retina set from the ASF answer); small 312, 480, 640; masonry 480 and 800. The set hash uses the shared `MediaPaths.SetHash` formula (a test shows it equals the Hero's). Hero's own `wide` (3:2) and `tall` (4:5, not the 2:3 the first design sketch said) stay as built in `VariantPlanner`. | Other widths or ratio values change only the definitions; the ASF `full` (lightbox) variant is not defined yet (it is the full-frame preview ratio). | `Core/Media/Library/MediaUseDefinition.cs` | -| 26 | **Choose or upload everywhere (ML-17)**: how does the Hero upload relate to the library? | Now the Hero keeps its own upload and table; its photos are already in the library list through the provider. When the library owns uploads (phase B) every upload creates exactly one library record (same file = same record by hash). The Hero switches to the shared picker with the phase C migration. Until then the Hero upload flow does not change. | Moving the Hero to the picker earlier (before phase B) would give a single upload path sooner but touches the Hero flow and needs the data model first. | Application design section 10 | -| 27 | **Scope of the shared picker**: single choice or several, and what does it include? | One photo per picker (single choice, radio group). It includes the library photos and one upload button (one file at a time); the Hero's multi-file upload and drag and drop stay on the Hero screen. The picker is pure: the module passes the list and the upload callback. | Several photos at once or drag and drop in the picker: a larger component, added when a module needs it (the gallery will probably need multiple). | `features/media/components/ImagePicker.tsx` | -| 28 | **Uploaded photo not ready yet** in the picker. | It is chosen at once but shows "no preview" until the background renderer has cut its set; an image without a set is not published (as in the Hero today). | Block choosing until it is ready: simpler to explain, slower to work with. | `ImagePicker`, `HeroRenderService` | +| 26 | **Choose or upload everywhere (ML-17)**: how does the Hero upload relate to the library? **[Confirmed by Bryan "as designed", 2026-11-17]** | Now the Hero keeps its own upload and table; its photos are already in the library list through the provider. When the library owns uploads (phase B) every upload creates exactly one library record (same file = same record by hash). The Hero switches to the shared picker with the phase C migration. Until then the Hero upload flow does not change. | Moving the Hero to the picker earlier (before phase B) would give a single upload path sooner but touches the Hero flow and needs the data model first. | Application design section 10 | +| 27 | **Scope of the shared picker**: single choice or several, and what does it include? **[Confirmed by Bryan "as designed", 2026-11-17]** | One photo per picker (single choice, radio group). It includes the library photos and one upload button (one file at a time); the Hero's multi-file upload and drag and drop stay on the Hero screen. The picker is pure: the module passes the list and the upload callback. | Several photos at once or drag and drop in the picker: a larger component, added when a module needs it (the gallery will probably need multiple). | `features/media/components/ImagePicker.tsx` | +| 28 | **Uploaded photo not ready yet** in the picker. **[Confirmed by Bryan "as designed", 2026-11-17]** | It is chosen at once but shows "no preview" until the background renderer has cut its set; an image without a set is not published (as in the Hero today). | Block choosing until it is ready: simpler to explain, slower to work with. | `ImagePicker`, `HeroRenderService` | ## Decisions of the second round (Bryan, 2026-11-17, via SLP Software - SLS - Main) @@ -54,3 +54,10 @@ Kept while Bryan is away (2026-11-17): no questions to him, a most probable assu | 30 | **Detaching a used photo when it is deleted** (decision 10). | In the Hero the slides that use the photo are removed from the hero (a slide cannot exist without an image); the second confirmation names them ("Hero, slide 3"). The hero then has fewer slides and stays published as long as it has a title. | Keep the slide and mark it "image missing" until a new image is chosen: needs a nullable slide image and a changed public contract. | `HeroMediaUsageProvider.TrashAsync` | | 31 | **Trash mechanics** (decision 12). | `DeletedAt` on the Hero image: a trashed photo is hidden from the Hero (slides, upload by hash, renderer) and shown in the library trash; Restore clears it. After 7 days the cleanup turns it into retired files (removed immediately) and removes the row. Uploading the same file again restores it. The trash period is `Media:TrashDays` (7). | Another period: the setting; no trash: delete straight to retired files. | `HeroImage.DeletedAt`, `HeroMediaCleanup`, `MediaOptions.TrashDays` | | 32 | **Migration of `HeroImages`** (decision 13): the plan and the safeguards. | Designed in `inception/application-design/migration-plan.md` (back-up, rollback, verification, test-only rollout). The additive columns of this round (`OriginalFileName`, `DeletedAt`, `LastUsedAt`) are copied with the rest. Not run anywhere until SLS-Main has been told and agrees to the test deploy. | n/a | `migration-plan.md` | + +### Status of the assumptions (2026-11-17) + +- **Decided by Bryan** (second round, table above): 3, 4, 7, 8, 10, 12, 13, 21. +- **Confirmed by Bryan "as designed"**: 1, 2, 5, 6, 9, 11, 14, 15, 16, 19, 20, 26, 27, 28. +- **Still assumptions** (not put to him separately): 17 (language), 18 (what phase A contained, now overtaken), 22 (selectability), 23 (performance), 24 (ASF data), 25 (use definitions); and the older rows 18 to 25 above. Assumptions 29 to 32 follow from his decisions. +- Assumption 12 now reads: there IS a trash (decision 12), the earlier "no trash in phase A" no longer applies. Assumption 10: deleting a used photo is possible after a second confirmation (built). Assumption 21: the original file name is stored from now on (built). diff --git a/aidlc-docs/features/media-library/inception/application-design/application-design.md b/aidlc-docs/features/media-library/inception/application-design/application-design.md index 0df30fa..cc190e8 100644 --- a/aidlc-docs/features/media-library/inception/application-design/application-design.md +++ b/aidlc-docs/features/media-library/inception/application-design/application-design.md @@ -216,3 +216,29 @@ Text alternative: a module screen uses the picker, which either chooses a librar - Phase C: the existing `HeroImages` are copied as library records with the same ids, hashes and set hashes (design section 6), after which the Hero screen switches to the picker. - **Other modules** (gallery, mosaic, masonry) use the picker from the start, with their own use definition (`GalleryUses`) deciding the ratios and crops of the chosen photo. - **Rights and limits**: the same Owner and Administrator rights as the library; the hero upload rate limit (100 per user per hour) applies to the shared upload service. + +## 11. Delete, trash and last use (built 2026-11-17, decisions 8, 10, 12, 21) + +```mermaid +flowchart LR + L[Library or Clean-up] -->|delete ids| C[MediaLibraryService] + C -->|uses again| P[Usage provider] + P -->|none, or confirmed twice| T[Module trash: detach and DeletedAt] + T --> TR[(Trash 7 days)] + TR -->|restore| P + TR -->|after the period| R[Retired files, removed with the sets] + classDef a fill:#f6e05e,stroke:#c05621,stroke-width:1px,color:#000; + classDef b fill:#63b3ed,stroke:#2b6cb0,stroke-width:1px,color:#000; + classDef c fill:#9ae6b4,stroke:#2f855a,stroke-width:1px,color:#000; + class L a; + class C,P b; + class T,TR,R c; +``` + +Text alternative: delete goes through the library service, which checks the usage again and asks the module to trash the photo; the trash keeps it for the trash period and can restore it; afterwards its files are retired and removed. + +- API: `POST media-library/delete {ids, confirmedInUse}` and `POST media-library/restore {ids}` (at most 100 ids), `GET media-library/trash`; the answer lists a status per photo (`trashed`, `inUse`, `notFound`, `failed`). +- Hero: `HeroImages.DeletedAt`, `LastUsedAt`, `OriginalFileName` (additive migration `AddMediaLibraryColumns`); a trashed image is left out of every Hero lookup, the renderer and slide validation; slides using it are removed when it is trashed; `HeroMediaCleanup` empties the trash after `Media:TrashDays`. +- Last use: `LastUsedAt` is set when a hero save detaches the photo from its last slide, and when it is trashed while in use. The clean-up counts from there (assumption 29). +- Frontend: `DeleteDialog` (first and second confirmation), trash view with Restore, the clean-up dialog now confirms into the same delete flow. +- The migration to own tables is planned in `migration-plan.md` (not built). diff --git a/aidlc-docs/features/media-library/inception/application-design/migration-plan.md b/aidlc-docs/features/media-library/inception/application-design/migration-plan.md new file mode 100644 index 0000000..78329b5 --- /dev/null +++ b/aidlc-docs/features/media-library/inception/application-design/migration-plan.md @@ -0,0 +1,73 @@ +# Migration plan: HeroImages to the library's own tables (decision 13) + +Status: plan, not built, not run anywhere. Decided by Bryan 2026-11-17 (via SLP Software - SLS - Main): it may be built in the next step, **only after this plan with its back-up and rollback exists**, **rolled out to TEST only (never production)**, and **SLS-Main is told before anything is deployed to test**. + +## Goal + +Give every photo one library record that does not depend on the Hero: `MediaAsset` (the photo) and `MediaUse` (where it is used), with **the same ids, hashes, set hashes and public addresses** as today. Nothing in `/media/hero//...` changes, so ASF, SLS and the golden files stay as they are. + +## Why expand then contract + +| Phase | What | Reversible? | +|---|---|---| +| 0 Back-up | Back-up of the database and a listing of the media directory (below). | n/a | +| 1 Expand | New tables `MediaAssets` and `MediaUses`, filled by copying `HeroImages` and `HeroSlides`. The Hero keeps reading and writing its own tables; the library reads the new tables behind a setting. | Yes: drop the two new tables, nothing else changed. | +| 2 Switch | Hero reads photos from the library tables (setting on). New uploads write both (dual write) so the old tables stay complete. | Yes: switch the setting off; the old tables are complete. | +| 3 Contract (a later release, after acceptance) | The Hero stops writing its own image columns; they are dropped in a separate migration. | Only from the back-up of that moment. Not part of the first rollout. | + +Files are never moved or renamed: the migration changes rows only, so the media directory is the same before and after. + +## Mapping + +| `HeroImages` column | `MediaAssets` column | Note | +|---|---|---| +| `Id` | `Id` | Same id, so references keep working. | +| `OriginalSha256`, `OriginalKey`, `SourceFormat`, `Width`, `Height`, `Bytes` | same | | +| `FocusX`, `FocusY`, `Zoom` | `DefaultFocusX`, `DefaultFocusY`, `DefaultZoom` | The photo's default focus. | +| `WideFocus*`, `TallFocus*` | `MediaUses` rows (one per slide use, ratios `wide` and `tall`) | The per-use crop; for a photo without a slide the default focus is enough. | +| `SetHash`, `Variants` | `MediaUses.SetHash` (per use) | Unchanged values; computed by the existing formula. | +| `CreatedAt`, `CreatedByUserId` | same | | +| `OriginalFileName`, `LastUsedAt`, `DeletedAt` | same | Added in the media-library step (additive columns of the Hero). | + +| `HeroSlides` | `MediaUses` | +|---|---| +| `Id`, `ImageId` | `Id`, `AssetId` (module `hero`, place kind `slide`, place id = slide id) | + +## Back-up (before phase 1, every environment) + +1. **Database**: a full dump of the Hero database (and of the CMS database if it is one), written to a dated file outside the deploy directory, for example `mysqldump --single-transaction > hero-before-media-migration-YYYYMMDD.sql`. Keep it until the contract phase is accepted. +2. **Media directory**: nothing is moved, but a listing with sizes and hashes is saved (`find -type f -exec sha256sum {} +` to a text file) so the directory can be compared afterwards. On the Raspberry Pi a copy of the directory is also a quick option (`cp -a`), if there is room. +3. **Row counts** noted: `HeroImages`, `HeroSlides`, `HeroRetiredFiles`. + +## Verification (right after phase 1, every environment) + +The migration job compares and **aborts** (rolls its transaction back) on any difference: + +- number of `MediaAssets` = number of `HeroImages` (all rows, also those in the trash); +- every `HeroImages.Id`, `OriginalSha256` and `SetHash` has an identical `MediaAssets`/`MediaUses` counterpart; +- number of `MediaUses` of module `hero` = number of `HeroSlides`; +- a sample of ten public addresses (`/media/hero//`) is requested before and after and gives the same bytes (checked by the smoke test). + +## Rollback + +| When | How | +|---|---| +| The verification fails | The migration runs in one transaction and rolls back by itself; nothing is left. | +| After phase 1, before the switch | Drop `MediaUses` and `MediaAssets` (the EF `Down` migration). The Hero never read them. | +| After the switch | Switch the setting back (`Media:Library:ReadFromLibrary=false`); the old tables are complete because of the dual write. Then drop the new tables if wanted. | +| After the contract phase (later) | Restore the database dump taken before that migration and the media listing check. | + +## Roll-out rules (from Bryan) + +1. **Test only.** No production variables, no production deploy, no release branch. +2. **Tell SLS-Main before deploying to test** (they run the deploy and the smoke test). +3. Back-up first (above), on the test host too. +4. Deploy with the setting **off**, check the verification result in the log, then switch it on, then the smoke test (hero markers, `/theme-init.js`, a sample of media addresses), then Bryan checks the admin. + +## What is built first (next step, when this plan is accepted) + +1. A new module `SlpModularCms.Modules.Media` with its own `DbContext`, the tables `MediaAssets` and `MediaUses` and an additive EF migration (no existing table touched), with tests. +2. The copy-and-verify job (idempotent, safe to run twice) behind a setting; unit and in-memory tests, and a test against MariaDB. +3. The library reading from the new tables behind `Media:Library:ReadFromLibrary` (default off). + +Nothing in steps 1 to 3 runs without the setting, so a deploy of that code alone changes no data except the new, empty tables. diff --git a/aidlc-docs/features/media-library/inception/requirements/requirements.md b/aidlc-docs/features/media-library/inception/requirements/requirements.md index 2d91930..6632683 100644 --- a/aidlc-docs/features/media-library/inception/requirements/requirements.md +++ b/aidlc-docs/features/media-library/inception/requirements/requirements.md @@ -39,9 +39,9 @@ | ML-02 | **Usage indicator.** Per photo: "in use" or "not used", and where (module and place, for example "Hero, slide 3"). | Several uses are all listed; the indicator is computed from the modules' own data, not guessed; a photo used nowhere shows "Not used". | | ML-03 | **Keep everything.** No automatic removal of any photo or its files. | The Hero step that retires unattached images is switched off once the library owns the retention (see section 8, phase A: behind a setting, default decided in the assumptions); a test proves nothing is removed without a person's action. | | ML-04 | **Selection component** (own reusable component): checkboxes per photo, select all and clear, a range with shift-click, keyboard operation, a visible count, and a live-region announcement of the count. | Works for mouse, keyboard and screen reader; reused by the library and the clean-up; uses the shared `Checkbox` of the theme. | -| ML-05 | **Bulk actions** on the selection, in the library itself. First action: **Delete**. The action bar is a separate component so more actions (tags, move) can be added without touching the list. | Delete asks for confirmation naming the number of photos and how many are in use; a failure of one photo does not stop the others and is reported per photo. | -| ML-06 | **Delete rules.** A photo that is in use is not deleted unless the person explicitly confirms and the use is detached first. | Default: in-use photos are not selectable for delete in "Clean up" and are marked in the library; deleting an in-use photo from the library shows what will lose its image and requires a second confirmation; the host falls back as it does today for a slide without a set. | -| ML-07 | **"Clean up" button.** Opens the overview of photos that would be cleaned: default everything older than 7 days, with a slider to look more or fewer days back, and a checkbox **Only unused photos**, default on (off = all photos in the period). | The list is newest first; all rows start selected; the person can deselect before confirming; confirming deletes exactly the selected rows; the summary shows the number and the bytes that will be freed. | +| ML-05 | **Bulk actions** on the selection, in the library itself. First action: **Delete** (to the trash, ML-18). The action bar is a separate component so more actions (tags, move) can be added without touching the list. | Delete asks for confirmation naming the number of photos and how many are in use; a failure of one photo does not stop the others and is reported per photo. | +| ML-06 | **Delete rules** (decision 10). A photo that is in use can be deleted after a **second confirmation that names the places**; the module detaches it first (Hero: its slides are removed). | The first confirmation says how many photos and how many are in use; the second names the places per photo; the server refuses a photo in use unless the request carries the confirmation and checks the usage again at that moment; one photo failing does not stop the others and is reported per photo. | +| ML-07 | **"Clean up" button.** Opens the overview of photos that would be cleaned: default everything not used for more than 7 days (counted from the LAST USE, decision 8), with a slider to look more or fewer days back, and a checkbox **Only unused photos**, default on (off = all photos in the period). | The list is newest first; all rows start selected; the person can deselect before confirming; confirming deletes exactly the selected rows; the summary shows the number and the bytes that will be freed. | | ML-08 | **Clean-up is the same component as the library** (ML-04, ML-05) in a preselected view, not a second implementation. | One list/selection component, two entry points. | | ML-09 | **Storage usage and limit warning.** The screen shows the used space (originals plus variants), the configured limit, and a warning at a threshold and at the limit. | Used bytes are computed from the store and cached for a short time; the warning level is configurable (assumption: 80 percent); at the limit, uploads give a clear message instead of a failure; the existing `Media:MaxTotalBytes` (2 GB) is the limit. | | ML-10 | **Upload into the library** (single and multiple), with the same limits and checks as Hero today (type signature, size, megapixels, rate limit). | The Hero upload path and the library share one upload service; the same file is one photo (hash). | @@ -105,3 +105,12 @@ | 8 (2026-11-17) Choose or upload in every part that needs an image | ML-17, design section 10 | | 7 Crop per use | ML-11, ML-12, design section 4 | | Boundary: addresses and set hashes | ML-14, NFR-ML-05 | + +## 11. Added by decisions of 2026-11-17 + +| ID | Requirement | Acceptance criteria | +|---|---|---| +| ML-18 | **Trash** (decision 12). Delete means "to the trash": recoverable for 7 days (`Media:TrashDays`); a trash view lists the photos with Restore; after the period the files are removed by the existing retired-file mechanism. Uploading the same file again brings it back. | A trashed photo is hidden from the hero and from the renderer; restore returns it (without its old slides); the clean-up of the trash is idempotent; a photo is never removed while it is referenced. | +| ML-19 | **Original file name** is stored at every upload (additive) and shown in the library; photos from before keep a neutral label. | The name is cleaned (no path, no control characters, at most 200 characters) and never used as a path. | +| ML-20 | **Last use** per photo: the moment it was last detached from a slide (or trashed); the clean-up period counts from there, from the upload date for a photo that was never used. | See assumption 29. | +| ML-21 | **Migration of the Hero photos** to the library's own tables, expand then contract, same ids, hashes and addresses; documented back-up and rollback first; test only; SLS-Main is told before a test deploy. | See `migration-plan.md`. | diff --git a/docs/hero-module.md b/docs/hero-module.md index b40ae1c..a5fca83 100644 --- a/docs/hero-module.md +++ b/docs/hero-module.md @@ -26,7 +26,7 @@ De admin toont alleen een badge Live of Niet live. | Instelling | Betekenis | |---|---| | `Media__Directory` | De map voor de afbeeldingen, **buiten de release** en buiten de webroot. Zonder deze instelling (of als de map niet beschrijfbaar is) staan uploads uit; bestaande bestanden en de publieke hero blijven werken. Niet in een committed appsettings-bestand. | -| `Media__MaxUploadBytes` (10 MB), `Media__MaxPixels` (64 miljoen), `Media__MaxParallelJobs` (2), `Media__DecodeTimeoutSeconds` (20), `Media__MaxTotalBytes` (2 GB), `Media__RetentionDays` (7), `Media__AutoCleanupUnattached` (standaard `true`; `false` bewaart ongebruikte uploads tot iemand ze verwijdert, voor de mediabibliotheek) | Grenzen en bewaartijd; standaardwaarden zijn bedoeld om te blijven. | +| `Media__MaxUploadBytes` (10 MB), `Media__MaxPixels` (64 miljoen), `Media__MaxParallelJobs` (2), `Media__DecodeTimeoutSeconds` (20), `Media__MaxTotalBytes` (2 GB), `Media__RetentionDays` (7), `Media__TrashDays` (standaard 7: bewaartijd van foto's in de prullenbak van de mediabibliotheek), `Media__AutoCleanupUnattached` (standaard `true`; `false` bewaart ongebruikte uploads tot iemand ze verwijdert, voor de mediabibliotheek) | Grenzen en bewaartijd; standaardwaarden zijn bedoeld om te blijven. | | `Hero__TextOnlyRegion` | `true` voor een site waarvan de hero geen afbeeldingen heeft (SLP Software; staat in de committed instellingen van die site): een hero zonder slides wordt dan als tekst (titelregels, lead, knoppen) in de eerste HTML geschreven. Uit (standaard, ook voor ASF): een hero zonder slides laat de pagina ongemoeid. | | `Hero__TitlePrefix` | Merktekst die in de tekst-only-regio als eerste, visueel te verbergen deel van de h1 wordt geschreven (``), zodat crawlers en schermlezers de volledige titel lezen. SLP Software: `"SLP Software: "` (committed instelling); leeg (standaard, ook ASF) schrijft niets. De site verbergt de klasse zelf visueel. | | `Media__RenderSetTimeoutSeconds` (600), `Media__StripTimeoutSeconds` (60) | De tijd die het knippen van alle varianten van één foto in de achtergrond mag duren, en het verwijderen van metadata bij een upload. Ruim gekozen: een grote foto op een Raspberry Pi kost minuten. | diff --git a/frontend/src/features/media/components/CleanupDialog.tsx b/frontend/src/features/media/components/CleanupDialog.tsx index 11b4974..11851ee 100644 --- a/frontend/src/features/media/components/CleanupDialog.tsx +++ b/frontend/src/features/media/components/CleanupDialog.tsx @@ -1,5 +1,6 @@ import { useEffect, useMemo, useRef, useState } from 'react'; import { useTranslation } from 'react-i18next'; +import { Button } from '@/components/ui/button'; import { CheckboxField } from '@/components/ui/checkbox'; import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from '@/components/ui/dialog'; import { Label } from '@/components/ui/label'; @@ -8,6 +9,7 @@ import { selectAll, type Selection } from '../lib/selection'; import { toPhotoItem } from '../lib/toPhotoItem'; import { useCleanupPreview } from '../services/hooks'; import { BulkActionBar } from './BulkActionBar'; +import { DeleteDialog } from './DeleteDialog'; import { PhotoSelectionList } from './PhotoSelectionList'; const DEFAULT_DAYS = 7; @@ -16,8 +18,8 @@ const MAX_DAYS = 365; /** * "Clean up": the photos older than the chosen number of days (by default 7), by default only the unused ones, newest - * first and all selected so single photos can be taken out. This step is a PREVIEW: nothing is deleted yet (deleting - * comes after the assumptions have been checked). + * first and all selected so single photos can be taken out. Confirming moves exactly the selected photos to the trash + * (a photo in use asks for a second confirmation naming the places). */ export function CleanupDialog({ open, onOpenChange }: { open: boolean; onOpenChange: (open: boolean) => void }) { const { t, i18n } = useTranslation(); @@ -26,6 +28,7 @@ export function CleanupDialog({ open, onOpenChange }: { open: boolean; onOpenCha const [onlyUnused, setOnlyUnused] = useState(true); // Everything starts selected: the person only takes photos OUT. A new period or filter starts again with all in. const [excluded, setExcluded] = useState>(new Set()); + const [deleting, setDeleting] = useState(false); const timer = useRef | undefined>(undefined); const preview = useCleanupPreview(debouncedDays, onlyUnused, open); @@ -46,6 +49,7 @@ export function CleanupDialog({ open, onOpenChange }: { open: boolean; onOpenCha const setSelection = (next: Selection) => setExcluded(new Set(ids.filter((id) => !next.has(id)))); const items = useMemo(() => (photos ?? []).map((p) => toPhotoItem(p, t)), [photos, t]); + const selectedItems = useMemo(() => items.filter((item) => selection.has(item.id)), [items, selection]); const selectedBytes = (photos ?? []).filter((p) => selection.has(p.id)).reduce((sum, p) => sum + p.bytes, 0); return ( @@ -82,7 +86,7 @@ export function CleanupDialog({ open, onOpenChange }: { open: boolean; onOpenCha />

- {t('media.cleanup.previewNote')} + {t('media.cleanup.trashNote')}

{preview.isError && ( @@ -103,9 +107,23 @@ export function CleanupDialog({ open, onOpenChange }: { open: boolean; onOpenCha onClear={() => setSelection(new Set())} summary={t('media.cleanup.selectedSize', { size: formatBytes(selectedBytes, i18n.language) })} /> +
+ +
)} + { + setExcluded(new Set()); + onOpenChange(false); + }} + /> ); diff --git a/frontend/src/features/media/components/DeleteDialog.tsx b/frontend/src/features/media/components/DeleteDialog.tsx new file mode 100644 index 0000000..33bcccf --- /dev/null +++ b/frontend/src/features/media/components/DeleteDialog.tsx @@ -0,0 +1,111 @@ +import { useState } from 'react'; +import { useTranslation } from 'react-i18next'; +import { Button } from '@/components/ui/button'; +import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog'; +import { usageLabel } from '../lib/usageLabel'; +import { useTrashPhotos } from '../services/hooks'; +import type { PhotoItem } from './PhotoSelectionList'; + +interface DeleteDialogProps { + open: boolean; + onOpenChange: (open: boolean) => void; + items: readonly PhotoItem[]; + /** Called with the ids that were moved to the trash. */ + onDone?: (trashedIds: string[]) => void; +} + +/** + * Deleting means "to the trash" (recoverable for a while). A photo that is in use needs a SECOND confirmation that names + * the places that lose it (decision 10). A photo that went wrong is reported; the others are done. + */ +export function DeleteDialog({ open, onOpenChange, items, onDone }: DeleteDialogProps) { + return ( + + {open && onOpenChange(false)} onDone={onDone} />} + + ); +} + +function DeleteDialogBody({ items, onClose, onDone }: { items: readonly PhotoItem[]; onClose: () => void; onDone?: (trashedIds: string[]) => void }) { + const { t } = useTranslation(); + const trash = useTrashPhotos(); + const [step, setStep] = useState<'first' | 'second'>('first'); + const [failed, setFailed] = useState(0); + const inUse = items.filter((item) => item.uses.length > 0); + + const submit = () => { + trash.mutate( + { ids: items.map((i) => i.id), confirmedInUse: inUse.length > 0 }, + { + onSuccess: ({ results }) => { + const trashed = results.filter((r) => r.status === 'trashed').map((r) => r.id); + onDone?.(trashed); + const problems = results.length - trashed.length; + if (problems === 0) onClose(); + else setFailed(problems); + }, + }, + ); + }; + + const onConfirm = () => { + if (inUse.length > 0 && step === 'first') setStep('second'); + else submit(); + }; + + if (failed > 0) { + return ( + <> + + {t('media.delete.title')} + + {t('media.delete.partial', { count: failed })} + + + + + + + ); + } + + return ( + <> + + {step === 'first' ? t('media.delete.title') : t('media.delete.secondTitle')} + + {step === 'first' ? t('media.delete.confirm', { count: items.length }) : t('media.delete.secondText', { count: inUse.length })} + + + {step === 'first' && inUse.length > 0 && ( +

+ {t('media.delete.inUseCount', { count: inUse.length })} +

+ )} + {step === 'second' && ( +
    + {inUse.map((item) => ( +
  • + {item.name}: {item.uses.map((use) => usageLabel(t, use)).join('; ')} +
  • + ))} +
+ )} + {trash.isError && ( +

+ {t('media.error')} +

+ )} + + + + + + ); +} diff --git a/frontend/src/features/media/components/PhotoSelectionList.tsx b/frontend/src/features/media/components/PhotoSelectionList.tsx index d9f7a46..f7b4e79 100644 --- a/frontend/src/features/media/components/PhotoSelectionList.tsx +++ b/frontend/src/features/media/components/PhotoSelectionList.tsx @@ -2,6 +2,7 @@ import { useRef } from 'react'; import { useTranslation } from 'react-i18next'; import { Checkbox } from '@/components/ui/checkbox'; import { formatBytes } from '../lib/format'; +import { usageLabel } from '../lib/usageLabel'; import { selectAll, selectRange, stateOf, type Selection } from '../lib/selection'; export interface PhotoUse { @@ -20,6 +21,10 @@ export interface PhotoItem { bytes: number; createdAt: string; uses: readonly PhotoUse[]; + /** When the photo was last detached from where it was used (null: never used). */ + unusedSince?: string | null; + /** When the photo went to the trash (only in the trash view). */ + deletedAt?: string | null; } interface PhotoSelectionListProps { @@ -47,12 +52,6 @@ export function PhotoSelectionList({ items, selection, onSelectionChange, isDisa anchor.current = id; }; - const usageLabel = (use: PhotoUse) => { - const place = t(`media.use.${use.kind}`, { defaultValue: use.kind }); - const where = use.position ? `${place} ${use.position}` : place; - return `${t(`media.module.${use.module}`, { defaultValue: use.module })}, ${where}${use.active ? '' : ` (${t('media.use.off')})`}`; - }; - if (items.length === 0) { return (

@@ -106,10 +105,14 @@ export function PhotoSelectionList({ items, selection, onSelectionChange, isDisa {dateFormat.format(new Date(item.createdAt))} · {formatBytes(item.bytes, i18n.language)}

- {item.uses.length === 0 ? ( - {t('media.use.none')} + {item.deletedAt ? ( + {t('media.trash.since', { date: dateFormat.format(new Date(item.deletedAt)) })} + ) : item.uses.length === 0 ? ( + + {item.unusedSince ? t('media.use.noneSince', { date: dateFormat.format(new Date(item.unusedSince)) }) : t('media.use.none')} + ) : ( - {item.uses.map(usageLabel).join('; ')} + {item.uses.map((use) => usageLabel(t, use)).join('; ')} )}

diff --git a/frontend/src/features/media/lib/toPhotoItem.ts b/frontend/src/features/media/lib/toPhotoItem.ts index 8607e91..10aa98d 100644 --- a/frontend/src/features/media/lib/toPhotoItem.ts +++ b/frontend/src/features/media/lib/toPhotoItem.ts @@ -2,14 +2,16 @@ import type { TFunction } from 'i18next'; import type { PhotoItem } from '../components/PhotoSelectionList'; import type { MediaPhotoDto } from '../services/types'; -/** The list shows a neutral name (the size of the photo): photos do not store a file name yet (assumption 21). */ +/** The list shows the original file name; photos uploaded before it was stored get a neutral label (the size, assumption 21). */ export function toPhotoItem(photo: MediaPhotoDto, t: TFunction): PhotoItem { return { id: photo.id, thumbnailUrl: photo.thumbnailUrl, - name: t('media.list.photoName', { width: photo.width, height: photo.height }), + name: photo.originalFileName ?? t('media.list.photoName', { width: photo.width, height: photo.height }), bytes: photo.bytes, createdAt: photo.createdAt, uses: photo.uses, + unusedSince: photo.unusedSince, + deletedAt: photo.deletedAt, }; } diff --git a/frontend/src/features/media/lib/usageLabel.ts b/frontend/src/features/media/lib/usageLabel.ts new file mode 100644 index 0000000..2b1d98c --- /dev/null +++ b/frontend/src/features/media/lib/usageLabel.ts @@ -0,0 +1,15 @@ +import type { TFunction } from 'i18next'; + +export interface UsePlace { + module: string; + kind: string; + position?: number | null; + active: boolean; +} + +/** "Hero, slide 3" (with "(uit)" for a switched-off place). */ +export function usageLabel(t: TFunction, use: UsePlace): string { + const place = t(`media.use.${use.kind}`, { defaultValue: use.kind }); + const where = use.position ? `${place} ${use.position}` : place; + return `${t(`media.module.${use.module}`, { defaultValue: use.module })}, ${where}${use.active ? '' : ` (${t('media.use.off')})`}`; +} diff --git a/frontend/src/features/media/mocks/handlers.ts b/frontend/src/features/media/mocks/handlers.ts index 4db340b..8463631 100644 --- a/frontend/src/features/media/mocks/handlers.ts +++ b/frontend/src/features/media/mocks/handlers.ts @@ -1,5 +1,5 @@ import { http, HttpResponse } from 'msw'; -import type { MediaCleanupPreviewDto, MediaLibraryDto, MediaPhotoDto, MediaStorageDto } from '@/features/media/services/types'; +import type { MediaCleanupPreviewDto, MediaLibraryDto, MediaPhotoDto, MediaStorageDto, MediaTrashRequest, MediaTrashResponse } from '@/features/media/services/types'; const daysAgo = (days: number) => new Date(Date.now() - days * 86_400_000).toISOString(); @@ -13,6 +13,9 @@ export const seedPhotos = (): MediaPhotoDto[] => [ createdAt: daysAgo(1), thumbnailUrl: '/media/hero/0123456789abcdef/wide-480.webp', uses: [{ module: 'hero', kind: 'slide', position: 1, active: true }], + originalFileName: 'zomer.jpg', + unusedSince: null, + deletedAt: null, }, { id: 'hero:22222222-2222-2222-2222-222222222222', @@ -23,6 +26,9 @@ export const seedPhotos = (): MediaPhotoDto[] => [ createdAt: daysAgo(12), thumbnailUrl: null, uses: [], + originalFileName: null, + unusedSince: null, + deletedAt: null, }, { id: 'hero:33333333-3333-3333-3333-333333333333', @@ -33,12 +39,37 @@ export const seedPhotos = (): MediaPhotoDto[] => [ createdAt: daysAgo(30), thumbnailUrl: null, uses: [{ module: 'hero', kind: 'slide', position: 2, active: false }], + originalFileName: null, + unusedSince: null, + deletedAt: null, }, ]; export const seedStorage = (): MediaStorageDto => ({ usedBytes: 100_000_000, limitBytes: 2_147_483_648, level: 'ok', warningPercent: 80 }); +/** Stateless mocks of trash and restore: a photo in use is refused without the second confirmation. */ +export const mediaTrashHandlers = [ + http.get('*/media-library/trash', () => HttpResponse.json({ photos: [], modules: ['hero'] } satisfies MediaLibraryDto)), + http.post('*/media-library/delete', async ({ request }) => { + const body = (await request.json()) as MediaTrashRequest; + const photos = seedPhotos(); + return HttpResponse.json({ + results: body.ids.map((id) => { + const photo = photos.find((p) => p.id === id); + if (!photo) return { id, status: 'notFound', uses: [] }; + if (photo.uses.length > 0 && !body.confirmedInUse) return { id, status: 'inUse', uses: photo.uses }; + return { id, status: 'trashed', uses: photo.uses }; + }), + } satisfies MediaTrashResponse); + }), + http.post('*/media-library/restore', async ({ request }) => { + const body = (await request.json()) as { ids: string[] }; + return HttpResponse.json({ results: body.ids.map((id) => ({ id, status: 'restored', uses: [] })) } satisfies MediaTrashResponse); + }), +]; + 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/cleanup-preview', ({ request }) => { diff --git a/frontend/src/features/media/pages/MediaLibraryPage.test.tsx b/frontend/src/features/media/pages/MediaLibraryPage.test.tsx index b8a4ffb..90544cf 100644 --- a/frontend/src/features/media/pages/MediaLibraryPage.test.tsx +++ b/frontend/src/features/media/pages/MediaLibraryPage.test.tsx @@ -5,7 +5,7 @@ import userEvent from '@testing-library/user-event'; import i18n from '@/i18n/config'; import { server } from '@/mocks/server'; import { renderWithProviders } from '@/test/utils'; -import { seedStorage } from '../mocks/handlers'; +import { seedPhotos, seedStorage } from '../mocks/handlers'; import { MediaLibraryPage } from './MediaLibraryPage'; beforeEach(async () => { @@ -37,14 +37,14 @@ describe('MediaLibraryPage', () => { expect(await screen.findByTestId('storage-warning')).toHaveTextContent('vol'); }); - it('selects photos and shows the bulk bar without any delete action yet', async () => { + it('selects photos and shows the bulk bar with the delete action', async () => { renderWithProviders(); await screen.findByTestId('photo-selection-list'); - await userEvent.click(screen.getAllByRole('checkbox', { name: /Foto 3000/ })[0]!); + await userEvent.click(screen.getByRole('checkbox', { name: 'zomer.jpg' })); expect(await screen.findByTestId('bulk-count')).toHaveTextContent('1 foto geselecteerd'); - expect(screen.queryByTestId('bulk-action-delete')).not.toBeInTheDocument(); + expect(screen.getByTestId('bulk-action-delete')).toHaveTextContent('Naar prullenbak'); }); it('opens the clean-up: older than 7 days, only unused, all selected, newest first, and nothing is deleted', async () => { @@ -56,7 +56,7 @@ describe('MediaLibraryPage', () => { const dialog = await screen.findByTestId('cleanup-dialog'); expect(within(dialog).getByTestId('cleanup-only-unused')).toBeChecked(); expect(await within(dialog).findByTestId('cleanup-summary')).toHaveTextContent('1 foto'); - expect(within(dialog).getByTestId('cleanup-preview-note')).toHaveTextContent('nog niets verwijderd'); + expect(within(dialog).getByTestId('cleanup-preview-note')).toHaveTextContent('prullenbak'); const boxes = within(dialog).getAllByRole('checkbox', { name: /Foto/ }); expect(boxes).toHaveLength(1); await waitFor(() => expect(boxes[0]).toBeChecked()); @@ -75,6 +75,108 @@ describe('MediaLibraryPage', () => { expect(within(dialog).getAllByRole('checkbox', { name: /Foto/ })).toHaveLength(2); }); + it('moves an unused photo to the trash after one confirmation', async () => { + let body: { ids: string[]; confirmedInUse: boolean } | null = null; + server.use( + http.post('*/media-library/delete', async ({ request }) => { + body = (await request.json()) as { ids: string[]; confirmedInUse: boolean }; + return HttpResponse.json({ results: body.ids.map((id) => ({ id, status: 'trashed', uses: [] })) }); + }), + ); + renderWithProviders(); + await screen.findByTestId('photo-selection-list'); + + await userEvent.click(screen.getByTestId('photo-select-hero:22222222-2222-2222-2222-222222222222')); + await userEvent.click(screen.getByTestId('bulk-action-delete')); + expect(await screen.findByTestId('delete-text')).toHaveTextContent('prullenbak'); + await userEvent.click(screen.getByTestId('delete-confirm')); + + await waitFor(() => expect(screen.queryByTestId('delete-dialog')).not.toBeInTheDocument()); + expect(body).toEqual({ ids: ['hero:22222222-2222-2222-2222-222222222222'], confirmedInUse: false }); + }); + + it('asks a second confirmation that names the places for a photo in use', async () => { + let body: { ids: string[]; confirmedInUse: boolean } | null = null; + server.use( + http.post('*/media-library/delete', async ({ request }) => { + body = (await request.json()) as { ids: string[]; confirmedInUse: boolean }; + return HttpResponse.json({ results: body.ids.map((id) => ({ id, status: 'trashed', uses: [] })) }); + }), + ); + renderWithProviders(); + await screen.findByTestId('photo-selection-list'); + + await userEvent.click(screen.getByTestId('photo-select-hero:11111111-1111-1111-1111-111111111111')); + await userEvent.click(screen.getByTestId('bulk-action-delete')); + expect(await screen.findByTestId('delete-inuse-count')).toHaveTextContent('1 foto wordt nog gebruikt'); + await userEvent.click(screen.getByTestId('delete-confirm')); + + expect(await screen.findByTestId('delete-places')).toHaveTextContent('Hero, slide 1'); + expect(body).toBeNull(); + await userEvent.click(screen.getByTestId('delete-confirm')); + + await waitFor(() => expect(body).toEqual({ ids: ['hero:11111111-1111-1111-1111-111111111111'], confirmedInUse: true })); + }); + + it('reports photos that could not be deleted', async () => { + server.use( + http.post('*/media-library/delete', async ({ request }) => { + const { ids } = (await request.json()) as { ids: string[] }; + return HttpResponse.json({ results: ids.map((id, i) => ({ id, status: i === 0 ? 'failed' : 'trashed', uses: [] })) }); + }), + ); + renderWithProviders(); + await screen.findByTestId('photo-selection-list'); + + await userEvent.click(screen.getByTestId('photo-select-hero:22222222-2222-2222-2222-222222222222')); + await userEvent.click(screen.getByTestId('photo-select-hero:33333333-3333-3333-3333-333333333333')); + await userEvent.click(screen.getByTestId('bulk-action-delete')); + await userEvent.click(screen.getByTestId('delete-confirm')); + await userEvent.click(await screen.findByTestId('delete-confirm')); + + expect(await screen.findByTestId('delete-partial')).toHaveTextContent('1 foto kon niet worden verwijderd'); + }); + + it('shows the trash and restores a photo', async () => { + let restored: string[] = []; + server.use( + http.get('*/media-library/trash', () => HttpResponse.json({ photos: [{ ...seedPhotos()[1]!, deletedAt: new Date().toISOString() }], modules: ['hero'] })), + http.post('*/media-library/restore', async ({ request }) => { + restored = ((await request.json()) as { ids: string[] }).ids; + return HttpResponse.json({ results: restored.map((id) => ({ id, status: 'restored', uses: [] })) }); + }), + ); + renderWithProviders(); + await screen.findByTestId('photo-selection-list'); + + await userEvent.click(screen.getByTestId('view-trash')); + expect(await screen.findByTestId('trash-note')).toBeInTheDocument(); + await userEvent.click(await screen.findByTestId('photo-select-hero:22222222-2222-2222-2222-222222222222')); + await userEvent.click(screen.getByTestId('bulk-action-restore')); + + await waitFor(() => expect(restored).toEqual(['hero:22222222-2222-2222-2222-222222222222'])); + }); + + it('confirming the clean-up moves exactly the selected photos to the trash', async () => { + let body: { ids: string[]; confirmedInUse: boolean } | null = null; + server.use( + http.post('*/media-library/delete', async ({ request }) => { + body = (await request.json()) as { ids: string[]; confirmedInUse: boolean }; + return HttpResponse.json({ results: body.ids.map((id) => ({ id, status: 'trashed', uses: [] })) }); + }), + ); + renderWithProviders(); + await screen.findByTestId('photo-selection-list'); + await userEvent.click(screen.getByTestId('cleanup-open')); + const dialog = await screen.findByTestId('cleanup-dialog'); + await within(dialog).findByTestId('cleanup-summary'); + + await userEvent.click(within(dialog).getByTestId('cleanup-confirm')); + await userEvent.click(await screen.findByTestId('delete-confirm')); + + await waitFor(() => expect(body).toEqual({ ids: ['hero:22222222-2222-2222-2222-222222222222'], confirmedInUse: false })); + }); + it('shows an error when the library cannot be loaded', async () => { server.use(http.get('*/media-library/photos', () => new HttpResponse(null, { status: 500 }))); renderWithProviders(); diff --git a/frontend/src/features/media/pages/MediaLibraryPage.tsx b/frontend/src/features/media/pages/MediaLibraryPage.tsx index d2b574f..8662caa 100644 --- a/frontend/src/features/media/pages/MediaLibraryPage.tsx +++ b/frontend/src/features/media/pages/MediaLibraryPage.tsx @@ -1,29 +1,56 @@ import { useMemo, useState } from 'react'; import { useTranslation } from 'react-i18next'; -import { Eraser } from 'lucide-react'; +import { Eraser, RotateCcw, Trash2 } from 'lucide-react'; import { Button } from '@/components/ui/button'; import { BulkActionBar } from '../components/BulkActionBar'; import { CleanupDialog } from '../components/CleanupDialog'; +import { DeleteDialog } from '../components/DeleteDialog'; import { PhotoSelectionList } from '../components/PhotoSelectionList'; import { StorageMeter } from '../components/StorageMeter'; import { emptySelection, prune, type Selection } from '../lib/selection'; import { toPhotoItem } from '../lib/toPhotoItem'; -import { useMediaPhotos, useMediaStorage } from '../services/hooks'; +import { useMediaPhotos, useMediaStorage, useMediaTrash, useRestorePhotos } from '../services/hooks'; + +type View = 'library' | 'trash'; /** * The media library: every photo of every module, newest first, with where it is used; the storage against its limit; - * the "Clean up" preview. Selecting works already (bulk actions come with deleting, after the assumptions are checked). + * the "Clean up" tool; bulk delete (to the trash); and the trash with restore. */ export function MediaLibraryPage() { const { t } = useTranslation(); + const [view, setView] = useState('library'); const photos = useMediaPhotos(); + const trash = useMediaTrash(view === 'trash'); const storage = useMediaStorage(); + const restore = useRestorePhotos(); const [chosen, setSelection] = useState(emptySelection); const [cleanupOpen, setCleanupOpen] = useState(false); + const [deleting, setDeleting] = useState(false); - const items = useMemo(() => (photos.data?.photos ?? []).map((p) => toPhotoItem(p, t)), [photos.data, t]); - // Photos that left the list (after a reload) drop out of the selection. + const source = view === 'library' ? photos : trash; + const items = useMemo(() => (source.data?.photos ?? []).map((p) => toPhotoItem(p, t)), [source.data, t]); + // Photos that left the list (after a reload or a move) drop out of the selection. const selection = useMemo(() => prune(chosen, items.map((i) => i.id)), [chosen, items]); + const selectedItems = items.filter((item) => selection.has(item.id)); + + const switchView = (next: View) => { + setView(next); + setSelection(emptySelection); + }; + + const actions = + view === 'library' + ? [{ id: 'delete', label: t('media.delete.action'), destructive: true, icon: