From a05fdd44ecdda761c5213f4bdf59ec693f8b85e2 Mon Sep 17 00:00:00 2001 From: Mohammed Abad Date: Fri, 10 May 2024 09:45:54 +0100 Subject: [PATCH] dashboard version 1 --- backend/routes/entrySeenRoutes.js | 24 ++ backend/routes/episodeSeenRoutes.js | 26 ++ backend/services/entryService.js | 184 +++++----- .../app/core/services/entry-seen.service.ts | 7 +- .../app/core/services/episode-seen.service.ts | 6 + .../src/app/features/home/home.component.html | 335 +++++++++++++++++- .../src/app/features/home/home.component.ts | 247 ++++++++++++- 7 files changed, 731 insertions(+), 98 deletions(-) diff --git a/backend/routes/entrySeenRoutes.js b/backend/routes/entrySeenRoutes.js index 8e04b0c..080fe9c 100644 --- a/backend/routes/entrySeenRoutes.js +++ b/backend/routes/entrySeenRoutes.js @@ -51,6 +51,30 @@ entrySeenRouter.get('/:id', async (req, res) => { } }); +// * GET - (STATS) YEAR SEEN HISTORY GROUPED BY MONTH +entrySeenRouter.get('/stats-year/:year', async (req, res) => { + try { + const { year } = req.params; + const stats = await EntrySeen.findAll({ + attributes: [ + [sequelize.fn('MONTH', sequelize.col('date_seen')), 'month'], + [sequelize.fn('COUNT', sequelize.col('*')), 'count'] + ], + where: { + date_seen: { + [Op.between]: [new Date(year, 0, 1), new Date(year, 11, 31)] + } + }, + group: [sequelize.fn('MONTH', sequelize.col('date_seen'))] + }); + + res.status(200).json(stats); + } catch (error) { + console.log(error) + res.status(500).json({ error: error.message }); + } +}); + // * GET - ENTRY SEEN LIST BY ENTRY ID entrySeenRouter.get('/by-entry/:entryId', async (req, res) => { try { diff --git a/backend/routes/episodeSeenRoutes.js b/backend/routes/episodeSeenRoutes.js index 43b4884..9a9470c 100644 --- a/backend/routes/episodeSeenRoutes.js +++ b/backend/routes/episodeSeenRoutes.js @@ -2,6 +2,8 @@ const express = require('express'); const Episode = require('../models/Episode'); const EpisodeSeen = require('../models/EpisodeSeen'); const Season = require('../models/Season'); +const sequelize = require('../db/database'); +const { Op } = require('sequelize'); const Entry = require('../models/Entry'); const episodeSeenRouter = express.Router(); @@ -95,6 +97,30 @@ episodeSeenRouter.get('/by-entry/:entryId', async (req, res) => { } }); +// * GET - (STATS) YEAR SEEN HISTORY GROUPED BY MONTH +episodeSeenRouter.get('/stats-year/:year', async (req, res) => { + try { + const { year } = req.params; + const stats = await EpisodeSeen.findAll({ + attributes: [ + [sequelize.fn('MONTH', sequelize.col('date_seen')), 'month'], + [sequelize.fn('COUNT', sequelize.col('*')), 'count'] + ], + where: { + date_seen: { + [Op.between]: [new Date(year, 0, 1), new Date(year, 11, 31)] + } + }, + group: [sequelize.fn('MONTH', sequelize.col('date_seen'))] + }); + + res.status(200).json(stats); + } catch (error) { + console.log(error) + res.status(500).json({ error: error.message }); + } +}); + // * PUT - UPDATE EPISODE SEEN episodeSeenRouter.put('/:id', async (req, res) => { try { diff --git a/backend/services/entryService.js b/backend/services/entryService.js index be94505..6f45d1f 100644 --- a/backend/services/entryService.js +++ b/backend/services/entryService.js @@ -8,113 +8,118 @@ const { fetchSeasonData } = require('./tmdbService.js'); const Episode = require('../models/Episode.js'); async function saveEntry(data) { - if (data == null) return; + try { + if (data == null) return; - // creating the object - var is_tvseries = data.release_date == null ? true : false; + // creating the object + var is_tvseries = data.release_date == null ? true : false; - let movie = Entry.build({ - title: data.title || data.name, - original_title: data.original_title || data.original_name, - release_date: data.release_date || data.first_air_date, - runtime: data.runtime || null, + let movie = Entry.build({ + title: data.title || data.name, + original_title: data.original_title || data.original_name, + release_date: data.release_date || data.first_air_date, + runtime: data.runtime || null, - tagline: data.tagline || null, - storyline: data.overview, - country: data.production_countries.length > 0 ? data.production_countries[0].name : null, + tagline: data.tagline || null, + storyline: data.overview, + country: data.production_countries.length > 0 ? data.production_countries[0].name : null, - is_tvseries: is_tvseries, - watchlist: true, - status: data.status, + is_tvseries: is_tvseries, + watchlist: true, + status: data.status, - genres: data.genre_ids, + genres: data.genre_ids, - poster_path: data.poster_path, - banner_path: data.backdrop_path, - }); + poster_path: data.poster_path, + banner_path: data.backdrop_path, + }); - const savedEntry = await movie.save(); + const savedEntry = await movie.save(); - // genres - data.genres.forEach(async (genre) => { - await EntryGenre.create({ - genre_id: genre.id, - entry_id: savedEntry.id - }) - }); - - const ratings = await EntryRating.create({ - entry_id: savedEntry.id, - user_rating: 0, - tmdb_rating: data.vote_average, - }); - - const ids = await EntryId.create({ - entry_id: savedEntry.id, - tmdb_id: data.id, - imdb_id: data.imdb_id, - }); - - if (is_tvseries) { - let seasons = []; - for (const season of data.seasons) { - let seasonData = await fetchSeasonData(data.id, season.season_number); - const savedSeason = await Season.create({ - tmdb_id: seasonData.id, - - entry_id: savedEntry.id, - - name: seasonData.name, - overview: seasonData.overview, - season_number: seasonData.season_number, - episode_count: seasonData.episodes.length, - air_date: seasonData.air_date, - - user_rating: 0, - tmdb_rating: seasonData.vote_average, - - poster_path: seasonData.poster_path, - banner_path: null, + // genres + data.genres.forEach(async (genre) => { + await EntryGenre.create({ + genre_id: genre.id, + entry_id: savedEntry.id }) + }); - // save episodes - let episodes = []; - for (const episode of seasonData.episodes) { - const savedEpisode = await Episode.create({ - tmdb_id: episode.id, + const ratings = await EntryRating.create({ + entry_id: savedEntry.id, + user_rating: 0, + tmdb_rating: data.vote_average, + }); - season_id: savedSeason.id, + const ids = await EntryId.create({ + entry_id: savedEntry.id, + tmdb_id: data.id, + imdb_id: data.imdb_id, + }); - name: episode.name, - overview: episode.overview, - episode_number: episode.episode_number, - episode_type: episode.episode_type, - runtime: episode.runtime, - air_date: episode.air_date, + if (is_tvseries) { + let seasons = []; + for (const season of data.seasons) { + let seasonData = await fetchSeasonData(data.id, season.season_number); + const savedSeason = await Season.create({ + tmdb_id: seasonData.id, - tmdb_rating: episode.vote_average, + entry_id: savedEntry.id, - still_path: episode.still_path, - }); + name: seasonData.name, + overview: seasonData.overview, + season_number: seasonData.season_number, + episode_count: seasonData.episodes.length, + air_date: seasonData.air_date, - episodes.push(savedEpisode); + user_rating: 0, + tmdb_rating: seasonData.vote_average, + + poster_path: seasonData.poster_path, + banner_path: null, + }) + + // save episodes + let episodes = []; + for (const episode of seasonData.episodes) { + const savedEpisode = await Episode.create({ + tmdb_id: episode.id, + + season_id: savedSeason.id, + + name: episode.name, + overview: episode.overview, + episode_number: episode.episode_number, + episode_type: episode.episode_type, + runtime: episode.runtime, + air_date: episode.air_date, + + tmdb_rating: episode.vote_average, + + still_path: episode.still_path, + }); + + episodes.push(savedEpisode); + } + + // TODO fetch cast + + savedSeason.setDataValue('episodes', episodes); + seasons.push(savedSeason) } - - // TODO fetch cast - - savedSeason.setDataValue('episodes', episodes); - seasons.push(savedSeason) + savedEntry.setDataValue('seasons', seasons); } - savedEntry.setDataValue('seasons', seasons); + + const currentGenresNames = await data.genres.map(genre => genre.name); + + savedEntry.setDataValue('entryId', ids); + savedEntry.setDataValue('entryRating', ratings); + savedEntry.setDataValue('genres', currentGenresNames); + + return savedEntry; + } catch (error) { + console.log(`Error saving entry (in entry serive): `, error); + return null } - - const currentGenresNames = await data.genres.map(genre => genre.name); - - savedEntry.setDataValue('entryId', ids); - savedEntry.setDataValue('entryRating', ratings); - savedEntry.setDataValue('genres', currentGenresNames); - - return savedEntry; } async function updateEntry(oldEntry, data) { @@ -217,7 +222,6 @@ async function updateEntry(oldEntry, data) { existingSeason = savedSeason; } - console.log(season.episodes) // Update or insert episodes for the season let updatedEpisodes = []; for (const episode of seasonData.episodes) { diff --git a/frontend/src/app/core/services/entry-seen.service.ts b/frontend/src/app/core/services/entry-seen.service.ts index 2046e8e..62b2666 100644 --- a/frontend/src/app/core/services/entry-seen.service.ts +++ b/frontend/src/app/core/services/entry-seen.service.ts @@ -21,7 +21,6 @@ export class EntrySeenService { } ); } - // get entry seen by entry id getEntrySeenById(id: string) { @@ -35,4 +34,10 @@ export class EntrySeenService { `${this.backend_apiUrl}/${this.apiAction}/${id}` ); } + + getYearlyStats(year: number) { + return this.http.get( + `${this.backend_apiUrl}/${this.apiAction}/stats-year/${year}` + ); + } } diff --git a/frontend/src/app/core/services/episode-seen.service.ts b/frontend/src/app/core/services/episode-seen.service.ts index 3d7bc33..7a8a726 100644 --- a/frontend/src/app/core/services/episode-seen.service.ts +++ b/frontend/src/app/core/services/episode-seen.service.ts @@ -58,4 +58,10 @@ export class EpisodeSeenService { `${this.backend_apiUrl}/${this.apiAction}/${id}` ); } + + getYearlyStats(year: number) { + return this.http.get( + `${this.backend_apiUrl}/${this.apiAction}/stats-year/${year}` + ); + } } diff --git a/frontend/src/app/features/home/home.component.html b/frontend/src/app/features/home/home.component.html index 95f8717..4429cc3 100644 --- a/frontend/src/app/features/home/home.component.html +++ b/frontend/src/app/features/home/home.component.html @@ -1,5 +1,332 @@ -

