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>
This commit is contained in:
2026-07-11 21:51:24 +02:00
co-authored by Claude Opus 4.8
parent 02a493e95e
commit b7428a9b95
7 changed files with 69 additions and 6 deletions
+8 -4
View File
@@ -57,10 +57,14 @@ export function addScheduleItem(scheduleId: number, body: ScheduleItemRequest):
return request<ScheduleItem>(`/api/schedules/${scheduleId}/items`, { body, method: 'POST' });
}
// Positional in-place reconcile: the server reuses same-typed item rows (keeping fill-group state) and
// triggers playout rebuilds. The editor batches all local draft edits into this single call. Pass the
// last-seen ETag as `If-Match` to reject a stale overwrite with 412; the resolved value carries the new
// ETag for a subsequent save (issue #253). See docs/decisions.md.
// Id-based reconcile (#259): each item's `id` (round-tripped from the GET response by the editor;
// `null` for a new/copied item never persisted) tells the server which existing row to update in place
// vs. insert, so fill-group/shuffle state on an existing row survives a reorder. The editor batches all
// local draft edits into this single call. Pass the last-seen ETag as `If-Match` to reject a stale
// overwrite with 412; the resolved value carries the new ETag for a subsequent save (issue #253). See
// docs/decisions.md. Note: switching an item's playout-mode/subtype can be a delete+insert server-side,
// so the response's ids may differ from what was sent — the editor must re-seed its draft from the PUT
// response (see SchedulesScreen.tsx `save()`), not reuse the ids it submitted.
export function replaceScheduleItems(
scheduleId: number,
body: ReplaceScheduleItemsRequest,
@@ -14,6 +14,7 @@ const schedules = [
// 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,
+1
View File
@@ -34,6 +34,7 @@ export function scheduleItemRequestForMediaItem(
mediaItemId: number
): ScheduleItemRequest {
return {
id: null,
startType: 'Dynamic',
startTime: null,
fixedStartTimeBehavior: null,
+15
View File
@@ -349,10 +349,14 @@ describe('factories', () => {
graphicsElementIds: []
});
expect(item._key).toMatch(/^draft-/);
// A never-persisted item must not carry a server id (#259) — the save projection relies on this
// to tell the server it's an insert.
expect(item.id).toBeNull();
});
it('copyDraftItem deep-copies multi/smart/rerun refs and gives a new key + array identity', () => {
const original = draft({
id: 99,
multiCollectionId: 3,
multiCollectionName: 'M',
smartCollectionId: 4,
@@ -372,6 +376,9 @@ describe('factories', () => {
expect(copy.watermarkIds).toEqual([1, 2]);
expect(copy.watermarkIds).not.toBe(original.watermarkIds);
expect(copy.graphicsElementIds).not.toBe(original.graphicsElementIds);
// A copy is a new row that was never persisted under its own id — it must not carry the source
// item's server id (#259), or a save would submit the same id twice.
expect(copy.id).toBeNull();
});
});
@@ -438,6 +445,9 @@ describe('fromResponse', () => {
durationEstimate: '01:00:00'
};
const item = fromResponse(model);
// The server id must round-trip onto the draft (#259) so a subsequent save reconciles this row by
// identity instead of by array position.
expect(item.id).toBe(42);
expect(item.smartCollectionId).toBe(7);
expect(item.smartCollectionName).toBe('Smarts');
expect(item.watermarkIds).toEqual([1, 2]);
@@ -500,6 +510,11 @@ describe('normalizeForSave', () => {
expect('collectionName' in req).toBe(false);
expect('name' in req).toBe(false);
});
it('passes the draft id through unchanged: null for a new item, the server id for a loaded one (#259)', () => {
expect(normalizeForSave(draft()).id).toBeNull();
expect(normalizeForSave(draft({ id: 42 })).id).toBe(42);
});
});
describe('validation', () => {
+12
View File
@@ -253,6 +253,9 @@ export function applyPlayoutModeChange(item: DraftItem, newMode: PlayoutMode): D
export function newDraftItem(): DraftItem {
return {
_key: nextDraftKey(),
// Never round-tripped from the server — the save projection must emit `id: null` for this item so
// the server treats it as an insert rather than colliding with (or misattributing) an existing row.
id: null,
startType: 'Dynamic',
startTime: null,
fixedStartTimeBehavior: null,
@@ -308,6 +311,9 @@ export function copyDraftItem(item: DraftItem): DraftItem {
return {
...item,
_key: nextDraftKey(),
// The copy is a new, never-persisted row — it must not carry the source item's server id, or the
// save projection would submit the same id twice (server would treat the copy as the same row).
id: null,
watermarkIds: [...(item.watermarkIds ?? [])],
graphicsElementIds: [...(item.graphicsElementIds ?? [])]
};
@@ -318,6 +324,9 @@ export function copyDraftItem(item: DraftItem): DraftItem {
export function fromResponse(model: ScheduleItem): DraftItem {
return {
_key: nextDraftKey(),
// Round-trip the server id so a subsequent save reconciles this row by identity (#259) rather
// than by array position.
id: model.id,
startType: model.startType,
startTime: model.startTime,
fixedStartTimeBehavior: model.fixedStartTimeBehavior,
@@ -379,6 +388,9 @@ export function normalizeForSave(item: DraftItem): ScheduleItemRequest {
const fillWithGroupMode = fillWithGroupModeEligible(item) ? item.fillWithGroupMode : 'None';
return {
// null for a draft item never round-tripped from the server (new / copied) — the server treats a
// null id as an insert. A non-null id reconciles the existing row by identity (#259).
id: item.id,
startType: item.startType,
startTime: isFixed ? item.startTime : null,
fixedStartTimeBehavior: isFixed ? item.fixedStartTimeBehavior : null,
+27 -2
View File
@@ -203,6 +203,10 @@ describe('SchedulesScreen — draft mutations issue a single PUT on Save', () =>
// exactly one PUT, and no POST/DELETE to items endpoints
expect(handle.requests.filter((r) => r.method === 'PUT' && r.url === '/api/schedules/1/items')).toHaveLength(1);
expect(handle.requests.filter((r) => r.url.includes('/items/'))).toHaveLength(0);
// #259: the pre-existing item (loaded via GET, id 10) round-trips its server id; the brand-new item
// (added in the editor, never persisted) sends a null id so the server treats it as an insert.
expect(items[0].id).toBe(10);
expect(items[1].id).toBeNull();
});
it('edit a field → PUT reflects it', async () => {
@@ -214,9 +218,9 @@ describe('SchedulesScreen — draft mutations issue a single PUT on Save', () =>
expect(lastPut(handle)[0].customTitle).toBe('Nightly');
});
it('copy item deep-copies references into the PUT payload', async () => {
it('copy item deep-copies references into the PUT payload, but the copy sends a null id', async () => {
const handle = await renderReady({
items: [responseItem({ collectionType: 'MultiCollection', collectionId: null, multiCollectionId: 8, multiCollectionName: 'Multi', playbackOrder: 'Shuffle', name: 'Multi' })]
items: [responseItem({ id: 10, collectionType: 'MultiCollection', collectionId: null, multiCollectionId: 8, multiCollectionName: 'Multi', playbackOrder: 'Shuffle', name: 'Multi' })]
});
fireEvent.click(screen.getByRole('button', { name: /Copy Multi/ }));
fireEvent.click(screen.getByRole('button', { name: /^Save$/ }));
@@ -225,6 +229,27 @@ describe('SchedulesScreen — draft mutations issue a single PUT on Save', () =>
expect(items).toHaveLength(2);
expect(items[0].multiCollectionId).toBe(8);
expect(items[1].multiCollectionId).toBe(8);
// The original round-trips its server id; the copy is a new row that was never persisted under its
// own id, so it must not send the original's id (#259) — that would collide with it server-side.
expect(items[0].id).toBe(10);
expect(items[1].id).toBeNull();
});
it('re-seeds ids from the PUT response so a second save reuses the fresh ids (#259)', async () => {
const handle = await renderReady();
const title = screen.getByLabelText('Custom title') as HTMLInputElement;
fireEvent.change(title, { target: { value: 'First edit' } });
fireEvent.click(screen.getByRole('button', { name: /^Save$/ }));
await waitFor(() => expect(handle.requests.filter((r) => r.method === 'PUT').length).toBe(1));
// The mock echoes the submitted item back with a new id (500 + index) — simulating a server-side
// delete+insert reconcile. The editor must adopt that id, not keep serving the id it submitted.
const titleAfterSave = screen.getByLabelText('Custom title') as HTMLInputElement;
fireEvent.change(titleAfterSave, { target: { value: 'Second edit' } });
fireEvent.click(screen.getByRole('button', { name: /^Save$/ }));
await waitFor(() => expect(handle.requests.filter((r) => r.method === 'PUT').length).toBe(2));
const secondPut = lastPut(handle);
expect(secondPut[0].id).toBe(500);
expect(secondPut[0].customTitle).toBe('Second edit');
});
it('remove item → PUT omits it', async () => {
+5
View File
@@ -334,6 +334,11 @@ export function SchedulesScreen() {
// Load-bearing: a same-tab second save must use the ETag this write produced, or it would 412
// against its own change (#253).
etagRef.current = etag;
// Also load-bearing for #259: re-seed the draft's ids from the PUT response, not the ids that
// were submitted. A subtype/playout-mode switch can be a delete+insert server-side, so the
// response id for that row can differ from what was sent; fromResponse captures response.id
// onto each draft, so a subsequent save reconciles by the now-current id instead of a stale one
// (which the server would 422 as unknown).
const drafts = [...response].sort((a, b) => a.index - b.index).map(fromResponse);
baselineRef.current = drafts;
setItems(drafts);