import { cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { App } from './App'; import { Button, Checkbox, Input, ProgressBar, Switch, Tabs, Toast, Tooltip } from './components'; import { applyDesignSystemTheme, designSystemStylesheet, getStoredDesignSystemTheme } from './designSystem'; describe('ChicoryTV SPA scaffold', () => { afterEach(() => { cleanup(); vi.useRealTimers(); window.history.replaceState(null, '', '/'); }); beforeEach(() => { window.localStorage.clear(); document.documentElement.removeAttribute('data-theme'); window.history.replaceState(null, '', '/app'); vi.restoreAllMocks(); mockDashboardApi(); }); it('renders the admin shell chrome and loads the design system stylesheet', async () => { render(); expect(screen.getByRole('img', { name: 'ChicoryTV' })).toBeInTheDocument(); expect(screen.getByRole('navigation', { name: 'Primary' })).toBeInTheDocument(); expect(screen.getByRole('banner')).toBeInTheDocument(); expect(screen.getByRole('searchbox', { name: 'Search' })).toBeInTheDocument(); expect(screen.getByRole('button', { name: 'Connect' })).toBeInTheDocument(); expect(screen.getByRole('button', { name: 'Add Channel' })).toBeInTheDocument(); expect(await screen.findAllByText('Healthy')).toHaveLength(2); expect(designSystemStylesheet).toBe('../../design-system/styles.css'); }); it('routes between shell screen slots without a page reload', async () => { render(); fireEvent.click(screen.getByRole('link', { name: 'Channels' })); expect(screen.getByRole('heading', { name: 'Channels' })).toBeInTheDocument(); expect(await screen.findByText('No channels returned')).toBeInTheDocument(); expect(screen.getByRole('link', { name: 'Channels' })).toHaveAttribute( 'aria-current', 'page' ); expect(window.location.pathname).toBe('/app/channels'); fireEvent.click(screen.getByRole('link', { name: 'Schedules' })); expect(screen.getByRole('heading', { name: 'Schedules' })).toBeInTheDocument(); expect(await screen.findByText('No schedules returned')).toBeInTheDocument(); expect(window.location.pathname).toBe('/app/schedules'); }); it('preserves native browser behavior for modified nav link clicks', () => { render(); fireEvent.click(screen.getByRole('link', { name: 'Channels' }), { ctrlKey: true }); expect(screen.getByRole('heading', { name: 'Dashboard' })).toBeInTheDocument(); expect(window.location.pathname).toBe('/app'); }); it('selects the active screen from the current location', () => { window.history.replaceState(null, '', '/app/guide'); render(); expect(screen.getByRole('heading', { name: 'Guide' })).toBeInTheDocument(); expect(screen.getByRole('heading', { name: 'Loading guide' })).toBeInTheDocument(); expect(screen.getByRole('link', { name: 'Guide' })).toHaveAttribute('aria-current', 'page'); }); it('renders the Guide screen from a bounded JSON guide window', async () => { vi.setSystemTime(new Date('2026-07-05T20:30:00Z')); mockDashboardApi({ channelStates: [ { channelId: 1, channelNumber: '5.1', onAir: true, nowPlaying: { finishUtc: '2026-07-05T21:00:00Z', startUtc: '2026-07-05T20:00:00Z', title: 'Saturday Morning Cartoons - s01e01 - Pilot' } }, { channelId: 2, channelNumber: '24', onAir: false, nowPlaying: null } ], guide: guideFixture() }); const { container } = render(); fireEvent.click(screen.getByRole('link', { name: 'Guide' })); expect(await screen.findByRole('grid', { name: 'Channel guide' })).toBeInTheDocument(); expect(screen.getByText('Retro Cartoons')).toBeInTheDocument(); expect(screen.getByText('News 24')).toBeInTheDocument(); expect(screen.getAllByText('Saturday Morning Cartoons').length).toBeGreaterThan(0); expect(screen.getByText('Pilot')).toBeInTheDocument(); expect(screen.getAllByText('Kids').length).toBeGreaterThan(0); expect(screen.getByText('Early Show')).toBeInTheDocument(); expect(screen.getByText('No programmes in this window')).toBeInTheDocument(); expect(screen.queryByText('Filler')).not.toBeInTheDocument(); expect(container.querySelectorAll('.ctv-epg-programme-live')).toHaveLength(1); const guideCall = fetchCallsStartingWith('/api/guide?')[0]; expect(guideCall).toBeDefined(); const guideUrl = new URL(guideCall, window.location.origin); expect(guideUrl.searchParams.get('start')).toBe('2026-07-05T19:30:00.000Z'); expect(guideUrl.searchParams.get('end')).toBe('2026-07-06T08:30:00.000Z'); expect(window.fetch).toHaveBeenCalledWith('/api/channels/state', expect.any(Object)); }); it('renders the Guide screen when an on-air channel omits nowPlaying', async () => { mockDashboardApi({ channelStates: [ { channelId: 1, channelNumber: '5.1', onAir: true } ], guide: guideFixture() }); render(); fireEvent.click(screen.getByRole('link', { name: 'Guide' })); expect(await screen.findByRole('grid', { name: 'Channel guide' })).toBeInTheDocument(); expect(screen.getByText('Retro Cartoons')).toBeInTheDocument(); }); it('moves the Guide now marker on timer ticks without polling the guide endpoint', async () => { const intervalHandlers: Array<() => void> = []; vi.setSystemTime(new Date('2026-07-05T20:30:00Z')); 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({ guide: guideFixture() }); const { container } = render(); fireEvent.click(screen.getByRole('link', { name: 'Guide' })); expect(await screen.findByRole('grid', { name: 'Channel guide' })).toBeInTheDocument(); const guideFetchesBeforeTick = fetchCallsStartingWith('/api/guide?').length; const marker = container.querySelector('.ctv-epg-now-marker') as HTMLElement; expect(marker.style.left).toBe('508px'); vi.setSystemTime(new Date('2026-07-05T21:00:00Z')); intervalHandlers.forEach((handler) => handler()); await waitFor(() => { expect(marker.style.left).toBe('664px'); }); expect(fetchCallsStartingWith('/api/guide?')).toHaveLength(guideFetchesBeforeTick); }); it('fetches one Guide window per explicit navigation and jumps back to now', async () => { vi.setSystemTime(new Date('2026-07-05T20:30:00Z')); mockDashboardApi({ guide: guideFixture() }); render(); fireEvent.click(screen.getByRole('link', { name: 'Guide' })); expect(await screen.findByRole('grid', { name: 'Channel guide' })).toBeInTheDocument(); expect(fetchCallsStartingWith('/api/guide?')).toHaveLength(1); fireEvent.click(screen.getByRole('button', { name: 'Next guide window' })); await waitFor(() => { expect(fetchCallsStartingWith('/api/guide?')).toHaveLength(2); }); const nextUrl = new URL(fetchCallsStartingWith('/api/guide?')[1], window.location.origin); expect(nextUrl.searchParams.get('start')).toBe('2026-07-06T08:30:00.000Z'); expect(nextUrl.searchParams.get('end')).toBe('2026-07-06T21:30:00.000Z'); fireEvent.click(screen.getByRole('button', { name: 'Jump to now' })); await waitFor(() => { expect(fetchCallsStartingWith('/api/guide?')).toHaveLength(3); }); const nowUrl = new URL(fetchCallsStartingWith('/api/guide?')[2], window.location.origin); expect(nowUrl.searchParams.get('start')).toBe('2026-07-05T19:30:00.000Z'); expect(nowUrl.searchParams.get('end')).toBe('2026-07-06T08:30:00.000Z'); }); it('shows Guide API errors and retries', async () => { mockDashboardApi({ guide: guideFixture(), guideFailuresBeforeSuccess: 1 }); render(); fireEvent.click(screen.getByRole('link', { name: 'Guide' })); expect(await screen.findByText('Request failed with status 500')).toBeInTheDocument(); fireEvent.click(screen.getByRole('button', { name: 'Retry' })); expect(await screen.findByRole('grid', { name: 'Channel guide' })).toBeInTheDocument(); }); it('shows a not-found screen for unknown app routes', () => { window.history.replaceState(null, '', '/app/channels/42'); render(); expect(screen.getByRole('heading', { name: 'Page not found' })).toBeInTheDocument(); expect(screen.getByText('/app/channels/42')).toBeInTheDocument(); expect(screen.getByRole('link', { name: 'Dashboard' })).not.toHaveAttribute( 'aria-current', 'page' ); }); it('opens the Connect menu with absolute player endpoints and live channel count', async () => { mockDashboardApi({ channels: [ { id: 1, name: 'Retro Cartoons', number: '5.1' }, { id: 2, name: 'News 24', number: '24' } ] }); render(); fireEvent.click(screen.getByRole('button', { name: 'Connect' })); expect(screen.getByRole('dialog', { name: 'Connect a player' })).toBeInTheDocument(); expect(screen.getByText('M3U playlist')).toBeInTheDocument(); expect(screen.getByText('XMLTV guide')).toBeInTheDocument(); expect(screen.getByText(`${window.location.origin}/iptv/channels.m3u`)).toBeInTheDocument(); expect(screen.getByText(`${window.location.origin}/iptv/xmltv.xml`)).toBeInTheDocument(); expect(await screen.findByText('2 channels')).toBeInTheDocument(); expect(screen.queryByRole('checkbox', { name: 'Only enabled channels' })).not.toBeInTheDocument(); }); it('focuses the Connect menu and closes it with Escape', () => { render(); fireEvent.click(screen.getByRole('button', { name: 'Connect' })); const dialog = screen.getByRole('dialog', { name: 'Connect a player' }); expect(dialog).toHaveFocus(); fireEvent.keyDown(dialog, { key: 'Escape' }); expect(screen.queryByRole('dialog', { name: 'Connect a player' })).not.toBeInTheDocument(); }); it('applies the warm design-system default by removing the theme attribute', () => { document.documentElement.dataset.theme = 'cool'; applyDesignSystemTheme('warm'); expect(document.documentElement).not.toHaveAttribute('data-theme'); expect(window.localStorage.getItem('ctv-theme')).toBe('warm'); }); it('applies and persists alternate design-system themes', () => { applyDesignSystemTheme('cool'); expect(document.documentElement).toHaveAttribute('data-theme', 'cool'); expect(window.localStorage.getItem('ctv-theme')).toBe('cool'); }); it('ignores invalid persisted themes', () => { window.localStorage.setItem('ctv-theme', 'unknown'); expect(getStoredDesignSystemTheme()).toBe('warm'); }); it('switches themes from the shell controls', () => { render(); fireEvent.click(screen.getByRole('button', { name: 'Dual accent theme' })); expect(document.documentElement).toHaveAttribute('data-theme', 'dual'); expect(window.localStorage.getItem('ctv-theme')).toBe('dual'); expect(screen.getByRole('button', { name: 'Dual accent theme' })).toHaveAttribute( 'aria-pressed', 'true' ); }); it('renders routed placeholder cards for the downstream screen work', async () => { render(); expect(await screen.findByText('On air now')).toBeInTheDocument(); expect(screen.getByText('System health')).toBeInTheDocument(); expect(screen.queryByText('Recent activity')).not.toBeInTheDocument(); expect(screen.queryByText('Release notes')).not.toBeInTheDocument(); }); it('renders dashboard cards and stats from live API responses', async () => { mockDashboardApi({ channels: [ { fFmpegProfile: 'HLS Direct', id: 1, language: 'en', name: 'Retro Cartoons', number: '5.1', streamingMode: 'HLS Direct' }, { fFmpegProfile: 'MPEG-TS', id: 2, language: 'fr', name: 'News 24', number: '24', streamingMode: 'MPEG-TS' } ], channelStates: [ { channelId: 1, channelNumber: '5.1', onAir: true, nowPlaying: { finishUtc: '2026-07-04T21:30:00Z', startUtc: '2026-07-04T21:00:00Z', title: 'Saturday Morning Cartoons' } }, { channelId: 2, channelNumber: '24', onAir: false, nowPlaying: null } ], health: [ { detail: 'SQLite is reachable', link: null, status: 'pass', title: 'Database' }, { detail: 'FFmpeg path is missing', link: null, status: 'warn', title: 'FFmpeg' } ], mediaSources: [ { connectionAddress: null, id: 30, kind: 'Local', libraries: [ { id: 31, kind: 'Movies', name: 'Movies' }, { id: 32, kind: 'Shows', name: 'Shows' } ], name: 'Local' } ], playouts: { page: [ { buildStatus: { lastBuild: '2026-07-04T20:00:00Z', message: null, success: true }, channelName: 'Retro Cartoons', channelNumber: '5.1', dailyRebuildTime: null, id: 20, scheduleKind: 'Classic', scheduleName: 'Default Schedule' } ], totalCount: 1 }, version: { apiVersion: 3, appVersion: '26.4.0-test' } }); render(); expect(await screen.findByRole('heading', { name: 'On air now' })).toBeInTheDocument(); expect(await screen.findByText('Retro Cartoons')).toBeInTheDocument(); expect(screen.getByText('5.1')).toBeInTheDocument(); expect(screen.queryByText('News 24')).not.toBeInTheDocument(); expect(screen.getAllByText('Saturday Morning Cartoons').length).toBeGreaterThan(0); expect(screen.getByText('1 on air')).toBeInTheDocument(); expect(screen.getAllByText('1 warning')).toHaveLength(2); expect(screen.getAllByText('2')).toHaveLength(2); expect(screen.getByText('26.4.0-test')).toBeInTheDocument(); expect(window.fetch).toHaveBeenCalledWith('/api/channels', expect.any(Object)); expect(window.fetch).toHaveBeenCalledWith('/api/channels/state', expect.any(Object)); expect(window.fetch).toHaveBeenCalledWith('/api/media-sources', expect.any(Object)); expect(window.fetch).toHaveBeenCalledWith('/api/playouts', expect.any(Object)); expect(window.fetch).toHaveBeenCalledWith('/api/health', expect.any(Object)); expect(window.fetch).toHaveBeenCalledWith('/api/version', expect.any(Object)); expect(window.fetch).not.toHaveBeenCalledWith('/api/sessions', expect.any(Object)); expect(window.fetch).not.toHaveBeenCalledWith('/api/schedules', expect.any(Object)); }); it('renders the Channels screen from live channel and state APIs', async () => { mockDashboardApi({ channels: [ { fFmpegProfile: 'HLS Direct', group: 'Kids', id: 1, isEnabled: true, language: 'en', name: 'Retro Cartoons', number: '5.1', showInEpg: true, sortNumber: 5.1, streamingMode: 'HLS Direct' }, { fFmpegProfile: 'MPEG-TS', group: 'News', id: 2, isEnabled: false, language: 'fr', name: 'News 24', number: '24', showInEpg: false, sortNumber: 24, streamingMode: 'MPEG-TS' } ], channelStates: [ { channelId: 1, channelNumber: '5.1', onAir: true, nowPlaying: { finishUtc: '2026-07-04T21:30:00Z', startUtc: '2026-07-04T21:00:00Z', title: 'Saturday Morning Cartoons' } }, { channelId: 2, channelNumber: '24', onAir: false, nowPlaying: null } ] }); render(); fireEvent.click(screen.getByRole('link', { name: 'Channels' })); expect(await screen.findByRole('heading', { name: 'Channels' })).toBeInTheDocument(); expect(await screen.findByRole('table', { name: 'Channels lineup' })).toBeInTheDocument(); expect(screen.getByText('Retro Cartoons')).toBeInTheDocument(); expect(screen.getAllByText('Saturday Morning Cartoons').length).toBeGreaterThan(0); expect(screen.getByText('News 24')).toBeInTheDocument(); expect(screen.getByText('Off air')).toBeInTheDocument(); expect(screen.getByTitle('Disabled')).toHaveTextContent('D'); expect(screen.getByTitle('Hidden from EPG')).toHaveTextContent('H'); expect(screen.getByRole('button', { name: 'On air 1' })).toBeInTheDocument(); expect(screen.getByText('2 of 2 channels')).toBeInTheDocument(); expect(window.fetch).toHaveBeenCalledWith('/api/channels/state', expect.any(Object)); }); it('polls only channel state after the Channels screen initial load', async () => { const intervalHandlers: Array<() => void> = []; vi.spyOn(window, 'setInterval').mockImplementation((handler) => { if (typeof handler === 'function') { intervalHandlers.push(handler as () => void); } return 1; }); vi.spyOn(window, 'clearInterval').mockImplementation(() => undefined); mockDashboardApi({ channels: [ { fFmpegProfile: 'HLS Direct', group: 'Kids', id: 1, isEnabled: true, language: 'en', name: 'Retro Cartoons', number: '5.1', showInEpg: true, sortNumber: 5.1, streamingMode: 'HLS Segmenter' } ], channelStates: [{ channelId: 1, channelNumber: '5.1', onAir: true, nowPlaying: null }] }); render(); fireEvent.click(screen.getByRole('link', { name: 'Channels' })); expect(await screen.findByText('Retro Cartoons')).toBeInTheDocument(); const channelFetchesBeforePoll = fetchCount('/api/channels'); const stateFetchesBeforePoll = fetchCount('/api/channels/state'); intervalHandlers.forEach((handler) => handler()); await waitFor(() => { expect(fetchCount('/api/channels/state')).toBeGreaterThan(stateFetchesBeforePoll); }); expect(fetchCount('/api/channels')).toBe(channelFetchesBeforePoll); }); it('keeps preview disabled because the list DTO lacks legacy preview support data', async () => { mockDashboardApi({ channels: [ { fFmpegProfile: 'HLS Direct', group: 'Kids', id: 1, isEnabled: true, language: 'en', name: 'Retro Cartoons', number: '5.1', showInEpg: true, sortNumber: 5.1, streamingMode: 'HLS Segmenter' } ], channelStates: [{ channelId: 1, channelNumber: '5.1', onAir: true, nowPlaying: null }] }); render(); fireEvent.click(screen.getByRole('link', { name: 'Channels' })); expect(await screen.findByText('Retro Cartoons')).toBeInTheDocument(); expect(screen.getByRole('button', { name: 'Preview unavailable for Retro Cartoons' })).toBeDisabled(); }); it('filters the Channels screen by on-air and disabled rows', async () => { mockDashboardApi({ channels: [ { fFmpegProfile: 'HLS Direct', group: 'Kids', id: 1, isEnabled: true, language: 'en', name: 'Retro Cartoons', number: '5.1', showInEpg: true, sortNumber: 5.1, streamingMode: 'HLS Direct' }, { fFmpegProfile: 'MPEG-TS', group: 'News', id: 2, isEnabled: false, language: 'fr', name: 'News 24', number: '24', showInEpg: false, sortNumber: 24, streamingMode: 'MPEG-TS' } ], channelStates: [ { channelId: 1, channelNumber: '5.1', onAir: true, nowPlaying: null }, { channelId: 2, channelNumber: '24', onAir: false, nowPlaying: null } ] }); render(); fireEvent.click(screen.getByRole('link', { name: 'Channels' })); expect(await screen.findByText('Retro Cartoons')).toBeInTheDocument(); fireEvent.click(screen.getByRole('button', { name: 'On air 1' })); expect(screen.getByText('Retro Cartoons')).toBeInTheDocument(); expect(screen.queryByText('News 24')).not.toBeInTheDocument(); fireEvent.click(screen.getByRole('button', { name: 'Disabled 1' })); expect(screen.queryByText('Retro Cartoons')).not.toBeInTheDocument(); expect(screen.getByText('News 24')).toBeInTheDocument(); }); it('runs channel row delete and refetches the Channels screen', async () => { mockDashboardApi({ channels: [ { fFmpegProfile: 'HLS Direct', group: 'Kids', id: 1, isEnabled: true, language: 'en', name: 'Retro Cartoons', number: '5.1', showInEpg: true, sortNumber: 5.1, streamingMode: 'HLS Direct' } ], confirm: true }); render(); fireEvent.click(screen.getByRole('link', { name: 'Channels' })); expect(await screen.findByText('Retro Cartoons')).toBeInTheDocument(); fireEvent.click(screen.getByRole('button', { name: 'Delete Retro Cartoons' })); await screen.findByText('Retro Cartoons'); expect(window.fetch).toHaveBeenCalledWith('/api/channels/1', expect.objectContaining({ method: 'DELETE' })); expect(fetchCount('/api/channels')).toBeGreaterThan(2); }); it('runs bulk move and delete actions with ProblemDetails error display', async () => { mockDashboardApi({ channels: [ { fFmpegProfile: 'HLS Direct', group: 'Kids', id: 1, isEnabled: true, language: 'en', name: 'Retro Cartoons', number: '5.1', showInEpg: true, sortNumber: 5.1, streamingMode: 'HLS Direct' } ], confirm: true, mutationFailures: { '/api/channels/bulk/delete': { detail: 'Channel 1 cannot be deleted while active', status: 422, title: 'Validation failed' } }, prompt: 'Movies' }); render(); fireEvent.click(screen.getByRole('link', { name: 'Channels' })); expect(await screen.findByText('Retro Cartoons')).toBeInTheDocument(); fireEvent.click(screen.getByRole('checkbox', { name: 'Select Retro Cartoons' })); fireEvent.click(screen.getByRole('button', { name: 'Move to group' })); expect(window.fetch).toHaveBeenCalledWith('/api/channels/bulk/group', expect.objectContaining({ body: JSON.stringify({ channelIds: [1], group: 'Movies' }), method: 'POST' })); expect(await screen.findByRole('checkbox', { name: 'Select Retro Cartoons' })).toHaveAttribute( 'aria-checked', 'false' ); fireEvent.click(screen.getByRole('checkbox', { name: 'Select Retro Cartoons' })); fireEvent.click(screen.getByRole('button', { name: 'Delete selected' })); expect(await screen.findByText('Channel 1 cannot be deleted while active')).toBeInTheDocument(); }); it('runs bulk renumber and clears the selection afterward', async () => { mockDashboardApi({ channels: [ { fFmpegProfile: 'HLS Direct', group: 'Kids', id: 1, isEnabled: true, language: 'en', name: 'Retro Cartoons', number: '5.1', showInEpg: true, sortNumber: 5.1, streamingMode: 'HLS Direct' }, { fFmpegProfile: 'MPEG-TS', group: 'News', id: 2, isEnabled: false, language: 'fr', name: 'News 24', number: '24', showInEpg: false, sortNumber: 24, streamingMode: 'MPEG-TS' } ], prompt: '10' }); render(); fireEvent.click(screen.getByRole('link', { name: 'Channels' })); expect(await screen.findByText('Retro Cartoons')).toBeInTheDocument(); fireEvent.click(screen.getByRole('checkbox', { name: 'Select Retro Cartoons' })); fireEvent.click(screen.getByRole('checkbox', { name: 'Select News 24' })); fireEvent.click(screen.getByRole('button', { name: 'Renumber' })); expect(window.fetch).toHaveBeenCalledWith('/api/channels/bulk/renumber', expect.objectContaining({ body: JSON.stringify({ channels: [{ id: 1, number: '10' }, { id: 2, number: '11' }] }), method: 'POST' })); expect(await screen.findByRole('checkbox', { name: 'Select Retro Cartoons' })).toHaveAttribute( 'aria-checked', 'false' ); expect(screen.getByRole('checkbox', { name: 'Select News 24' })).toHaveAttribute( 'aria-checked', 'false' ); }); it('clears the selection when the channel view filter changes', async () => { mockDashboardApi({ channels: [ { fFmpegProfile: 'HLS Direct', group: 'Kids', id: 1, isEnabled: true, language: 'en', name: 'Retro Cartoons', number: '5.1', showInEpg: true, sortNumber: 5.1, streamingMode: 'HLS Direct' }, { fFmpegProfile: 'MPEG-TS', group: 'News', id: 2, isEnabled: true, language: 'fr', name: 'News 24', number: '24', showInEpg: true, sortNumber: 24, streamingMode: 'MPEG-TS' } ], channelStates: [ { channelId: 1, channelNumber: '5.1', onAir: true, nowPlaying: null }, { channelId: 2, channelNumber: '24', onAir: false, nowPlaying: null } ] }); render(); fireEvent.click(screen.getByRole('link', { name: 'Channels' })); expect(await screen.findByText('Retro Cartoons')).toBeInTheDocument(); fireEvent.click(screen.getByRole('checkbox', { name: 'Select Retro Cartoons' })); fireEvent.click(screen.getByRole('checkbox', { name: 'Select News 24' })); expect(screen.getByRole('button', { name: 'Delete selected' })).toBeInTheDocument(); fireEvent.click(screen.getByRole('button', { name: 'Clear' })); expect(screen.getByRole('button', { name: 'On air 1' })).toBeInTheDocument(); fireEvent.click(screen.getByRole('button', { name: 'On air 1' })); expect(screen.queryByText('News 24')).not.toBeInTheDocument(); fireEvent.click(screen.getByRole('checkbox', { name: 'Select Retro Cartoons' })); fireEvent.click(screen.getByRole('button', { name: 'Clear' })); expect(screen.queryByRole('button', { name: 'Delete selected' })).not.toBeInTheDocument(); expect(screen.getByRole('button', { name: 'All 2' })).toBeInTheDocument(); }); it('renders the Schedule editor from live schedule APIs', async () => { mockDashboardApi({ scheduleItems: [ scheduleItem({ durationEstimate: '01:30:00', id: 11, name: 'Saturday Cartoons' }), scheduleItem({ collection: { id: 6, name: 'Station IDs' }, collectionType: 'Collection', durationEstimate: null, guideMode: 'Filler', id: 12, name: 'Station IDs', playoutMode: 'Flood' }) ], schedules: [schedule({ id: 5, name: 'Prime Time Cartoons' })], scheduleItemsTotalDuration: '01:30:00' }); render(); fireEvent.click(screen.getByRole('link', { name: 'Schedules' })); expect(await screen.findByRole('heading', { name: 'Prime Time Cartoons' })).toBeInTheDocument(); expect(screen.getByRole('list', { name: 'Schedule lineup' })).toBeInTheDocument(); expect(screen.getAllByText('Saturday Cartoons').length).toBeGreaterThan(0); expect(screen.getAllByText('01:30:00').length).toBeGreaterThan(0); expect(screen.getAllByText('Station IDs').length).toBeGreaterThan(0); expect(screen.getByText('unknown')).toBeInTheDocument(); expect(screen.getByRole('tab', { name: 'Content' })).toHaveAttribute('aria-selected', 'true'); expect(screen.getAllByDisplayValue('Prime Time Cartoons').length).toBeGreaterThan(0); expect(window.fetch).toHaveBeenCalledWith('/api/schedules', expect.any(Object)); expect(window.fetch).toHaveBeenCalledWith('/api/schedules/5/items', expect.any(Object)); expect(window.fetch).toHaveBeenCalledWith('/api/collections', expect.any(Object)); expect(window.fetch).not.toHaveBeenCalledWith('/api/languages', expect.any(Object)); }); it('fetches the schedules screen data exactly once on mount', async () => { mockDashboardApi({ schedules: [schedule({ id: 5, name: 'Prime Time Cartoons' })] }); render(); fireEvent.click(screen.getByRole('link', { name: 'Schedules' })); expect(await screen.findByRole('heading', { name: 'Prime Time Cartoons' })).toBeInTheDocument(); expect(fetchCount('/api/schedules')).toBe(1); }); it('shows the Schedule editor error state when a picker endpoint fails', async () => { vi.spyOn(window, 'fetch').mockImplementation((input: RequestInfo | URL) => { const path = input.toString(); if (path === '/api/schedules') { return Promise.resolve(jsonResponse([schedule({ id: 5, name: 'Prime Time Cartoons' })])); } if (path === '/api/schedules/5/items') { return Promise.resolve(jsonResponse({ items: [], totalDurationEstimate: null })); } if (path === '/api/collections') { return Promise.resolve(jsonResponse({ detail: 'Collections service is unavailable', status: 500, title: 'Internal error' }, 500)); } return Promise.resolve(jsonResponse([])); }); render(); fireEvent.click(screen.getByRole('link', { name: 'Schedules' })); expect(await screen.findByText('Collections service is unavailable')).toBeInTheDocument(); expect(screen.getByRole('button', { name: 'Retry' })).toBeInTheDocument(); }); it('shows the Schedule editor loading state', async () => { vi.spyOn(window, 'fetch').mockImplementation((input: RequestInfo | URL) => { const path = input.toString(); if (path === '/api/schedules') { return new Promise(() => {}); } return Promise.resolve(jsonResponse([])); }); render(); fireEvent.click(screen.getByRole('link', { name: 'Schedules' })); expect(await screen.findByText('Loading schedules')).toBeInTheDocument(); }); it('shows Schedule editor API errors and retries 404 parent handling', async () => { mockDashboardApi({ scheduleItemFailuresBeforeSuccess: 1, scheduleItemFailure: { detail: 'Schedule 5 was not found', status: 404, title: 'Not found' }, schedules: [schedule({ id: 5, name: 'Missing Schedule' })] }); render(); fireEvent.click(screen.getByRole('link', { name: 'Schedules' })); expect(await screen.findByText('Schedule 5 was not found')).toBeInTheDocument(); fireEvent.click(screen.getByRole('button', { name: 'Retry' })); expect(await screen.findByText('No schedule items')).toBeInTheDocument(); expect(fetchCount('/api/schedules/5/items')).toBe(2); }); it('shows an empty Schedule editor state when no schedule exists', async () => { mockDashboardApi({ schedules: [] }); render(); fireEvent.click(screen.getByRole('link', { name: 'Schedules' })); expect(await screen.findByText('No schedules returned')).toBeInTheDocument(); }); it('shows an empty Schedule editor lineup for a schedule with no items', async () => { mockDashboardApi({ schedules: [schedule({ id: 5, name: 'Empty Schedule' })] }); render(); fireEvent.click(screen.getByRole('link', { name: 'Schedules' })); expect(await screen.findByText('No schedule items')).toBeInTheDocument(); expect(screen.getByRole('button', { name: 'Add item' })).toBeInTheDocument(); }); it('reorders schedule items with keyboard controls and sends the exact replace-all body', async () => { const first = scheduleItem({ id: 11, name: 'Saturday Cartoons' }); const second = scheduleItem({ collection: { id: 6, name: 'Station IDs' }, durationEstimate: null, guideMode: 'Filler', id: 12, name: 'Station IDs', playoutMode: 'Flood' }); mockDashboardApi({ replaceScheduleItemsResponse: [second, first], scheduleItems: [first, second], schedules: [schedule({ id: 5, name: 'Prime Time Cartoons' })] }); render(); fireEvent.click(screen.getByRole('link', { name: 'Schedules' })); expect(await screen.findAllByText('Saturday Cartoons')).not.toHaveLength(0); const collectionsFetchesBeforeReorder = fetchCount('/api/collections'); fireEvent.click(screen.getByRole('button', { name: 'Move Station IDs up' })); await waitFor(() => { expect(window.fetch).toHaveBeenCalledWith('/api/schedules/5/items', expect.objectContaining({ body: JSON.stringify({ items: [scheduleItemRequest(second), scheduleItemRequest(first)] }), method: 'PUT' })); }); const lineup = screen.getByRole('list', { name: 'Schedule lineup' }); const rows = within(lineup).getAllByRole('listitem'); expect(rows[0]).toHaveTextContent('Station IDs'); expect(rows[1]).toHaveTextContent('Saturday Cartoons'); expect(fetchCount('/api/collections')).toBe(collectionsFetchesBeforeReorder); }); it('rolls back schedule reorder and shows ProblemDetails on replace failure', async () => { mockDashboardApi({ mutationFailures: { '/api/schedules/5/items': { detail: 'Schedule items are locked', status: 422, title: 'Validation failed' } }, scheduleItems: [ scheduleItem({ id: 11, name: 'Saturday Cartoons' }), scheduleItem({ collection: { id: 6, name: 'Station IDs' }, id: 12, name: 'Station IDs' }) ], schedules: [schedule({ id: 5, name: 'Prime Time Cartoons' })] }); render(); fireEvent.click(screen.getByRole('link', { name: 'Schedules' })); expect(await screen.findAllByText('Saturday Cartoons')).not.toHaveLength(0); fireEvent.click(screen.getByRole('button', { name: 'Move Station IDs up' })); expect(await screen.findByText('Schedule items are locked')).toBeInTheDocument(); const lineup = screen.getByRole('list', { name: 'Schedule lineup' }); expect(within(lineup).getAllByRole('listitem')[0]).toHaveTextContent('Saturday Cartoons'); }); it('adds schedule items using the selected (non-first) collection', async () => { const added = scheduleItem({ collection: { id: 4, name: 'Nature Docs' }, id: 20, name: 'Nature Docs' }); mockDashboardApi({ addScheduleItemResponse: added, collections: [ collection({ id: 3, name: 'Movie Mix' }), collection({ id: 4, name: 'Nature Docs' }) ], scheduleItems: [], scheduleItemsAfterAdd: [added], schedules: [schedule({ id: 5, name: 'Prime Time Cartoons' })] }); render(); fireEvent.click(screen.getByRole('link', { name: 'Schedules' })); expect(await screen.findByText('No schedule items')).toBeInTheDocument(); const collectionsFetchesBeforeAdd = fetchCount('/api/collections'); fireEvent.change(screen.getByRole('combobox', { name: 'Collection for new item' }), { target: { value: '4' } }); fireEvent.click(screen.getByRole('button', { name: 'Add item' })); expect(await screen.findAllByText('Nature Docs')).not.toHaveLength(0); const expectedBody = scheduleItemRequest(added); expect(expectedBody.collectionId).toBe(4); expect(expectedBody.collectionType).toBe('Collection'); expect(window.fetch).toHaveBeenCalledWith('/api/schedules/5/items', expect.objectContaining({ body: JSON.stringify(expectedBody), method: 'POST' })); expect(fetchCount('/api/schedules/5/items')).toBeGreaterThan(2); expect(fetchCount('/api/collections')).toBe(collectionsFetchesBeforeAdd); }); it('shows ProblemDetails when adding a schedule item fails', async () => { mockDashboardApi({ collections: [collection({ id: 3, name: 'Movie Mix' })], mutationFailures: { '/api/schedules/5/items': { detail: 'Collection is required', status: 422, title: 'Validation failed' } }, scheduleItems: [], schedules: [schedule({ id: 5, name: 'Prime Time Cartoons' })] }); render(); fireEvent.click(screen.getByRole('link', { name: 'Schedules' })); expect(await screen.findByText('No schedule items')).toBeInTheDocument(); fireEvent.click(screen.getByRole('button', { name: 'Add item' })); expect(await screen.findByText('Collection is required')).toBeInTheDocument(); }); it('deletes schedule items and refetches after success', async () => { mockDashboardApi({ confirm: true, scheduleItems: [scheduleItem({ id: 11, name: 'Saturday Cartoons' })], scheduleItemsAfterDelete: [], schedules: [schedule({ id: 5, name: 'Prime Time Cartoons' })] }); render(); fireEvent.click(screen.getByRole('link', { name: 'Schedules' })); expect(await screen.findAllByText('Saturday Cartoons')).not.toHaveLength(0); fireEvent.click(screen.getByRole('button', { name: 'Remove Saturday Cartoons' })); expect(await screen.findByText('No schedule items')).toBeInTheDocument(); expect(window.fetch).toHaveBeenCalledWith('/api/schedules/5/items/11', expect.objectContaining({ method: 'DELETE' })); }); it('shows ProblemDetails when deleting a schedule item fails', async () => { mockDashboardApi({ confirm: true, mutationFailures: { '/api/schedules/5/items/11': { detail: 'Item is in use by an active playout', status: 422, title: 'Validation failed' } }, scheduleItems: [scheduleItem({ id: 11, name: 'Saturday Cartoons' })], schedules: [schedule({ id: 5, name: 'Prime Time Cartoons' })] }); render(); fireEvent.click(screen.getByRole('link', { name: 'Schedules' })); expect(await screen.findAllByText('Saturday Cartoons')).not.toHaveLength(0); fireEvent.click(screen.getByRole('button', { name: 'Remove Saturday Cartoons' })); expect(await screen.findByText('Item is in use by an active playout')).toBeInTheDocument(); }); it('renders the Playouts monitor from live playout and channel state APIs', 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 } }); render(); 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/playouts', expect.any(Object)); expect(window.fetch).toHaveBeenCalledWith('/api/playouts/20', expect.any(Object)); expect(window.fetch).toHaveBeenCalledWith('/api/playouts/20/items', expect.any(Object)); expect(window.fetch).toHaveBeenCalledWith('/api/playouts/warnings/count', expect.any(Object)); expect(window.fetch).toHaveBeenCalledWith('/api/channels/state', expect.any(Object)); }); it('renders the Libraries screen from live media source and scan status APIs', async () => { mockDashboardApi({ libraryScanStatuses: [{ libraryId: 31, percent: 0.625 }], mediaSources: [ mediaSource({ connectionAddress: null, id: 30, kind: 'Local', libraries: [ library({ id: 31, itemCount: 1250, lastScan: '2026-07-05T14:30:00Z', mediaKind: 'Movies', name: 'Movies' }), library({ id: 32, itemCount: 14, lastScan: null, mediaKind: 'OtherVideos', name: 'Station IDs' }) ], name: 'Local' }), mediaSource({ connectionAddress: 'https://plex.example.test', id: 40, kind: 'Plex', libraries: [ library({ id: 41, itemCount: 80, lastScan: '2026-07-04T08:00:00Z', mediaKind: 'Shows', name: 'TV Shows' }) ], name: 'Plex Server' }), mediaSource({ connectionAddress: 'https://jellyfin.example.test', id: 50, kind: 'Jellyfin', libraries: [], name: 'Jellyfin Home' }), mediaSource({ connectionAddress: 'https://emby.example.test', id: 60, kind: 'Emby', libraries: [ library({ id: 61, itemCount: 22, lastScan: '2026-07-01T00:00:00Z', mediaKind: 'MusicVideos', name: 'Music Videos' }) ], name: 'Emby Archive' }) ] }); render(); fireEvent.click(screen.getByRole('link', { name: 'Libraries' })); expect(await screen.findByRole('heading', { name: 'Media Libraries' })).toBeInTheDocument(); expect(screen.getByText('4 sources')).toBeInTheDocument(); expect(screen.getByText('1,366 items')).toBeInTheDocument(); expect(screen.getByRole('region', { name: 'Local media source' })).toBeInTheDocument(); expect(screen.getByText('Local connection')).toBeInTheDocument(); expect(screen.getByRole('region', { name: 'Plex Server media source' })).toBeInTheDocument(); expect(screen.getByText('https://plex.example.test')).toBeInTheDocument(); expect(screen.getAllByText('Movies').length).toBeGreaterThan(0); expect(screen.getByText('Station IDs')).toBeInTheDocument(); expect(screen.getByText('TV Shows')).toBeInTheDocument(); expect(screen.getAllByText('Music Videos').length).toBeGreaterThan(0); expect(screen.getByText('Other Videos')).toBeInTheDocument(); expect(screen.getAllByText('Music Videos').length).toBeGreaterThan(0); // "Scanning" now appears twice: once as the source-header status label (paired with // the StatusDot, not color alone) and once as the per-library scanning Badge. expect(screen.getAllByText('Scanning').length).toBeGreaterThan(0); // Wire contract: percent is a 0-1 fraction (0.625) - the UI must render it as 63%, not 0.625%. expect(screen.getByText('63%')).toBeInTheDocument(); expect(screen.getAllByText('Synced').length).toBeGreaterThan(0); expect(screen.getAllByText('Never scanned').length).toBeGreaterThan(0); expect(screen.getByRole('button', { name: 'Add Source' })).toBeDisabled(); expect(screen.getByText('Adding sources is deferred to the existing server setup screens.')).toBeInTheDocument(); expect(window.fetch).toHaveBeenCalledWith('/api/media-sources', expect.any(Object)); expect(window.fetch).toHaveBeenCalledWith('/api/libraries/scan-status', expect.any(Object)); }); it('converts 0 and 1 fractional scan-status percents to 0% and 100%', async () => { mockDashboardApi({ libraryScanStatuses: [ { libraryId: 31, percent: 0 }, { libraryId: 32, percent: 1 } ], mediaSources: [ mediaSource({ libraries: [ library({ id: 31, itemCount: 10, mediaKind: 'Movies', name: 'Movies' }), library({ id: 32, itemCount: 5, mediaKind: 'Shows', name: 'TV Shows' }) ] }) ] }); render(); fireEvent.click(screen.getByRole('link', { name: 'Libraries' })); expect(await screen.findByText('0%')).toBeInTheDocument(); expect(screen.getByText('100%')).toBeInTheDocument(); }); it('fetches Libraries data as a route delta and does not poll sources', async () => { const intervalHandlers: Array<() => void> = []; vi.spyOn(window, 'setInterval').mockImplementation((handler: TimerHandler, timeout?: number) => { if (typeof handler === 'function' && (timeout ?? 0) >= 10000) { intervalHandlers.push(handler as () => void); } return intervalHandlers.length; }); vi.spyOn(window, 'clearInterval').mockImplementation(() => undefined); mockDashboardApi({ libraryScanStatuses: [{ libraryId: 31, percent: 0.1 }], mediaSources: [ mediaSource({ libraries: [library({ id: 31, itemCount: 10, mediaKind: 'Movies', name: 'Movies' })] }) ] }); render(); await waitFor(() => { expect(fetchCount('/api/media-sources')).toBeGreaterThan(0); }); const sourceFetchesBeforeNavigation = fetchCount('/api/media-sources'); fireEvent.click(screen.getByRole('link', { name: 'Libraries' })); expect(await screen.findByRole('heading', { name: 'Media Libraries' })).toBeInTheDocument(); expect(fetchCount('/api/media-sources')).toBe(sourceFetchesBeforeNavigation + 1); expect(fetchCount('/api/libraries/scan-status')).toBe(1); const sourceFetchesBeforePoll = fetchCount('/api/media-sources'); intervalHandlers.forEach((handler) => handler()); await waitFor(() => { expect(fetchCount('/api/libraries/scan-status')).toBeGreaterThan(1); }); expect(fetchCount('/api/media-sources')).toBe(sourceFetchesBeforePoll); }); it('stops Libraries scan polling and refreshes sources once when scans complete', async () => { const intervalHandlers: Array<() => void> = []; let clearCount = 0; vi.spyOn(window, 'setInterval').mockImplementation((handler: TimerHandler) => { if (typeof handler === 'function') { intervalHandlers.push(handler as () => void); } return intervalHandlers.length; }); vi.spyOn(window, 'clearInterval').mockImplementation(() => { clearCount += 1; }); mockDashboardApi({ libraryScanStatusSequence: [ [{ libraryId: 31, percent: 0.75 }], [] ], mediaSources: [ mediaSource({ libraries: [library({ id: 31, itemCount: 10, mediaKind: 'Movies', name: 'Movies' })] }) ] }); render(); fireEvent.click(screen.getByRole('link', { name: 'Libraries' })); expect(await screen.findByText('75%')).toBeInTheDocument(); const sourceFetchesBeforeCompletion = fetchCount('/api/media-sources'); intervalHandlers.forEach((handler) => handler()); await waitFor(() => { expect(screen.queryByText('75%')).not.toBeInTheDocument(); }); expect(fetchCount('/api/media-sources')).toBe(sourceFetchesBeforeCompletion + 1); expect(clearCount).toBeGreaterThan(0); }); it('triggers a library scan, disables that library while in flight, and starts polling scan status', async () => { const scanStatusesAfterMutation = [{ libraryId: 31, percent: 0.05 }]; mockDashboardApi({ libraryScanStatuses: [], libraryScanStatusesAfterMutation: scanStatusesAfterMutation, mediaSources: [ mediaSource({ libraries: [library({ id: 31, itemCount: 10, mediaKind: 'Movies', name: 'Movies' })] }) ] }); render(); fireEvent.click(screen.getByRole('link', { name: 'Libraries' })); expect((await screen.findAllByText('Movies')).length).toBeGreaterThan(0); fireEvent.click(screen.getByRole('button', { name: 'Scan Movies' })); await waitFor(() => { expect(window.fetch).toHaveBeenCalledWith('/api/libraries/31/scan', expect.objectContaining({ method: 'POST' })); }); expect(await screen.findByText('5%')).toBeInTheDocument(); expect(screen.getByRole('button', { name: 'Scan Movies' })).toBeDisabled(); }); it('keeps the scan button disabled and polling armed through the queue-to-start race, then clears once the scan finishes', async () => { const intervalHandlers: Array<() => void> = []; let clearCount = 0; vi.spyOn(window, 'setInterval').mockImplementation((handler: TimerHandler, timeout?: number) => { if (typeof handler === 'function' && (timeout ?? 0) >= 10000) { intervalHandlers.push(handler as () => void); } return intervalHandlers.length; }); vi.spyOn(window, 'clearInterval').mockImplementation(() => { clearCount += 1; }); mockDashboardApi({ libraryScanStatusSequence: [ [], // initial screen load [], // trigger's immediate post-POST fetch: scanner hasn't started yet [{ libraryId: 31, percent: 0.3 }], // first poll tick: now active [] // second poll tick: scan finished ], mediaSources: [ mediaSource({ libraries: [library({ id: 31, itemCount: 10, mediaKind: 'Movies', name: 'Movies' })] }) ] }); render(); fireEvent.click(screen.getByRole('link', { name: 'Libraries' })); expect((await screen.findAllByText('Movies')).length).toBeGreaterThan(0); fireEvent.click(screen.getByRole('button', { name: 'Scan Movies' })); await waitFor(() => { expect(window.fetch).toHaveBeenCalledWith('/api/libraries/31/scan', expect.objectContaining({ method: 'POST' })); }); // The immediate post-trigger status fetch returned [] - without pending-id tracking // the button would re-enable here and polling would never start. Both must hold. await waitFor(() => { expect(fetchCount('/api/libraries/scan-status')).toBe(2); }); expect(screen.getByRole('button', { name: 'Scan Movies' })).toBeDisabled(); expect(intervalHandlers.length).toBeGreaterThan(0); const sourceFetchesBeforeCompletion = fetchCount('/api/media-sources'); intervalHandlers.forEach((handler) => handler()); expect(await screen.findByText('30%')).toBeInTheDocument(); expect(screen.getByRole('button', { name: 'Scan Movies' })).toBeDisabled(); intervalHandlers.forEach((handler) => handler()); await waitFor(() => { expect(screen.queryByText('30%')).not.toBeInTheDocument(); }); expect(screen.getByRole('button', { name: 'Scan Movies' })).not.toBeDisabled(); expect(fetchCount('/api/media-sources')).toBe(sourceFetchesBeforeCompletion + 1); expect(clearCount).toBeGreaterThan(0); }); it('re-enables the scan button and stops polling when a queued scan never appears (grace window expiry)', async () => { const intervalHandlers: Array<() => void> = []; let clearCount = 0; vi.spyOn(window, 'setInterval').mockImplementation((handler: TimerHandler, timeout?: number) => { if (typeof handler === 'function' && (timeout ?? 0) >= 10000) { intervalHandlers.push(handler as () => void); } return intervalHandlers.length; }); vi.spyOn(window, 'clearInterval').mockImplementation(() => { clearCount += 1; }); mockDashboardApi({ libraryScanStatuses: [], mediaSources: [ mediaSource({ libraries: [library({ id: 31, itemCount: 10, mediaKind: 'Movies', name: 'Movies' })] }) ] }); render(); fireEvent.click(screen.getByRole('link', { name: 'Libraries' })); expect((await screen.findAllByText('Movies')).length).toBeGreaterThan(0); fireEvent.click(screen.getByRole('button', { name: 'Scan Movies' })); await waitFor(() => { expect(window.fetch).toHaveBeenCalledWith('/api/libraries/31/scan', expect.objectContaining({ method: 'POST' })); }); await waitFor(() => { expect(fetchCount('/api/libraries/scan-status')).toBe(2); }); expect(screen.getByRole('button', { name: 'Scan Movies' })).toBeDisabled(); expect(intervalHandlers.length).toBeGreaterThan(0); // The id never shows up in scan-status. It survives a couple of ticks... intervalHandlers.forEach((handler) => handler()); await waitFor(() => { expect(fetchCount('/api/libraries/scan-status')).toBe(3); }); expect(screen.getByRole('button', { name: 'Scan Movies' })).toBeDisabled(); // ...but expires once the grace window runs out, freeing the button and the poll. intervalHandlers.forEach((handler) => handler()); await waitFor(() => { expect(screen.getByRole('button', { name: 'Scan Movies' })).not.toBeDisabled(); }); expect(clearCount).toBeGreaterThan(0); }); it('re-enables the scan button and stops polling when scan-status errors repeatedly after a trigger (grace window on error)', async () => { const intervalHandlers: Array<() => void> = []; let clearCount = 0; vi.spyOn(window, 'setInterval').mockImplementation((handler: TimerHandler, timeout?: number) => { if (typeof handler === 'function' && (timeout ?? 0) >= 10000) { intervalHandlers.push(handler as () => void); } return intervalHandlers.length; }); vi.spyOn(window, 'clearInterval').mockImplementation(() => { clearCount += 1; }); mockDashboardApi({ libraryScanStatuses: [], libraryScanStatusFailAfterTrigger: true, mediaSources: [ mediaSource({ libraries: [library({ id: 31, itemCount: 10, mediaKind: 'Movies', name: 'Movies' })] }) ] }); render(); fireEvent.click(screen.getByRole('link', { name: 'Libraries' })); expect((await screen.findAllByText('Movies')).length).toBeGreaterThan(0); fireEvent.click(screen.getByRole('button', { name: 'Scan Movies' })); await waitFor(() => { expect(window.fetch).toHaveBeenCalledWith('/api/libraries/31/scan', expect.objectContaining({ method: 'POST' })); }); // The immediate post-trigger status fetch errors (first grace-tick burn), but the // button must stay disabled and the poll must stay armed - a transient failure must // not be indistinguishable from "give up immediately". await waitFor(() => { expect(fetchCount('/api/libraries/scan-status')).toBe(2); }); expect(screen.getByRole('button', { name: 'Scan Movies' })).toBeDisabled(); expect(intervalHandlers.length).toBeGreaterThan(0); // scan-status keeps erroring on every poll tick... intervalHandlers.forEach((handler) => handler()); await waitFor(() => { expect(fetchCount('/api/libraries/scan-status')).toBe(3); }); expect(screen.getByRole('button', { name: 'Scan Movies' })).toBeDisabled(); // ...but the same grace budget burns down on failures too, so persistent failure // eventually frees the button and stops the interval instead of polling forever. intervalHandlers.forEach((handler) => handler()); await waitFor(() => { expect(screen.getByRole('button', { name: 'Scan Movies' })).not.toBeDisabled(); }); expect(clearCount).toBeGreaterThan(0); }); it('shows Libraries API errors and retries', async () => { // The backend has no exception middleware, so a real failure is a bare 500 with no // ProblemDetails body - do not invent one here (mirrors the scan-trigger-404 test below). mockDashboardApi({ mediaSourcesFailuresBeforeSuccess: 2, mediaSources: [mediaSource({ libraries: [] })] }); render(); fireEvent.click(screen.getByRole('link', { name: 'Libraries' })); expect(await screen.findByText('Request failed with status 500')).toBeInTheDocument(); fireEvent.click(screen.getByRole('button', { name: 'Retry' })); expect(await screen.findByRole('heading', { name: 'Media Libraries' })).toBeInTheDocument(); }); it('shows scan trigger failures without inventing application ProblemDetails', async () => { mockDashboardApi({ mediaSources: [ mediaSource({ libraries: [library({ id: 31, itemCount: 10, mediaKind: 'Movies', name: 'Movies' })] }) ], mutationFailures: { '/api/libraries/31/scan': { status: 404 } } }); render(); fireEvent.click(screen.getByRole('link', { name: 'Libraries' })); expect((await screen.findAllByText('Movies')).length).toBeGreaterThan(0); fireEvent.click(screen.getByRole('button', { name: 'Scan Movies' })); expect(await screen.findByText('Request failed with status 404')).toBeInTheDocument(); }); it('scans every library in a source when its Scan-all button is clicked', async () => { mockDashboardApi({ mediaSources: [ mediaSource({ id: 30, libraries: [ library({ id: 31, itemCount: 10, mediaKind: 'Movies', name: 'Movies' }), library({ id: 32, itemCount: 5, mediaKind: 'Shows', name: 'TV Shows' }) ], name: 'Local' }) ] }); render(); fireEvent.click(screen.getByRole('link', { name: 'Libraries' })); expect(await screen.findByText('TV Shows')).toBeInTheDocument(); fireEvent.click(screen.getByRole('button', { name: 'Scan all libraries in Local' })); await waitFor(() => { expect(window.fetch).toHaveBeenCalledWith('/api/libraries/31/scan', expect.objectContaining({ method: 'POST' })); }); await waitFor(() => { expect(window.fetch).toHaveBeenCalledWith('/api/libraries/32/scan', expect.objectContaining({ method: 'POST' })); }); expect(fetchCount('/api/libraries/31/scan')).toBe(1); expect(fetchCount('/api/libraries/32/scan')).toBe(1); }); it('shows an empty Libraries state when no media sources exist', async () => { mockDashboardApi({ mediaSources: [] }); render(); fireEvent.click(screen.getByRole('link', { name: 'Libraries' })); expect(await screen.findByText('No media sources returned')).toBeInTheDocument(); }); 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/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/playouts on load; measure the Playouts // screen's own contribution as a delta instead of absorbing that prefetch. await waitFor(() => { expect(fetchCount('/api/playouts')).toBeGreaterThan(0); }); const playoutFetchesBeforeNavigation = fetchCount('/api/playouts'); fireEvent.click(screen.getByRole('link', { name: /Playouts/ })); expect(await screen.findByRole('heading', { name: 'Retro Cartoons' })).toBeInTheDocument(); expect(fetchCount('/api/playouts')).toBe(playoutFetchesBeforeNavigation + 1); expect(fetchCount('/api/playouts/20')).toBe(1); expect(fetchCount('/api/playouts/20/items')).toBe(1); const playoutFetchesBeforePoll = fetchCount('/api/playouts'); const stateFetchesBeforePoll = fetchCount('/api/channels/state'); intervalHandlers.forEach((handler) => handler()); await waitFor(() => { expect(fetchCount('/api/channels/state')).toBeGreaterThan(stateFetchesBeforePoll); }); expect(fetchCount('/api/playouts')).toBe(playoutFetchesBeforePoll); expect(fetchCount('/api/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/playouts/21', expect.any(Object)); expect(window.fetch).toHaveBeenCalledWith('/api/playouts/21/items', expect.any(Object)); expect(fetchCount('/api/playouts')).toBe(2); }); it('shows the Playouts loading state', async () => { vi.spyOn(window, 'fetch').mockImplementation((input: RequestInfo | URL) => { const path = input.toString(); if (path === '/api/playouts') { return new Promise(() => {}); } if (path === '/api/channels/state') { return Promise.resolve(jsonResponse([])); } if (path === '/api/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/playouts'); const itemFetchesBeforeReset = fetchCount('/api/playouts/20/items'); fireEvent.click(screen.getByRole('button', { name: 'Reset all playouts' })); await waitFor(() => { expect(window.fetch).toHaveBeenCalledWith('/api/playouts/reset-all', expect.objectContaining({ method: 'POST' })); }); expect(fetchCount('/api/playouts')).toBe(playoutFetchesBeforeReset + 1); expect(fetchCount('/api/playouts/20/items')).toBe(itemFetchesBeforeReset + 1); }); it('shows ProblemDetails when the reset-all transport fails with a 5xx', async () => { // Backend contract: POST /api/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/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('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('shows the dashboard loading state while requests are pending', async () => { vi.spyOn(window, 'fetch').mockImplementation(() => new Promise(() => {})); render(); expect(await screen.findByText('Loading dashboard')).toBeInTheDocument(); }); it('shows an empty on-air state when no channel state is on air', async () => { mockDashboardApi({ channels: [{ id: 1, name: 'Retro Cartoons', number: '5.1' }], channelStates: [{ channelId: 1, channelNumber: '5.1', onAir: false, nowPlaying: null }] }); render(); expect(await screen.findByText('No on-air channels reported')).toBeInTheDocument(); }); it('shows failing health checks with error styling, distinct from neutral info checks', async () => { mockDashboardApi({ health: [ { detail: 'SQLite is reachable', link: null, status: 'pass', title: 'Database' }, { detail: 'FFmpeg path is missing', link: null, status: 'fail', title: 'FFmpeg' }, { detail: 'Scheduled maintenance window active', link: null, status: 'info', title: 'Maintenance' } ] }); const { container } = render(); expect(await screen.findByText('FFmpeg path is missing')).toBeInTheDocument(); expect(screen.getAllByText('1 failing')).toHaveLength(2); expect(container.querySelectorAll('.ctv-health-icon-error')).toHaveLength(1); expect(container.querySelectorAll('.ctv-health-icon-idle').length).toBeGreaterThanOrEqual(1); }); it('refreshes health on demand without polling it', async () => { mockDashboardApi({ health: [ { detail: 'All checks passed', link: null, status: 'pass', title: 'System' } ] }); render(); expect(await screen.findByText('All checks passed')).toBeInTheDocument(); expect(fetchCount('/api/health')).toBe(1); fireEvent.click(screen.getByRole('button', { name: 'Refresh health' })); expect(await screen.findByText('All checks passed')).toBeInTheDocument(); expect(fetchCount('/api/health')).toBe(2); }); it('shows the API error detail when dashboard loading fails', async () => { vi.spyOn(window, 'fetch').mockImplementation(() => Promise.resolve(new Response( JSON.stringify({ detail: 'API write key is invalid', status: 401, title: 'Unauthorized' }), { headers: { 'Content-Type': 'application/json' }, status: 401 } )) ); render(); expect(await screen.findByText('API write key is invalid')).toBeInTheDocument(); }); it('exports typed primitives with expected interactions', () => { const onSwitch = vi.fn(); const onCheckbox = vi.fn(); const onTab = vi.fn(); render( <> {}} /> ); expect(screen.getByRole('button', { name: 'Saving' })).toBeDisabled(); fireEvent.click(screen.getByRole('switch', { name: 'Show disabled' })); expect(onSwitch).toHaveBeenCalledWith(true); expect(screen.getByRole('checkbox', { name: 'Select all' })).toHaveAttribute( 'aria-checked', 'mixed' ); expect(screen.getByText('Already in use')).toBeInTheDocument(); expect(screen.getByText('62%')).toBeInTheDocument(); fireEvent.click(screen.getByRole('tab', { name: 'Streaming' })); expect(onTab).toHaveBeenCalledWith('streaming'); fireEvent.mouseEnter(screen.getByText('Reset')); expect(screen.getByRole('tooltip')).toHaveTextContent('Reset playout'); }); it('uses distinct semantic icons for warning and error toasts', () => { const { container } = render( <> ); expect(container.querySelector('.lucide-triangle-alert')).toBeInTheDocument(); expect(container.querySelector('.lucide-circle-x')).toBeInTheDocument(); }); // ---- Channel Builder (#89) ----------------------------------------------- const renderBuilder = async () => { window.history.replaceState(null, '', '/app/new-channel'); const utils = render(); await screen.findByPlaceholderText('Search shows & movies…'); return utils; }; // The shell's nav link and top-bar primary action also read "New Channel" / // "Create Channel"; scope these to the builder toolbar. const createBtn = () => within(document.querySelector('.ctv-builder-toolbar') as HTMLElement).getByRole('button', { name: 'Create Channel' }); const builderTitle = () => screen.getByText('New Channel', { selector: '.ctv-builder-title' }); const numberField = () => screen.getByLabelText('Number', { exact: false }) as HTMLInputElement; const builderDefaults = () => ({ channels: [channelSummary()], channelTemplates: [channelTemplate()], defaultChannelTemplate: channelTemplate(), ffmpegProfiles: [ffmpegProfile()] }); it('renders the builder three-column layout with library items and the default template', async () => { mockDashboardApi({ ...builderDefaults(), browseItems: [browseItem(), browseItem({ id: 2, mediaItemId: 2, title: 'Tom & Jerry' })] }); const { container } = await renderBuilder(); expect(builderTitle()).toBeInTheDocument(); expect(screen.getByText('Lineup')).toBeInTheDocument(); expect(screen.getByText('Channel Template')).toBeInTheDocument(); expect(screen.getByText('Standard')).toBeInTheDocument(); expect(await screen.findByText('Looney Tunes')).toBeInTheDocument(); expect(screen.getByText('Tom & Jerry')).toBeInTheDocument(); expect(container.querySelectorAll('.ctv-builder-col')).toHaveLength(3); expect(screen.getByText('This channel has no content yet. Double-click or drag titles from the library to build the lineup.')).toBeInTheDocument(); }); it('computes the AUTO channel number from the max integer part of existing channels', async () => { mockDashboardApi({ ...builderDefaults(), channels: [channelSummary({ id: 1, number: '5' }), channelSummary({ id: 2, number: '13.1' })], browseItems: [browseItem()] }); await renderBuilder(); const numberInput = numberField(); expect(numberInput.value).toBe('14'); expect(screen.getByText('AUTO')).toBeInTheDocument(); }); it('adds a library item to the lineup on double-click and dedupes repeats', async () => { mockDashboardApi({ ...builderDefaults(), browseItems: [browseItem()] }); const { container } = await renderBuilder(); fireEvent.doubleClick(await screen.findByText('Looney Tunes')); expect(container.querySelector('.ctv-builder-summary')?.textContent).toContain('1 in lineup'); expect(container.querySelectorAll('.ctv-builder-lineup-row')).toHaveLength(1); fireEvent.doubleClick(screen.getAllByText('Looney Tunes')[0]); expect(container.querySelectorAll('.ctv-builder-lineup-row')).toHaveLength(1); }); it('removes a lineup item and clears the lineup through the confirm dialog', async () => { mockDashboardApi({ ...builderDefaults(), browseItems: [browseItem(), browseItem({ id: 2, mediaItemId: 2, title: 'Tom & Jerry' })] }); const { container } = await renderBuilder(); fireEvent.doubleClick(await screen.findByText('Looney Tunes')); fireEvent.doubleClick(screen.getByText('Tom & Jerry')); expect(container.querySelectorAll('.ctv-builder-lineup-row')).toHaveLength(2); fireEvent.click(within(container.querySelectorAll('.ctv-builder-lineup-row')[0] as HTMLElement).getByRole('button', { name: 'Remove' })); expect(container.querySelectorAll('.ctv-builder-lineup-row')).toHaveLength(1); fireEvent.click(screen.getByRole('button', { name: 'Clear' })); fireEvent.click(await screen.findByRole('button', { name: 'Clear lineup' })); await waitFor(() => expect(container.querySelectorAll('.ctv-builder-lineup-row')).toHaveLength(0)); }); it('filters library results through the debounced search query', async () => { mockDashboardApi({ ...builderDefaults(), browseHandler: (search) => { const query = (search.get('query') ?? '').toLowerCase(); const all = [ browseItem(), browseItem({ id: 2, mediaItemId: 2, mediaType: 'Movie', collectionType: 'Movie', title: 'Blade Runner', libraryName: 'Movies' }) ]; const page = query ? all.filter((item) => String(item.title).toLowerCase().includes(query)) : all; return { page, totalCount: page.length }; } }); await renderBuilder(); expect(await screen.findByText('Blade Runner')).toBeInTheDocument(); fireEvent.change(screen.getByPlaceholderText('Search shows & movies…'), { target: { value: 'blade' } }); await waitFor(() => expect(screen.queryByText('Looney Tunes')).not.toBeInTheDocument()); expect(screen.getByText('Blade Runner')).toBeInTheDocument(); }); it('reorders lineup items with native drag and drop', async () => { mockDashboardApi({ ...builderDefaults(), browseItems: [browseItem(), browseItem({ id: 2, mediaItemId: 2, title: 'Tom & Jerry' })] }); const { container } = await renderBuilder(); fireEvent.doubleClick(await screen.findByText('Looney Tunes')); fireEvent.doubleClick(screen.getByText('Tom & Jerry')); let rows = container.querySelectorAll('.ctv-builder-lineup-row'); expect(rows[0].querySelector('.ctv-builder-row-title')?.textContent).toBe('Looney Tunes'); fireEvent.dragStart(rows[0]); fireEvent.dragOver(rows[1]); fireEvent.drop(rows[1]); rows = container.querySelectorAll('.ctv-builder-lineup-row'); expect(rows[0].querySelector('.ctv-builder-row-title')?.textContent).toBe('Tom & Jerry'); expect(rows[1].querySelector('.ctv-builder-row-title')?.textContent).toBe('Looney Tunes'); }); it('validates the channel number for format and uniqueness', async () => { mockDashboardApi({ ...builderDefaults(), channels: [channelSummary({ number: '5' })], browseItems: [browseItem()] }); await renderBuilder(); const numberInput = numberField(); fireEvent.change(numberInput, { target: { value: 'abc' } }); expect(await screen.findByText(/Use digits/)).toBeInTheDocument(); fireEvent.change(numberInput, { target: { value: '5' } }); expect(await screen.findByText(/already in use/)).toBeInTheDocument(); }); it('keeps Create disabled until a name and at least one lineup item exist', async () => { mockDashboardApi({ ...builderDefaults(), browseItems: [browseItem()] }); await renderBuilder(); const createButton = createBtn(); expect(createButton).toBeDisabled(); fireEvent.doubleClick(await screen.findByText('Looney Tunes')); fireEvent.change(screen.getByLabelText('Channel name'), { target: { value: 'Retro Cartoons' } }); expect(createButton).toBeEnabled(); }); it('preselects the default template and flags an override when the Shuffle toggle diverges', async () => { mockDashboardApi({ ...builderDefaults(), browseItems: [browseItem()] }); const { container } = await renderBuilder(); // default template has shuffleScheduleItems=false -> no override tag yet expect(screen.queryByText('overrides template')).not.toBeInTheDocument(); const shuffleRow = container.querySelector('.ctv-builder-toggle-row:not(.ctv-builder-toggle-live)') as HTMLElement; fireEvent.click(shuffleRow); expect(await screen.findByText('overrides template')).toBeInTheDocument(); }); it('applies a selected template shuffle default and clears the override', async () => { mockDashboardApi({ ...builderDefaults(), channelTemplates: [ channelTemplate(), channelTemplate({ id: 11, isDefault: false, name: 'Music videos', shuffleScheduleItems: true }) ], browseItems: [browseItem()] }); const { container } = await renderBuilder(); const shuffleRow = container.querySelector('.ctv-builder-toggle-row:not(.ctv-builder-toggle-live)') as HTMLElement; fireEvent.click(shuffleRow); expect(await screen.findByText('overrides template')).toBeInTheDocument(); // open the template picker and select the shuffle-by-default template fireEvent.click(screen.getByText('Standard')); fireEvent.click(await screen.findByText('Music videos')); await waitFor(() => expect(screen.queryByText('overrides template')).not.toBeInTheDocument()); }); it('marks a rerun-collection row invalid in a multi-item lineup and blocks Create', async () => { mockDashboardApi({ ...builderDefaults(), browseItems: [ browseItem(), browseItem({ id: 9, title: 'Saturday Block', mediaType: 'RerunCollection', collectionType: 'RerunFirstRun', collectionKind: 'Rerun', rerunCollectionId: 9, mediaItemId: undefined }) ] }); await renderBuilder(); fireEvent.doubleClick(await screen.findByText('Looney Tunes')); fireEvent.doubleClick(screen.getByText('Saturday Block')); fireEvent.change(screen.getByLabelText('Channel name'), { target: { value: 'Mixed' } }); expect(await screen.findByText('Only valid alone')).toBeInTheDocument(); expect(createBtn()).toBeDisabled(); }); it('clears a MultiCollection shuffle requirement when the Shuffle toggle is turned on', async () => { mockDashboardApi({ ...builderDefaults(), browseItems: [ browseItem({ id: 7, title: 'Prime Time', mediaType: 'MultiCollection', collectionType: 'MultiCollection', multiCollectionId: 7, mediaItemId: undefined }) ] }); const { container } = await renderBuilder(); fireEvent.doubleClick(await screen.findByText('Prime Time')); fireEvent.change(screen.getByLabelText('Channel name'), { target: { value: 'Multi' } }); expect(await screen.findByText('Requires Shuffle')).toBeInTheDocument(); expect(createBtn()).toBeDisabled(); const shuffleRow = container.querySelector('.ctv-builder-toggle-row:not(.ctv-builder-toggle-live)') as HTMLElement; fireEvent.click(shuffleRow); await waitFor(() => expect(screen.queryByText('Requires Shuffle')).not.toBeInTheDocument()); expect(createBtn()).toBeEnabled(); }); it('posts a well-formed create request and navigates to channels on success', async () => { mockDashboardApi({ ...builderDefaults(), channels: [channelSummary({ number: '5' })], browseItems: [browseItem(), browseItem({ id: 2, mediaItemId: 2, title: 'Tom & Jerry' })] }); await renderBuilder(); fireEvent.doubleClick(await screen.findByText('Looney Tunes')); fireEvent.doubleClick(screen.getByText('Tom & Jerry')); fireEvent.change(screen.getByLabelText('Channel name'), { target: { value: ' Retro Cartoons ' } }); fireEvent.click(createBtn()); await waitFor(() => expect(window.location.pathname).toBe('/app/channels')); const body = requestBodyFor('/api/channels/from-lineup'); expect(body.name).toBe('Retro Cartoons'); expect(body.number).toBe('6'); expect(body.group).toBe('ChicoryTV'); expect(body.templateId).toBe(10); expect(body.logo).toEqual({ contentType: '', path: '' }); expect((body.advanced as Record).playbackOrder).toBe('Chronological'); expect((body.advanced as Record).playoutMode).toBe('Continuous'); const lineup = body.lineup as Array>; expect(lineup).toHaveLength(2); expect(lineup[0].mediaItemId).toBe(1); expect(lineup[1].mediaItemId).toBe(2); expect(lineup[0].mediaType).toBe('TelevisionShow'); }); it('highlights the offending lineup row and shows the detail on a 422 ProblemDetails', async () => { mockDashboardApi({ ...builderDefaults(), browseItems: [browseItem(), browseItem({ id: 2, mediaItemId: 2, title: 'Tom & Jerry' })], // Verbatim wire shape: ApiResults hard-codes the 422 title "Validation failed", // and the handler's not-found detail is "lineup[i]