From 6bff2055b4d935023c165b36ad38f61d9b42bf6e Mon Sep 17 00:00:00 2001 From: Mohammed Abad Date: Fri, 3 Apr 2026 17:49:16 +0100 Subject: [PATCH] fix: season episode dialog, mark season watched, episode 404 handling Seasons Page: - Episode watch button now opens EpisodeSeenEditDialog instead of directly marking as watched, allowing date/seen-with input - Added "Mark Season as Watched" button that sequentially marks all unwatched episodes in the season Episode Page: - Fixed UI not updating after deleting the last episode seen record; the backend returns 404 when no records exist for an episode, which caused the query to error instead of resolving to an empty array. The API layer now catches 404 and returns [] gracefully. --- backend/controllers/entrySeenController.js | 4 - backend/routes/entry-seen.routes.js | 6 +- react_frontend/src/api/entry-seen.ts | 8 +- react_frontend/src/api/episode-seen.ts | 6 +- .../dialogs/EpisodeSeenEditDialog.tsx | 10 ++ .../dialogs/MovieWatchHistoryDialog.tsx | 81 +++++++++++++ .../components/entries/SeasonsContainer.tsx | 109 ++++++++++-------- react_frontend/src/hooks/useEpisodeSeen.ts | 6 + react_frontend/src/pages/EntryDetailsPage.tsx | 45 ++++++++ react_frontend/src/pages/EpisodePage.tsx | 2 + react_frontend/src/pages/LibraryPage.tsx | 95 +++++++++++---- react_frontend/src/pages/SeasonPage.tsx | 98 ++++++++++++++-- 12 files changed, 380 insertions(+), 90 deletions(-) create mode 100644 react_frontend/src/components/dialogs/MovieWatchHistoryDialog.tsx diff --git a/backend/controllers/entrySeenController.js b/backend/controllers/entrySeenController.js index 9e4fbcd..e510a93 100644 --- a/backend/controllers/entrySeenController.js +++ b/backend/controllers/entrySeenController.js @@ -54,10 +54,6 @@ class EntrySeenController { } - async getEntrySeensByEntryId(req, res) { - - } - async updateEntrySeen(req, res) { const { date_seen, seen_with } = req.body; const updated = await EntrySeen.update({ date_seen, seen_with }, { where: { id: req.params.id } }); diff --git a/backend/routes/entry-seen.routes.js b/backend/routes/entry-seen.routes.js index a284f27..d3d1b72 100644 --- a/backend/routes/entry-seen.routes.js +++ b/backend/routes/entry-seen.routes.js @@ -7,15 +7,15 @@ const entrySeenController = require('../controllers/entrySeenController'); // * GET - ALL ENTRY SEEN entrySeenRouter.get('/', entrySeenController.getEntrySeens); +// * GET - ENTRY SEEN BY ENTRY ID (must be before /:id to avoid conflict) +entrySeenRouter.get('/by-entry/:entryId', entrySeenController.getEntrySeensByEntryId); + // * GET - ENTRY SEEN BY ID entrySeenRouter.get('/:id', entrySeenController.getEntrySeenById); // * POST - CREATE ENTRY SEEN entrySeenRouter.post('/', entrySeenController.createEntrySeen); -// * GET - ENTRY SEEN BY ENTRY ID -entrySeenRouter.get('/by-entry/:entryId', entrySeenController.getEntrySeensByEntryId); - // * PUT - UPDATE ENTRY SEEN entrySeenRouter.put('/:id', entrySeenController.updateEntrySeen); diff --git a/react_frontend/src/api/entry-seen.ts b/react_frontend/src/api/entry-seen.ts index 28f86ec..4a3894b 100644 --- a/react_frontend/src/api/entry-seen.ts +++ b/react_frontend/src/api/entry-seen.ts @@ -8,7 +8,13 @@ export const entrySeenApi = { api.get(`/entry-seen/${id}`).then((r) => r.data), getByEntry: (entryId: number) => - api.get(`/entry-seen/by-entry/${entryId}`).then((r) => r.data), + api + .get(`/entry-seen/by-entry/${entryId}`) + .then((r) => r.data) + .catch((err) => { + if (err?.response?.status === 404) return [] as EntrySeen[]; + throw err; + }), create: (data: { entry_id: number; date_seen: string; seen_with?: string }) => api.post('/entry-seen', data).then((r) => r.data), diff --git a/react_frontend/src/api/episode-seen.ts b/react_frontend/src/api/episode-seen.ts index 3e5645e..91e09d1 100644 --- a/react_frontend/src/api/episode-seen.ts +++ b/react_frontend/src/api/episode-seen.ts @@ -10,7 +10,11 @@ export const episodeSeenApi = { getByEpisode: (episodeId: number) => api .get(`/episode-seen/by-episode/${episodeId}`) - .then((r) => r.data), + .then((r) => r.data) + .catch((err) => { + if (err?.response?.status === 404) return [] as EpisodeSeen[]; + throw err; + }), create: (data: { entry_id: number; diff --git a/react_frontend/src/components/dialogs/EpisodeSeenEditDialog.tsx b/react_frontend/src/components/dialogs/EpisodeSeenEditDialog.tsx index 22affc5..d9f7696 100644 --- a/react_frontend/src/components/dialogs/EpisodeSeenEditDialog.tsx +++ b/react_frontend/src/components/dialogs/EpisodeSeenEditDialog.tsx @@ -20,7 +20,10 @@ interface EpisodeSeenEditDialogProps { /** Required for create mode */ episodeId?: number; entryId: number; + seasonId?: number; mode?: 'create' | 'edit'; + /** If provided, called instead of the normal create/update mutation */ + overrideSubmit?: (date: string, seenWith: string) => void; } export function EpisodeSeenEditDialog({ @@ -29,7 +32,9 @@ export function EpisodeSeenEditDialog({ record, episodeId, entryId, + seasonId, mode = record ? 'edit' : 'create', + overrideSubmit, }: EpisodeSeenEditDialogProps) { const today = new Date().toISOString().split('T')[0]; const [date, setDate] = useState(record?.date_seen?.split('T')[0] ?? today); @@ -39,6 +44,10 @@ export function EpisodeSeenEditDialog({ const createEpisodeSeen = useCreateEpisodeSeen(); const handleSave = () => { + if (overrideSubmit) { + overrideSubmit(date, seenWith); + return; + } if (mode === 'edit' && record) { updateEpisodeSeen.mutate({ id: record.id, @@ -57,6 +66,7 @@ export function EpisodeSeenEditDialog({ episode_id: epId, date_seen: date, seen_with: seenWith || undefined, + season_id: seasonId, }); } onOpenChange(false); diff --git a/react_frontend/src/components/dialogs/MovieWatchHistoryDialog.tsx b/react_frontend/src/components/dialogs/MovieWatchHistoryDialog.tsx new file mode 100644 index 0000000..21387d6 --- /dev/null +++ b/react_frontend/src/components/dialogs/MovieWatchHistoryDialog.tsx @@ -0,0 +1,81 @@ +import { format } from 'date-fns'; +import { + Dialog, + DialogContent, + DialogHeader, + DialogTitle, +} from '@/components/ui/dialog'; +import { Button } from '@/components/ui/button'; +import { Trash2 } from 'lucide-react'; +import type { EntrySeen } from '@/types'; + +interface MovieWatchHistoryDialogProps { + open: boolean; + onOpenChange: (open: boolean) => void; + entryId: number; + watchHistory: EntrySeen[]; + onDelete: (seenId: number) => void; +} + +export function MovieWatchHistoryDialog({ + open, + onOpenChange, + watchHistory, + onDelete, +}: MovieWatchHistoryDialogProps) { + return ( + + + + Watch History + + {watchHistory.length === 0 ? ( +

+ No watch history yet. +

+ ) : ( +
+ + + + + + + + + + {watchHistory.map((record) => ( + + + + + + ))} + +
DateSeen WithActions
+ {record.date_seen + ? format(new Date(record.date_seen), 'MMM d, yyyy') + : '-'} + + {record.seen_with || '-'} + +
+ +
+
+
+ )} +
+
+ ); +} diff --git a/react_frontend/src/components/entries/SeasonsContainer.tsx b/react_frontend/src/components/entries/SeasonsContainer.tsx index ba466da..06cc660 100644 --- a/react_frontend/src/components/entries/SeasonsContainer.tsx +++ b/react_frontend/src/components/entries/SeasonsContainer.tsx @@ -3,8 +3,8 @@ import { Link } from 'react-router-dom'; import { ChevronDown, ChevronUp, Play } from 'lucide-react'; import { Button } from '@/components/ui/button'; import { Progress } from '@/components/ui/progress'; +import { EpisodeSeenEditDialog } from '@/components/dialogs/EpisodeSeenEditDialog'; import { getYear, getTmdbPosterUrl } from '@/lib/media-utils'; -import { useCreateEpisodeSeen } from '@/hooks/useEpisodeSeen'; import type { Season } from '@/types'; interface SeasonsContainerProps { @@ -65,7 +65,7 @@ function SeasonItem({ season: Season; entryId: number; }) { - const createEpisodeSeen = useCreateEpisodeSeen(); + const [dialogOpen, setDialogOpen] = useState(false); const watchedCount = season.episodes?.filter( (ep) => ep.date_first_seen || (ep.episodeSeens && ep.episodeSeens.length > 0) @@ -79,56 +79,63 @@ function SeasonItem({ .find((ep) => !ep.date_first_seen && (!ep.episodeSeens || ep.episodeSeens.length === 0)); return ( - - {/* Poster thumbnail */} -
- {season.name} + + {/* Poster thumbnail */} +
+ {season.name} +
+ + {/* Info */} +
+
+ {season.name} + + {getYear(season.air_date)} + +
+
+ + + {watchedCount}/{totalEpisodes} + +
+
+ + {/* Quick watch button - opens dialog */} + {nextUnwatched && ( + + )} + + + {nextUnwatched && dialogOpen && ( + -
- - {/* Info */} -
-
- {season.name} - - {getYear(season.air_date)} - -
-
- - - {watchedCount}/{totalEpisodes} - -
-
- - {/* Quick watch button */} - {nextUnwatched && ( - )} - + ); } diff --git a/react_frontend/src/hooks/useEpisodeSeen.ts b/react_frontend/src/hooks/useEpisodeSeen.ts index 223273c..89b1659 100644 --- a/react_frontend/src/hooks/useEpisodeSeen.ts +++ b/react_frontend/src/hooks/useEpisodeSeen.ts @@ -27,6 +27,7 @@ export function useCreateEpisodeSeen() { episode_id: number; date_seen: string; seen_with?: string; + season_id?: number; }) => episodeSeenApi.create(data), onSuccess: (_data, variables) => { queryClient.invalidateQueries({ @@ -38,6 +39,11 @@ export function useCreateEpisodeSeen() { queryClient.invalidateQueries({ queryKey: entryKeys.seasons(variables.entry_id), }); + if (variables.season_id) { + queryClient.invalidateQueries({ + queryKey: seasonKeys.episodes(variables.season_id), + }); + } toast.success('Episode marked as watched'); }, onError: () => { diff --git a/react_frontend/src/pages/EntryDetailsPage.tsx b/react_frontend/src/pages/EntryDetailsPage.tsx index 31b823d..4813430 100644 --- a/react_frontend/src/pages/EntryDetailsPage.tsx +++ b/react_frontend/src/pages/EntryDetailsPage.tsx @@ -25,6 +25,7 @@ import { Settings, Star, Loader2, + History, } from 'lucide-react'; import { Tooltip, @@ -40,6 +41,7 @@ import { EntrySeenDialog } from '@/components/dialogs/EntrySeenDialog'; import { EntryMediaDialog } from '@/components/dialogs/EntryMediaDialog'; import { AddEntryToCollectionDialog } from '@/components/dialogs/AddEntryToCollectionDialog'; import { RatingDialog } from '@/components/dialogs/RatingDialog'; +import { MovieWatchHistoryDialog } from '@/components/dialogs/MovieWatchHistoryDialog'; import { EntryDetailsSkeleton } from '@/components/skeletons/PageSkeletons'; import { getPosterUrl, @@ -73,6 +75,7 @@ export function EntryDetailsPage() { const [showMediaDialog, setShowMediaDialog] = useState(false); const [showCollectionDialog, setShowCollectionDialog] = useState(false); const [showRatingDialog, setShowRatingDialog] = useState(false); + const [showWatchHistoryDialog, setShowWatchHistoryDialog] = useState(false); if (isLoading || !displayEntry) { return ; @@ -155,6 +158,12 @@ export function EntryDetailsPage() { Rate this + {!e.is_tvseries && ( + setShowWatchHistoryDialog(true)}> + + Watch History + + )} updateEntry.mutate({ id: e.id, data: { hidden: !e.hidden } }) @@ -241,6 +250,31 @@ export function EntryDetailsPage() { {formatRuntime(e.runtime)} )} + {!e.is_tvseries && watchHistory.length > 0 && ( + <> + • + {watchHistory.length === 1 ? ( + seen {formatDate(watchHistory[0].date_seen)} + ) : ( + + + + + seen {watchHistory.length} times + + + +
+ {watchHistory.map((wh) => ( +

{formatDate(wh.date_seen)}

+ ))} +
+
+
+
+ )} + + )} {/* Genres */} @@ -372,6 +406,17 @@ export function EntryDetailsPage() { entry={e} /> )} + {showWatchHistoryDialog && ( + + deleteEntrySeen.mutate({ id: seenId, entryId: e.id }) + } + /> + )} ); } diff --git a/react_frontend/src/pages/EpisodePage.tsx b/react_frontend/src/pages/EpisodePage.tsx index c80741f..5736f74 100644 --- a/react_frontend/src/pages/EpisodePage.tsx +++ b/react_frontend/src/pages/EpisodePage.tsx @@ -172,6 +172,7 @@ export function EpisodePage() { mode="create" episodeId={episode.id} entryId={entryIdNum} + seasonId={parseInt(seasonId!, 10)} /> )} @@ -183,6 +184,7 @@ export function EpisodePage() { mode="edit" record={editRecord} entryId={entryIdNum} + seasonId={parseInt(seasonId!, 10)} /> )} diff --git a/react_frontend/src/pages/LibraryPage.tsx b/react_frontend/src/pages/LibraryPage.tsx index ce3b080..e9ec703 100644 --- a/react_frontend/src/pages/LibraryPage.tsx +++ b/react_frontend/src/pages/LibraryPage.tsx @@ -1,4 +1,5 @@ -import { useState, useMemo, useCallback } from 'react'; +import { useState, useMemo, useCallback, useEffect, useRef } from 'react'; +import { useSearchParams } from 'react-router-dom'; import { useLibrary } from '@/hooks/useEntries'; import { useLibraryEntries } from '@/stores/useLibraryStore'; import { EntryLibraryGrid } from '@/components/entries/EntryLibraryGrid'; @@ -44,8 +45,8 @@ function sortEntries(entries: Entry[], field: SortField, dir: SortDir): Entry[] cmp = new Date(a.release_date || '1900').getTime() - new Date(b.release_date || '1900').getTime(); break; case 'rating': - cmp = (a.entryRatings?.user_rating || a.entryRatings?.tmdb_rating || 0) - - (b.entryRatings?.user_rating || b.entryRatings?.tmdb_rating || 0); + cmp = (a.entryRatings?.user_rating ?? 0) - + (b.entryRatings?.user_rating ?? 0); break; case 'date_last_seen': cmp = new Date(a.date_last_seen || '1900').getTime() - new Date(b.date_last_seen || '1900').getTime(); @@ -58,16 +59,56 @@ function sortEntries(entries: Entry[], field: SortField, dir: SortDir): Entry[] }); } +const PAGE_SIZE = 28; + export function LibraryPage() { const { isLoading } = useLibrary(); + const [searchParams, setSearchParams] = useSearchParams(); const [activeTab, setActiveTab] = useState('all'); const [search, setSearch] = useState(''); + const [debouncedSearch, setDebouncedSearch] = useState(''); const [sortField, setSortField] = useState('date_last_seen'); const [sortDir, setSortDir] = useState('desc'); const [filters, setFilters] = useState(defaultFilters); + const [debouncedFilters, setDebouncedFilters] = useState(defaultFilters); + const [visibleCount, setVisibleCount] = useState(PAGE_SIZE); + const filtersInitialized = useRef(false); const allEntries = useLibraryEntries(); + // Read URL query params once on mount + useEffect(() => { + if (filtersInitialized.current) return; + filtersInitialized.current = true; + const genre = searchParams.get('genre') || ''; + const ratingMin = searchParams.get('ratingMin') || ''; + const ratingMax = searchParams.get('ratingMax') || ''; + if (genre || ratingMin || ratingMax) { + const newFilters = { ...defaultFilters, genre, ratingMin, ratingMax }; + setFilters(newFilters); + setDebouncedFilters(newFilters); + // Clear URL params after applying + setSearchParams({}, { replace: true }); + } + }, [searchParams, setSearchParams]); + + // Debounce search + useEffect(() => { + const timer = setTimeout(() => setDebouncedSearch(search), 300); + return () => clearTimeout(timer); + }, [search]); + + // Debounce filters + useEffect(() => { + const timer = setTimeout(() => setDebouncedFilters(filters), 300); + return () => clearTimeout(timer); + }, [filters]); + + // Reset visible count when filters/search/tab/sort change + useEffect(() => { + setVisibleCount(PAGE_SIZE); + }, [activeTab, debouncedSearch, debouncedFilters, sortField, sortDir]); + // Gather unique genres from the library const allGenres = useMemo(() => { const set = new Set(); @@ -95,33 +136,40 @@ export function LibraryPage() { const filteredEntries = useMemo(() => { let result = baseEntries; - if (search) { - const q = search.toLowerCase(); + if (debouncedSearch) { + const q = debouncedSearch.toLowerCase(); result = result.filter((e) => e.title.toLowerCase().includes(q)); } - if (filters.genre) { - result = result.filter((e) => e.genres?.some((g) => g.name === filters.genre)); + if (debouncedFilters.genre) { + result = result.filter((e) => e.genres?.some((g) => g.name === debouncedFilters.genre)); } - if (filters.ratingMin) { - const min = parseFloat(filters.ratingMin); - result = result.filter((e) => (e.entryRatings?.user_rating || e.entryRatings?.tmdb_rating || 0) >= min); + if (debouncedFilters.ratingMin) { + const min = parseFloat(debouncedFilters.ratingMin); + result = result.filter((e) => (e.entryRatings?.user_rating ?? 0) >= min); } - if (filters.ratingMax) { - const max = parseFloat(filters.ratingMax); - result = result.filter((e) => (e.entryRatings?.user_rating || e.entryRatings?.tmdb_rating || 0) <= max); + if (debouncedFilters.ratingMax) { + const max = parseFloat(debouncedFilters.ratingMax); + result = result.filter((e) => (e.entryRatings?.user_rating ?? 0) <= max); } - if (filters.yearMin) { - const min = parseInt(filters.yearMin); + if (debouncedFilters.yearMin) { + const min = parseInt(debouncedFilters.yearMin); result = result.filter((e) => e.release_date && new Date(e.release_date).getFullYear() >= min); } - if (filters.yearMax) { - const max = parseInt(filters.yearMax); + if (debouncedFilters.yearMax) { + const max = parseInt(debouncedFilters.yearMax); result = result.filter((e) => e.release_date && new Date(e.release_date).getFullYear() <= max); } return sortEntries(result, sortField, sortDir); - }, [baseEntries, search, filters, sortField, sortDir]); + }, [baseEntries, debouncedSearch, debouncedFilters, sortField, sortDir]); + + const paginatedEntries = useMemo( + () => filteredEntries.slice(0, visibleCount), + [filteredEntries, visibleCount] + ); + const hasMore = visibleCount < filteredEntries.length; + const loadMore = useCallback(() => setVisibleCount((c) => c + PAGE_SIZE), []); const clearFilters = useCallback(() => setFilters(defaultFilters), []); @@ -214,7 +262,7 @@ export function LibraryPage() {
- setFilters((f) => ({ ...f, genre: v === '_all' ? '' : (v || '') }))}> All genres @@ -325,7 +373,7 @@ export function LibraryPage() {
- setFilters((f) => ({ ...f, genre: v === '_all' ? '' : (v || '') }))}> All genres @@ -367,7 +415,12 @@ export function LibraryPage() {
- +
); } diff --git a/react_frontend/src/pages/SeasonPage.tsx b/react_frontend/src/pages/SeasonPage.tsx index 320cd45..53507b6 100644 --- a/react_frontend/src/pages/SeasonPage.tsx +++ b/react_frontend/src/pages/SeasonPage.tsx @@ -1,12 +1,16 @@ +import { useState } from 'react'; import { useParams, Link } from 'react-router-dom'; import { useSeason, useSeasonEpisodes } from '@/hooks/useSeasons'; import { useCreateEpisodeSeen } from '@/hooks/useEpisodeSeen'; +import { EpisodeSeenEditDialog } from '@/components/dialogs/EpisodeSeenEditDialog'; +import { ConfirmDialog } from '@/components/dialogs/ConfirmDialog'; import { Skeleton } from '@/components/ui/skeleton'; import { Progress } from '@/components/ui/progress'; import { Badge } from '@/components/ui/badge'; import { Button } from '@/components/ui/button'; -import { Eye, CheckCircle2 } from 'lucide-react'; +import { Eye, CheckCircle2, ListChecks } from 'lucide-react'; import { getTmdbPosterUrl, getYear, formatDate } from '@/lib/media-utils'; +import type { Episode } from '@/types'; export function SeasonPage() { const { entryId, seasonId } = useParams<{ @@ -16,6 +20,12 @@ export function SeasonPage() { const { data: season, isLoading } = useSeason(parseInt(seasonId!, 10)); const { data: episodes = [] } = useSeasonEpisodes(parseInt(seasonId!, 10)); const createEpisodeSeen = useCreateEpisodeSeen(); + const [dialogEpisode, setDialogEpisode] = useState(null); + const [markingAll, setMarkingAll] = useState(false); + const [showMarkAllDialog, setShowMarkAllDialog] = useState(false); + const [markAllDate, setMarkAllDate] = useState(new Date().toISOString().split('T')[0]); + const [markAllSeenWith, setMarkAllSeenWith] = useState(''); + const [showMarkAllConfirm, setShowMarkAllConfirm] = useState(false); if (isLoading || !season) { return ( @@ -49,8 +59,23 @@ export function SeasonPage() { alt={season.name} className="h-56 w-36 shrink-0 rounded-lg object-cover shadow-lg" /> -
-

{season.name}

+
+
+

{season.name}

+ {/* Mark Season as Watched — top right */} + {watchedCount < totalEpisodes && ( + + )} +
Season {season.season_number} {season.air_date && ( @@ -144,14 +169,10 @@ export function SeasonPage() { ev.preventDefault(); ev.stopPropagation(); if (!isWatched) { - createEpisodeSeen.mutate({ - entry_id: parseInt(entryId!, 10), - episode_id: episode.id, - date_seen: new Date().toISOString(), - }); + setDialogEpisode(episode); } }} - disabled={isWatched || createEpisodeSeen.isPending} + disabled={isWatched} > @@ -160,6 +181,65 @@ export function SeasonPage() { })}
+ + {/* Episode Seen Dialog */} + {dialogEpisode && ( + { if (!open) setDialogEpisode(null); }} + mode="create" + episodeId={dialogEpisode.id} + entryId={parseInt(entryId!, 10)} + seasonId={parseInt(seasonId!, 10)} + /> + )} + + {/* Mark Season Watched — step 1: date/seen-with dialog */} + {showMarkAllDialog && ( + { + if (!open) setShowMarkAllDialog(false); + }} + mode="create" + episodeId={-1} + entryId={parseInt(entryId!, 10)} + seasonId={parseInt(seasonId!, 10)} + overrideSubmit={(date, seenWith) => { + setMarkAllDate(date); + setMarkAllSeenWith(seenWith); + setShowMarkAllDialog(false); + setShowMarkAllConfirm(true); + }} + /> + )} + + {/* Mark Season Watched — step 2: confirmation */} + !ep.date_first_seen && (!ep.episodeSeens || ep.episodeSeens.length === 0)).length} unwatched episodes as seen on ${markAllDate}. Continue?`} + confirmLabel="Mark All" + isLoading={markingAll} + onConfirm={async () => { + setMarkingAll(true); + const unwatched = episodes.filter( + (ep) => !ep.date_first_seen && (!ep.episodeSeens || ep.episodeSeens.length === 0) + ); + for (const ep of unwatched) { + await createEpisodeSeen.mutateAsync({ + entry_id: parseInt(entryId!, 10), + episode_id: ep.id, + date_seen: markAllDate, + seen_with: markAllSeenWith || undefined, + season_id: parseInt(seasonId!, 10), + }); + } + setMarkingAll(false); + setShowMarkAllConfirm(false); + }} + />
); }