Home page

+ + + - \ No newline at end of file +
+
+
+
+
+
+ movie +
+
+

{{counts.movies}}

+

Movies

+
+
+
+
+
+
+
+
+
+
+ tv +
+
+

{{counts.series}}

+

Tv-Series

+
+
+
+
+
+
+
+
+
+
+ favorite_border +
+
+

{{counts.favorit}}

+

Favorits

+
+
+
+
+
+
+
+
+
+
+ playlist_add_check +
+
+

{{counts.watchlist}}

+

Watchlist

+
+
+
+
+
+
+ +
+
+
+
+
+
+
+
+
+
+

97.4K

+

Total Users

+
+ +
+
+
+
+
+

12.5% from last month

+
+
+
+
+
+
+
+
+
+

42.5K

+

Active Users

+
+ +
+
+
+
+ +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 78% + + + + + + +
+
+
+
+

24K users increased from last month

+
+
+
+
+
+
+
+
+
+

$65,129

+
+
+

+ arrow_upward8.6% +

+
+
+

Sales This Year

+
+

285 left to Goal78%

+
+
+
+
+ +
+
+
+ +
+
+
+
+
+
+
+
+
+
{{watchCount.year}} Watch Stats
+
+ +
+
+
+
+
+

+ 5/7 + + + +

