Files
ersatztv/web/src/media/addTo/AddToScheduleDialog.test.tsx
T
timothyandClaude Opus 4.8 b7428a9b95 feat(#259): SPA round-trips schedule item server id
The backend (already on this branch) added an optional int? Id to
ScheduleItemRequest so the server reconciles PUT /api/schedules/{id}/items
rows by identity instead of by array position. The SPA previously
discarded the server id on load (only a client-local _key survived) and
never sent one back, so a reorder could misattribute fill-group/shuffle
state onto the wrong persisted row.

- itemRules.ts: fromResponse now captures the response item's id onto
  the draft; normalizeForSave emits it back unchanged. newDraftItem and
  copyDraftItem explicitly set id: null (a brand-new/copied row was
  never persisted under an id, and copyDraftItem must not duplicate the
  source's id onto a second row).
- scheduleItem.ts (Add-to-schedule dialog, POST path): id: null for the
  same reason — it always creates a new row.
- SchedulesScreen.tsx save(): the PUT-response re-seed already existed
  (fromResponse over the response array) but now carries ids through.
  This matters because a subtype/playout-mode switch can be a
  delete+insert server-side, so the response id for that row can differ
  from what was submitted — a second save must use the *response's* id
  or the server 422s it as unknown. Added a comment documenting this.
- schedules.ts: replaced the stale "server reuses same-typed rows by
  position" comment with the current id-based reconcile contract.
- Added/updated tests in itemRules.test.ts, SchedulesScreen.test.tsx,
  and AddToScheduleDialog.test.tsx covering id round-tripping, the
  null-id-for-new/copied-item cases, and a second-save-reuses-the-
  response-id regression test.

Verified: npm run lint, tsc -b --noEmit, npm run build, and npm test
(680/680) all pass.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-11 21:51:24 +02:00

153 lines
5.6 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { AddToScheduleDialog } from './AddToScheduleDialog';
function jsonResponse(body: unknown, status = 200): Response {
return new Response(JSON.stringify(body), { headers: { 'Content-Type': 'application/json' }, status });
}
const schedules = [
{ id: 1, name: 'Weekdays', fixedStartTimeBehavior: 'Never', keepMultiPartEpisodesTogether: false, randomStartPoint: false, shuffleScheduleItems: false, treatCollectionsAsShows: false },
{ id: 2, name: 'Weekends', fixedStartTimeBehavior: 'Never', keepMultiPartEpisodesTogether: false, randomStartPoint: false, shuffleScheduleItems: false, treatCollectionsAsShows: false }
];
// Mirrors AddProgramScheduleItem.ForMediaItem defaults (AddProgramScheduleItem.cs:48-87), with the
// mapped collectionType + mediaItemId for a TelevisionShow item.
const expectedShowPayload = {
id: null,
startType: 'Dynamic',
startTime: null,
fixedStartTimeBehavior: null,
playoutMode: 'One',
collectionType: 'TelevisionShow',
collectionId: null,
multiCollectionId: null,
smartCollectionId: null,
rerunCollectionId: null,
mediaItemId: 42,
playlistId: null,
searchTitle: null,
searchQuery: null,
playbackOrder: 'Shuffle',
marathonGroupBy: 'None',
marathonShuffleGroups: false,
marathonShuffleItems: false,
marathonBatchSize: null,
fillWithGroupMode: 'None',
multipleMode: 'Count',
multipleCount: null,
playoutDuration: null,
tailMode: 'None',
discardToFillAttempts: null,
customTitle: null,
guideMode: 'Normal',
preRollFillerId: null,
midRollFillerId: null,
postRollFillerId: null,
tailFillerId: null,
fallbackFillerId: null,
watermarkIds: [],
graphicsElementIds: [],
preferredAudioLanguageCode: null,
preferredAudioTitle: null,
preferredSubtitleLanguageCode: null,
subtitleMode: null
};
interface Recorded {
url: string;
method: string;
body: unknown;
}
function mockApi() {
const calls: Recorded[] = [];
vi.spyOn(window, 'fetch').mockImplementation((input: RequestInfo | URL, init?: RequestInit) => {
const url = input.toString();
const method = (init?.method ?? 'GET').toUpperCase();
const body = init?.body ? JSON.parse(String(init.body)) : undefined;
calls.push({ body, method, url });
if (url === '/api/schedules' && method === 'GET') {
return Promise.resolve(jsonResponse(schedules));
}
if (/^\/api\/schedules\/\d+\/items$/.test(url) && method === 'POST') {
return Promise.resolve(jsonResponse({ id: 500 }, 201));
}
return Promise.resolve(new Response(null, { status: 204 }));
});
return { calls };
}
describe('AddToScheduleDialog', () => {
beforeEach(() => {
window.localStorage.clear();
vi.restoreAllMocks();
});
afterEach(() => {
cleanup();
});
it('loads schedules into the select', async () => {
mockApi();
render(<AddToScheduleDialog item={{ id: 42, mediaType: 'TelevisionShow', title: 'The Office' }} onClose={() => {}} open />);
await waitFor(() => expect(screen.getByRole('option', { name: 'Weekdays' })).toBeTruthy());
expect(screen.getByRole('option', { name: 'Weekends' })).toBeTruthy();
});
it('adds the media item with the ForMediaItem defaults payload', async () => {
const onAdded = vi.fn();
const onClose = vi.fn();
const { calls } = mockApi();
render(
<AddToScheduleDialog
item={{ id: 42, mediaType: 'TelevisionShow', title: 'The Office' }}
onAdded={onAdded}
onClose={onClose}
open
/>
);
await waitFor(() => expect(screen.getByRole('option', { name: 'Weekends' })).toBeTruthy());
fireEvent.change(screen.getByRole('combobox'), { target: { value: '2' } });
fireEvent.click(screen.getByRole('button', { name: /Add to schedule/ }));
await waitFor(() => expect(onClose).toHaveBeenCalled());
const addCall = calls.find((call) => call.url === '/api/schedules/2/items');
expect(addCall?.method).toBe('POST');
expect(addCall?.body).toEqual(expectedShowPayload);
expect(onAdded).toHaveBeenCalledWith('Weekends');
});
// The server validator (ProgramScheduleItemCommandBase.CollectionTypeMustBeValid) only accepts
// shows / seasons / artists as per-media-item schedule items; a movie must hit the defensive
// "can't be added" path instead of POSTing a payload the server would 422.
it('refuses a non-schedulable kind (movie) without posting', async () => {
const { calls } = mockApi();
render(<AddToScheduleDialog item={{ id: 7, mediaType: 'Movie', title: 'Alien' }} onClose={() => {}} open />);
await waitFor(() => expect(screen.getByText(/can’t be added to a schedule/)).toBeTruthy());
const submit = screen.getByRole('button', { name: /Add to schedule/ });
expect(submit).toHaveProperty('disabled', true);
fireEvent.click(submit);
expect(calls.some((call) => call.method === 'POST')).toBe(false);
});
it('maps an Artist item to the Artist collection type', async () => {
const { calls } = mockApi();
render(<AddToScheduleDialog item={{ id: 7, mediaType: 'Artist', title: 'Kraftwerk' }} onClose={() => {}} open />);
await waitFor(() => expect(screen.getByRole('option', { name: 'Weekdays' })).toBeTruthy());
fireEvent.click(screen.getByRole('button', { name: /Add to schedule/ }));
await waitFor(() => expect(calls.some((call) => call.url === '/api/schedules/1/items')).toBe(true));
const addCall = calls.find((call) => call.url === '/api/schedules/1/items');
expect(addCall?.body).toMatchObject({ collectionType: 'Artist', mediaItemId: 7 });
});
});