From ce01dc34fa7df8ec0cbdddd38f29aca63bc40263 Mon Sep 17 00:00:00 2001 From: Mohammed Abad Date: Thu, 23 Apr 2026 16:51:18 +0100 Subject: [PATCH] feat(backend): fix credit duplicates, support multi-role TV credits, fix collection upload - Fix credit dedup key to people_id + cast_type (scoped to entry_id) - Detect aggregate_credits format via Array.isArray(c.roles) instead of is_tvseries flag - Join multiple roles/jobs with "; " instead of taking only the first - Add episode_count field to Credit model from total_episode_count - Increase character and job columns to VARCHAR(500) - Deselect existing collection posters/backdrops before inserting new upload - Updated docs-vault - Updated some agents files --- .../prompts/commit-from-milestone.prompt.md | 47 +++++ AGENTS.md | 2 +- CLAUDE.md | 1 + backend/controllers/collectionController.js | 16 +- backend/models/Credit.js | 9 +- backend/services/entryManager.js | 190 +++++++++++++++--- changes.md | 16 ++ docs-vault/Changelog.md | 18 ++ docs-vault/Collections.md | 3 + docs-vault/Components.md | 1 + docs-vault/Models.md | 8 +- docs-vault/Pages.md | 4 +- docs-vault/People.md | 7 +- docs-vault/Watch Tracking.md | 16 +- 14 files changed, 293 insertions(+), 45 deletions(-) create mode 100644 .github/prompts/commit-from-milestone.prompt.md create mode 100644 CLAUDE.md diff --git a/.github/prompts/commit-from-milestone.prompt.md b/.github/prompts/commit-from-milestone.prompt.md new file mode 100644 index 0000000..bd9fd49 --- /dev/null +++ b/.github/prompts/commit-from-milestone.prompt.md @@ -0,0 +1,47 @@ +--- +description: Generate backend & frontend commit messages from the latest milestone in changes.md +mode: ask +--- + +Read the file `changes.md` and find the **last `### Milestone` section** (the one closest to the end of the file). + +From that milestone, generate **two conventional-commit messages** — one for backend changes and one for frontend changes. + +## Rules + +1. **Format** — Use [Conventional Commits](https://www.conventionalcommits.org/): + + ``` + (): + + - detail 1 + - detail 2 + ``` + +2. **Types** — Pick the most fitting: `feat`, `fix`, `refactor`, `chore`, `docs`, `perf`, `style`. + If the milestone contains both features and fixes, prefer `feat` for the summary and list fixes in the body. +3. **Scope** — Use `backend` or `frontend` (include the docs/docs-vault with the backend). +4. **Summary line** — Max 72 characters, imperative mood, no period. +5. **Body bullets** — One bullet per change listed in the milestone. Keep them concise but preserve meaning. +6. **Output** — Return exactly two fenced code blocks labelled `Backend Commit` and `Frontend Commit`. Nothing else. + +## Example output + +```text +feat(backend): add episode_count to credits and fix duplicate inserts + +- Fix credit dedup key to people_id + cast_type (scoped to entry_id) +- Detect aggregate_credits format via Array.isArray(c.roles) +- Join multiple roles/jobs with "; " instead of taking only the first +- Add episode_count field to Credit model from total_episode_count +- Increase character and job columns to VARCHAR(500) +- Deselect old collection media before inserting new upload +``` + +```text +feat(frontend): add MarkSeasonWatchedDialog with scatter mode + +- Create MarkSeasonWatchedDialog replacing two-step flow +- Add scatter mode to distribute episodes across a date range +- Always show "Mark Season Watched" button +``` diff --git a/AGENTS.md b/AGENTS.md index 8ec9c18..5a739fb 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -38,7 +38,7 @@ Append a new section at the end of `changes.md` using this exact format: - If no task number is provided, use the next available number based on the last entry in the file. - Always ensure formatting matches exactly (heading + code block + bullets). -### Documentation +### Documentation (Skip the legacy docs, we're using obsidian docs-vault now) Update the `/backend/docs` and `/react_frontend/docs` folders with any relevant documentation changes related to the task you completed. This includes API documentation, architectural diagrams, or any other relevant docs. diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 0000000..9323e7d --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1 @@ +Checkout the `AGENTS.md` file for instructions on how to use Agents in this project. diff --git a/backend/controllers/collectionController.js b/backend/controllers/collectionController.js index 03211cf..01146a4 100644 --- a/backend/controllers/collectionController.js +++ b/backend/controllers/collectionController.js @@ -108,7 +108,7 @@ class CollectionController { }; if (posterPath) { - // ? generating preview + // ? generating preview _mediaOptimizerService.doGeneratePreview("collections", 'posters', posterPath).then((result) => { const msg = `Collection Service | Generated Collection Preview`; logToFile(msg); @@ -118,6 +118,12 @@ class CollectionController { logToFile(err); }); + // Deselect existing posters for this collection + await Media.update( + { isSelected: false }, + { where: { mediaable: 'collection', mediaableId: collectionId, type: 'poster', isSelected: true } } + ); + await Media.create({ mediaable: 'collection', mediaableId: collectionId, @@ -130,7 +136,7 @@ class CollectionController { } if (backdropPath) { - // ? generating preview + // ? generating preview _mediaOptimizerService.doGeneratePreview("collections", 'backdrops', backdropPath).then((result) => { const msg = `Collection Routes | Generated Collection Preview`; logToFile(msg); @@ -140,6 +146,12 @@ class CollectionController { logToFile(err); }); + // Deselect existing backdrops for this collection + await Media.update( + { isSelected: false }, + { where: { mediaable: 'collection', mediaableId: collectionId, type: 'backdrop', isSelected: true } } + ); + // ? inserting data await Media.create({ mediaable: 'collection', diff --git a/backend/models/Credit.js b/backend/models/Credit.js index 49afcc5..b86b31d 100644 --- a/backend/models/Credit.js +++ b/backend/models/Credit.js @@ -10,16 +10,17 @@ const Credit = sequelize.define("credits", adult: { type: DataTypes.BOOLEAN, defaultValue: false }, profile_path: { type: DataTypes.STRING(200), field: 'profile_path' }, - character: { type: DataTypes.STRING(100) }, + character: { type: DataTypes.STRING(500) }, order: { type: DataTypes.INTEGER }, - + episode_count: { type: DataTypes.INTEGER, defaultValue: null }, + cast_type: { type: DataTypes.ENUM('cast', 'crew'), field: 'cast_type', defaultValue: 'cast' }, department: { type: DataTypes.STRING(100) }, - job: { type: DataTypes.STRING(100) }, + job: { type: DataTypes.STRING(500) }, entry_id: { type: DataTypes.INTEGER, field: 'entry_id' }, people_id: { type: DataTypes.INTEGER, field: 'people_id' }, } ); -module.exports = Credit; \ No newline at end of file +module.exports = Credit; diff --git a/backend/services/entryManager.js b/backend/services/entryManager.js index 75c672a..e046c0e 100644 --- a/backend/services/entryManager.js +++ b/backend/services/entryManager.js @@ -157,7 +157,7 @@ class EntryManager { // * For TV-Series (Seasons & Episodes) if (oldEntry.is_tvseries) { // ? Only refrech if the series's status is not 'Ended' - // ? and atleast 48 hours has passed + // ? and atleast 48 hours has passed // * Update or insert seasons for the entry for (const season of entryData.seasons) { @@ -257,19 +257,30 @@ class EntryManager { } // * Credits - if (!oldEntry.cast_fetched || oldEntry.credits.length === 0) { + // if (!oldEntry.cast_fetched || oldEntry.credits.length === 0) { + if (true) { const creditData = await fetchEntryCredits(oldEntry.entryId.tmdb_id, oldEntry.is_tvseries); + if (!creditData) { throw new InternalServerError(`Couldn't fetch entry crew data`); } - const allCredits = [...creditData.cast.map(c => ({ ...c, cast_type: 'cast' })), - ...creditData.crew.map(c => ({ ...c, cast_type: 'crew' }))]; + const allCredits = [ + ...creditData.cast.map(c => ({ ...c, cast_type: "cast" })), + ...creditData.crew.map(c => ({ ...c, cast_type: "crew" })) + ]; const tmdbIds = [...new Set(allCredits.map(c => c.id))]; + + // ------------------------- + // FETCH EXISTING PEOPLE + // ------------------------- const existingPeopleList = await People.findAll({ where: { tmdb_id: tmdbIds } }); const existingPeopleMap = Object.fromEntries(existingPeopleList.map(p => [p.tmdb_id, p])); + // ------------------------- + // CREATE NEW PEOPLE + // ------------------------- const newPeopleData = tmdbIds .filter(id => !existingPeopleMap[id]) .map(id => { @@ -286,34 +297,157 @@ class EntryManager { }; }); + if (newPeopleData.length) { + console.log(`[PEOPLE] Adding ${newPeopleData.length} new people...`); + } + const createdPeople = await People.bulkCreate(newPeopleData); + for (const person of createdPeople) { + console.log(`[PEOPLE] Added: ${person.name} (tmdb_id=${person.tmdb_id})`); existingPeopleMap[person.tmdb_id] = person; } - const existingPeopleIds = new Set(oldEntry.credits.map(c => c.people_id)); + // ------------------------- + // UPDATE EXISTING PEOPLE POPULARITY + // ------------------------- + const peopleToUpdate = []; - const newCredits = allCredits - .map(c => { - const person = existingPeopleMap[c.id]; - if (existingPeopleIds.has(person.id)) return null; - return { - entry_id: oldEntry.id, - people_id: person.id, - tmdb_credit_id: c.credit_id, - character: c.cast_type === 'cast' ? c.character : null, - order: c.cast_type === 'cast' ? c.order : null, - profile_path: person.profile_path, - adult: person.adult, - cast_type: c.cast_type, - department: c.cast_type === 'crew' ? c.department || null : null, - job: c.cast_type === 'crew' ? c.job || null : null - }; - }) - .filter(Boolean); + for (const credit of allCredits) { + const existingPerson = existingPeopleMap[credit.id]; + if (!existingPerson) continue; - if (newCredits.length) { - await Credit.bulkCreate(newCredits); + // only update if changed + if (existingPerson.popularity !== credit.popularity) { + existingPerson.popularity = credit.popularity; + existingPerson.last_fetch = new Date(); + // TODO: update person photo and add a new field to track the last photo update + peopleToUpdate.push(existingPerson); + } + } + + if (peopleToUpdate.length) { + await People.bulkCreate( + peopleToUpdate.map(p => ({ + id: p.id, + tmdb_id: p.tmdb_id, + popularity: p.popularity, + last_fetch: p.last_fetch + })), + { + updateOnDuplicate: ["popularity", "last_fetch"] + } + ); + + console.log(`[PEOPLE] Updated popularity for ${peopleToUpdate.length} people`); + } + + // ------------------------- + // FETCH EXISTING CREDITS FOR ENTRY + // ------------------------- + const existingCreditsList = await Credit.findAll({ + where: { entry_id: oldEntry.id } + }); + + const existingCreditsMap = new Map(); + for (const credit of existingCreditsList) { + // unique key: people_id + cast_type (scoped to entry_id already) + existingCreditsMap.set(`${credit.people_id}_${credit.cast_type}`, credit); + } + + const creditsToInsert = []; + const creditsToUpdate = []; + + for (const c of allCredits) { + const person = existingPeopleMap[c.id]; + if (!person) continue; + + const key = `${person.id}_${c.cast_type}`; + const existingCredit = existingCreditsMap.get(key); + + // For TV series (aggregate_credits), character/job are nested inside roles[]/jobs[]. + // Detect TV format by presence of roles/jobs arrays rather than relying on is_tvseries. + const character = c.cast_type === "cast" + ? (Array.isArray(c.roles) + ? (c.roles.map(r => r.character).filter(Boolean).join("; ") || null) + : (c.character || null)) + : null; + + const job = c.cast_type === "crew" + ? (Array.isArray(c.jobs) + ? (c.jobs.map(j => j.job).filter(Boolean).join("; ") || null) + : (c.job || null)) + : null; + + const tmdbCreditId = Array.isArray(c.roles) + ? c.roles?.[0]?.credit_id + : Array.isArray(c.jobs) + ? c.jobs?.[0]?.credit_id + : c.credit_id; + + const newCreditData = { + entry_id: oldEntry.id, + people_id: person.id, + tmdb_credit_id: tmdbCreditId, + character, + order: c.cast_type === "cast" ? c.order : null, + episode_count: c.total_episode_count ?? null, + profile_path: person.profile_path, + adult: person.adult, + cast_type: c.cast_type, + department: c.cast_type === "crew" ? c.department || null : null, + job + }; + + if (!existingCredit) { + creditsToInsert.push(newCreditData); + console.log( + `[CREDIT] INSERT ${c.cast_type.toUpperCase()} -> ${person.name} (people_id=${person.id})` + ); + } else { + // check if update needed + let changed = false; + + if (existingCredit.order !== newCreditData.order) changed = true; + if (existingCredit.character !== newCreditData.character) changed = true; + if (existingCredit.department !== newCreditData.department) changed = true; + if (existingCredit.job !== newCreditData.job) changed = true; + if (existingCredit.episode_count !== newCreditData.episode_count) changed = true; + + if (changed) { + creditsToUpdate.push({ + id: existingCredit.id, + ...newCreditData + }); + + console.log( + `[CREDIT] UPDATE ${c.cast_type.toUpperCase()} -> ${person.name} (people_id=${person.id})` + ); + } + } + } + + // ------------------------- + // INSERT NEW CREDITS + // ------------------------- + if (creditsToInsert.length) { + await Credit.bulkCreate(creditsToInsert); + console.log(`[CREDITS] Inserted ${creditsToInsert.length} new credits for entry ${oldEntry.id}`); + } + + // ------------------------- + // UPDATE EXISTING CREDITS + // ------------------------- + if (creditsToUpdate.length) { + await Credit.bulkCreate(creditsToUpdate, { + updateOnDuplicate: ["order", "character", "episode_count", "department", "job", "profile_path", "adult"] + }); + + console.log(`[CREDITS] Updated ${creditsToUpdate.length} credits for entry ${oldEntry.id}`); + } + + if (!creditsToInsert.length && !creditsToUpdate.length) { + console.log(`[CREDITS] No changes for entry ${oldEntry.id}`); } } @@ -370,13 +504,13 @@ class EntryManager { /** * Retrieves an entry by its ID and refreshes it if needed. - * + * * An entry is refreshed if: * - It has never been fetched before (`last_fetch` is null or undefined), or * - The last fetch was more than 24 hours ago. - * + * * If a refresh is required, it logs the operation and calls `refrechEntryById`. - * + * * @async * @function getUpdatedEntry * @param {number} id - The ID of the entry to retrieve. diff --git a/changes.md b/changes.md index 794cfa8..05d5940 100644 --- a/changes.md +++ b/changes.md @@ -13,3 +13,19 @@ - **EpisodePage**: Added `max-w-4xl` width constraint; changed breadcrumb from generic "Entry / Season" to "Title / Season x / Episode x"; fixed S## display to use `season.season_number` instead of `seasonId` (DB id) - **SettingsPage**: Added "Cleanup" card section with Scan/Delete buttons for orphan files and orphan media records, using existing maintenance API endpoints - Created `api/maintenance.ts` API client for maintenance endpoints + +### Milestone 001.1 + +#### Backend Changes + +- Fixed credit duplicate bug: changed unique key from `people_id + cast_type + tmdb_credit_id` to `people_id + cast_type` (scoped to entry_id) so TV series credits aren't re-inserted on every refresh +- Fixed TV series character/job extraction: now detects aggregate_credits format via `Array.isArray(c.roles)` instead of relying on `is_tvseries` flag; joins all roles/jobs with `"; "` instead of only taking the first +- Added `episode_count` field to Credit model, populated from `total_episode_count` in aggregate_credits response, tracked in change detection and `updateOnDuplicate` +- Increased `character` and `job` column size from VARCHAR(100) to VARCHAR(500) to accommodate multiple roles joined by `"; "` +- Fixed collection media upload: now deselects existing posters/backdrops (`isSelected = false`) before inserting new custom upload + +#### Frontend Changes + +- Created `MarkSeasonWatchedDialog` — dedicated dialog for marking a season as watched, replacing the old two-step EpisodeSeenEditDialog+ConfirmDialog flow +- Added **Scatter Mode** toggle: distributes episodes across a date range (start → end) with an even spread, shows preview of days and max episodes/day +- "Mark Season Watched" button is now always visible (not hidden when all episodes are watched) diff --git a/docs-vault/Changelog.md b/docs-vault/Changelog.md index 5ba8193..aa72255 100644 --- a/docs-vault/Changelog.md +++ b/docs-vault/Changelog.md @@ -27,3 +27,21 @@ All project milestones. See also `changes.md` in project root. - Fixed EpisodePage using `seasonId` (DB id) instead of `season.season_number` for display - Added cleanup section to [[Settings Page]] for orphan files/media records - Created [[API Clients|maintenance.ts]] API client + +--- + +## Milestone 001.1 + +### Backend + +- Fixed [[People|credit]] duplicate bug: changed dedup key from `people_id + cast_type + tmdb_credit_id` to `people_id + cast_type` — TV series credits no longer re-inserted on every refresh +- Fixed TV series character/job extraction: detects `aggregate_credits` format via `Array.isArray(c.roles)` instead of `is_tvseries` flag; joins all roles/jobs with `"; "` +- Added `episode_count` field to [[Models#Credit|Credit]] model (from TMDB `total_episode_count`) +- Increased `character` and `job` columns from `VARCHAR(100)` to `VARCHAR(500)` for multiple roles +- Fixed [[Collections|collection]] media upload: deselects existing posters/backdrops before inserting new custom upload + +### Frontend + +- Created [[Components#Dialogs|MarkSeasonWatchedDialog]] — dedicated dialog replacing the old two-step EpisodeSeenEditDialog + ConfirmDialog flow +- Added **Scatter Mode**: distributes episodes across a date range with even spread and live preview +- "Mark Season Watched" button on [[Pages#SeasonPage|SeasonPage]] is now always visible diff --git a/docs-vault/Collections.md b/docs-vault/Collections.md index 9901efd..1c1478c 100644 --- a/docs-vault/Collections.md +++ b/docs-vault/Collections.md @@ -41,6 +41,9 @@ Users can create custom collections: - Poster and backdrop (upload via multipart) - Add/remove entries, reorder +> [!info] Media Upload Behavior +> When a new poster or backdrop is uploaded for a collection, all existing media of the same type are deselected (`isSelected = false`) before the new one is created with `isSelected = true`. This ensures only the latest upload is active. + ## API Endpoints See [[API Reference#Collections]]. diff --git a/docs-vault/Components.md b/docs-vault/Components.md index 6f6cb45..84cee18 100644 --- a/docs-vault/Components.md +++ b/docs-vault/Components.md @@ -64,6 +64,7 @@ See [[Statistics]] for data details. | `ConfirmDialog` | `dialogs/ConfirmDialog.tsx` | Generic confirmation dialog | | `AddEntryToCollectionDialog` | `dialogs/AddEntryToCollectionDialog.tsx` | Add entry to collection picker | | `CollectionEditDialog` | `dialogs/CollectionEditDialog.tsx` | Create/edit collection | +| `MarkSeasonWatchedDialog` | `dialogs/MarkSeasonWatchedDialog.tsx` | Mark season as watched — single date or scatter mode | ## Skeletons diff --git a/docs-vault/Models.md b/docs-vault/Models.md index 3080f6c..16c508e 100644 --- a/docs-vault/Models.md +++ b/docs-vault/Models.md @@ -219,14 +219,18 @@ Join table for Collection ↔ Entry (M:N). Managed by hooks in `sequelizeHooks.j | `tmdb_credit_id` | STRING(100) | | | `adult` | BOOLEAN | Default `false` | | `profile_path` | STRING(200) | TMDB profile image | -| `character` | STRING(100) | Role name (for cast) | +| `character` | STRING(500) | Role name(s) for cast — multiple roles joined by `"; "` | | `order` | INTEGER | Display order | +| `episode_count` | INTEGER | Total episode count (from TMDB aggregate_credits) | | `cast_type` | ENUM | `'cast'`, `'crew'`. Default `'cast'` | | `department` | STRING(100) | For crew | -| `job` | STRING(100) | For crew | +| `job` | STRING(500) | Job title(s) for crew — multiple jobs joined by `"; "` | | `entry_id` | INTEGER FK | → Entry | | `people_id` | INTEGER FK | → People | +> [!info] TV Series Credits +> For TV series, TMDB returns `aggregate_credits` where a person can have multiple roles/jobs. These are joined with `"; "` into the `character` and `job` fields respectively. `episode_count` tracks the total episodes the person appeared in. + --- ## People diff --git a/docs-vault/Pages.md b/docs-vault/Pages.md index f63bfe1..e80660f 100644 --- a/docs-vault/Pages.md +++ b/docs-vault/Pages.md @@ -75,7 +75,9 @@ Season detail with episode list. Width: `max-w-4xl`. - Breadcrumb: `Title / Season x` (see [[Navigation]]) - Episode progress bar -- Mark-all-as-seen action +- **Mark Season Watched** button (always visible) → opens [[Components#Dialogs|MarkSeasonWatchedDialog]] + - **Single Date mode**: marks all unwatched episodes on one date + - **Scatter Mode**: distributes episodes evenly across a date range (start → end) - Episode list with watch status - Links to EpisodePage diff --git a/docs-vault/People.md b/docs-vault/People.md index 61dd710..172e131 100644 --- a/docs-vault/People.md +++ b/docs-vault/People.md @@ -33,8 +33,11 @@ See [[Models#People]] and [[Models#Credit]]. | `cast_type` | Fields Used | |---|---| -| `cast` | `character`, `order` | -| `crew` | `department`, `job` | +| `cast` | `character`, `order`, `episode_count` | +| `crew` | `department`, `job`, `episode_count` | + +> [!info] Multiple Roles +> For TV series (using TMDB `aggregate_credits`), a person may have multiple roles or jobs. These are stored joined by `"; "` in the `character` (cast) or `job` (crew) fields. The `episode_count` field tracks total episodes across all roles/jobs. ## Pages diff --git a/docs-vault/Watch Tracking.md b/docs-vault/Watch Tracking.md index 32149ec..2e3639f 100644 --- a/docs-vault/Watch Tracking.md +++ b/docs-vault/Watch Tracking.md @@ -58,13 +58,19 @@ See [[API Reference#Entry Seen (Movie Watch Records)]] and [[API Reference#Episo ## Batch Operations -### Mark All Seen (Season) +### Mark Season Watched -The [[Pages#SeasonPage|SeasonPage]] has a "Mark All as Seen" action that: +The [[Pages#SeasonPage|SeasonPage]] has a "Mark Season Watched" button (always visible) that opens the [[Components#Dialogs|MarkSeasonWatchedDialog]]. Two modes: -1. Filters unwatched episodes -2. Creates an `EpisodeSeen` for each -3. Uses the selected date and accuracy +#### Single Date Mode +1. User picks a single date, accuracy, and optional "seen with" +2. All unwatched episodes are marked as seen on that date + +#### Scatter Mode +1. User toggles scatter mode and picks a start date and end date +2. Episodes are distributed evenly across the date range +3. A preview shows total days and max episodes/day +4. Each episode gets a different `date_seen` based on the distribution ## Side Effects