From 533abe7cdbe49b60b6866d6c8cc888a7b5de2675 Mon Sep 17 00:00:00 2001 From: Timothy Date: Tue, 14 Jul 2026 18:54:32 +0200 Subject: [PATCH] refactor(spa): extract playouts screen Move the Playouts UI, route wrapper, helpers, and detailed behavior tests into a colocated screen module while preserving App-level navigation coverage. Refs #245 Co-Authored-By: OpenAI Codex --- docs/decisions.md | 21 + docs/spa-conventions.md | 16 +- web/src/App.test.tsx | 634 +------------ web/src/App.tsx | 1072 +--------------------- web/src/screens/PlayoutsScreen.test.tsx | 901 +++++++++++++++++++ web/src/screens/PlayoutsScreen.tsx | 1089 +++++++++++++++++++++++ 6 files changed, 2029 insertions(+), 1704 deletions(-) create mode 100644 web/src/screens/PlayoutsScreen.test.tsx create mode 100644 web/src/screens/PlayoutsScreen.tsx diff --git a/docs/decisions.md b/docs/decisions.md index d1aa94948..e03c628ac 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -54,6 +54,7 @@ keep append-only from accreting stale, contradictory, or unreadably-large histor - [2026-07-11 — Channel editor: bare-create entry point + external-logo mutual exclusion (#212)](#2026-07-11--channel-editor-bare-create-entry-point--external-logo-mutual-exclusion-212) - [2026-07-11 — EntityLocker: atomic flags + single-owner release discipline, no owner tokens (#231)](#2026-07-11--entitylocker-atomic-flags--single-owner-release-discipline-no-owner-tokens-231) - [2026-07-11 — Channels screen extraction (#244): single-file screen, no sibling helper dir (epic #243 phase 1)](#2026-07-11--channels-screen-extraction-244-single-file-screen-no-sibling-helper-dir-epic-243-phase-1) +- [2026-07-14 — Playouts screen extraction (#245): screen-owned route wrapper (epic #243 phase 2)](#2026-07-14--playouts-screen-extraction-245-screen-owned-route-wrapper-epic-243-phase-2) - [2026-07-11 — Media-source management REST write API + SPA (#202)](#2026-07-11--media-source-management-rest-write-api--spa-202) - [2026-07-11 — Legacy→SPA redirect matcher: exact map + ordered segment-template patterns (#204)](#2026-07-11--legacyspa-redirect-matcher-exact-map--ordered-segment-template-patterns-204) - [2026-07-11 — Blazor removal auth posture: no new exposure beyond phase (a); real auth deferred to #197 (#206)](#2026-07-11--blazor-removal-auth-posture-no-new-exposure-beyond-phase-a-real-auth-deferred-to-197-206) @@ -1788,3 +1789,23 @@ explicit `Api:CorsAllowedOrigins` machine-client path continues to work. It is a server-side HTTP clients, so Jellyfin's `/iptv/*` requests are unaffected; same-origin SPA artwork and IPTV requests remain allowed. This is defense in depth for browser embedding and does not replace CORS or authentication. Refs #330 #319 #314. + +## 2026-07-14 — Playouts screen extraction (#245): screen-owned route wrapper (epic #243 phase 2) + +Second bounded extraction under the App.tsx modularization epic (#243): the Playouts domain moved from +`web/src/App.tsx` into `web/src/screens/PlayoutsScreen.tsx`, including its loading/error/empty states, +dialogs, mutations, timeline/filter helpers, and the existing `PlayoutsRouteScreen`. The dedicated +`PlayoutScheduleEditors.tsx` modules remain separate. This is a pure structural move: no API, route, CSS, +or runtime behavior changed; `App.tsx` retains only the import and `` dispatch. + +**The unguarded route wrapper moves with the screen.** Playouts owns two sibling sub-path editors and, +per `spa-conventions.md` §2, must keep its local pathname state plus `popstate` listener because App's +allow-sub-path route object is reference-stable. Colocating the wrapper keeps that screen-specific route +ownership beside the base screen while App-level tests retain the cross-route navigation assertions. + +**Temporal mutation behavior stays verbatim.** `mutatingRef`, `runMutation`, and the explicit +`query.refresh()` after a 409 moved as one unit. The extraction deliberately does not add mount/current +guards to these pre-existing promise completions; changing those semantics belongs to a separate issue. +Detailed behavior tests now render `PlayoutsScreen` directly with a scoped fetch mock, including the +zero-playout Add Playout affordance, lock/409 handling, refresh/poll ownership, action and kind gates, and +dialog flows. Refs #245 #243. diff --git a/docs/spa-conventions.md b/docs/spa-conventions.md index c0507ed39..3051be929 100644 --- a/docs/spa-conventions.md +++ b/docs/spa-conventions.md @@ -33,13 +33,14 @@ for the base path and every sub-path under it. `App`'s state update is `setActiveRoute(routeFromLocation())`; React's `useState` setter bails via `Object.is` when the new value is reference-equal to the old one — so navigating from `/app/blocks` to `/app/blocks/42` (or between `/app/blocks/42` and `/app/blocks/17`) **never re-invokes `ScreenContent`** at the `App` -level. See the comment block directly above `PlayoutsRouteScreen` in `App.tsx` (~line 3540) for the -canonical explanation, and its implementation (`useState(() => window.location.pathname)` + +level. See the comment block directly above `PlayoutsRouteScreen` in +`screens/PlayoutsScreen.tsx` for the canonical explanation, and its implementation +(`useState(() => window.location.pathname)` + `useEffect` with a `popstate` listener local to the wrapper component) for the fix. Exemplars of screens that already do this correctly: `BlocksScreen.tsx`, `TemplatesScreen.tsx`, -`DecosScreen.tsx`, `DecoTemplatesScreen.tsx`, and the `PlayoutsRouteScreen` wrapper in `App.tsx` -(which owns two sibling sub-paths, `/playouts/{id}/alternate-schedules` and +`DecosScreen.tsx`, `DecoTemplatesScreen.tsx`, and the `PlayoutsRouteScreen` wrapper colocated in +`PlayoutsScreen.tsx` (which owns two sibling sub-paths, `/playouts/{id}/alternate-schedules` and `/playouts/{id}/templates`, dispatching internally via `parsePlayoutSubRoute`). **Exception — a guarded sub-path route defers pathname ownership to App.** When a sub-path route's @@ -251,7 +252,7 @@ is gone. The SPA seams now are: - Every screen with meaningful logic gets a screen test; every API client module gets a param-mapping / URL-building test (e.g. `logs.test.ts` next to `logs.ts`). - `web/src/App.test.tsx` covers navigation + the route table, including regressions like the - sub-path bug in §2 (see the tests around `PlayoutsRouteScreen`, ~line 1682+, that click into + sub-path bug in §2 (see the tests around `PlayoutsRouteScreen` that click into `/app/playouts/{id}/...` sub-paths and assert the correct sub-screen rendered). - **Nav-label test-selector care**: `getByRole('link'/'button', { name: /Regex/ })` matches by substring by default — a loose regex can match more than one nav item. Verified example: the @@ -260,7 +261,8 @@ is gone. The SPA seams now are: contain "System". Anchor (`^`/`$`) or use exact strings in `getByRole` name matchers whenever a new label could be a substring of (or share a substring with) an existing one — check `App.tsx`'s nav `label:` list for collisions before picking a new label. -- **Extracted-screen tests own their own fetch mock** (Schedules #207, Channels #244): when a +- **Extracted-screen tests own their own fetch mock** (Schedules #207, Channels #244, Playouts + #245): when a screen is pulled out of `App.tsx` into `web/src/screens/Screen.tsx`, its colocated `Screen.test.tsx` builds a **self-contained** `vi.spyOn(window, 'fetch')` mock scoped to that screen's own endpoints (plus local `jsonResponse`/fixture-factory helpers) and renders the @@ -269,7 +271,7 @@ is gone. The SPA seams now are: screen (route to it, assert it mounted and hit its own endpoint) plus genuinely cross-cutting shell concerns (route table, sub-path ownership §2, the unsaved-changes/popstate guard §8, the TopBar action wiring). Detailed screen behavior lives in the screen's own test file. See - `ChannelsScreen.test.tsx` / `SchedulesScreen.test.tsx` for the shape. + `ChannelsScreen.test.tsx` / `SchedulesScreen.test.tsx` / `PlayoutsScreen.test.tsx` for the shape. ## 7. Verification gate — run before every commit touching `web/` diff --git a/web/src/App.test.tsx b/web/src/App.test.tsx index 2407fcfd1..e8e051a60 100644 --- a/web/src/App.test.tsx +++ b/web/src/App.test.tsx @@ -646,34 +646,10 @@ describe('ChicoryTV SPA scaffold', () => { expect((await screen.findAllByRole('button', { name: 'Add schedule' })).length).toBeGreaterThan(0); }); - it('renders the Playouts monitor from live playout and channel state APIs', async () => { + it('routes to the extracted Playouts screen and mounts its query', async () => { mockDashboardApi({ - channelStates: [ - { - channelId: 1, - channelNumber: '5.1', - onAir: true, - nowPlaying: { - finishUtc: '2026-07-05T20:30:00Z', - startUtc: '2026-07-05T20:00:00Z', - title: 'Saturday Morning Cartoons' - } - } - ], - playoutDetails: playout({ id: 20, playoutMode: 'Continuous', scheduleFile: '/config/schedules/retro.json' }), - playoutItems: [ - playoutItem({ title: 'Saturday Morning Cartoons', start: '2026-07-05T20:00:00Z', finish: '2026-07-05T20:30:00Z' }), - playoutItem({ title: 'Station ID', start: '2026-07-05T20:30:00Z', finish: '2026-07-05T20:31:00Z', duration: '00:01:00' }), - playoutItem({ title: 'Moon Patrol', start: '2026-07-05T20:31:00Z', finish: '2026-07-05T21:00:00Z' }) - ], - playoutWarningsCount: 3, - playouts: { - page: [ - listPlayout({ id: 20, channelName: 'Retro Cartoons', channelNumber: '5.1', scheduleName: 'Prime Time Cartoons' }), - listPlayout({ id: 21, channelName: 'News 24', channelNumber: '24', scheduleName: 'News Rotation' }) - ], - totalCount: 2 - } + playoutItems: [playoutItem()], + playouts: { page: [listPlayout({ id: 20 })], totalCount: 1 } }); render(); @@ -681,20 +657,7 @@ describe('ChicoryTV SPA scaffold', () => { fireEvent.click(screen.getByRole('link', { name: /Playouts/ })); expect(await screen.findByRole('heading', { name: 'Retro Cartoons' })).toBeInTheDocument(); - expect(screen.getByText('2 playouts loaded')).toBeInTheDocument(); - expect(screen.getByText('3 warnings')).toBeInTheDocument(); - expect(screen.getAllByText('Saturday Morning Cartoons').length).toBeGreaterThan(0); - expect(screen.getAllByText('Moon Patrol').length).toBeGreaterThan(0); - expect(screen.getAllByText('Station ID').length).toBeGreaterThan(0); - // Real items carry fillerKind 'None' and must not be badged as filler. - expect(screen.queryByText('Filler')).not.toBeInTheDocument(); - expect(screen.getByText('Metadata preview only')).toBeInTheDocument(); - expect(screen.getByDisplayValue('Continuous')).toBeInTheDocument(); - expect(window.fetch).toHaveBeenCalledWith('/api/v1/playouts', expect.any(Object)); expect(window.fetch).toHaveBeenCalledWith('/api/v1/playouts/20', expect.any(Object)); - expect(window.fetch).toHaveBeenCalledWith('/api/v1/playouts/20/items', expect.any(Object)); - expect(window.fetch).toHaveBeenCalledWith('/api/v1/playouts/warnings/count', expect.any(Object)); - expect(window.fetch).toHaveBeenCalledWith('/api/v1/channels/state', expect.any(Object)); }); it('renders the extracted Libraries screen from live media source and scan status APIs (#202)', async () => { @@ -720,109 +683,14 @@ describe('ChicoryTV SPA scaffold', () => { expect(window.fetch).toHaveBeenCalledWith('/api/v1/libraries/scan-status', expect.any(Object)); }); - it('toggles Show filler to refetch playout items with showFiller=true and badge filler rows', async () => { - mockDashboardApi({ - playoutItems: [ - playoutItem({ title: 'Saturday Morning Cartoons', start: '2026-07-05T20:00:00Z', finish: '2026-07-05T20:30:00Z' }), - playoutItem({ title: 'Station ID', start: '2026-07-05T20:30:00Z', finish: '2026-07-05T20:31:00Z', duration: '00:01:00', fillerKind: 'PreRoll' }) - ], - playouts: { page: [listPlayout({ id: 20 })], totalCount: 1 } - }); - - render(); - - fireEvent.click(screen.getByRole('link', { name: /Playouts/ })); - expect(await screen.findByRole('heading', { name: 'Retro Cartoons' })).toBeInTheDocument(); - - // Toggle off: the filler item is not requested, so no Filler badge renders. - expect(screen.queryByText('Station ID')).not.toBeInTheDocument(); - expect(screen.queryByText('Filler')).not.toBeInTheDocument(); - - fireEvent.click(screen.getByRole('switch', { name: 'Show filler' })); - - expect((await screen.findAllByText('Station ID')).length).toBeGreaterThan(0); - expect(screen.getByText('Filler')).toBeInTheDocument(); - expect(window.fetch).toHaveBeenCalledWith('/api/v1/playouts/20/items?showFiller=true', expect.any(Object)); - }); - - it('fetches the Playouts screen data exactly once on mount and only polls channel state', async () => { - const intervalHandlers: Array<() => void> = []; - vi.spyOn(window, 'setInterval').mockImplementation((handler: TimerHandler) => { - if (typeof handler === 'function') { - intervalHandlers.push(handler as () => void); - } - - return intervalHandlers.length; - }); - vi.spyOn(window, 'clearInterval').mockImplementation(() => undefined); - mockDashboardApi({ - channelStates: [ - { channelId: 1, channelNumber: '5.1', onAir: true, nowPlaying: null } - ], - playoutItems: [playoutItem()], - playouts: { page: [listPlayout({ id: 20 })], totalCount: 1 } - }); - - render(); - - // The Dashboard also fetches /api/v1/playouts on load; measure the Playouts - // screen's own contribution as a delta instead of absorbing that prefetch. - await waitFor(() => { - expect(fetchCount('/api/v1/playouts')).toBeGreaterThan(0); - }); - const playoutFetchesBeforeNavigation = fetchCount('/api/v1/playouts'); - - fireEvent.click(screen.getByRole('link', { name: /Playouts/ })); - expect(await screen.findByRole('heading', { name: 'Retro Cartoons' })).toBeInTheDocument(); - - expect(fetchCount('/api/v1/playouts')).toBe(playoutFetchesBeforeNavigation + 1); - expect(fetchCount('/api/v1/playouts/20')).toBe(1); - expect(fetchCount('/api/v1/playouts/20/items')).toBe(1); - const playoutFetchesBeforePoll = fetchCount('/api/v1/playouts'); - const stateFetchesBeforePoll = fetchCount('/api/v1/channels/state'); - - intervalHandlers.forEach((handler) => handler()); - - await waitFor(() => { - expect(fetchCount('/api/v1/channels/state')).toBeGreaterThan(stateFetchesBeforePoll); - }); - expect(fetchCount('/api/v1/playouts')).toBe(playoutFetchesBeforePoll); - expect(fetchCount('/api/v1/playouts/20/items')).toBe(1); - }); - - it('switches selected playouts and fetches only the selected playout detail and items', async () => { - mockDashboardApi({ - playoutDetails: playout({ id: 20, channelName: 'Retro Cartoons', channelNumber: '5.1' }), - playoutItems: [playoutItem({ title: 'Saturday Morning Cartoons' })], - playouts: { - page: [ - listPlayout({ id: 20, channelName: 'Retro Cartoons', channelNumber: '5.1' }), - listPlayout({ id: 21, channelName: 'News 24', channelNumber: '24' }) - ], - totalCount: 2 - } - }); - - render(); - - fireEvent.click(screen.getByRole('link', { name: /Playouts/ })); - expect(await screen.findByRole('heading', { name: 'Retro Cartoons' })).toBeInTheDocument(); - - fireEvent.click(screen.getByRole('button', { name: /News 24/ })); - - expect(await screen.findByRole('heading', { name: 'News 24' })).toBeInTheDocument(); - expect(window.fetch).toHaveBeenCalledWith('/api/v1/playouts/21', expect.any(Object)); - expect(window.fetch).toHaveBeenCalledWith('/api/v1/playouts/21/items', expect.any(Object)); - expect(fetchCount('/api/v1/playouts')).toBe(2); - }); - // Regression coverage for the live-E2E finding: clicking "Alternate schedules" / "Templates" // used to update the URL via navigateToPath's pushState + synthetic popstate but never swap // the rendered screen, because routeFromLocation() returns the SAME ScreenRoute object // reference for /app/playouts and every /app/playouts/{id}/* sub-path, so React's // setActiveRoute(sameRef) bailed via Object.is and ScreenContent never re-ran. The fix (see - // PlayoutsRouteScreen in App.tsx) mirrors BlocksScreen/TemplatesScreen/DecosScreen: it owns its - // own pathname state and popstate listener instead of relying on the shell's activeRoute. + // PlayoutsRouteScreen in screens/PlayoutsScreen.tsx) mirrors + // BlocksScreen/TemplatesScreen/DecosScreen: it owns its own pathname state and popstate listener + // instead of relying on the shell's activeRoute. it('client-side navigates into and back out of the alternate-schedules editor without a reload', async () => { mockDashboardApi({ playoutDetails: playout({ id: 20, channelName: 'Retro Cartoons', channelNumber: '5.1' }), @@ -918,496 +786,6 @@ describe('ChicoryTV SPA scaffold', () => { expect(window.location.pathname).toBe('/app/playouts'); }); - it('shows the Playouts loading state', async () => { - vi.spyOn(window, 'fetch').mockImplementation((input: RequestInfo | URL) => { - const path = input.toString(); - - if (path === '/api/v1/playouts') { - return new Promise(() => {}); - } - - if (path === '/api/v1/channels/state') { - return Promise.resolve(jsonResponse([])); - } - - if (path === '/api/v1/playouts/warnings/count') { - return Promise.resolve(jsonResponse(0)); - } - - return Promise.resolve(jsonResponse([])); - }); - - render(); - - fireEvent.click(screen.getByRole('link', { name: /Playouts/ })); - - expect((await screen.findAllByText('Loading playouts')).length).toBeGreaterThan(0); - }); - - it('shows Playouts API errors and retries 404 parent handling', async () => { - mockDashboardApi({ - playoutItemsFailure: { - detail: 'Playout 20 was not found', - status: 404, - title: 'Not found' - }, - playoutItemsFailuresBeforeSuccess: 1, - playouts: { page: [listPlayout({ id: 20 })], totalCount: 1 } - }); - - render(); - - fireEvent.click(screen.getByRole('link', { name: /Playouts/ })); - - expect(await screen.findByText('Playout 20 was not found')).toBeInTheDocument(); - fireEvent.click(screen.getByRole('button', { name: 'Retry' })); - - expect(await screen.findByRole('heading', { name: 'Retro Cartoons' })).toBeInTheDocument(); - }); - - it('shows an empty Playouts state when no playouts exist', async () => { - mockDashboardApi({ playouts: { page: [], totalCount: 0 } }); - - render(); - - fireEvent.click(screen.getByRole('link', { name: /Playouts/ })); - - expect((await screen.findAllByText('No playouts returned')).length).toBeGreaterThan(0); - }); - - it('resets all playouts with confirmation and refetches playout-scoped data', async () => { - mockDashboardApi({ - confirm: true, - playoutItems: [playoutItem()], - playouts: { page: [listPlayout({ id: 20 })], totalCount: 1 } - }); - - render(); - - fireEvent.click(screen.getByRole('link', { name: /Playouts/ })); - expect(await screen.findByRole('heading', { name: 'Retro Cartoons' })).toBeInTheDocument(); - - const playoutFetchesBeforeReset = fetchCount('/api/v1/playouts'); - const itemFetchesBeforeReset = fetchCount('/api/v1/playouts/20/items'); - - fireEvent.click(screen.getByRole('button', { name: 'Reset all playouts' })); - - await waitFor(() => { - expect(window.fetch).toHaveBeenCalledWith('/api/v1/playouts/reset-all', expect.objectContaining({ method: 'POST' })); - }); - expect(fetchCount('/api/v1/playouts')).toBe(playoutFetchesBeforeReset + 1); - expect(fetchCount('/api/v1/playouts/20/items')).toBe(itemFetchesBeforeReset + 1); - }); - - it('shows ProblemDetails when the reset-all transport fails with a 5xx', async () => { - // Backend contract: POST /api/v1/playouts/reset-all is an unconditional 202 — there is no - // application-level error path today. This test guards client robustness only, against - // transport/server failures (proxy errors, unhandled exceptions). - mockDashboardApi({ - confirm: true, - mutationFailures: { - '/api/v1/playouts/reset-all': { - detail: 'The playout worker crashed while queueing rebuilds', - status: 500, - title: 'Internal Server Error' - } - }, - playoutItems: [playoutItem()], - playouts: { page: [listPlayout({ id: 20 })], totalCount: 1 } - }); - - render(); - - fireEvent.click(screen.getByRole('link', { name: /Playouts/ })); - expect(await screen.findByRole('heading', { name: 'Retro Cartoons' })).toBeInTheDocument(); - - fireEvent.click(screen.getByRole('button', { name: 'Reset all playouts' })); - - expect(await screen.findByText('The playout worker crashed while queueing rebuilds')).toBeInTheDocument(); - }); - - it('deletes the selected playout with confirmation and refetches', async () => { - mockDashboardApi({ - confirm: true, - playoutItems: [playoutItem()], - playoutDetails: playout({ id: 20, scheduleKind: 'Classic' }), - playouts: { page: [listPlayout({ id: 20 })], totalCount: 1 } - }); - - render(); - - fireEvent.click(screen.getByRole('link', { name: /Playouts/ })); - expect(await screen.findByRole('heading', { name: 'Retro Cartoons' })).toBeInTheDocument(); - - const playoutFetchesBeforeDelete = fetchCount('/api/v1/playouts'); - - fireEvent.click(screen.getByRole('button', { name: 'Delete' })); - - await waitFor(() => { - expect(window.fetch).toHaveBeenCalledWith('/api/v1/playouts/20', expect.objectContaining({ method: 'DELETE' })); - }); - expect(fetchCount('/api/v1/playouts')).toBe(playoutFetchesBeforeDelete + 1); - }); - - it('resets the selected channel playout with confirmation', async () => { - mockDashboardApi({ - confirm: true, - playoutItems: [playoutItem()], - playoutDetails: playout({ id: 20, scheduleKind: 'Classic' }), - channelStates: [{ channelId: 7, channelNumber: '5.1', onAir: true, nowPlaying: null }], - playouts: { page: [listPlayout({ id: 20, channelNumber: '5.1' })], totalCount: 1 } - }); - - render(); - - fireEvent.click(screen.getByRole('link', { name: /Playouts/ })); - expect(await screen.findByRole('heading', { name: 'Retro Cartoons' })).toBeInTheDocument(); - - fireEvent.click(screen.getByRole('button', { name: 'Reset' })); - - await waitFor(() => { - // Keyed on the resolved channel id (7), not the playout id (20) or the channel number. - expect(window.fetch).toHaveBeenCalledWith( - '/api/v1/channels/7/playout/reset', - expect.objectContaining({ method: 'POST' }) - ); - }); - }); - - it('shows both erase buttons for a Block playout and posts to the right routes', async () => { - mockDashboardApi({ - confirm: true, - playoutItems: [playoutItem()], - playoutDetails: playout({ id: 20, scheduleKind: 'Block' }), - playouts: { page: [listPlayout({ id: 20, scheduleKind: 'Block' })], totalCount: 1 } - }); - - render(); - - fireEvent.click(screen.getByRole('link', { name: /Playouts/ })); - expect(await screen.findByRole('heading', { name: 'Retro Cartoons' })).toBeInTheDocument(); - - fireEvent.click(screen.getByRole('button', { name: 'Erase items' })); - await waitFor(() => { - expect(window.fetch).toHaveBeenCalledWith( - '/api/v1/playouts/20/erase-items', - expect.objectContaining({ method: 'POST' }) - ); - }); - - fireEvent.click(screen.getByRole('button', { name: 'Erase items and history' })); - await waitFor(() => { - expect(window.fetch).toHaveBeenCalledWith( - '/api/v1/playouts/20/erase-items-and-history', - expect.objectContaining({ method: 'POST' }) - ); - }); - }); - - it('shows only erase-items-and-history for a Classic playout', async () => { - mockDashboardApi({ - playoutItems: [playoutItem()], - playoutDetails: playout({ id: 20, scheduleKind: 'Classic' }), - playouts: { page: [listPlayout({ id: 20, scheduleKind: 'Classic' })], totalCount: 1 } - }); - - render(); - - fireEvent.click(screen.getByRole('link', { name: /Playouts/ })); - expect(await screen.findByRole('heading', { name: 'Retro Cartoons' })).toBeInTheDocument(); - - expect(screen.getByRole('button', { name: 'Erase items and history' })).toBeInTheDocument(); - expect(screen.queryByRole('button', { name: 'Erase items' })).not.toBeInTheDocument(); - }); - - it('shows no erase buttons for an ExternalJson playout', async () => { - mockDashboardApi({ - playoutItems: [playoutItem()], - playoutDetails: playout({ id: 20, scheduleKind: 'ExternalJson' }), - playouts: { page: [listPlayout({ id: 20, scheduleKind: 'ExternalJson' })], totalCount: 1 } - }); - - render(); - - fireEvent.click(screen.getByRole('link', { name: /Playouts/ })); - expect(await screen.findByRole('heading', { name: 'Retro Cartoons' })).toBeInTheDocument(); - - expect(screen.queryByRole('button', { name: 'Erase items and history' })).not.toBeInTheDocument(); - expect(screen.queryByRole('button', { name: 'Erase items' })).not.toBeInTheDocument(); - }); - - it('disables mutation buttons and shows a Building cue for a locked (building) playout', async () => { - mockDashboardApi({ - playoutItems: [playoutItem()], - playoutDetails: playout({ id: 20, scheduleKind: 'Block' }), - playouts: { page: [listPlayout({ id: 20, isLocked: true, scheduleKind: 'Block' })], totalCount: 1 } - }); - - render(); - - fireEvent.click(screen.getByRole('link', { name: /Playouts/ })); - expect(await screen.findByRole('heading', { name: 'Retro Cartoons' })).toBeInTheDocument(); - - expect(screen.getByText('Building…')).toBeInTheDocument(); - expect(screen.getByRole('button', { name: 'Reset' })).toBeDisabled(); - expect(screen.getByRole('button', { name: 'Erase items' })).toBeDisabled(); - expect(screen.getByRole('button', { name: 'Erase items and history' })).toBeDisabled(); - expect(screen.getByRole('button', { name: 'Delete' })).toBeDisabled(); - }); - - it('disables Alternate schedules for an on-demand Classic playout', async () => { - mockDashboardApi({ - playoutItems: [playoutItem()], - playoutDetails: playout({ id: 20, playoutMode: 'OnDemand', scheduleKind: 'Classic' }), - playouts: { page: [listPlayout({ id: 20, playoutMode: 'OnDemand', scheduleKind: 'Classic' })], totalCount: 1 } - }); - - render(); - - fireEvent.click(screen.getByRole('link', { name: /Playouts/ })); - expect(await screen.findByRole('heading', { name: 'Retro Cartoons' })).toBeInTheDocument(); - - expect(screen.getByRole('button', { name: 'Alternate schedules' })).toBeDisabled(); - }); - - it('enables Alternate schedules for a continuous Classic playout', async () => { - mockDashboardApi({ - playoutItems: [playoutItem()], - playoutDetails: playout({ id: 20, playoutMode: 'Continuous', scheduleKind: 'Classic' }), - playouts: { page: [listPlayout({ id: 20, playoutMode: 'Continuous', scheduleKind: 'Classic' })], totalCount: 1 } - }); - - render(); - - fireEvent.click(screen.getByRole('link', { name: /Playouts/ })); - expect(await screen.findByRole('heading', { name: 'Retro Cartoons' })).toBeInTheDocument(); - - expect(screen.getByRole('button', { name: 'Alternate schedules' })).toBeEnabled(); - }); - - it('opens the scheduling-context dialog for an item that has one', async () => { - mockDashboardApi({ - playoutItems: [playoutItem({ hasSchedulingContext: true, id: 99, title: 'Context Item' })], - playoutDetails: playout({ id: 20 }), - playoutSchedulingContext: 'SCHEDULING_CONTEXT_BODY', - playouts: { page: [listPlayout({ id: 20 })], totalCount: 1 } - }); - - render(); - - fireEvent.click(screen.getByRole('link', { name: /Playouts/ })); - expect(await screen.findByRole('heading', { name: 'Retro Cartoons' })).toBeInTheDocument(); - - fireEvent.click(screen.getByRole('button', { name: 'Scheduling context' })); - - expect(await screen.findByText('SCHEDULING_CONTEXT_BODY')).toBeInTheDocument(); - await waitFor(() => { - expect(window.fetch).toHaveBeenCalledWith( - '/api/v1/playouts/items/99/scheduling-context', - expect.any(Object) - ); - }); - }); - - it('shows an error in the scheduling-context dialog when the fetch fails', async () => { - mockDashboardApi({ - playoutItems: [playoutItem({ hasSchedulingContext: true, id: 99, title: 'Context Item' })], - playoutDetails: playout({ id: 20 }), - playoutSchedulingContextFailure: { detail: 'No scheduling context available', status: 404 }, - playouts: { page: [listPlayout({ id: 20 })], totalCount: 1 } - }); - - render(); - - fireEvent.click(screen.getByRole('link', { name: /Playouts/ })); - expect(await screen.findByRole('heading', { name: 'Retro Cartoons' })).toBeInTheDocument(); - - fireEvent.click(screen.getByRole('button', { name: 'Scheduling context' })); - - expect(await screen.findByText('No scheduling context available')).toBeInTheDocument(); - }); - - it('does not show a scheduling-context button for items without one', async () => { - mockDashboardApi({ - playoutItems: [playoutItem({ hasSchedulingContext: false, id: 99 })], - playoutDetails: playout({ id: 20 }), - playouts: { page: [listPlayout({ id: 20 })], totalCount: 1 } - }); - - render(); - - fireEvent.click(screen.getByRole('link', { name: /Playouts/ })); - expect(await screen.findByRole('heading', { name: 'Retro Cartoons' })).toBeInTheDocument(); - - expect(screen.queryByRole('button', { name: 'Scheduling context' })).not.toBeInTheDocument(); - }); - - it('filters the playout selector rail by channel name', async () => { - mockDashboardApi({ - playoutItems: [playoutItem()], - playouts: { - page: [ - listPlayout({ id: 20, channelName: 'Retro Cartoons', channelNumber: '5.1' }), - listPlayout({ id: 21, channelName: 'News 24', channelNumber: '24', scheduleName: 'News Rotation' }) - ], - totalCount: 2 - } - }); - - render(); - - fireEvent.click(screen.getByRole('link', { name: /Playouts/ })); - expect(await screen.findByRole('heading', { name: 'Retro Cartoons' })).toBeInTheDocument(); - - const rail = screen.getByRole('complementary', { name: 'Playout selector' }); - expect(within(rail).getByRole('button', { name: /Retro Cartoons/ })).toBeInTheDocument(); - expect(within(rail).getByRole('button', { name: /News 24/ })).toBeInTheDocument(); - - fireEvent.change(screen.getByLabelText('Filter playouts'), { target: { value: 'News' } }); - - expect(within(rail).queryByRole('button', { name: /Retro Cartoons/ })).not.toBeInTheDocument(); - expect(within(rail).getByRole('button', { name: /News 24/ })).toBeInTheDocument(); - expect(screen.getByText('1 of 2 playouts')).toBeInTheDocument(); - }); - - it('renders honestly when totalCount exceeds the returned page length', async () => { - mockDashboardApi({ - playoutItems: [playoutItem()], - playoutItemsTotalCount: 500, - playouts: { - page: [ - listPlayout({ id: 20, channelName: 'Retro Cartoons', channelNumber: '5.1' }), - listPlayout({ id: 21, channelName: 'News 24', channelNumber: '24' }) - ], - totalCount: 150 - } - }); - - render(); - - fireEvent.click(screen.getByRole('link', { name: /Playouts/ })); - - expect(await screen.findByRole('heading', { name: 'Retro Cartoons' })).toBeInTheDocument(); - // Only 2 of 150 rows were returned; the count label must not claim all 150 loaded. - expect(screen.getByText('2 of 150 playouts')).toBeInTheDocument(); - // Items page is also partial (1 of 500); the monitor must still render without crashing. - expect(screen.getAllByText('Saturday Morning Cartoons').length).toBeGreaterThan(0); - }); - - it('creates a classic playout from the Add Playout dialog and selects it', async () => { - mockDashboardApi({ - channels: [channelSummary({ id: 1, name: 'Retro Cartoons', number: '5' })], - createPlayoutResponse: playout({ id: 42 }), - playoutItems: [playoutItem()], - playouts: { page: [listPlayout({ id: 20 })], totalCount: 1 }, - schedules: [schedule({ id: 7, name: 'Weekend Lineup' })] - }); - - render(); - - fireEvent.click(screen.getByRole('link', { name: /Playouts/ })); - expect(await screen.findByRole('heading', { name: 'Retro Cartoons' })).toBeInTheDocument(); - - fireEvent.click(screen.getByRole('button', { name: 'Add Playout' })); - expect(await screen.findByText('Add playout')).toBeInTheDocument(); - - fireEvent.change(screen.getByLabelText('Channel'), { target: { value: '1' } }); - await screen.findByRole('option', { name: 'Weekend Lineup' }); - fireEvent.change(screen.getByLabelText('Classic schedule'), { target: { value: '7' } }); - - fireEvent.click(screen.getByRole('button', { name: 'Create' })); - - await waitFor(() => { - expect(requestBodyFor('/api/v1/playouts')).toMatchObject({ - channelId: 1, - programScheduleId: 7, - scheduleKind: 'Classic' - }); - }); - expect(window.fetch).toHaveBeenCalledWith('/api/v1/playouts', expect.objectContaining({ method: 'POST' })); - await waitFor(() => { - expect(screen.queryByText('Add playout')).not.toBeInTheDocument(); - }); - }); - - it('shows the create-playout error inline when the API rejects the request', async () => { - mockDashboardApi({ - channels: [channelSummary({ id: 1, name: 'Retro Cartoons', number: '5' })], - mutationFailures: { - '/api/v1/playouts': { - detail: 'Channel already has one playout', - status: 422, - title: 'Validation failed' - } - }, - playoutItems: [playoutItem()], - playouts: { page: [listPlayout({ id: 20 })], totalCount: 1 }, - schedules: [schedule({ id: 7, name: 'Weekend Lineup' })] - }); - - render(); - - fireEvent.click(screen.getByRole('link', { name: /Playouts/ })); - expect(await screen.findByRole('heading', { name: 'Retro Cartoons' })).toBeInTheDocument(); - - fireEvent.click(screen.getByRole('button', { name: 'Add Playout' })); - expect(await screen.findByText('Add playout')).toBeInTheDocument(); - - fireEvent.change(screen.getByLabelText('Channel'), { target: { value: '1' } }); - await screen.findByRole('option', { name: 'Weekend Lineup' }); - fireEvent.change(screen.getByLabelText('Classic schedule'), { target: { value: '7' } }); - - fireEvent.click(screen.getByRole('button', { name: 'Create' })); - - expect(await screen.findByText('Channel already has one playout')).toBeInTheDocument(); - }); - - it('edits daily rebuild time from the playout detail panel', async () => { - mockDashboardApi({ - playoutDetails: playout({ id: 20, dailyRebuildTime: '04:00:00' }), - playoutItems: [playoutItem()], - playouts: { page: [listPlayout({ id: 20 })], totalCount: 1 }, - updatePlayoutDetailsResponse: playout({ id: 20, dailyRebuildTime: '05:00:00' }) - }); - - render(); - - fireEvent.click(screen.getByRole('link', { name: /Playouts/ })); - expect(await screen.findByRole('heading', { name: 'Retro Cartoons' })).toBeInTheDocument(); - - fireEvent.click(screen.getByRole('button', { name: 'Edit details' })); - expect(await screen.findByText('Edit playout details')).toBeInTheDocument(); - - fireEvent.change(screen.getByLabelText('Daily reset time'), { target: { value: '05:00:00' } }); - fireEvent.click(screen.getByRole('button', { name: 'Save changes' })); - - await waitFor(() => { - expect(requestBodyFor('/api/v1/playouts/20')).toMatchObject({ dailyRebuildTime: '05:00:00' }); - }); - expect(window.fetch).toHaveBeenCalledWith('/api/v1/playouts/20', expect.objectContaining({ method: 'PUT' })); - await waitFor(() => { - expect(screen.queryByText('Edit playout details')).not.toBeInTheDocument(); - }); - }); - - it('shows the schedule-file field only for file-backed playout kinds when editing', async () => { - mockDashboardApi({ - playoutDetails: playout({ id: 20, scheduleFile: '/config/schedule.yml', scheduleKind: 'Sequential' }), - playoutItems: [playoutItem()], - playouts: { page: [listPlayout({ id: 20, scheduleKind: 'Sequential' })], totalCount: 1 } - }); - - render(); - - fireEvent.click(screen.getByRole('link', { name: /Playouts/ })); - expect(await screen.findByRole('heading', { name: 'Retro Cartoons' })).toBeInTheDocument(); - - fireEvent.click(screen.getByRole('button', { name: 'Edit details' })); - expect(await screen.findByText('Edit playout details')).toBeInTheDocument(); - - expect(screen.getByLabelText('Sequential schedule')).toBeInTheDocument(); - }); - it('shows the dashboard loading state while requests are pending', async () => { vi.spyOn(window, 'fetch').mockImplementation(() => new Promise(() => {})); diff --git a/web/src/App.tsx b/web/src/App.tsx index a213ff985..82bd72106 100644 --- a/web/src/App.tsx +++ b/web/src/App.tsx @@ -19,11 +19,9 @@ import { ChevronDown, Clapperboard, CircleHelp, - Clock, ClipboardCopy, Crosshair, Film, - Eraser, FolderTree, Info, Layers, @@ -36,8 +34,6 @@ import { ListMusic, ListVideo, Plus, - Pencil, - Play, Radio, RefreshCw, Repeat, @@ -45,7 +41,6 @@ import { Search, Settings, SlidersHorizontal, - Sparkles, Stamp, Stethoscope, Trash2, @@ -97,49 +92,28 @@ import { BlocksScreen } from './screens/BlocksScreen'; import { DecosScreen } from './screens/DecosScreen'; import { DecoTemplatesScreen } from './screens/DecoTemplatesScreen'; import { TemplatesScreen } from './screens/TemplatesScreen'; -import { - PlayoutAlternateSchedulesScreen, - PlayoutTemplatesEditorScreen -} from './screens/PlayoutScheduleEditors'; +import { PlayoutsRouteScreen } from './screens/PlayoutsScreen'; import { navigateToPath, parseLibrariesSubRoute, - parseMediaSubRoute, - parsePlayoutSubRoute + parseMediaSubRoute } from './routing'; import { Badge, Button, Card, ChannelLogo, - Dialog, IconButton, - Input, NavItem, NavSection, ProgressBar, Select, Spinner, Stat, - StatusDot, - Switch + StatusDot } from './components'; import { useChannelsQuery, - createPlayout, - deletePlayout, - erasePlayoutItems, - erasePlayoutItemsAndHistory, - getPlayoutItemSchedulingContext, - resetChannelPlayout, - getDecos, - ApiError, - messageFromError, - getSchedules, - resetAllPlayouts, - updatePlayoutDefaultDeco, - updatePlayoutDetails, - usePlayoutsScreenQuery, useDashboardHealthQuery, useDashboardQuery, useDashboardVersionQuery, @@ -149,16 +123,9 @@ import { type ChannelState, type ChannelGuideChannel, type ChannelGuideProgramme, - type CreatePlayoutRequest, type DashboardChannel, - type DecoListItem, type DashboardChannelState, type DashboardHealthQueryState, - type PlayoutDetail, - type PlayoutScheduleKind, - type ProgramSchedule, - type PlayoutItem, - type PlayoutSummary, } from './api'; import { applyDesignSystemTheme, @@ -1199,10 +1166,6 @@ function DashboardScreen({ ); } -function formatScheduleEnum(value: string): string { - return value.replace(/([a-z])([A-Z])/g, '$1 $2'); -} - const EPG_SLOT_MINUTES = 30; const EPG_SLOT_WIDTH = 156; const EPG_RAIL_WIDTH = 196; @@ -1479,1006 +1442,6 @@ function programmeMatchesNowPlaying(programme: ClippedProgramme, nowPlaying: Cha programme.stop.getTime() === nowPlayingFinish.getTime(); } -function PlayoutsLoadingState() { - return ( - Loading playouts} subtitle="Fetching playouts, channel state, and upcoming items."> -
- - Loading playouts -
-
- ); -} - -function PlayoutsErrorState({ error, refresh }: { error: string; refresh: () => void }) { - return ( - Playouts unavailable} - subtitle="The API returned an error while loading the monitor." - actions={} - > -
-
-
- ); -} - -function PlayoutsEmptyState() { - return ( - No playouts returned} subtitle="Create a channel playout before using the runtime monitor."> -
No playouts returned
-
- ); -} - -const PLAYOUT_KIND_OPTIONS: Array<{ label: string; value: PlayoutScheduleKind }> = [ - { label: 'Classic', value: 'Classic' }, - { label: 'Block', value: 'Block' }, - { label: 'Sequential', value: 'Sequential' }, - { label: 'Scripted', value: 'Scripted' }, - { label: 'External JSON (dizqueTV)', value: 'ExternalJson' } -]; - -function scheduleFileHelperText(kind: PlayoutScheduleKind): string { - switch (kind) { - case 'Sequential': - return 'The full path to the sequential schedule (YAML) file'; - case 'Scripted': - return 'The command line used to run the scripted schedule'; - case 'ExternalJson': - return 'The full path to the JSON (dizqueTV) schedule file'; - default: - return ''; - } -} - -function AddPlayoutDialog({ - busy, - channelsWithPlayouts, - error, - onCancel, - onSubmit, - open -}: { - busy: boolean; - channelsWithPlayouts: Set; - error: string | null; - onCancel: () => void; - onSubmit: (request: CreatePlayoutRequest) => void; - open: boolean; -}) { - const channelsQuery = useChannelsQuery(); - const [kind, setKind] = useState('Classic'); - const [channelId, setChannelId] = useState(''); - const [scheduleId, setScheduleId] = useState(''); - const [scheduleFile, setScheduleFile] = useState(''); - const [schedules, setSchedules] = useState(null); - const schedulesLoading = kind === 'Classic' && schedules === null; - - useEffect(() => { - if (kind !== 'Classic' || schedules !== null) { - return; - } - - let active = true; - getSchedules() - .then((result) => { - if (active) { - setSchedules(result); - } - }) - .catch(() => { - if (active) { - setSchedules([]); - } - }); - - return () => { - active = false; - }; - }, [kind, schedules]); - - const channels = channelsQuery.status === 'success' ? channelsQuery.channels : []; - const needsScheduleFile = kind === 'Sequential' || kind === 'Scripted' || kind === 'ExternalJson'; - const canSubmit = - channelId.length > 0 && - (kind !== 'Classic' || scheduleId.length > 0) && - (!needsScheduleFile || scheduleFile.trim().length > 0); - - const submit = () => { - if (!canSubmit) { - return; - } - - const request: CreatePlayoutRequest = { - channelId: Number(channelId), - programScheduleId: kind === 'Classic' ? Number(scheduleId) : null, - scheduleFile: needsScheduleFile ? scheduleFile.trim() : null, - scheduleKind: kind - }; - onSubmit(request); - }; - - return ( - - - - - } - onClose={onCancel} - open={open} - title="Add playout" - width={480} - > - setChannelId(event.target.value)} - options={[ - { label: 'Select a channel...', value: '' }, - ...channels.map((channel) => ({ - label: `${channel.number} - ${channel.name}${channelsWithPlayouts.has(channel.number) ? ' (already has a playout)' : ''}`, - value: `${channel.id}` - })) - ]} - value={channelId} - /> - - {kind === 'Classic' && ( -
- setScheduleFile(event.target.value)} - value={scheduleFile} - /> - {scheduleFileHelperText(kind)} -
- )} - {error && ( - - {error} - - )} -
- ); -} - -function EditPlayoutDetailsDialog({ - busy, - error, - onCancel, - onSubmit, - open, - playout -}: { - busy: boolean; - error: string | null; - onCancel: () => void; - onSubmit: (dailyRebuildTime: string | null, scheduleFile: string | null) => void; - open: boolean; - playout: PlayoutDetail; -}) { - const canEditScheduleFile = - playout.scheduleKind === 'Sequential' || playout.scheduleKind === 'Scripted' || playout.scheduleKind === 'ExternalJson'; - - const [dailyRebuildTime, setDailyRebuildTime] = useState(playout.dailyRebuildTime ?? ''); - const [scheduleFile, setScheduleFile] = useState(playout.scheduleFile ?? ''); - - const rebuildOptions = [ - { label: 'Do not automatically reset', value: '' }, - ...Array.from({ length: 47 }, (_, index) => { - const totalMinutes = (index + 1) * 30; - const hours = Math.floor(totalMinutes / 60); - const minutes = totalMinutes % 60; - const value = `${String(hours).padStart(2, '0')}:${String(minutes).padStart(2, '0')}:00`; - const label = new Date(2000, 0, 1, hours, minutes).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }); - return { label, value }; - }) - ]; - - return ( - - - - - } - onClose={onCancel} - open={open} - title="Edit playout details" - width={480} - > - setScheduleFile(event.target.value)} - value={scheduleFile} - /> - - )} - {error && ( - - {error} - - )} - - ); -} - -function PlayoutsScreen() { - const query = usePlayoutsScreenQuery(); - const [filter, setFilter] = useState(''); - const [mutationError, setMutationError] = useState(null); - const [mutating, setMutating] = useState(false); - const mutatingRef = useRef(false); - const [addOpen, setAddOpen] = useState(false); - const [addBusy, setAddBusy] = useState(false); - const [addError, setAddError] = useState(null); - const [editOpen, setEditOpen] = useState(false); - const [editBusy, setEditBusy] = useState(false); - const [editError, setEditError] = useState(null); - const [contextItemId, setContextItemId] = useState(null); - - if (query.status === 'loading') { - return ; - } - - if (query.status === 'error') { - return ; - } - - const { channelStates, items, playout, playouts, selectedPlayoutId, totalCount, warningsCount } = query.data; - const { itemsLoading, setShowFiller, showFiller } = query; - const selectedSummary = playouts.find((candidate) => candidate.id === selectedPlayoutId) ?? playouts[0] ?? null; - const channelsWithPlayouts = new Set(playouts.map((candidate) => candidate.channelNumber)); - - const setMutatingState = (value: boolean) => { - mutatingRef.current = value; - setMutating(value); - }; - - const resetAll = () => { - if (mutatingRef.current || !window.confirm('Reset all playouts?')) { - return; - } - - setMutationError(null); - setMutatingState(true); - resetAllPlayouts() - .then(() => { - query.refresh(); - }) - .catch((error: unknown) => { - setMutationError(messageFromError(error)); - }) - .finally(() => { - setMutatingState(false); - }); - }; - - const runMutation = (confirmMessage: string, action: () => Promise) => { - if (mutatingRef.current || !window.confirm(confirmMessage)) { - return; - } - - setMutationError(null); - setMutatingState(true); - action() - .then(() => { - query.refresh(); - }) - .catch((error: unknown) => { - setMutationError(messageFromError(error)); - // A 409 means a build lock is now held for this playout; refresh so the row - // picks up its IsLocked state and the mutation buttons disable themselves. - if (error instanceof ApiError && error.status === 409) { - query.refresh(); - } - }) - .finally(() => { - setMutatingState(false); - }); - }; - - const resetSelectedChannel = () => { - if (!selectedSummary) { - return; - } - // The reset endpoint keys on the immutable channel id. The playout summary only carries the - // channel number, so resolve the id from channel state (which covers every channel). - const channelId = channelStates.find( - (state) => state.channelNumber === selectedSummary.channelNumber - )?.channelId; - if (channelId == null) { - setMutationError('Unable to resolve the channel for this playout.'); - return; - } - runMutation(`Reset the playout for ${selectedSummary.channelName}?`, () => - resetChannelPlayout(channelId) - ); - }; - - const deleteSelectedPlayout = () => { - if (!selectedSummary) { - return; - } - runMutation(`Delete the playout for ${selectedSummary.channelName}? This cannot be undone.`, () => - deletePlayout(selectedSummary.id) - ); - }; - - const eraseSelectedItems = () => { - if (!selectedSummary) { - return; - } - runMutation(`Erase all built items for ${selectedSummary.channelName}?`, () => - erasePlayoutItems(selectedSummary.id) - ); - }; - - const eraseSelectedItemsAndHistory = () => { - if (!selectedSummary) { - return; - } - runMutation(`Erase all built items and history for ${selectedSummary.channelName}?`, () => - erasePlayoutItemsAndHistory(selectedSummary.id) - ); - }; - - const submitAddPlayout = (request: CreatePlayoutRequest) => { - setAddBusy(true); - setAddError(null); - createPlayout(request) - .then((created) => { - setAddOpen(false); - query.setActivePlayout(created.id); - query.refresh(); - }) - .catch((error: unknown) => { - setAddError(messageFromError(error)); - }) - .finally(() => { - setAddBusy(false); - }); - }; - - const submitEditPlayoutDetails = (dailyRebuildTime: string | null, scheduleFile: string | null) => { - if (!selectedSummary) { - return; - } - - setEditBusy(true); - setEditError(null); - updatePlayoutDetails(selectedSummary.id, { dailyRebuildTime, scheduleFile }) - .then(() => { - setEditOpen(false); - query.refresh(); - }) - .catch((error: unknown) => { - setEditError(messageFromError(error)); - }) - .finally(() => { - setEditBusy(false); - }); - }; - - if (!selectedSummary) { - return ( -
-
- - -
- - setAddOpen(false)} - onSubmit={submitAddPlayout} - open={addOpen} - /> -
- ); - } - - const selectedState = channelStates.find((state) => state.channelNumber === selectedSummary.channelNumber); - // The playout's build lock is held (a build is in flight). Server rejects destructive - // mutations with 409 while locked; mirror that by disabling the buttons here. - const selectedLocked = selectedSummary.isLocked; - const nowPlaying = selectedState?.nowPlaying ?? null; - const nowItem = itemMatchingNow(items, nowPlaying?.title) ?? items[0] ?? null; - const nextItem = nextPlayoutItem(items, nowItem); - const filteredPlayouts = filterPlayouts(playouts, filter); - - return ( -
-
- - - 0 ? 'warn' : 'neutral'} dot={warningsCount > 0}>{warningsCount} warning{warningsCount === 1 ? '' : 's'} - -
- - {mutationError && ( -
-
- )} - -
- - -
-
- -
- {selectedSummary.channelNumber} {selectedState?.onAir && On air} {selectedLocked && Building…} -

