@@ -200,39 +200,52 @@ function computeDailyBreakdown(
200200 } ) )
201201}
202202
203+ function getDateRangeForPeriod (
204+ period : StatsPeriod ,
205+ now : Date ,
206+ movieData : { date : Date | null } [ ] ,
207+ episodes : { watchedAt : Date | null } [ ]
208+ ) : { startDate : Date ; endDate : Date } | null {
209+ if ( period === 'month' ) {
210+ return {
211+ startDate : new Date ( now . getFullYear ( ) , now . getMonth ( ) , 1 ) ,
212+ endDate : now ,
213+ }
214+ }
215+ if ( period === 'last_month' ) {
216+ return {
217+ startDate : new Date ( now . getFullYear ( ) , now . getMonth ( ) - 1 , 1 ) ,
218+ endDate : new Date ( now . getFullYear ( ) , now . getMonth ( ) , 0 ) ,
219+ }
220+ }
221+ if ( period === 'year' ) {
222+ return {
223+ startDate : new Date ( now . getFullYear ( ) , 0 , 1 ) ,
224+ endDate : now ,
225+ }
226+ }
227+ const allTimestamps = [
228+ ...movieData . flatMap ( m => ( m . date ? [ m . date . getTime ( ) ] : [ ] ) ) ,
229+ ...episodes . flatMap ( e => ( e . watchedAt ? [ e . watchedAt . getTime ( ) ] : [ ] ) ) ,
230+ ]
231+ if ( allTimestamps . length === 0 ) return null
232+ const start = new Date ( Math . min ( ...allTimestamps ) )
233+ return {
234+ startDate : new Date ( start . getFullYear ( ) , start . getMonth ( ) , start . getDate ( ) ) ,
235+ endDate : now ,
236+ }
237+ }
238+
203239function computeAllDailyActivity (
204240 movieData : { runtime : number ; date : Date | null } [ ] ,
205241 episodes : { runtime : number ; watchedAt : Date | null } [ ] ,
206242 period : StatsPeriod
207243) {
208244 const now = new Date ( )
209- let startDate : Date
210- let endDate : Date
211-
212- if ( period === 'month' ) {
213- startDate = new Date ( now . getFullYear ( ) , now . getMonth ( ) , 1 )
214- endDate = now
215- } else if ( period === 'last_month' ) {
216- startDate = new Date ( now . getFullYear ( ) , now . getMonth ( ) - 1 , 1 )
217- endDate = new Date ( now . getFullYear ( ) , now . getMonth ( ) , 0 )
218- } else if ( period === 'year' ) {
219- startDate = new Date ( now . getFullYear ( ) , 0 , 1 )
220- endDate = now
221- } else {
222- const allDates = [
223- ...movieData . filter ( m => m . date ) . map ( m => m . date ! . getTime ( ) ) ,
224- ...episodes . filter ( e => e . watchedAt ) . map ( e => e . watchedAt ! . getTime ( ) ) ,
225- ]
226- if ( allDates . length === 0 ) return [ ]
227- startDate = new Date ( Math . min ( ...allDates ) )
228- startDate = new Date (
229- startDate . getFullYear ( ) ,
230- startDate . getMonth ( ) ,
231- startDate . getDate ( )
232- )
233- endDate = now
234- }
245+ const range = getDateRangeForPeriod ( period , now , movieData , episodes )
246+ if ( ! range ) return [ ]
235247
248+ const { startDate, endDate } = range
236249 const dayMap = new Map < string , number > ( )
237250 const cursor = new Date ( startDate )
238251 while ( cursor <= endDate ) {
0 commit comments