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
This commit is contained in:
Mohammed Abad committed 2026-04-23 16:51:18 +01:00
1 parent 260282a0e2
commit ce01dc34fa
14 files changed
+278 -30

No files matched your search

@@ -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/):
```
<type>(<scope>): <summary>
- 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
```
+1 -1
View File
@@ -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. - 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). - 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. 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.
+1
View File
@@ -0,0 +1 @@
Checkout the `AGENTS.md` file for instructions on how to use Agents in this project.
@@ -118,6 +118,12 @@ class CollectionController {
logToFile(err); 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({ await Media.create({
mediaable: 'collection', mediaable: 'collection',
mediaableId: collectionId, mediaableId: collectionId,
@@ -140,6 +146,12 @@ class CollectionController {
logToFile(err); logToFile(err);
}); });
// Deselect existing backdrops for this collection
await Media.update(
{ isSelected: false },
{ where: { mediaable: 'collection', mediaableId: collectionId, type: 'backdrop', isSelected: true } }
);
// ? inserting data // ? inserting data
await Media.create({ await Media.create({
mediaable: 'collection', mediaable: 'collection',
+3 -2
View File
@@ -10,12 +10,13 @@ const Credit = sequelize.define("credits",
adult: { type: DataTypes.BOOLEAN, defaultValue: false }, adult: { type: DataTypes.BOOLEAN, defaultValue: false },
profile_path: { type: DataTypes.STRING(200), field: 'profile_path' }, profile_path: { type: DataTypes.STRING(200), field: 'profile_path' },
character: { type: DataTypes.STRING(100) }, character: { type: DataTypes.STRING(500) },
order: { type: DataTypes.INTEGER }, order: { type: DataTypes.INTEGER },
episode_count: { type: DataTypes.INTEGER, defaultValue: null },
cast_type: { type: DataTypes.ENUM('cast', 'crew'), field: 'cast_type', defaultValue: 'cast' }, cast_type: { type: DataTypes.ENUM('cast', 'crew'), field: 'cast_type', defaultValue: 'cast' },
department: { type: DataTypes.STRING(100) }, department: { type: DataTypes.STRING(100) },
job: { type: DataTypes.STRING(100) }, job: { type: DataTypes.STRING(500) },
entry_id: { type: DataTypes.INTEGER, field: 'entry_id' }, entry_id: { type: DataTypes.INTEGER, field: 'entry_id' },
people_id: { type: DataTypes.INTEGER, field: 'people_id' }, people_id: { type: DataTypes.INTEGER, field: 'people_id' },
+151 -17
View File
@@ -257,19 +257,30 @@ class EntryManager {
} }
// * Credits // * 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); const creditData = await fetchEntryCredits(oldEntry.entryId.tmdb_id, oldEntry.is_tvseries);
if (!creditData) { if (!creditData) {
throw new InternalServerError(`Couldn't fetch entry crew data`); throw new InternalServerError(`Couldn't fetch entry crew data`);
} }
const allCredits = [...creditData.cast.map(c => ({ ...c, cast_type: 'cast' })), const allCredits = [
...creditData.crew.map(c => ({ ...c, cast_type: 'crew' }))]; ...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))]; const tmdbIds = [...new Set(allCredits.map(c => c.id))];
// -------------------------
// FETCH EXISTING PEOPLE
// -------------------------
const existingPeopleList = await People.findAll({ where: { tmdb_id: tmdbIds } }); const existingPeopleList = await People.findAll({ where: { tmdb_id: tmdbIds } });
const existingPeopleMap = Object.fromEntries(existingPeopleList.map(p => [p.tmdb_id, p])); const existingPeopleMap = Object.fromEntries(existingPeopleList.map(p => [p.tmdb_id, p]));
// -------------------------
// CREATE NEW PEOPLE
// -------------------------
const newPeopleData = tmdbIds const newPeopleData = tmdbIds
.filter(id => !existingPeopleMap[id]) .filter(id => !existingPeopleMap[id])
.map(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); const createdPeople = await People.bulkCreate(newPeopleData);
for (const person of createdPeople) { for (const person of createdPeople) {
console.log(`[PEOPLE] Added: ${person.name} (tmdb_id=${person.tmdb_id})`);
existingPeopleMap[person.tmdb_id] = person; 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 for (const credit of allCredits) {
.map(c => { const existingPerson = existingPeopleMap[credit.id];
if (!existingPerson) continue;
// 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]; const person = existingPeopleMap[c.id];
if (existingPeopleIds.has(person.id)) return null; if (!person) continue;
return {
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, entry_id: oldEntry.id,
people_id: person.id, people_id: person.id,
tmdb_credit_id: c.credit_id, tmdb_credit_id: tmdbCreditId,
character: c.cast_type === 'cast' ? c.character : null, character,
order: c.cast_type === 'cast' ? c.order : null, order: c.cast_type === "cast" ? c.order : null,
episode_count: c.total_episode_count ?? null,
profile_path: person.profile_path, profile_path: person.profile_path,
adult: person.adult, adult: person.adult,
cast_type: c.cast_type, cast_type: c.cast_type,
department: c.cast_type === 'crew' ? c.department || null : null, department: c.cast_type === "crew" ? c.department || null : null,
job: c.cast_type === 'crew' ? c.job || null : null job
}; };
})
.filter(Boolean);
if (newCredits.length) { if (!existingCredit) {
await Credit.bulkCreate(newCredits); 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}`);
} }
} }
+16
View File
@@ -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) - **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 - **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 - 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)
+18
View File
@@ -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 - Fixed EpisodePage using `seasonId` (DB id) instead of `season.season_number` for display
- Added cleanup section to [[Settings Page]] for orphan files/media records - Added cleanup section to [[Settings Page]] for orphan files/media records
- Created [[API Clients|maintenance.ts]] API client - 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
+3
View File
@@ -41,6 +41,9 @@ Users can create custom collections:
- Poster and backdrop (upload via multipart) - Poster and backdrop (upload via multipart)
- Add/remove entries, reorder - 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 ## API Endpoints
See [[API Reference#Collections]]. See [[API Reference#Collections]].
+1
View File
@@ -64,6 +64,7 @@ See [[Statistics]] for data details.
| `ConfirmDialog` | `dialogs/ConfirmDialog.tsx` | Generic confirmation dialog | | `ConfirmDialog` | `dialogs/ConfirmDialog.tsx` | Generic confirmation dialog |
| `AddEntryToCollectionDialog` | `dialogs/AddEntryToCollectionDialog.tsx` | Add entry to collection picker | | `AddEntryToCollectionDialog` | `dialogs/AddEntryToCollectionDialog.tsx` | Add entry to collection picker |
| `CollectionEditDialog` | `dialogs/CollectionEditDialog.tsx` | Create/edit collection | | `CollectionEditDialog` | `dialogs/CollectionEditDialog.tsx` | Create/edit collection |
| `MarkSeasonWatchedDialog` | `dialogs/MarkSeasonWatchedDialog.tsx` | Mark season as watched — single date or scatter mode |
## Skeletons ## Skeletons
+6 -2
View File
@@ -219,14 +219,18 @@ Join table for Collection ↔ Entry (M:N). Managed by hooks in `sequelizeHooks.j
| `tmdb_credit_id` | STRING(100) | | | `tmdb_credit_id` | STRING(100) | |
| `adult` | BOOLEAN | Default `false` | | `adult` | BOOLEAN | Default `false` |
| `profile_path` | STRING(200) | TMDB profile image | | `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 | | `order` | INTEGER | Display order |
| `episode_count` | INTEGER | Total episode count (from TMDB aggregate_credits) |
| `cast_type` | ENUM | `'cast'`, `'crew'`. Default `'cast'` | | `cast_type` | ENUM | `'cast'`, `'crew'`. Default `'cast'` |
| `department` | STRING(100) | For crew | | `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 | | `entry_id` | INTEGER FK | → Entry |
| `people_id` | INTEGER FK | → People | | `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 ## People
+3 -1
View File
@@ -75,7 +75,9 @@ Season detail with episode list. Width: `max-w-4xl`.
- Breadcrumb: `Title / Season x` (see [[Navigation]]) - Breadcrumb: `Title / Season x` (see [[Navigation]])
- Episode progress bar - 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 - Episode list with watch status
- Links to EpisodePage - Links to EpisodePage
+5 -2
View File
@@ -33,8 +33,11 @@ See [[Models#People]] and [[Models#Credit]].
| `cast_type` | Fields Used | | `cast_type` | Fields Used |
|---|---| |---|---|
| `cast` | `character`, `order` | | `cast` | `character`, `order`, `episode_count` |
| `crew` | `department`, `job` | | `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 ## Pages
+11 -5
View File
@@ -58,13 +58,19 @@ See [[API Reference#Entry Seen (Movie Watch Records)]] and [[API Reference#Episo
## Batch Operations ## 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 #### Single Date Mode
2. Creates an `EpisodeSeen` for each 1. User picks a single date, accuracy, and optional "seen with"
3. Uses the selected date and accuracy 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 ## Side Effects