{selectedSummary.channelName}

-
-
- -
-
-
-
- On air now -

{nowPlaying?.title ?? nowItem?.title ?? 'No current item reported'}

- -
- {formatDateTime(nowPlaying?.startUtc ?? nowItem?.start)} - {formatDateTime(nowPlaying?.finishUtc ?? nowItem?.finish)} -
-
-
- -
- -
-
-
- { - setEditError(null); - setEditOpen(true); - }} - size="sm" - startIcon={ -
- - : undefined}> - - - - - {itemsLoading && } - - - } - > -
- {items.length === 0 ? ( -
{itemsLoading ? : 'No upcoming items'}
- ) : ( - items.map((item, index) => { - const itemId = item.id; - - return ( -
- {formatDateTime(item.start)} - {isFillerItem(item) ?
- ); - }) - )} -
-
-
-
- - setAddOpen(false)} - onSubmit={submitAddPlayout} - open={addOpen} - /> - {playout && ( - setEditOpen(false)} - onSubmit={submitEditPlayoutDetails} - open={editOpen} - playout={playout} - /> - )} - setContextItemId(null)} - /> -
- ); -} - -function PlayoutSchedulingContextDialog({ itemId, onClose }: { itemId: number | null; onClose: () => void }) { - const [state, setState] = useState< - | { status: 'loading' } - | { status: 'success'; context: string } - | { status: 'error'; error: string } - >({ status: 'loading' }); - const activeRef = useRef(true); - - useEffect(() => { - activeRef.current = true; - - if (itemId != null) { - getPlayoutItemSchedulingContext(itemId) - .then((result) => { - if (activeRef.current) { - setState({ context: result.context, status: 'success' }); - } - }) - .catch((error: unknown) => { - if (activeRef.current) { - setState({ error: messageFromError(error), status: 'error' }); - } - }); - } - - return () => { - activeRef.current = false; - }; - }, [itemId]); - - return ( - - {state.status === 'loading' && } - {state.status === 'error' && ( -
-
- )} - {state.status === 'success' && ( -
-          {state.context}
-        
- )} -
- ); -} - -function PlayoutDefaultDecoField({ playout, onSaved }: { playout: PlayoutDetail; onSaved: () => void }) { - const [decos, setDecos] = useState(null); - const [saving, setSaving] = useState(false); - const [error, setError] = useState(null); - const activeRef = useRef(true); - - useEffect(() => { - activeRef.current = true; - getDecos() - .then((list) => { - if (activeRef.current) { - setDecos(list.filter((deco) => deco.id > 0)); - } - }) - .catch(() => { - if (activeRef.current) { - setDecos([]); - } - }); - return () => { - activeRef.current = false; - }; - }, []); - - const options = [ - { label: 'None (no default deco)', value: '' }, - ...(decos ?? []) - .slice() - .sort((a, b) => `${a.decoGroupName}${a.name}`.localeCompare(`${b.decoGroupName}${b.name}`)) - .map((deco) => ({ label: `${deco.decoGroupName} / ${deco.name}`, value: String(deco.id) })) - ]; - - return ( -
- setKind(event.target.value as PlayoutScheduleKind)} + options={PLAYOUT_KIND_OPTIONS} + value={kind} + /> +
+ setScheduleId(event.target.value)} + options={[ + { label: schedulesLoading ? 'Loading...' : 'Select a schedule...', value: '' }, + ...(schedules ?? []).map((schedule) => ({ label: schedule.name ?? `Schedule ${schedule.id}`, value: `${schedule.id}` })) + ]} + value={scheduleId} + /> +
+ )} + {kind === 'Block' && ( +

Block templates are added later.

+ )} + {needsScheduleFile && ( +
+ setScheduleFile(event.target.value)} + value={scheduleFile} + /> + {scheduleFileHelperText(kind)} +
+ )} + {error && ( + + {error} + + )} + + ); +} + +function EditPlayoutDetailsDialog({ + busy, + error, + onCancel, + onSubmit, + open, + playout +}: { + busy: boolean; + error: string | null; + onCancel: () => void; + onSubmit: (dailyRebuildTime: string | null, scheduleFile: string | null) => void; + open: boolean; + playout: PlayoutDetail; +}) { + const canEditScheduleFile = + playout.scheduleKind === 'Sequential' || playout.scheduleKind === 'Scripted' || playout.scheduleKind === 'ExternalJson'; + + const [dailyRebuildTime, setDailyRebuildTime] = useState(playout.dailyRebuildTime ?? ''); + const [scheduleFile, setScheduleFile] = useState(playout.scheduleFile ?? ''); + + const rebuildOptions = [ + { label: 'Do not automatically reset', value: '' }, + ...Array.from({ length: 47 }, (_, index) => { + const totalMinutes = (index + 1) * 30; + const hours = Math.floor(totalMinutes / 60); + const minutes = totalMinutes % 60; + const value = `${String(hours).padStart(2, '0')}:${String(minutes).padStart(2, '0')}:00`; + const label = new Date(2000, 0, 1, hours, minutes).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }); + return { label, value }; + }) + ]; + + return ( + + + + + } + onClose={onCancel} + open={open} + title="Edit playout details" + width={480} + > + setScheduleFile(event.target.value)} + value={scheduleFile} + /> +
+ )} + {error && ( + + {error} + + )} + + ); +} + +export function PlayoutsScreen() { + const query = usePlayoutsScreenQuery(); + const [filter, setFilter] = useState(''); + const [mutationError, setMutationError] = useState(null); + const [mutating, setMutating] = useState(false); + const mutatingRef = useRef(false); + const [addOpen, setAddOpen] = useState(false); + const [addBusy, setAddBusy] = useState(false); + const [addError, setAddError] = useState(null); + const [editOpen, setEditOpen] = useState(false); + const [editBusy, setEditBusy] = useState(false); + const [editError, setEditError] = useState(null); + const [contextItemId, setContextItemId] = useState(null); + + if (query.status === 'loading') { + return ; + } + + if (query.status === 'error') { + return ; + } + + const { channelStates, items, playout, playouts, selectedPlayoutId, totalCount, warningsCount } = query.data; + const { itemsLoading, setShowFiller, showFiller } = query; + const selectedSummary = playouts.find((candidate) => candidate.id === selectedPlayoutId) ?? playouts[0] ?? null; + const channelsWithPlayouts = new Set(playouts.map((candidate) => candidate.channelNumber)); + + const setMutatingState = (value: boolean) => { + mutatingRef.current = value; + setMutating(value); + }; + + const resetAll = () => { + if (mutatingRef.current || !window.confirm('Reset all playouts?')) { + return; + } + + setMutationError(null); + setMutatingState(true); + resetAllPlayouts() + .then(() => { + query.refresh(); + }) + .catch((error: unknown) => { + setMutationError(messageFromError(error)); + }) + .finally(() => { + setMutatingState(false); + }); + }; + + const runMutation = (confirmMessage: string, action: () => Promise) => { + if (mutatingRef.current || !window.confirm(confirmMessage)) { + return; + } + + setMutationError(null); + setMutatingState(true); + action() + .then(() => { + query.refresh(); + }) + .catch((error: unknown) => { + setMutationError(messageFromError(error)); + // A 409 means a build lock is now held for this playout; refresh so the row + // picks up its IsLocked state and the mutation buttons disable themselves. + if (error instanceof ApiError && error.status === 409) { + query.refresh(); + } + }) + .finally(() => { + setMutatingState(false); + }); + }; + + const resetSelectedChannel = () => { + if (!selectedSummary) { + return; + } + // The reset endpoint keys on the immutable channel id. The playout summary only carries the + // channel number, so resolve the id from channel state (which covers every channel). + const channelId = channelStates.find( + (state) => state.channelNumber === selectedSummary.channelNumber + )?.channelId; + if (channelId == null) { + setMutationError('Unable to resolve the channel for this playout.'); + return; + } + runMutation(`Reset the playout for ${selectedSummary.channelName}?`, () => + resetChannelPlayout(channelId) + ); + }; + + const deleteSelectedPlayout = () => { + if (!selectedSummary) { + return; + } + runMutation(`Delete the playout for ${selectedSummary.channelName}? This cannot be undone.`, () => + deletePlayout(selectedSummary.id) + ); + }; + + const eraseSelectedItems = () => { + if (!selectedSummary) { + return; + } + runMutation(`Erase all built items for ${selectedSummary.channelName}?`, () => + erasePlayoutItems(selectedSummary.id) + ); + }; + + const eraseSelectedItemsAndHistory = () => { + if (!selectedSummary) { + return; + } + runMutation(`Erase all built items and history for ${selectedSummary.channelName}?`, () => + erasePlayoutItemsAndHistory(selectedSummary.id) + ); + }; + + const submitAddPlayout = (request: CreatePlayoutRequest) => { + setAddBusy(true); + setAddError(null); + createPlayout(request) + .then((created) => { + setAddOpen(false); + query.setActivePlayout(created.id); + query.refresh(); + }) + .catch((error: unknown) => { + setAddError(messageFromError(error)); + }) + .finally(() => { + setAddBusy(false); + }); + }; + + const submitEditPlayoutDetails = (dailyRebuildTime: string | null, scheduleFile: string | null) => { + if (!selectedSummary) { + return; + } + + setEditBusy(true); + setEditError(null); + updatePlayoutDetails(selectedSummary.id, { dailyRebuildTime, scheduleFile }) + .then(() => { + setEditOpen(false); + query.refresh(); + }) + .catch((error: unknown) => { + setEditError(messageFromError(error)); + }) + .finally(() => { + setEditBusy(false); + }); + }; + + if (!selectedSummary) { + return ( +
+
+ + +
+ + setAddOpen(false)} + onSubmit={submitAddPlayout} + open={addOpen} + /> +
+ ); + } + + const selectedState = channelStates.find((state) => state.channelNumber === selectedSummary.channelNumber); + // The playout's build lock is held (a build is in flight). Server rejects destructive + // mutations with 409 while locked; mirror that by disabling the buttons here. + const selectedLocked = selectedSummary.isLocked; + const nowPlaying = selectedState?.nowPlaying ?? null; + const nowItem = itemMatchingNow(items, nowPlaying?.title) ?? items[0] ?? null; + const nextItem = nextPlayoutItem(items, nowItem); + const filteredPlayouts = filterPlayouts(playouts, filter); + + return ( +
+
+ + + 0 ? 'warn' : 'neutral'} dot={warningsCount > 0}>{warningsCount} warning{warningsCount === 1 ? '' : 's'} + +
+ + {mutationError && ( +
+
+ )} + +
+ + +
+
+ +
+ {selectedSummary.channelNumber} {selectedState?.onAir && On air} {selectedLocked && Building…} +

