11import { getMidnightWithTimezoneOffset , getUTCMidnight } from '../utils/dates' ;
2- import { groupBy } from '../utils/grouper' ;
32import safe from 'safe-regex' ;
43
54const Factory = require ( './modelFactory' ) ;
@@ -8,6 +7,8 @@ const Event = require('../models/event');
87const { ObjectID } = require ( 'mongodb' ) ;
98const { composeEventPayloadByRepetition } = require ( '../utils/merge' ) ;
109
10+ const MAX_DB_READ_BATCH_SIZE = 80000 ;
11+
1112/**
1213 * @typedef {import('mongodb').UpdateWriteOpResult } UpdateWriteOpResult
1314 */
@@ -423,24 +424,35 @@ class EventsFactory extends Factory {
423424 } ;
424425 }
425426
426- let dailyEvents = await this . getCollection ( this . TYPES . DAILY_EVENTS )
427- . find ( options )
428- . toArray ( ) ;
427+ const dailyEventsCursor = await this . getCollection ( this . TYPES . DAILY_EVENTS )
428+ . find ( options , {
429+ projection : {
430+ lastRepetitionTime : 1 ,
431+ groupingTimestamp : 1 ,
432+ count : 1 ,
433+ } ,
434+ } )
435+ . batchSize ( MAX_DB_READ_BATCH_SIZE ) ;
429436
430- /**
431- * Convert UTC midnight to midnights in user's timezone
432- */
433- dailyEvents = dailyEvents . map ( ( item ) => {
434- return Object . assign ( { } , item , {
435- groupingTimestamp : getMidnightWithTimezoneOffset ( item . lastRepetitionTime , item . groupingTimestamp , timezoneOffset ) ,
436- } ) ;
437- } ) ;
437+ const groupedCounts = { } ;
438438
439- /**
440- * Group events using 'groupingTimestamp:NNNNNNNN' key
441- * @type {ProjectChartItem[] }
442- */
443- const groupedData = groupBy ( 'groupingTimestamp' ) ( dailyEvents ) ;
439+ for await ( const item of dailyEventsCursor ) {
440+ const groupingTimestamp = getMidnightWithTimezoneOffset (
441+ item . lastRepetitionTime ,
442+ item . groupingTimestamp ,
443+ timezoneOffset
444+ ) ;
445+
446+ const key = `groupingTimestamp:${ groupingTimestamp } ` ;
447+ const current = groupedCounts [ key ] || 0 ;
448+
449+ if ( item . count === undefined || item . count === null ) {
450+ console . warn ( `Missing 'count' field for daily event with key ${ key } . Defaulting to 0.` ) ;
451+ groupedCounts [ key ] = current ;
452+ } else {
453+ groupedCounts [ key ] = current + item . count ;
454+ }
455+ }
444456
445457 /**
446458 * Now fill all requested days
@@ -451,11 +463,16 @@ class EventsFactory extends Factory {
451463 const now = new Date ( ) ;
452464 const day = new Date ( now . setDate ( now . getDate ( ) - i ) ) ;
453465 const dayMidnight = getUTCMidnight ( day ) / 1000 ;
454- const groupedEvents = groupedData [ `groupingTimestamp:${ dayMidnight } ` ] ;
466+
467+ let groupedCount = groupedCounts [ `groupingTimestamp:${ dayMidnight } ` ] ;
468+
469+ if ( ! groupedCount ) {
470+ groupedCount = 0 ;
471+ }
455472
456473 result . push ( {
457474 timestamp : dayMidnight ,
458- count : groupedEvents ? groupedEvents . reduce ( ( sum , value ) => sum + value . count , 0 ) : 0 ,
475+ count : groupedCount ,
459476 } ) ;
460477 }
461478
0 commit comments