diff --git a/docs/spa-conventions.md b/docs/spa-conventions.md index 334edecf9..33621bba0 100644 --- a/docs/spa-conventions.md +++ b/docs/spa-conventions.md @@ -457,6 +457,28 @@ string-keyed dispatcher, or generic screen-action framework participates in norm bulk-create), closing the panel does **not** lose data (it's still in screen state) — so the `window.confirm` guard belongs on *screen navigation / unload* while any uncommitted edit exists, not on panel close. Show an "Edited" badge on customised rows so the pending edits are visible. +- **Per-source correction rows: weight stepper + include/exclude toggle, keyed by the server's source id** + (#440 wiring #425's backend into the Auto-Tune DetailPanel's Content-sources pane). The row model is + reusable wherever an item list carries per-item rotation weights: + - The row's draft (`SourceDraft` in `AutoTuneScreen.tsx`) holds `weight` as a **string** per §4a, plus a + boolean `excluded`; the shared bound `WEIGHT_MIN`/`WEIGHT_MAX` = 1..1000 mirrors the server's + `MultiCollectionItemWeight` validator (the same const pair the multi-collection editor uses, #404) and is + clamped on `onBlur` **and** again in the draft→request mapping. + - **Only genuinely customised rows go on the wire.** The draft→request mapper (`sourcesRequest`) drops any + row that is still fair-share (weight 1, not excluded, not added) and returns `undefined` when nothing is + left, so the field is **omitted** rather than sent as an all-default array. That predicate mirrors the + server's own `customized` check exactly — an all-default array is a documented no-op there, and omitting + it keeps the channel on the cheaper single-SmartCollection shape. The same predicate drives the row's + "Edited" badge and the §8 dirty guard, so a value touched and set back to the default is correctly *not* + an edit (same rule as a name cleared back to empty). + - **A library picker compiles typed text; it never forwards raw Lucene.** The "add a source not in the + base set" typeahead sends `title:**` (`titleContainsQuery`), not the user's literal text: the + search index's default field does **not** match bare title words (`Alpha` finds nothing for "Show Alpha" + — see `e2e-local.md`), so a raw forward like `SearchScreen`'s (where the box is explicitly a query box) + would look broken in a *name* picker. Escape every Lucene special + whitespace so the boundary stars are + the only live wildcards — the same shape `builder/rules/compile.ts` emits for `contains`. + - Rows are read-keyed by the **server's** id (`GET /api/v1/channels/auto-tune/members`), and an added id + that turns out to already be a base member patches the existing row instead of appending a duplicate. - **Advanced channel-options overrides are shared, not duplicated** (`web/src/builder/advancedOptions.tsx`). The `CreateChannelFromLineupAdvancedOptionsRequest` override model — the enum catalogs, `ADVANCED_KEYS`, `effectiveValue`, and the field adapters (`useAdvancedOverrides`) — is one module diff --git a/web/src/api/autoTune.ts b/web/src/api/autoTune.ts index 8daa9db57..d19ee146f 100644 --- a/web/src/api/autoTune.ts +++ b/web/src/api/autoTune.ts @@ -7,6 +7,11 @@ export type PreviewAutoTuneChannelsRequest = components['schemas']['PreviewAutoT export type AutoTunedChannelRequest = components['schemas']['AutoTunedChannelRequest']; export type CreateAutoTunedChannelsRequest = components['schemas']['CreateAutoTunedChannelsRequest']; export type AutoTuneChannelResult = components['schemas']['AutoTuneChannelResultModel']; +// Per-source rotation weight + query correction on a create request (#425). `sourceId` is a show +// (TV axes) or movie (MovieGenre axis) id — the ids the members endpoint below returns; `weight` is +// 1..1000 with 1 = fair share; `excluded` drops the source from the channel entirely. An entry whose +// id is NOT in the axis's base set is an "add-untagged" source and simply airs alongside the rest. +export type AutoTuneSourceWeightRequest = components['schemas']['AutoTuneSourceWeightRequest']; export type AutoTuneResult = components['schemas']['AutoTuneResultResponseModel']; export type PagedAutoTuneMembers = components['schemas']['PagedLibraryBrowseItemsResponseModel']; export type AutoTuneMember = components['schemas']['LibraryBrowseItemResponseModel']; @@ -33,8 +38,8 @@ export function createAutoTunedChannels(body: CreateAutoTunedChannelsRequest): P } // #384 read endpoint: the distinct members a proposed channel's smart collection -// resolves to (axis+value identify the proposal). Read-only source list for the -// DetailPanel; per-source rotation weights + corrections are #425, not here. +// resolves to (axis+value identify the proposal). Backs the DetailPanel's content-source +// rows — its ids are the `sourceId`s a per-source weight/exclusion is keyed by (#425/#440). export function getAutoTuneChannelMembers(params: GetAutoTuneMembersParams): Promise { const searchParams = new URLSearchParams(); searchParams.set('axis', params.axis); diff --git a/web/src/screens/AutoTuneScreen.test.tsx b/web/src/screens/AutoTuneScreen.test.tsx index 5fd6c3631..d968ee61f 100644 --- a/web/src/screens/AutoTuneScreen.test.tsx +++ b/web/src/screens/AutoTuneScreen.test.tsx @@ -47,6 +47,13 @@ function autoTuneAuxRoute(path: string, method: string): Response | null { if (path.startsWith('/api/v1/channels/auto-tune/members') && method === 'GET') { return jsonResponse(members); } + // Backs the #440 add-untagged typeahead: a show that is NOT in the axis's base member set. + if (path.startsWith('/api/v1/search?') && method === 'GET') { + return jsonResponse({ + movies: { totalCount: 0, items: [] }, + shows: { totalCount: 1, items: [{ id: 99, mediaType: 'TelevisionShow', title: 'Dark Matter', artwork: '' }] } + }); + } return null; } @@ -266,7 +273,9 @@ describe('AutoTuneScreen', () => { // Panel opens as a dialog titled with the proposal name; members load from GET /members. expect(await screen.findByRole('dialog', { name: 'The Office' })).toBeInTheDocument(); expect(await screen.findByText('Parks and Rec')).toBeInTheDocument(); - expect(screen.getByText(/rotation weights/i)).toBeInTheDocument(); // #425 hint + // Each member row is now writable (#440): a weight stepper + an exclude toggle. + expect(screen.getByRole('spinbutton', { name: 'Weight for Parks and Rec' })).toHaveValue(1); + expect(screen.getByRole('button', { name: 'Exclude Parks and Rec' })).toBeInTheDocument(); }); it('threads per-channel edits (name, shuffle) into the create payload and flags the row Edited', async () => { @@ -339,4 +348,135 @@ describe('AutoTuneScreen', () => { expect(screen.queryByText('Edited')).not.toBeInTheDocument(); expect(screen.getByRole('checkbox', { name: 'The Office' })).toBeInTheDocument(); }); + + // ---- per-source weights / exclusions / add-untagged (#440 over #425's backend) ---- + + async function openSources() { + await openPreview(); + fireEvent.click(screen.getAllByRole('button', { name: 'Configure' })[0]); + await screen.findByRole('dialog', { name: 'The Office' }); + await screen.findByText('Parks and Rec'); + } + + function postedChannels(fetchSpy: ReturnType) { + const createCall = fetchSpy.mock.calls.find( + ([url, init]: [RequestInfo | URL, RequestInit | undefined]) => + url === '/api/v1/channels/auto-tune' && (init?.method ?? '').toUpperCase() === 'POST' + ); + return JSON.parse(String(createCall?.[1]?.body)).channels as { value: string; sources?: unknown }[]; + } + + it('threads per-source weights and exclusions into the create payload as `sources`', async () => { + const fetchSpy = mockAutoTuneApi(); + await openSources(); + + // Weight The Office 3× and drop Parks and Rec entirely. + fireEvent.change(screen.getByRole('spinbutton', { name: 'Weight for The Office' }), { target: { value: '3' } }); + fireEvent.click(screen.getByRole('button', { name: 'Exclude Parks and Rec' })); + // The toggle flips to the inverse action once excluded. + expect(screen.getByRole('button', { name: 'Include Parks and Rec' })).toBeInTheDocument(); + + // The pending corrections are visible on the row (screen-level draft, §11 "Edited" badge). + fireEvent.click(screen.getByRole('button', { name: 'Close' })); + expect(screen.getByText('Edited')).toBeInTheDocument(); + + fireEvent.click(screen.getByRole('button', { name: /Create 2 channels/ })); + await screen.findByText(/Added to group/); + + const office = postedChannels(fetchSpy).find((c) => c.value === 'The Office'); + expect(office?.sources).toEqual([ + { sourceId: 11, weight: 3, excluded: false }, + { sourceId: 12, weight: 1, excluded: true } + ]); + // An untouched proposal still sends no `sources` at all. + expect(postedChannels(fetchSpy).find((c) => c.value === 'Comedy')).toEqual({ + axis: 'TvGenre', + value: 'Comedy', + name: 'Comedy', + number: '502' + }); + }); + + it('omits `sources` when every weight is left at (or returned to) the fair-share default', async () => { + const fetchSpy = mockAutoTuneApi(); + await openSources(); + + const weight = screen.getByRole('spinbutton', { name: 'Weight for The Office' }); + fireEvent.change(weight, { target: { value: '4' } }); + fireEvent.change(weight, { target: { value: '1' } }); + + fireEvent.click(screen.getByRole('button', { name: 'Close' })); + // Back at fair-share, so the row is not "Edited" and the request stays clean. + expect(screen.queryByText('Edited')).not.toBeInTheDocument(); + + fireEvent.click(screen.getByRole('button', { name: /Create 2 channels/ })); + await screen.findByText(/Added to group/); + + expect(postedChannels(fetchSpy).every((channel) => !('sources' in channel))).toBe(true); + }); + + it('clamps an out-of-range weight on blur and again at save', async () => { + const fetchSpy = mockAutoTuneApi(); + await openSources(); + + const weight = screen.getByRole('spinbutton', { name: 'Weight for The Office' }); + + // Blur clamp: immediate feedback in the field itself. + fireEvent.change(weight, { target: { value: '5000' } }); + fireEvent.blur(weight); + expect(screen.getByRole('spinbutton', { name: 'Weight for The Office' })).toHaveValue(1000); + + // Save clamp: a value that never got blurred is still clamped before it reaches the server. + fireEvent.change(screen.getByRole('spinbutton', { name: 'Weight for The Office' }), { target: { value: '9999' } }); + fireEvent.click(screen.getByRole('button', { name: 'Close' })); + fireEvent.click(screen.getByRole('button', { name: /Create 2 channels/ })); + await screen.findByText(/Added to group/); + + const office = postedChannels(fetchSpy).find((c) => c.value === 'The Office'); + expect(office?.sources).toEqual([{ sourceId: 11, weight: 1000, excluded: false }]); + }); + + it('adds an untagged source from the library search and sends its id', async () => { + const fetchSpy = mockAutoTuneApi(); + await openSources(); + + fireEvent.change(screen.getByRole('textbox', { name: 'Add a show not in this axis' }), { target: { value: 'Dark' } }); + + // Debounced search resolves to a show outside the axis; picking it adds a row. + fireEvent.click(await screen.findByRole('button', { name: /Dark Matter/ })); + + // Typed text is compiled to a substring title match — the index's default field does not match + // bare title words, so forwarding the raw text would silently return nothing. + const searchCall = fetchSpy.mock.calls.find(([url]: [RequestInfo | URL, RequestInit | undefined]) => + String(url).startsWith('/api/v1/search?') + ); + expect(String(searchCall?.[0])).toContain(`query=${encodeURIComponent('title:*Dark*')}`); + expect(screen.getByRole('spinbutton', { name: 'Weight for Dark Matter' })).toBeInTheDocument(); + expect(screen.getByText('Added')).toBeInTheDocument(); + + fireEvent.change(screen.getByRole('spinbutton', { name: 'Weight for Dark Matter' }), { target: { value: '2' } }); + fireEvent.click(screen.getByRole('button', { name: 'Close' })); + fireEvent.click(screen.getByRole('button', { name: /Create 2 channels/ })); + await screen.findByText(/Added to group/); + + const office = postedChannels(fetchSpy).find((c) => c.value === 'The Office'); + expect(office?.sources).toEqual([{ sourceId: 99, weight: 2, excluded: false }]); + }); + + it('removes an added source again, leaving the base members untouched', async () => { + const fetchSpy = mockAutoTuneApi(); + await openSources(); + + fireEvent.change(screen.getByRole('textbox', { name: 'Add a show not in this axis' }), { target: { value: 'Dark' } }); + fireEvent.click(await screen.findByRole('button', { name: /Dark Matter/ })); + fireEvent.click(screen.getByRole('button', { name: 'Remove Dark Matter' })); + expect(screen.queryByRole('spinbutton', { name: 'Weight for Dark Matter' })).not.toBeInTheDocument(); + + fireEvent.click(screen.getByRole('button', { name: 'Close' })); + expect(screen.queryByText('Edited')).not.toBeInTheDocument(); + + fireEvent.click(screen.getByRole('button', { name: /Create 2 channels/ })); + await screen.findByText(/Added to group/); + expect(postedChannels(fetchSpy).every((channel) => !('sources' in channel))).toBe(true); + }); }); diff --git a/web/src/screens/AutoTuneScreen.tsx b/web/src/screens/AutoTuneScreen.tsx index 57a596495..08224729b 100644 --- a/web/src/screens/AutoTuneScreen.tsx +++ b/web/src/screens/AutoTuneScreen.tsx @@ -6,6 +6,7 @@ import { Circle, Clapperboard, Eye, + EyeOff, Film, FolderTree, Hash, @@ -14,16 +15,33 @@ import { ListOrdered, MinusCircle, Pencil, + Plus, RotateCcw, + Search, SearchX, Settings2, Shuffle, Sparkles, TriangleAlert, + Trash2, Tv, XCircle } from 'lucide-react'; -import { Badge, Button, ChannelLogo, Checkbox, Input, Select, SlideOver, Spinner, Stat, Switch, Tag, Tooltip } from '../components'; +import { + Badge, + Button, + ChannelLogo, + Checkbox, + IconButton, + Input, + Select, + SlideOver, + Spinner, + Stat, + Switch, + Tag, + Tooltip +} from '../components'; import { createAutoTunedChannels, getAutoTuneChannelMembers, @@ -31,9 +49,11 @@ import { getDefaultChannelTemplate, getFFmpegProfiles, getFillerPresets, + getSearchResults, getWatermarks, messageFromAutoTuneError, messageFromChannelTemplateError, + messageFromSearchError, uploadArtwork, previewAutoTune, type AutoTuneAxis, @@ -41,6 +61,7 @@ import { type AutoTuneMember, type AutoTuneProposal, type AutoTuneResult, + type AutoTuneSourceWeightRequest, type ChannelTemplate, type FFmpegProfile, type FillerPreset, @@ -102,12 +123,50 @@ const monoStyle: CSSProperties = { fontFamily: 'var(--font-mono)', fontVariantNu // space separates it unambiguously from the metadata value. const proposalKey = (proposal: { axis: string; value: string }) => `${proposal.axis} ${proposal.value}`; +// Per-source weight bounds. Mirrors the server's MultiCollectionItemWeight validator (1..1000) — +// the same bound the multi-collection editor enforces (#404) and the one #425's auto-tune handler +// clamps to. Clamp client-side on blur AND again at save so an out-of-range value never reaches the +// server as a raw 400 (spa-conventions §4a). +const WEIGHT_MIN = 1; +const WEIGHT_MAX = 1000; + +// Coerce a free-text weight to a valid integer share: empty / non-numeric / out-of-range all snap +// into [1,1000], with 1 (the floor, = fair share) for a blank or invalid field. +function clampWeight(raw: string): number { + const parsed = Math.trunc(Number(raw)); + if (!Number.isFinite(parsed)) { + return WEIGHT_MIN; + } + return Math.min(WEIGHT_MAX, Math.max(WEIGHT_MIN, parsed)); +} + +// One per-source correction in the draft, keyed by the member's source id (a show id on the TV axes, +// a movie id on MovieGenre — the ids GET /channels/auto-tune/members returns). `weight` is held as a +// string so the number field edits smoothly (transient empty/partial values), clamped on blur and at +// save. `addedTitle` is set only for an add-untagged source — one that is NOT in the axis's base set, +// so the members list can't supply its title/artwork for the row. +interface SourceDraft { + weight: string; + excluded: boolean; + addedTitle?: string; + addedArtwork?: string; +} + +const defaultSourceDraft = (): SourceDraft => ({ weight: String(WEIGHT_MIN), excluded: false }); + +// A source only counts as customized when it actually diverges from fair-share: a non-default weight, +// an exclusion, or an added out-of-axis id. This is exactly the server's `customized` predicate in +// CreateAutoTunedChannelsHandler.BuildWeightedPlan — an all-default list is a no-op there, so we keep +// it off the wire entirely rather than send noise. +const sourceCustomized = (draft: SourceDraft): boolean => + draft.excluded || draft.addedTitle != null || clampWeight(draft.weight) !== WEIGHT_MIN; + // A per-channel edit accumulated in the Preview step's DetailPanel, keyed by proposalKey. // Everything is optional/inherited: an unset field falls back to the proposal default or the // (per-channel-or-batch) template. playbackOrder + playoutMode mirror the Channel Builder's // dedicated-state model (see builder/advancedOptions ADVANCED_KEYS comment) — the Shuffle and // Always-playing toggles — and are merged into `advanced` only when the user diverges from the -// template default. Per-source rotation weights + query corrections are #425, not modelled here. +// template default. `sources` carries the #425 per-source weights / corrections, keyed by source id. interface ChannelOverride { name?: string; number?: string; @@ -117,10 +176,28 @@ interface ChannelOverride { playbackOrder?: PlaybackOrder; playoutMode?: PlayoutMode; advanced: Overrides; + sources?: Record; } const emptyOverride = (): ChannelOverride => ({ advanced: {} }); +// Draft → request mapping for the #425 `sources` array. Only genuinely customized sources are sent +// (an all-default array is a backend no-op, so omitting it keeps the request clean and keeps the +// channel on the cheaper single-SmartCollection fair-share shape). Returns undefined when nothing +// was customized. Weights are clamped here too — the blur clamp is feedback, this one is +// authoritative (a value can reach save unblurred). +function sourcesRequest(override: ChannelOverride | undefined): AutoTuneSourceWeightRequest[] | undefined { + const entries = Object.entries(override?.sources ?? {}).filter(([, draft]) => sourceCustomized(draft)); + if (entries.length === 0) { + return undefined; + } + return entries.map(([id, draft]) => ({ + sourceId: Number(id), + weight: clampWeight(draft.weight), + excluded: draft.excluded + })); +} + // True when the user actually diverged this proposal from its defaults (drives the "Edited" // row badge + the unsaved-changes guard). A name/number equal to the proposal default does // not count as edited. @@ -138,7 +215,10 @@ function overrideEdited(override: ChannelOverride | undefined, proposal: AutoTun override.logoFile || override.playbackOrder != null || override.playoutMode != null || - Object.keys(override.advanced).length > 0 + Object.keys(override.advanced).length > 0 || + // A weight/exclusion/added source only counts once it diverges from fair-share, mirroring the + // cleared-name rule above: a source row touched and set back to weight 1 is not an edit. + sourcesRequest(override) != null ); } @@ -340,6 +420,12 @@ export function AutoTuneScreen() { if (Object.keys(advanced).length > 0) { channel.advanced = advanced as AutoTunedChannelRequest['advanced']; } + // Per-source weights / exclusions / added sources (#425). Omitted entirely when nothing was + // customized so the server keeps the fair-share single-SmartCollection shape. + const sources = sourcesRequest(override); + if (sources) { + channel.sources = sources; + } return channel; }) ); @@ -1183,35 +1269,22 @@ function DetailPanel({ onPatchAdvanced: (updater: (prev: Overrides) => Overrides) => void; onClose: () => void; }) { - const [membersState, setMembersState] = useState({ status: 'loading' }); const [advancedOpen, setAdvancedOpen] = useState(false); const fileInputRef = useRef(null); - const activeRef = useRef(true); - useEffect(() => { - activeRef.current = true; - return () => { - activeRef.current = false; - }; - }, []); + // Per-source draft writers (#440). Each lazily materializes a fair-share draft for the row, so a + // source only enters `sources` once it is actually touched. + const patchSource = (id: number, delta: Partial) => + onPatch((current) => ({ + sources: { ...current.sources, [id]: { ...defaultSourceDraft(), ...current.sources?.[id], ...delta } } + })); - // Load the distinct members this proposal's smart collection resolves to (#384). The parent - // keys the panel by proposalKey, so it remounts per proposal and `membersState` starts at - // 'loading' each time — the effect never sets state synchronously (spa-conventions §3), only in - // the fetch callbacks. - useEffect(() => { - getAutoTuneChannelMembers({ axis: proposal.axis as AutoTuneAxis, value: proposal.value, pageNum: 0, pageSize: MEMBER_PREVIEW_SIZE }) - .then((page) => { - if (activeRef.current) { - setMembersState({ status: 'success', totalCount: page.totalCount, members: page.page ?? [] }); - } - }) - .catch((error: unknown) => { - if (activeRef.current) { - setMembersState({ status: 'error', message: messageFromAutoTuneError(error, 'Unable to load content sources') }); - } - }); - }, [proposal.axis, proposal.value]); + const removeSource = (id: number) => + onPatch((current) => { + const next = { ...current.sources }; + delete next[id]; + return { sources: next }; + }); const readImage = (file: File | null | undefined) => { if (!file) { @@ -1378,62 +1451,219 @@ function DetailPanel({ - - ); }