diff --git a/backend/db/relations.js b/backend/db/relations.js index a81ad34..deb7772 100644 --- a/backend/db/relations.js +++ b/backend/db/relations.js @@ -96,6 +96,11 @@ Episode.belongsTo(Season, { foreignKey: 'season_id' }); Episode.hasMany(EpisodeSeen, { foreignKey: 'episode_id', onDelete: 'CASCADE', }); EpisodeSeen.belongsTo(Episode, { foreignKey: 'episode_id' }); +// * ENTRY & EPISODE_SEEN - ONE TO MANY +Entry.hasMany(EpisodeSeen, { foreignKey: 'entry_id', onDelete: 'CASCADE', }); +EpisodeSeen.belongsTo(Entry, { foreignKey: 'entry_id' }); + +// * ---- Franchise.hasMany(Entry, { foreignKey: 'franchise_id' }); Entry.belongsTo(Franchise, { foreignKey: 'franchise_id' }); diff --git a/backend/models/EpisodeSeen.js b/backend/models/EpisodeSeen.js index 4263ebb..14332f3 100644 --- a/backend/models/EpisodeSeen.js +++ b/backend/models/EpisodeSeen.js @@ -6,6 +6,13 @@ const EpisodeSeen = sequelize.define("episodeSeen", { id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true }, + entry_id: { + type: DataTypes.INTEGER, + references: { + model: 'Entries', + key: 'id' + } + }, episode_id: { type: DataTypes.INTEGER, references: { diff --git a/backend/routes/episodeSeenRoutes.js b/backend/routes/episodeSeenRoutes.js index f0277cf..9ea0ac9 100644 --- a/backend/routes/episodeSeenRoutes.js +++ b/backend/routes/episodeSeenRoutes.js @@ -1,15 +1,14 @@ const express = require('express'); -const EntrySeen = require('../models/EntrySeen'); -const Entry = require('../models/Entry'); const Episode = require('../models/Episode'); const EpisodeSeen = require('../models/EpisodeSeen'); +const Season = require('../models/Season'); const episodeSeenRouter = express.Router(); // ! /episode-seen // * POST - CREATE ENTRY SEEN episodeSeenRouter.post('/', async (req, res) => { try { - const { episode_id, date_seen, seen_with } = req.body; + const { entry_id, episode_id, date_seen, seen_with } = req.body; // Fetch the Entry based on entry_id const episode = await Episode.findByPk(episode_id); @@ -47,7 +46,7 @@ episodeSeenRouter.post('/', async (req, res) => { } // Create a new EpisodeSeen record - const newEpisodeSeen = await EntrySeen.create({ episode_id: episode_id, date_seen, seen_with }); + const newEpisodeSeen = await EpisodeSeen.create({ entry_id, episode_id, date_seen, seen_with }); res.status(201).json(newEpisodeSeen); } catch (error) { res.status(400).json({ error: error.message }); @@ -80,7 +79,7 @@ episodeSeenRouter.get('/:id', async (req, res) => { } }); -// * GET - EPISODE SEEN BY ENTRY ID +// * GET - EPISODE SEEN BY EPISODE ID episodeSeenRouter.get('/by-episode/:episodeId', async (req, res) => { try { const { episodeId } = req.params; @@ -99,6 +98,33 @@ episodeSeenRouter.get('/by-episode/:episodeId', async (req, res) => { } }); +// * GET - EPISODE SEEN BY ENTRY ID +episodeSeenRouter.get('/by-entry/:entryId', async (req, res) => { + try { + const { entryId } = req.params; + const episodeSeens = await EpisodeSeen.findAll({ + where: { entry_id: entryId }, + include: [{ + model: Episode, + include: [{ + model: Season, + attributes: ['season_number'], + }], + attributes: ['episode_number'], + }], + order: [['date_seen', 'DESC']] + }); + + if (episodeSeens.length > 0) { + res.status(200).json(episodeSeens); + } else { + res.status(404).json({ message: 'No records found for the given entry ID.' }); + } + } catch (error) { + res.status(500).json({ error: error.message }); + } +}); + // * PUT - UPDATE EPISODE SEEN episodeSeenRouter.put('/:id', async (req, res) => { try { diff --git a/frontend/src/app/core/services/episode-seen.service.ts b/frontend/src/app/core/services/episode-seen.service.ts index be55636..fffb0e0 100644 --- a/frontend/src/app/core/services/episode-seen.service.ts +++ b/frontend/src/app/core/services/episode-seen.service.ts @@ -11,17 +11,28 @@ export class EpisodeSeenService { constructor(private http: HttpClient) {} - createEpisodeSeen(episodeId: number, dateSeen: Date, seenWith: string) { + createEpisodeSeen( + entryId: number, + episodeId: number, + dateSeen: Date, + seenWith: string + ) { return this.http.post( `${this.backend_apiUrl}/${this.apiAction}`, { + entry_id: entryId, episode_id: episodeId, date_seen: dateSeen, seen_with: seenWith, } ); } - + + getEpisodeSeenByEntryId(entryId: number) { + return this.http.get( + `${this.backend_apiUrl}/${this.apiAction}/by-entry/${entryId}` + ); + } // get episode-seen by episode Id getEpisodeSeenById(id: number) { diff --git a/frontend/src/app/features/entry/entry-page/entry-page.component.html b/frontend/src/app/features/entry/entry-page/entry-page.component.html index c1ebe97..c3c3cd0 100644 --- a/frontend/src/app/features/entry/entry-page/entry-page.component.html +++ b/frontend/src/app/features/entry/entry-page/entry-page.component.html @@ -67,7 +67,7 @@
-
diff --git a/frontend/src/app/features/entry/entry-page/entry-page.component.ts b/frontend/src/app/features/entry/entry-page/entry-page.component.ts index 8986a9f..4572679 100644 --- a/frontend/src/app/features/entry/entry-page/entry-page.component.ts +++ b/frontend/src/app/features/entry/entry-page/entry-page.component.ts @@ -1,10 +1,11 @@ import { Component, OnInit, ViewEncapsulation } from '@angular/core'; -import { trigger, state, style, transition, animate } from '@angular/animations'; +import { trigger, style, transition, animate } from '@angular/animations'; import { ActivatedRoute, Router } from '@angular/router'; import { MatDialog } from '@angular/material/dialog'; import { Entry } from '../../../shared/models/entry.model'; +import { EpisodeSeenDto } from '../../../shared/models/dtos/episode-seen.dto'; import { DatePipe } from '@angular/common'; @@ -16,6 +17,8 @@ import { EntryRatingsService } from '../../../core/services/entry-ratings.servic import { TmdbService } from '../../../core/services/tmdb.service'; import { LibraryService } from '../../../core/services/library.service'; import { EntryService } from '../../../core/services/entry.service'; +import { EpisodeSeenService } from '../../../core/services/episode-seen.service'; +import e from 'express'; @Component({ selector: 'app-entry-page', @@ -24,14 +27,16 @@ import { EntryService } from '../../../core/services/entry.service'; encapsulation: ViewEncapsulation.None, animations: [ trigger('fadeInOut', [ - transition(':enter', [ // void => * + transition(':enter', [ + // void => * style({ opacity: 0 }), - animate('0.5s ease-in', style({ opacity: 1 })) + animate('0.5s ease-in', style({ opacity: 1 })), ]), - transition(':leave', [ // * => void - animate('0.5s ease-out', style({ opacity: 0 })) - ]) - ]) + transition(':leave', [ + // * => void + animate('0.5s ease-out', style({ opacity: 0 })), + ]), + ]), ], }) export class EntryPageComponent implements OnInit { @@ -39,12 +44,19 @@ export class EntryPageComponent implements OnInit { public showAll = false; public initialCount = 2; + seenHistory: any[] = []; + seenHistoryToShow: any[] = []; + + itemsCount: number = 0; + maxPage: number = 10; + currentPage: number = 1; + pageSize: number = 10; + constructor( private route: ActivatedRoute, private router: Router, public dialog: MatDialog, - private tmdbService: TmdbService, - private libraryService: LibraryService, + private episodeSeenService: EpisodeSeenService, private entryService: EntryService, private entrySeenService: EntrySeenService, private entryRatingsService: EntryRatingsService, @@ -55,7 +67,9 @@ export class EntryPageComponent implements OnInit { this.route.data.subscribe( (data) => { this.entry = data['entry'] as Entry; - this.entry.seasons = this.entry.seasons.sort((a, b) => a.name.localeCompare(b.name)); + this.entry.seasons = this.entry.seasons.sort((a, b) => + a.name.localeCompare(b.name) + ); console.log(this.entry); if (!this.entry) { this.router.navigate(['/error'], { @@ -70,9 +84,11 @@ export class EntryPageComponent implements OnInit { }); } ); + + this.getEpisodesSeenHistory(); } - openDialog() { + openEntrySeenModal() { if (!this.entry) return; const dialogRef = this.dialog.open(SeenModalComponent, { @@ -135,6 +151,10 @@ export class EntryPageComponent implements OnInit { }); } + onEpisodeWatchedEvent() { + this.getEpisodesSeenHistory(); + } + removeEntrySeen(id: number) { // TODO add confirm modal this.entrySeenService.removeEntrySeen(id).subscribe({ @@ -180,6 +200,102 @@ export class EntryPageComponent implements OnInit { }); } + getEpisodesSeenHistory() { + if (!this.entry.is_tvseries) return; + + this.episodeSeenService.getEpisodeSeenByEntryId(this.entry.id).subscribe({ + next: (data) => { + let episodeSeens = [] as EpisodeSeenDto[]; + + // mapping + data.forEach((item) => { + let e = { + id: item.id, + + entryId: item.entry_id, + episodeId: item.episode_id, + + season_number: item.episode.season.season_number, + episode_number: item.episode.episode_number, + + date_seen: item.date_seen, + seen_with: item.seen_with, + + createdAt: item.createdAt, + updatedAt: item.updatedAt, + } as EpisodeSeenDto; + + episodeSeens.push(e); + }); + + this.seenHistory = episodeSeens; + console.log(`Episode Seen History Received: `, episodeSeens); + this.filterEpisodesSeenHistory(); + }, + error: (error) => { + console.log(error); + }, + }); + } + + // nextPage(): void { + // this.currentPage++; + // } + + // previousPage(): void { + // if (this.currentPage > 1) { + // this.currentPage--; + // } + // } + + filterEpisodesSeenHistory() { + var temp = [] as EpisodeSeenDto[]; + + temp = this.seenHistory; + + const startIndex = (this.currentPage - 1) * this.pageSize; + const endIndex = startIndex + this.pageSize; + + this.itemsCount = temp.length; + this.maxPage = Math.ceil(this.itemsCount / this.pageSize); + this.seenHistoryToShow = temp.slice(startIndex, endIndex); + } + + // totalPageCount(): number { + // return this.seenHistory.length / this.pageSize; + // } + + // ? pagination + goToPage(page: number) { + this.currentPage = page; + this.filterEpisodesSeenHistory(); + } + + get pageNumbers(): number[] { + let pagesToShow = 5; // Total pages to show at any time + let startPage: number, endPage: number; + + if (this.maxPage <= pagesToShow) { + startPage = 1; + endPage = this.maxPage; + } else { + startPage = Math.max(this.currentPage - Math.floor(pagesToShow / 2), 1); + endPage = startPage + pagesToShow - 1; + + if (endPage >= this.maxPage) { + endPage = this.maxPage; + startPage = endPage - pagesToShow + 1; + } + } + + // Generate the page numbers array. + return Array.from( + { length: endPage - startPage + 1 }, + (_, i) => startPage + i + ); + } + // ? end pagination + toggleShowAllSeasons() { this.showAll = !this.showAll; } diff --git a/frontend/src/app/shared/cards/season-main-card/season-main-card.component.html b/frontend/src/app/shared/cards/season-main-card/season-main-card.component.html index 799520c..2006fc0 100644 --- a/frontend/src/app/shared/cards/season-main-card/season-main-card.component.html +++ b/frontend/src/app/shared/cards/season-main-card/season-main-card.component.html @@ -6,7 +6,7 @@
{{season.name}}

