Merge pull request 'feat: schedules editor full mutation depth + channel-editor gaps (#207, #212, #126)' (#229) from feat/207-212-schedules-channel-depth into main
Build ErsatzTV Image / Docs update reminder (push) Has been skipped
Build ErsatzTV Image / Build & push image (amd64) (push) Has been cancelled
Build ErsatzTV Image / EF migration integrity (SQLite + MySql) (push) Has been cancelled
Build ErsatzTV Image / Build & test (.NET) (push) Has been cancelled

This commit was merged in pull request #229.
This commit is contained in:
2026-07-11 10:05:53 +00:00
53 changed files with 5772 additions and 2104 deletions
+29 -1
View File
@@ -58,7 +58,24 @@ Exemplars:
`ToReplaceCommand(int index)`) method that maps it to the Application-layer command type.
- **`ErsatzTV.Application` has no nullable context** (no `<Nullable>` = C# default `disable` for
that TFM in this repo — confirms CS8632 would otherwise fire) — do **not** add `?` nullable
annotations to types living there; that's a Core/Api-layer-only convention.
annotations to types living there; that's a Core/Api-layer-only convention. A static mapper that
lives in `ErsatzTV.Application` but returns a Core/Api response DTO with nullable members is fine
(e.g. `ScheduleItemResponseMapper`) — the nullability lives on the DTO record, not the mapper.
- **Shared `{id, name}` embeds**: use `ErsatzTV.Core/Api/NamedIdResponseModel.cs`
(`record NamedIdResponseModel(int Id, string Name)`) when a response DTO needs to embed a list of
named references (e.g. a schedule item's `watermarks` / `graphicsElements`) rather than minting a
one-off `(int, string)` record per domain.
- **Flatten polymorphic VMs for the wire**: when an Application ViewModel is an abstract/polymorphic
record (subtypes carrying extra fields), the OpenAPI schema only captures the base shape — promote
every subtype field to a nullable top-level member on a flat response DTO and pattern-match the
concrete VM in the mapper. Exemplar: `ScheduleItemResponseModel` (issue #126, see
`docs/decisions.md` 2026-07-10). Keep the flat DTO's **mutation** fields named 1:1 with the
matching request DTO so GET→PUT is lossless (guard with a round-trip handler test).
- **Optional enum filter via query param**: to filter a list endpoint by an enum, add a nullable
enum parameter to the query record (default `null`) and bind it with `[FromQuery] TEnum? name` on
the action; filter server-side only when it has a value. Exemplar: `?fillerKind=` on
`GET /api/filler-presets` (`GetAllFillerPresetsForApi(FillerKind? FillerKind = null)`). An invalid
enum value is rejected by model binding (400) — no handler-side guard needed.
## 3. Error mapping
@@ -214,6 +231,17 @@ items), index items from **array order** in the request body rather than trustin
index/order field. Exemplar: `ReplaceScheduleItemsRequest.ToCommand(scheduleId)` —
`Items.Select((item, index) => item.ToReplaceCommand(index))`.
**Project the write-path response through the same include chain the GET uses — never off the
freshly-built graph.** After `SaveChanges`, a command's entities carry only the foreign-key ids you set
(e.g. `ProgramScheduleItemWatermark.WatermarkId`); their reference navs are null, and any mapper that
dereferences one unguarded throws an NRE that surfaces as a 500. Reload with the read-side includes
before mapping. Exemplars: `ReplaceProgramScheduleItemsHandler` / `AddProgramScheduleItemHandler` reload
via `ProgramScheduleItemQueryExtensions.IncludeScheduleItemDetails()` (the one include chain shared with
`GetProgramScheduleItemsHandler`). Also beware LanguageExt `Map` is **lazy** — returning
`items.Map(ProjectToViewModel)` defers the projection, so a test that only checks `.IsRight` won't catch
the NRE; the controller's `.ToList()`/serialization does (regression: `ScheduleItemWriteProjectionTests`).
GET handlers that feed an ordered list must also `.OrderBy(i => i.Index)` — id order is not index order.
## 8. Known API warts (don't "fix" without discussion — they're deliberate synthesized rows)
`GET /api/blocks` and `GET /api/templates` (via `GetAllBlocksHandler` / `GetAllTemplatesHandler` in
+18 -13
View File
@@ -62,15 +62,15 @@ redirect).
> | Playout kind-editors + list actions | PARITY-OK (delete/reset/erase/scheduling-context wired + templates preview calendar, 2026-07-09; EntityLocker build-lock gating enforced server-side via 409 + mirrored in SPA `IsLocked`, 2026-07-10 #215) | — |
> | Multi/rerun collections, playlists, trash | PARITY-OK (trash select-all/clear + per-kind "see all" paging past 100, 2026-07-11) | — |
> | Collections | PARITY-OK (custom-order endpoint + reorder UI, all-10-kind add picker, 2026-07-09) | — |
> | Channel editor | GAPS (external logo URL, bare create, pickers) | #212 |
> | Channel editor | PARITY-OK (external logo URL mutual-exclusion, bare-create defaults, enumerated pickers — 2026-07-11) | #212 |
> | Channels-numbers / Logs | PARITY-OK (logs sort + page-size persistence added, 2026-07-11) | — |
> | Search | PARITY-OK (card nav incl. episode cards — #220; per-card/multi-select add-to, add-all, save-as-smart-collection; mutation controls + Add-all gated during refetch — #221; 2026-07-11) | — |
> | Media browse/detail (read paths + image browser) | PARITY-OK | — |
> | Media browse/detail (mutations, per-show scan, episode info/troubleshoot) | PARITY-OK (shared Add-to layer + scan/info/troubleshoot wired, 2026-07-10; mutation controls gated on kind/query/page refetch — #221) | — |
> | Schedules editors | **disproven — moved to Section 3** | **#207** |
> | Schedules editors | PARITY-OK (full item + schedule CRUD rebuild, draft/explicit-Save, all Blazor fields/gates/resets; 2026-07-11) | **#207 DONE** |
> | Media sources | **disproven — moved to Section 3** | **#202** |
>
> Bold issues + #202 are MUST-FIX gates for #91 phase (b); #212 is SHOULD-FIX (#213 closed 2026-07-11).
> Bold issues + #202 are MUST-FIX gates for #91 phase (b); #212 DONE 2026-07-11; #213 closed 2026-07-11.
Confirmed as of this doc: the SPA screen exists (verified against `web/src/App.tsx`'s route table
and `web/src/screens/`) but `LegacyUiRedirects.cs` has **no entry** for the Blazor route yet.
@@ -84,7 +84,7 @@ been added to the redirect map yet.
| Blazor route | Blazor file | SPA route | Notes |
|---|---|---|---|
| `/channels/{Id:int?}` | `ChannelEditor.razor` | `/app/edit-channel/{id}` | allowSubPaths |
| `/channels/{Id:int?}` | `ChannelEditor.razor` | `/app/edit-channel/{id}` | allowSubPaths; external logo URL field (mutual exclusion with upload), enumerated language/credits-template/stream-selector pickers, and bare-channel create (`ChannelsScreen`'s "New blank channel") landed #212 |
| `/channels/numbers` | `ChannelNumbers.razor` | `/app/channels` | merged into channels table |
| `/search` | `Search.razor` | `/app/search` | |
| `/system/logs` | `Logs.razor` | `/app/logs` | |
@@ -167,20 +167,25 @@ connection parameters, path replacements, and library enable/disable have **no S
write REST API** (`MediaSourcesController` is GET-only; the "Add Source" button is a hardcoded
disabled stub). A fresh install could not connect any library without Blazor.
### Schedule editors — #207 (found by the #203 mutation-depth sweep, 2026-07-09)
### Schedule editors — #207 DONE (2026-07-11)
| Blazor route | Blazor file | Blocking issue |
|---|---|---|
| `/schedules/{Id:int}`, `/schedules/add`, `/schedules/{Id:int}/items` | `ScheduleEditor.razor`, `ScheduleItemsEditor.razor` | **#207** |
| Blazor route | Blazor file | SPA route | Status |
|---|---|---|---|
| `/schedules/{Id:int}`, `/schedules/add`, `/schedules/{Id:int}/items` | `ScheduleEditor.razor`, `ScheduleItemsEditor.razor` | `/app/schedules` (`SchedulesScreen`) | **PARITY-OK** |
Previously (wrongly) listed in Section 2 as "merged into schedules screen": the SPA schedules
screen is a near read-only viewer — no schedule create/edit/delete, every per-item inspector
control hard-coded disabled (~35 Blazor fields unchangeable), add-item is defaults-only. The
REST endpoints exist and are unused; only item delete/reorder and the schedule switcher work.
Was (correctly, until #207) a near read-only viewer — no schedule create/edit/delete, every per-item
inspector control hard-coded disabled (~35 Blazor fields unchangeable), add-item defaults-only.
**Rebuilt in #207** (`web/src/screens/SchedulesScreen.tsx` + `web/src/schedules/`): full schedule
CRUD (create via TopBar/in-screen, edit properties, delete) + full item mutation — every Blazor field,
option list, enable-gate and forced-reset, encoded in the pure `itemRules.ts` (exhaustively unit-tested)
and applied in the inspector. Uses a **draft / explicit-Save** model over the single destructive
`PUT .../items` replace (not the old instant-persist), with Discard + a dirty navigation guard — see
`decisions.md` 2026-07-11 (a)/(b)/(c) and `spa-conventions.md` §8. The capability matrix (issue #207)
maps each Blazor field → SPA control → request key → test.
### Remaining mutation-depth gaps inside Section 2 rows
Tracked as #91 phase (b) gates without moving whole rows — SHOULD-FIX: #212 (channel editor),
Tracked as #91 phase (b) gates without moving whole rows — #212 DONE 2026-07-11 (channel editor),
#213 CLOSED 2026-07-11 — full remainder landed across two branches: block-history page-size
persistence (`localStorage` key `ctv-block-history-page-size`, same `ctv-` namespace as
`ctv-theme`) + History action gated on `block.id >= 0` + client-side name/group filter boxes on
+85 -1
View File
@@ -262,6 +262,26 @@ TelevisionShow/TelevisionSeason/Artist per-media-item CollectionTypes and 422s t
via `GET /api/search/all-items`, then reuse the id-list add endpoints — no query-based add
command exists server-side. Issues #208/#209.
## 2026-07-10 — Schedule-item GET returns a flat, non-polymorphic DTO (`ScheduleItemResponseModel`)
`GET/POST/PUT /api/schedules/{id}/items` return `ScheduleItemResponseModel` /
`ScheduleItemsResponseModel` (`ErsatzTV.Core/Api/Scheduling/`), **not** the Application-layer
`ProgramScheduleItemViewModel` hierarchy (One/Flood/Multiple/Duration subtypes). The polymorphic VM
only described its base shape in OpenAPI, so the SPA couldn't see the subtype fields (issue #126).
The flat DTO promotes every subtype field to a nullable top-level member — `multipleMode`,
`multipleCount` (renamed from the VM's `Count`), `playoutDuration`, `tailMode`,
`discardToFillAttempts` — mapped by pattern-matching the concrete VM in
`ScheduleItemResponseMapper` (`ErsatzTV.Application/ProgramSchedules/`). Its **mutation fields are
named 1:1 with `ScheduleItemRequest`** so a GET maps losslessly back to a PUT/POST
(`ScheduleItemResponseRoundTripTests` is the release gate proving the fixed point). It also carries
picker-hydration fields the editor needs: `collectionName`/`smartCollectionName`/…/`playlistName`,
`playlistGroupId` (to preselect the playlist's group), per-filler names, `watermarks` /
`graphicsElements` as `NamedIdResponseModel` lists, the computed `name`, and `durationEstimate`.
`GetProgramScheduleItemsHandler.EnforceProperties` still rewrites StartType→Dynamic, Flood→One and
Playlist/Rerun→PlaybackOrder None when `ShuffleScheduleItems` is on — that lossy normalization is
deliberate and lives on the read side (documented + tested). New shared `NamedIdResponseModel`
(`ErsatzTV.Core/Api/`) is the generic `{id, name}` embed for API responses. Issues #126/#207/#212.
## 2026-07-10 — Playout API mutations return 409 while the build lock is held (#215)
Blazor disabled per-playout Reset/Erase/Delete/Edit while a `BuildPlayout` was in flight
@@ -299,7 +319,71 @@ is "no mutation during a build", matching Blazor's edit-disable.
Precedent for the 409 shape: `TraktController` (left as-is with its own private `ConflictProblem()`
to keep the diff small). Convention recorded in `api-conventions.md` §3a.
## 2026-07-11 — Queue state lives in the pinned Gitea tracker (#237), not in the handoff file
## 2026-07-11 — Schedules SPA editor: draft/explicit-Save over instant-persist; Copy includes multi/smart/rerun; shuffled-GET normalization preserved
The ChicoryTV schedules editor (`web/src/screens/SchedulesScreen.tsx` + `web/src/schedules/`,
issue #207) rebuilds the schedule-item lineup to full mutation parity with the legacy Blazor editor.
Three deliberate decisions:
**(a) Draft model with one explicit Save, replacing instant-persist.** All add/edit/copy/remove/
reorder mutate a **local draft list only**; a single **Save** issues one
`PUT /api/schedules/{id}/items` (the replace endpoint). This is intentional because that PUT is
**destructive server-side** — it deletes and recreates every item row (new ids) and triggers playout
rebuilds — so batching edits into one flush (vs. the old per-action POST/DELETE/PUT) minimizes churn
and gives the user a Discard/dirty affordance. On 422/network error the draft is kept and the error
surfaced; on success the draft is replaced with the server response. A **Discard** action and a dirty
guard (native `confirm()` on schedule-switch + in-app nav via `navigationGuard.ts`, plus a
`beforeunload` listener) protect the draft. See `docs/spa-conventions.md` §8. This retires the old
inline `ScheduleScreen` in `App.tsx` and its instant-persist add/delete/reorder tests.
**(b) Copy item deep-copies ALL source references, including multi/smart/rerun collections.** Blazor's
`CopyItem` omitted the multi-collection / smart-collection / rerun-collection references when
duplicating an item (copying only the plain collection/media-item/playlist refs) — a latent bug. The
SPA's `copyDraftItem` (`web/src/schedules/itemRules.ts`) copies every source field + display name, so
copying a MultiCollection/SmartCollection/Rerun item preserves its source. Deliberate deviation
fixing the Blazor omission.
**(c) The shuffled-schedule GET normalization (`EnforceProperties`) is preserved lossiness, matching
Blazor.** When a schedule has `ShuffleScheduleItems`, `GET .../items` still rewrites startType→Dynamic,
Flood→One, and Playlist/Rerun playbackOrder→None (and zeroes discardToFillAttempts for non-random
Duration items). The SPA does **not** fight this — it hides the Fixed start type and Flood playout
mode from the option lists (and disables the reorder arrows) for shuffled schedules, mirroring Blazor,
so a GET→edit→PUT round-trip stays consistent with the server's read-side normalization. Issue #207.
## 2026-07-11 — Channel editor: bare-create entry point + external-logo mutual exclusion (#212)
Two Blazor-parity decisions closing the channel-editor gaps (`ChannelEditor.razor` +
`ChannelEditViewModel`):
1. **Bare-channel create lives on the channels list, not a form-first route.** Blazor's
`/channels` (no `Id`) is a full add form; the SPA instead adds a "New blank channel" action next
to "Add Channel" on `ChannelsScreen` (`web/src/App.tsx`) that POSTs `CreateChannelRequest` with
Blazor's computed add-mode defaults (`(max existing int-parsed channel number) + 1`, `name: "New
Channel"`, `group: "ErsatzTV"`, `ffmpegProfileId` = `GET /api/settings/ffmpeg`'s
`defaultFFmpegProfileId`, `streamingMode: "TransportStreamHybrid"`, `isEnabled`/`showInEpg: true`,
every other field at its C# `default(T)` — see `ChannelEditor.razor`'s `else` branch for the
source of truth) directly, then navigates to `/app/edit-channel/{id}` for the rest of the fields.
This is a deliberate equivalent, not a parity gap: it reuses the existing full editor instead of
duplicating its ~20 fields into a second form. "Add Channel" (`/app/new-channel`, the
library-to-lineup `ChannelBuilder` flow) is unrelated and untouched.
2. **External logo URL wins over an uploaded logo, mirroring
`ChannelEditViewModel.ToUpdate/ToCreate`.** The channel's logo is `ArtworkContentTypeModel {
path, contentType, isExternalUrl }`; on hydration, `isExternalUrl: true` populates a separate
"External logo URL" field and the uploaded-logo draft state is treated as empty (`EMPTY_LOGO =
{ path: '', contentType: '' }` in `ChannelEditScreen.tsx`) so the two never disagree. On submit,
a non-blank URL always wins: `logo: { path: url, contentType: '' }`, exactly matching
`ExternalLogoUrl`'s precedence in the C# view model. Uploading a file clears the URL field (the
last-set field wins, Blazor parity via `UploadLogo`'s `_model.ExternalLogoUrl = null`). The URL
is validated as http(s) client-side before save is enabled (Blazor has no equivalent validation;
added because the field is free text with no server-side format check surfaced to the SPA).
Also landed with #212: `preferredAudioLanguageCode`/`preferredSubtitleLanguageCode`,
`musicVideoCreditsTemplate`, and `streamSelector` moved from free-text `Input`s to `Select`s fed by
`GET /api/languages` / `/api/channels/music-video-credits-templates` /
`/api/channels/stream-selectors`. Each keeps the channel's currently-stored value selectable even if
it's absent from the reference list (`optionsKeepingCurrent` in `ChannelEditScreen.tsx`) so loading
an existing channel never silently changes the value out from under an unmanaged language code or a
template/selector file removed from disk since save.## 2026-07-11 — Queue state lives in the pinned Gitea tracker (#237), not in the handoff file
With multiple sessions/agents working the repo in parallel, the old protocol — every session
wholesale-rewrites `docs/handoffs/chicorytv-issue-queue.md` on main (session state + queue +
+9 -1
View File
@@ -2,7 +2,7 @@
*Generated by `scripts/generate-endpoint-index.py` from `ErsatzTV/wwwroot/openapi/v1.json`. Do not edit by hand -- regenerated by `scripts/update-openapi.sh`.*
130 endpoints, 204 operations.
133 endpoints, 207 operations.
## Artists
@@ -59,7 +59,9 @@
| POST | `/api/channels/bulk/group` | | Move channels to a group |
| POST | `/api/channels/bulk/renumber` | | Renumber channels |
| POST | `/api/channels/from-lineup` | CreateChannelFromLineup | Create a channel from a library lineup |
| GET | `/api/channels/music-video-credits-templates` | GetMusicVideoCreditsTemplates | Get available music video credits template names |
| GET | `/api/channels/state` | | Get channel runtime state |
| GET | `/api/channels/stream-selectors` | GetChannelStreamSelectors | Get available channel stream selector names |
| POST | `/api/channels/{channelNumber}/playout/reset` | | Reset channel playout |
| DELETE | `/api/channels/{id}` | | Delete a channel |
| GET | `/api/channels/{id}` | GetChannelById | Get a channel by id |
@@ -147,6 +149,12 @@
| GET | `/api/images/folders` | GetImageFolders | List image library folders |
| PUT | `/api/images/folders/{id}/duration` | UpdateImageFolderDuration | Set or clear an image folder's playout duration |
## Languages
| Method | Path | Operation | Summary |
|---|---|---|---|
| GET | `/api/languages` | GetLanguages | Get all available language codes |
## Libraries
| Method | Path | Operation | Summary |
+19 -1
View File
@@ -201,7 +201,25 @@ Also run `npm run check:api` if you touched anything OpenAPI-relevant (see `api-
— it regenerates `src/api/generated/v1.d.ts` and fails the build if it's out of sync with what's
committed.
## 8. Review checklist — temporal semantics
## 8. Unsaved-changes navigation guard
Screens with a **draft / explicit-Save** model (edits accumulate locally, one Save flushes them —
e.g. the schedules editor, `web/src/screens/SchedulesScreen.tsx`) must guard against losing the
draft to navigation. The shared module `web/src/navigationGuard.ts` is the seam:
- The screen **registers a guard** on mount: `registerNavigationGuard(() => !dirtyRef.current ||
window.confirm(...))`, returning the unregister fn from the mount `useEffect` for cleanup. Only one
guard is active at a time (the mounted screen); a stale unregister only clears its own guard.
- `App.tsx`'s `navigate` handler calls `canLeaveCurrentScreen()` before `pushState` — a `false`
return aborts the in-app sidebar/nav click. This covers React-router-less in-app navigation only.
- The screen **also** guards the three paths the module can't see — a **schedule switch** and any
in-screen action that would replace the draft use their own `window.confirm(...)`, and a
`beforeunload` listener (installed while `dirty`) covers full-page unloads (reload / close tab /
external link).
Keep the guard predicate reading a **ref** (`dirtyRef`), not the `dirty` state value, so
`canLeaveCurrentScreen()` sees the current dirtiness synchronously at click time.
## 9. Review checklist — temporal semantics
- **For every effect / timer / async completion, ask: *when* does it fire (mount, dependency change,
unmount, StrictMode double-invoke) and *which* render/request does it still own?** A debounce timer