{selectedSummary.channelName}

+
+
+ +
+
+
+
+ On air now +

{nowPlaying?.title ?? nowItem?.title ?? 'No current item reported'}

+ +
+ {formatDateTime(nowPlaying?.startUtc ?? nowItem?.start)} + {formatDateTime(nowPlaying?.finishUtc ?? nowItem?.finish)} +
+
+
+ +
+ +
+
+
+ { + setEditError(null); + setEditOpen(true); + }} + size="sm" + startIcon={ +
+ + : undefined}> + + + + + {itemsLoading && } + + + } + > +
+ {items.length === 0 ? ( +
{itemsLoading ? : 'No upcoming items'}
+ ) : ( + items.map((item, index) => { + const itemId = item.id; + + return ( +
+ {formatDateTime(item.start)} + {isFillerItem(item) ?
+ ); + }) + )} +
+
+
+
+ + setAddOpen(false)} + onSubmit={submitAddPlayout} + open={addOpen} + /> + {playout && ( + setEditOpen(false)} + onSubmit={submitEditPlayoutDetails} + open={editOpen} + playout={playout} + /> + )} + setContextItemId(null)} + /> +
+ ); +} + +function PlayoutSchedulingContextDialog({ itemId, onClose }: { itemId: number | null; onClose: () => void }) { + const [state, setState] = useState< + | { status: 'loading' } + | { status: 'success'; context: string } + | { status: 'error'; error: string } + >({ status: 'loading' }); + const activeRef = useRef(true); + + useEffect(() => { + activeRef.current = true; + + if (itemId != null) { + getPlayoutItemSchedulingContext(itemId) + .then((result) => { + if (activeRef.current) { + setState({ context: result.context, status: 'success' }); + } + }) + .catch((error: unknown) => { + if (activeRef.current) { + setState({ error: messageFromError(error), status: 'error' }); + } + }); + } + + return () => { + activeRef.current = false; + }; + }, [itemId]); + + return ( + + {state.status === 'loading' && } + {state.status === 'error' && ( +
+
+ )} + {state.status === 'success' && ( +
+          {state.context}
+        
+ )} +
+ ); +} + +function PlayoutDefaultDecoField({ playout, onSaved }: { playout: PlayoutDetail; onSaved: () => void }) { + const [decos, setDecos] = useState(null); + const [saving, setSaving] = useState(false); + const [error, setError] = useState(null); + const activeRef = useRef(true); + + useEffect(() => { + activeRef.current = true; + getDecos() + .then((list) => { + if (activeRef.current) { + setDecos(list.filter((deco) => deco.id > 0)); + } + }) + .catch(() => { + if (activeRef.current) { + setDecos([]); + } + }); + return () => { + activeRef.current = false; + }; + }, []); + + const options = [ + { label: 'None (no default deco)', value: '' }, + ...(decos ?? []) + .slice() + .sort((a, b) => `${a.decoGroupName}${a.name}`.localeCompare(`${b.decoGroupName}${b.name}`)) + .map((deco) => ({ label: `${deco.decoGroupName} / ${deco.name}`, value: String(deco.id) })) + ]; + + return ( +
+