+
+
+

Movies

+

{{this.watchCount.moviesTotal}}

+

16.5%55.21 USD

+
+
+
+
+
+

+ 5/7 + + + +

+
+
+

Tv-Series

+

{{this.watchCount.seriesTotal}}

+

24.9%267.35 USD

+
+
+
+
+
+
+
+ + + \ No newline at end of file diff --git a/frontend/src/app/features/home/home.component.ts b/frontend/src/app/features/home/home.component.ts index cddba90..c24547b 100644 --- a/frontend/src/app/features/home/home.component.ts +++ b/frontend/src/app/features/home/home.component.ts @@ -1,10 +1,251 @@ -import { Component } from '@angular/core'; +import { Component, OnInit } from '@angular/core'; +import ApexCharts from 'apexcharts'; +import { EntrySeenService } from '../../core/services/entry-seen.service'; +import { LibraryService } from '../../core/services/library.service'; +import { EpisodeSeenService } from '../../core/services/episode-seen.service'; +import { Observable, forkJoin } from 'rxjs'; @Component({ selector: 'app-home-page', templateUrl: './home.component.html', - styleUrls: ['./home.component.css'] + styleUrls: ['./home.component.css'], }) -export class HomeComponent { +export class HomeComponent implements OnInit { + counts: { + movies: number; + series: number; + favorit: number; + watchlist: number; + } = { + movies: 0, + series: 0, + favorit: 0, + watchlist: 0, + }; + yearlyChart: any; + watchCount: { + movies: number[]; + series: number[]; + moviesTotal: number; + seriesTotal: number; + year: number; + } = { + movies: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + series: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + moviesTotal: 0, + seriesTotal: 0, + year: 0, + }; + + constructor( + private entrySeenService: EntrySeenService, + private episodeSeenService: EpisodeSeenService, + private libraryService: LibraryService + ) { + console.log('hey im home'); + } + + async ngOnInit() { + // ? get counts (movies, series, favorit, watchlist) + this.getCounts(); + + // ? get yearly watch stats + let year: number = new Date().getFullYear(); + this.watchCount.year = year; + this.getYearlyWatchHistoryStats(); + } + + changeYear(year: number) { + // TODO implement this in the view + this.watchCount.year = year; + console.log(`Year set to: `, this.watchCount.year); + this.getYearlyWatchHistoryStats(); + } + + async getYearlyWatchHistoryStats() { + let moviesObs = this.entrySeenService.getYearlyStats(this.watchCount.year); + let seriesObs = this.episodeSeenService.getYearlyStats( + this.watchCount.year + ); + + const forkObs = forkJoin([moviesObs, seriesObs]).subscribe({ + next: ([movies, series]) => { + console.log(`results: `, movies, series); + this.watchCount.moviesTotal = 0; + this.watchCount.seriesTotal = 0; + this.watchCount.movies = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; + this.watchCount.series = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; + + for (let i = 0; i < movies.length; i++) { + this.watchCount.movies[movies[i].month - 1] = movies[i].count; + this.watchCount.moviesTotal += movies[i].count; + } + + for (let i = 0; i < series.length; i++) { + this.watchCount.series[series[i].month - 1] = series[i].count; + this.watchCount.seriesTotal += series[i].count; + } + + console.log( + `Watch stats for the year ${this.watchCount.year} fetched successfully.` + ); + this.showYearlyStats(); + }, + error: (error) => { + console.log(error); + }, + complete: () => { + forkObs.unsubscribe(); + }, + }); + + // this.entrySeenService.getYearlyStats(year).subscribe({ + // next: (stats) => { + // // looping through stats + // for (let i = 0; i < stats.length; i++) { + // this.watchCount.movies[stats[i].month - 1] = stats[i].count; + // } + // console.log(`Movies Stats for the year ${year}`, stats); + // }, + // error: (error) => { + // console.log(`Error getting stats for the year ${year}`, error); + // }, + // }); + + // this.episodeSeenService.getYearlyStats(year).subscribe({ + // next: (stats) => { + // // looping through stats + // for (let i = 0; i < stats.length; i++) { + // this.watchCount.series[stats[i].month - 1] = stats[i].count; + // } + // this.showYearlyStats(); + // console.log(`Series Stats for the year ${year}`, stats); + // }, + // error: (error) => { + // console.log(`Error getting series stats for the year ${year}`, error); + // }, + // }); + } + + getCounts() { + // TODO performance: change this to get stats from backend directly + this.libraryService.getAllEntries(true).subscribe((entries) => { + this.counts.favorit = entries.filter((e) => e.favorit).length; + this.counts.watchlist = entries.filter((e) => e.watchlist).length; + this.counts.movies = entries.filter( + (e) => !e.is_tvseries && !e.watchlist + ).length; + this.counts.series = entries.filter( + (e) => e.is_tvseries && !e.watchlist + ).length; + }); + } + + showYearlyStats() { + var yearlyChartOptions = { + series: [ + { + name: 'Movies', + data: this.watchCount.movies, + }, + { + name: 'Tv-Series Episodes', + data: this.watchCount.series, + // data: [17, 10, 45, 15, 25, 15, 40, 10, 24, 5, 6, 3], + }, + ], + chart: { + //width:150, + foreColor: '#9ba7b2', + height: 235, + type: 'bar', + toolbar: { + show: !1, + }, + sparkline: { + enabled: !1, + }, + zoom: { + enabled: false, + }, + }, + dataLabels: { + enabled: false, + }, + stroke: { + width: 4, + curve: 'smooth', + colors: ['transparent'], + }, + fill: { + type: 'gradient', + gradient: { + shade: 'dark', + gradientToColors: ['#0d6efd', '#6f42c1'], + shadeIntensity: 1, + type: 'vertical', + // opacityFrom: 0.8, + // opacityTo: 0.1, + stops: [0, 100, 100, 100], + }, + }, + colors: ['#0d6efd', '#6f42c1'], + plotOptions: { + bar: { + horizontal: false, + borderRadius: 0, + borderRadiusApplication: 'around', + borderRadiusWhenStacked: 'last', + columnWidth: '55%', + }, + }, + grid: { + show: false, + borderColor: 'rgba(0, 0, 0, 0.15)', + strokeDashArray: 4, + }, + tooltip: { + theme: 'dark', + fixed: { + enabled: !0, + }, + x: { + show: !0, + }, + y: { + title: 'dd', + }, + marker: { + show: !1, + }, + }, + xaxis: { + categories: [ + 'Jan', + 'Feb', + 'Mar', + 'Apr', + 'May', + 'Jun', + 'Jul', + 'Aug', + 'Sep', + 'Oct', + 'Nov', + 'Dec', + ], + }, + }; + + if (this.yearlyChart) { + this.yearlyChart.destroy(); // Destroy the existing chart instance if it exists + } + + this.yearlyChart = new ApexCharts( + document.querySelector('#yearlyChart'), + yearlyChartOptions + ); + this.yearlyChart.render(); + } }