{{season.air_date | dateFormat:'yyyy'}}

-
+
@@ -14,10 +14,15 @@
{{episodesWatchedCount}}/{{this.season.episode_count}}
-
+ +
diff --git a/frontend/src/app/shared/cards/season-main-card/season-main-card.component.ts b/frontend/src/app/shared/cards/season-main-card/season-main-card.component.ts index 8649bfb..ecec543 100644 --- a/frontend/src/app/shared/cards/season-main-card/season-main-card.component.ts +++ b/frontend/src/app/shared/cards/season-main-card/season-main-card.component.ts @@ -1,4 +1,4 @@ -import { Component, Input, OnInit } from '@angular/core'; +import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core'; import { Season } from '../../models/season.model'; import { SeasonService } from '../../../core/services/season.service'; import { @@ -30,6 +30,7 @@ import { EpisodeSeenService } from '../../../core/services/episode-seen.service' ], }) export class SeasonMainCardComponent implements OnInit { + @Output() episodeWatchedEvent = new EventEmitter(); @Input() season: Season = {} as Season; isChecked: boolean = false; isLocked: boolean = false; @@ -43,7 +44,7 @@ export class SeasonMainCardComponent implements OnInit { // TODO: GET SEASON EPISODES this.seasonService.getSeasonEpisodes(this.season.id).subscribe({ next: (episodes) => { - console.log(episodes); + console.log(`Loaded Season Episodes: `, episodes); this.season.episodes = episodes; }, error: (error) => { @@ -82,48 +83,42 @@ export class SeasonMainCardComponent implements OnInit { return count; } - handleCheckChange() { - this.isChecked = true; - + episodeMarkSeenClick() { if (this.isLocked) return; this.isLocked = true; - if (this.isChecked) { - for (let i = this.season.episode_count; i > 0; i--) { - if (this.season.episodes[i - 1].date_first_seen != null) { - let currentEpisode = this.season.episodes[i]; - this.episodeSeenService - .createEpisodeSeen(currentEpisode.id, new Date(), 'Me, My Self & I') - .subscribe({ - next: (episodeSeen) => { - console.log(`Episode marked as seen`, episodeSeen); - this.season.episodes[i].date_first_seen = new Date(); - this.season.episodes[i].date_last_seen = new Date(); - // TODO show notification - this.isChecked = false; - this.isLocked = false; - }, - error: (error) => { - console.log(`Couldn't mark episode as seen:`, error); - // TODO show notification - this.isChecked = false; - this.isLocked = false; - }, - }); - break; - } + // starts looping from the last available episode + for (let i = this.season.episode_count; i >= 0; i--) { + // ? untils it finds that the previous episode episode is marked as seen + // ? > in that case it chooses the current one to mark + if (i == 0 || this.season.episodes[i - 1].date_first_seen != null) { + let currentEpisode = this.season.episodes[i]; + // todo: show episode seen modal + this.episodeSeenService + .createEpisodeSeen( + this.season.entry_id, + currentEpisode.id, + new Date(), + 'Me, My Self & I' + ) + .subscribe({ + next: (episodeSeen) => { + console.log(`Episode marked as seen`, episodeSeen); + this.season.episodes[i].date_first_seen = new Date(); + this.season.episodes[i].date_last_seen = new Date(); + this.episodeWatchedEvent.emit(); + // TODO show notification + }, + error: (error) => { + console.log(`Couldn't mark episode as seen:`, error); + // TODO show notification + }, + complete: () => { + this.isLocked = false; + }, + }); + break; } - - // console.log('checking'); - // this.executeFunction() - // .then(() => { - // this.isChecked = false; - // console.log('unchecking'); - // }) - // .catch((error) => { - // console.error('Failed to execute function:', error); - // this.isChecked = false; - // }); } } } diff --git a/frontend/src/app/shared/models/dtos/episode-seen.dto.ts b/frontend/src/app/shared/models/dtos/episode-seen.dto.ts new file mode 100644 index 0000000..10c64b4 --- /dev/null +++ b/frontend/src/app/shared/models/dtos/episode-seen.dto.ts @@ -0,0 +1,15 @@ +export interface EpisodeSeenDto { + id: number; + + entryId: number; + episodeId: number; + + season_number: number; + episode_number: number; + + date_seen: Date; + seen_with: string; + + createdAt: Date; + updatedAt: Date; +} diff --git a/frontend/src/app/shared/models/episodeSeen.model.ts b/frontend/src/app/shared/models/episodeSeen.model.ts index e56b4b3..8100430 100644 --- a/frontend/src/app/shared/models/episodeSeen.model.ts +++ b/frontend/src/app/shared/models/episodeSeen.model.ts @@ -1,6 +1,7 @@ export interface EpisodeSeen { id: number; + entry_id: number; episode_id: number; date_seen: Date; diff --git a/frontend/src/app/shared/models/season.model.ts b/frontend/src/app/shared/models/season.model.ts index f712360..47b1fb3 100644 --- a/frontend/src/app/shared/models/season.model.ts +++ b/frontend/src/app/shared/models/season.model.ts @@ -8,7 +8,7 @@ export interface Season { tmdb_id: string; imdb_id: string; - entry_id: string; + entry_id: number; name: string; overview: string;