Add impossible seen dates maintenance endpoint

- Backend: fixImpossibleSeenDates scan/fix in maintenanceService
  detects movies with EntrySeen date before release_date, adds
  them to a "Movies with impossible seen date" collection
- Frontend: ImpossibleSeenDatesSection in SettingsPage with
  Scan and Fix buttons
- Updated API docs (Clients + Reference), cleaned up removed
  migrateSeenWith references
This commit is contained in:
X4Lo committed 2026-06-25 21:38:31 +01:00
1 parent 3df2e2ce3e
commit d984210dd9
8 files changed
+294 -124

No files matched your search

+11 -1
View File
@@ -1,4 +1,4 @@
const maintenanceService = require('../services/maintenanceService');
const maintenanceService = require("../services/maintenanceService");
const _maintenanceService = maintenanceService;
@@ -68,6 +68,16 @@ class MaintenanceController {
const result = await _maintenanceService.autoFixWatchStatuses();
return res.status(200).json(result);
}
async getImpossibleSeenDates(req, res) {
const result = await _maintenanceService.fixImpossibleSeenDates(true);
return res.status(200).json(result);
}
async fixImpossibleSeenDates(req, res) {
const result = await _maintenanceService.fixImpossibleSeenDates();
return res.status(200).json(result);
}
}
module.exports = new MaintenanceController();
+25 -13
View File
@@ -1,67 +1,79 @@
const express = require('express');
const express = require("express");
const maintenanceRouter = express.Router();
const maintenanceController = require('../controllers/maintenanceController');
const maintenanceController = require("../controllers/maintenanceController");
// ! /maintenance
// * GET - Orphan files
maintenanceRouter.get('/orphan-files', maintenanceController.getOrpanFiles);
maintenanceRouter.get("/orphan-files", maintenanceController.getOrpanFiles);
// * GET - Missing files
maintenanceRouter.get(
'/orphan-media-records',
"/orphan-media-records",
maintenanceController.getOrphanMediaRecords,
);
// * DELETE - Orphan files
maintenanceRouter.delete(
'/orphan-files',
"/orphan-files",
maintenanceController.deleteOrpanFiles,
);
// * DELETE - Missing files
maintenanceRouter.delete(
'/orphan-media-records',
"/orphan-media-records",
maintenanceController.deleteOrphanMediaRecords,
);
// * GET - Orphan people (dry run)
maintenanceRouter.get('/orphan-people', maintenanceController.getOrphanPeople);
maintenanceRouter.get("/orphan-people", maintenanceController.getOrphanPeople);
// * DELETE - Orphan people
maintenanceRouter.delete(
'/orphan-people',
"/orphan-people",
maintenanceController.deleteOrphanPeople,
);
// * GET - Missing directors count
maintenanceRouter.get(
'/missing-directors',
"/missing-directors",
maintenanceController.getMissingDirectors,
);
// * POST - Fix missing directors
maintenanceRouter.post(
'/missing-directors',
"/missing-directors",
maintenanceController.fixMissingDirectors,
);
// * GET - Duplicate credits count
maintenanceRouter.get(
'/duplicate-credits',
"/duplicate-credits",
maintenanceController.getDuplicateCredits,
);
// * DELETE - Clean duplicate credits
maintenanceRouter.delete(
'/duplicate-credits',
"/duplicate-credits",
maintenanceController.cleanDuplicateCredits,
);
// * POST - Auto-fix watch statuses based on watched episodes
maintenanceRouter.post(
'/auto-fix-watch-statuses',
"/auto-fix-watch-statuses",
maintenanceController.autoFixWatchStatuses,
);
// * GET - Scan impossible seen dates (movies watched before release)
maintenanceRouter.get(
"/impossible-seen-dates",
maintenanceController.getImpossibleSeenDates,
);
// * POST - Fix impossible seen dates (add to collection)
maintenanceRouter.post(
"/impossible-seen-dates",
maintenanceController.fixImpossibleSeenDates,
);
module.exports = maintenanceRouter;
+150 -69
View File
@@ -1,14 +1,14 @@
const path = require('path');
const fsPromises = require('fs').promises;
const fs = require('fs');
const path = require("path");
const fsPromises = require("fs").promises;
const fs = require("fs");
const Media = require('../models/Media');
const People = require('../models/People');
const Credit = require('../models/Credit');
const Entry = require('../models/Entry');
const Media = require("../models/Media");
const People = require("../models/People");
const Credit = require("../models/Credit");
const Entry = require("../models/Entry");
const { logToFile } = require('./logService');
const configService = require('./configService');
const { logToFile } = require("./logService");
const configService = require("./configService");
const _configService = configService;
@@ -32,30 +32,30 @@ class MaintenanceService {
const dataPath = await _configService.getMediaFolder();
const mediaTypeFolder = {
'entry;poster': path.join(dataPath, 'images', 'entries', 'posters'),
'entry;logo': path.join(dataPath, 'images', 'entries', 'logos'),
'entry;backdrop': path.join(dataPath, 'images', 'entries', 'backdrops'),
"entry;poster": path.join(dataPath, "images", "entries", "posters"),
"entry;logo": path.join(dataPath, "images", "entries", "logos"),
"entry;backdrop": path.join(dataPath, "images", "entries", "backdrops"),
'collection;poster': path.join(
"collection;poster": path.join(
dataPath,
'images',
'collections',
'posters',
"images",
"collections",
"posters",
),
'collection;backdrop': path.join(
"collection;backdrop": path.join(
dataPath,
'images',
'collections',
'backdrops',
"images",
"collections",
"backdrops",
),
'season;poster': path.join(dataPath, 'images', 'seasons', 'posters'),
'episode;still': path.join(dataPath, 'images', 'episodes', 'stills'),
"season;poster": path.join(dataPath, "images", "seasons", "posters"),
"episode;still": path.join(dataPath, "images", "episodes", "stills"),
};
let missingFiles = [];
for (let i = 0; i < allMedia.length; i++) {
const folderType = `${allMedia[i].mediaable};${allMedia[i].type.replace('_preview', '')}`;
const folderType = `${allMedia[i].mediaable};${allMedia[i].type.replace("_preview", "")}`;
if (!mediaTypeFolder[folderType]) continue;
@@ -73,7 +73,7 @@ class MaintenanceService {
};
for (let i = 0; i < missingFiles.length; i++) {
removed[missingFiles[i].type + 's'] += 1;
removed[missingFiles[i].type + "s"] += 1;
if (!dry) missingFiles[i].destroy();
}
@@ -100,31 +100,31 @@ class MaintenanceService {
// ? Getting the name (without extention) of all media in database
const allMedia = (await Media.findAll()).map((m) => {
return m.path.split('.')[0];
return m.path.split(".")[0];
});
// ? Loop trough the files of the images folder and check
// ? if a file doesnt exist in the allMedia array and mark it to delete
const mediaTypeFolder = {
'entry;poster': path.join(dataPath, 'images', 'entries', 'posters'),
'entry;logo': path.join(dataPath, 'images', 'entries', 'logos'),
'entry;backdrop': path.join(dataPath, 'images', 'entries', 'backdrops'),
"entry;poster": path.join(dataPath, "images", "entries", "posters"),
"entry;logo": path.join(dataPath, "images", "entries", "logos"),
"entry;backdrop": path.join(dataPath, "images", "entries", "backdrops"),
'collection;poster': path.join(
"collection;poster": path.join(
dataPath,
'images',
'collections',
'posters',
"images",
"collections",
"posters",
),
'collection;backdrop': path.join(
"collection;backdrop": path.join(
dataPath,
'images',
'collections',
'backdrops',
"images",
"collections",
"backdrops",
),
'season;poster': path.join(dataPath, 'images', 'seasons', 'posters'),
'episode;still': path.join(dataPath, 'images', 'episodes', 'stills'),
"season;poster": path.join(dataPath, "images", "seasons", "posters"),
"episode;still": path.join(dataPath, "images", "episodes", "stills"),
};
// * counter
@@ -146,12 +146,12 @@ class MaintenanceService {
// Check each file in the directory
for (let file of files) {
// preparing the file name
const fileName = file.split('.')[0].replace('_preview', '');
const fileName = file.split(".")[0].replace("_preview", "");
const isInDatabase = allMedia.includes(fileName);
// if the file isn't in database even on other extentions then delete it
if (!isInDatabase) {
removed[folderType.split(';')[1] + 's']++; // Increment the count of removed files
removed[folderType.split(";")[1] + "s"]++; // Increment the count of removed files
if (!dry) {
const filePath = path.join(directory, file);
await fsPromises.unlink(filePath);
@@ -182,14 +182,14 @@ class MaintenanceService {
* @param {boolean} [dry=false] - if true only return the count
*/
async deleteOrphanPeople(dry = false) {
const { Sequelize } = require('sequelize');
const { Sequelize } = require("sequelize");
// Find all people who have no credits and are not pinned
const allPeople = await People.findAll({
include: [
{
model: Credit,
as: 'roles',
as: "roles",
required: false,
},
],
@@ -222,9 +222,9 @@ class MaintenanceService {
include: [
{
model: Credit,
as: 'credits',
where: { cast_type: 'crew', job: 'Director' },
include: [{ model: People, as: 'person', attributes: ['name'] }],
as: "credits",
where: { cast_type: "crew", job: "Director" },
include: [{ model: People, as: "person", attributes: ["name"] }],
required: false,
},
],
@@ -257,20 +257,20 @@ class MaintenanceService {
* @param {boolean} [dry=false] - if true only count, if false also delete
*/
async cleanDuplicateCredits(dry = false) {
const { Sequelize } = require('sequelize');
const { Sequelize } = require("sequelize");
const duplicates = await Credit.findAll({
attributes: [
'entry_id',
'people_id',
'cast_type',
'character',
'job',
[Sequelize.fn('COUNT', Sequelize.col('id')), 'cnt'],
[Sequelize.fn('GROUP_CONCAT', Sequelize.col('id')), 'ids'],
"entry_id",
"people_id",
"cast_type",
"character",
"job",
[Sequelize.fn("COUNT", Sequelize.col("id")), "cnt"],
[Sequelize.fn("GROUP_CONCAT", Sequelize.col("id")), "ids"],
],
group: ['entry_id', 'people_id', 'cast_type', 'character', 'job'],
having: Sequelize.literal('COUNT(id) > 1'),
group: ["entry_id", "people_id", "cast_type", "character", "job"],
having: Sequelize.literal("COUNT(id) > 1"),
raw: true,
});
@@ -280,7 +280,7 @@ class MaintenanceService {
if (!dry) {
for (const row of duplicates) {
const idList = row.ids
.split(',')
.split(",")
.map(Number)
.sort((a, b) => a - b);
// Keep the newest (highest ID), delete the older ones
@@ -312,23 +312,23 @@ class MaintenanceService {
}
async autoFixWatchStatuses() {
const Episode = require('../models/Episode');
const EpisodeSeen = require('../models/EpisodeSeen');
const Season = require('../models/Season');
const { Op } = require('sequelize');
const Episode = require("../models/Episode");
const EpisodeSeen = require("../models/EpisodeSeen");
const Season = require("../models/Season");
const { Op } = require("sequelize");
const tvEntries = await Entry.findAll({
where: { is_tvseries: true },
include: [
{
model: Season,
as: 'seasons',
as: "seasons",
where: { season_number: { [Op.gt]: 0 } },
include: [
{
model: Episode,
as: 'episodes',
include: [{ model: EpisodeSeen, as: 'episodeSeens' }],
as: "episodes",
include: [{ model: EpisodeSeen, as: "episodeSeens" }],
},
],
},
@@ -356,16 +356,16 @@ class MaintenanceService {
const hasSomeWatched = watchedEpisodes > 0;
// Completed but not all watched → downgrade to watching
if (entry.watch_status === 'completed' && !allWatched) {
entry.watch_status = 'watching';
if (entry.watch_status === "completed" && !allWatched) {
entry.watch_status = "watching";
await entry.save();
toWatching++;
continue;
}
// All watched → completed (unless already completed)
if (allWatched && entry.watch_status !== 'completed') {
entry.watch_status = 'completed';
if (allWatched && entry.watch_status !== "completed") {
entry.watch_status = "completed";
await entry.save();
toCompleted++;
continue;
@@ -373,7 +373,7 @@ class MaintenanceService {
// Has some watched but no status → watching
if (hasSomeWatched && !entry.watch_status) {
entry.watch_status = 'watching';
entry.watch_status = "watching";
await entry.save();
toWatching++;
continue;
@@ -381,7 +381,7 @@ class MaintenanceService {
// In watchlist with no status → plan to watch
if (entry.watchlist && !entry.watch_status) {
entry.watch_status = 'plan_to_watch';
entry.watch_status = "plan_to_watch";
await entry.save();
toPlanToWatch++;
}
@@ -396,6 +396,87 @@ class MaintenanceService {
planToWatch: toPlanToWatch,
};
}
/**
* Find movies where an EntrySeen date is before the movie's release_date.
* @param {boolean} [dry=false] - if true only return the entries, if false also add to collection
*/
async fixImpossibleSeenDates(dry = false) {
const { Op } = require("sequelize");
const EntrySeen = require("../models/EntrySeen");
const UserCollectionEntry = require("../models/UserCollectionEntry");
const Collection = require("../models/Collection");
// Find movies with entry_seen before release_date
const allMovies = await Entry.findAll({
where: {
is_tvseries: false,
release_date: { [Op.ne]: null },
},
include: [
{
model: EntrySeen,
as: "entrySeen",
required: true,
},
],
});
const impossibleEntries = [];
for (const movie of allMovies) {
for (const seen of movie.entrySeen || []) {
if (
seen.date_seen &&
new Date(seen.date_seen) < new Date(movie.release_date)
) {
impossibleEntries.push(movie);
break;
}
}
}
if (!dry) {
// Find or create the collection
const COLLECTION_NAME = "Movies with impossible seen date";
let [collection] = await Collection.findOrCreate({
where: { name: COLLECTION_NAME, isUserCollection: true },
defaults: {
name: COLLECTION_NAME,
description:
"Movies that have a watch date before their official release date.",
isUserCollection: true,
},
});
// Add entries that are not already in the collection
let added = 0;
for (const entry of impossibleEntries) {
const exists = await UserCollectionEntry.findOne({
where: {
user_collection_id: collection.id,
entry_id: entry.id,
},
});
if (!exists) {
await UserCollectionEntry.create({
user_collection_id: collection.id,
entry_id: entry.id,
});
added++;
}
}
logToFile(
`Impossible seen dates: ${impossibleEntries.length} movies found, ${added} added to collection`,
);
return { count: impossibleEntries.length, added };
}
logToFile(
`Dry impossible seen dates check: ${impossibleEntries.length} movies found`,
);
return { count: impossibleEntries.length };
}
}
module.exports = new MaintenanceService();
-37
View File
@@ -1,37 +0,0 @@
### Milestone 001
#### Backend Changes
- Added `WHERE accuracy = 'EXACT'` filter to `getWatchdayDistribution` in `statisticsController.js` for both EpisodeSeen and EntrySeen queries, so CouchDay chart only reflects exact-date data
#### Frontend Changes
- **EntrySeenDialog**: Replaced Calendar popover with native `<input type="date">` for easier year selection; merged date + accuracy into a single row; removed unused `date` state
- **EpisodeSeenEditDialog**: Merged date input and accuracy select into one flex row
- **LibraryGrowthChart**: Changed `getEntryDate` to use only `createdAt` (removed `date_first_seen` fallback); removed watchlist filter so all entries are included
- **SeasonPage**: Added `max-w-4xl` width constraint; changed breadcrumb from "Back to entry" to "Title / Season x" with link to entry
- **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)
### Milestone 001.2
#### Frontend Changes
- **TmdbPreviewPage**: Added redirect when entry is already in library — navigating to `/entry/tmdb/:type/:id` for an in-library entry now immediately redirects to `/entry/:id` (EntryDetailsPage) with `replace: true`, eliminating the extra "Already in Library — View" button step
+3 -3
View File
@@ -35,7 +35,6 @@ Watch buddy management.
| `create(data)` | POST | `/watch-buddies` |
| `update(id, data)` | PUT | `/watch-buddies/:id` |
| `remove(id)` | DELETE | `/watch-buddies/:id` |
| `migrateSeenWith()` | POST | `/watch-buddies/migrate-seen-with` |
---
@@ -190,7 +189,8 @@ Maintenance and cleanup utilities.
| `scanDuplicateCredits()` | GET | `/maintenance/duplicate-credits` |
| `cleanDuplicateCredits()` | DELETE | `/maintenance/duplicate-credits` |
| `autoFixWatchStatuses()` | POST | `/maintenance/auto-fix-watch-statuses` |
| `migrateSeenWith()` | POST | `/watch-buddies/migrate-seen-with` |
| `scanImpossibleSeenDates()` | GET | `/maintenance/impossible-seen-dates` |
| `fixImpossibleSeenDates()` | POST | `/maintenance/impossible-seen-dates` |
Response types:
- **Orphan files/media:** `{ posters: number, logos: number, backdrops: number, stills: number }`
@@ -198,4 +198,4 @@ Response types:
- **Missing directors:** `{ count: number, fixed: number }`
- **Duplicate credits:** `{ groups: number, duplicates: number, deleted: number }`
- **Auto-fix watch statuses:** `{ completed: number, watching: number, planToWatch: number }`
- **Migrate seen-with:** `{ created: number, linked: number, processed: number }`
- **Impossible seen dates:** Scan → `{ count: number }`, Fix → `{ count: number, added: number }`
+9 -1
View File
@@ -39,7 +39,6 @@ All endpoints are prefixed with `/api/v1`. See [[Backend]] for server setup.
| `POST` | `/watch-buddies` | Create watch buddy |
| `PUT` | `/watch-buddies/:id` | Update watch buddy |
| `DELETE` | `/watch-buddies/:id` | Delete watch buddy |
| `POST` | `/watch-buddies/migrate-seen-with` | Migrate `seen_with` string field to watch buddy references |
---
@@ -275,6 +274,15 @@ See [[Settings Page#Cleanup]] for the UI.
**Response:** `{ completed: number, watching: number, planToWatch: number }`
### Impossible Seen Dates
| Method | Path | Description |
|---|---|---|
| `GET` | `/maintenance/impossible-seen-dates` | Scan for movies watched before their release date |
| `POST` | `/maintenance/impossible-seen-dates` | Fix — add to "Movies with impossible seen date" collection |
**Response:** Scan → `{ count: number }`, Fix → `{ count: number, added: number }`
---
## Import
+13
View File
@@ -74,4 +74,17 @@ export const maintenanceApi = {
planToWatch: number;
}>("/maintenance/auto-fix-watch-statuses")
.then((r) => r.data),
scanImpossibleSeenDates: () =>
api
.get<{ count: number }>("/maintenance/impossible-seen-dates")
.then((r) => r.data),
fixImpossibleSeenDates: () =>
api
.post<{
count: number;
added: number;
}>("/maintenance/impossible-seen-dates")
.then((r) => r.data),
};
+83
View File
@@ -210,6 +210,76 @@ function WatchStatusesSection() {
);
}
function ImpossibleSeenDatesSection() {
const [scanResult, setScanResult] = useState<{ count: number } | null>(null);
const [fixResult, setFixResult] = useState<{
count: number;
added: number;
} | null>(null);
const scan = useMutation({
mutationFn: maintenanceApi.scanImpossibleSeenDates,
onSuccess: (data) => setScanResult(data),
});
const fix = useMutation({
mutationFn: maintenanceApi.fixImpossibleSeenDates,
onSuccess: (data) => {
setFixResult(data);
setScanResult(null);
},
});
return (
<div className="space-y-2">
<p className="text-xs text-muted-foreground">
Detects movies with a watch date before their official release date and
adds them to a "Movies with impossible seen date" collection.
</p>
<div className="flex items-center gap-2">
<Button
variant="outline"
size="sm"
onClick={() => scan.mutate()}
disabled={scan.isPending}
>
{scan.isPending ? (
<Loader2 className="mr-1.5 h-3.5 w-3.5 animate-spin" />
) : (
<Search className="mr-1.5 h-3.5 w-3.5" />
)}
Scan
</Button>
<Button
variant="outline"
size="sm"
onClick={() => fix.mutate()}
disabled={fix.isPending || (scanResult?.count ?? 0) === 0}
>
{fix.isPending ? (
<Loader2 className="mr-1.5 h-3.5 w-3.5 animate-spin" />
) : (
<Save className="mr-1.5 h-3.5 w-3.5" />
)}
Fix
</Button>
</div>
{scanResult && (
<p className="text-xs text-muted-foreground">
Found {scanResult.count} movie
{scanResult.count !== 1 ? "s" : ""} with impossible seen dates.
</p>
)}
{fixResult && (
<p className="text-xs text-muted-foreground">
{fixResult.added} movie
{fixResult.added !== 1 ? "s" : ""} added to collection.
</p>
)}
</div>
);
}
export function SettingsPage() {
const queryClient = useQueryClient();
const { data: settings, isLoading } = useQuery({
@@ -502,6 +572,19 @@ export function SettingsPage() {
<MissingDirectorsSection />
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle>Impossible Seen Dates</CardTitle>
<CardDescription>
Find movies watched before their release date and add them to
a dedicated collection.
</CardDescription>
</CardHeader>
<CardContent>
<ImpossibleSeenDatesSection />
</CardContent>
</Card>
</div>
</TabsContent>
</Tabs>