@@ -1558,13 +1558,26 @@ const timeEntrycontroller = function (TimeEntry) {
15581558 * recalculate the hoursByCategory for all users and update the field
15591559 */
15601560 const recalculateHoursByCategoryAllUsers = async function ( taskId ) {
1561- if ( mongoose . connection . readyState === 0 ) {
1561+ // Check if MongoDB connection is ready before attempting to start a session
1562+ // readyState: 0 = disconnected, 1 = connected, 2 = connecting, 3 = disconnecting
1563+ if ( mongoose . connection . readyState !== 1 ) {
1564+ const recalculationTask = recalculationTaskQueue . find ( ( task ) => task . taskId === taskId ) ;
1565+ if ( recalculationTask ) {
1566+ recalculationTask . status = 'Failed' ;
1567+ recalculationTask . completionTime = new Date ( ) . toISOString ( ) ;
1568+ }
1569+
1570+ logger . logInfo (
1571+ `Recalculation task ${ taskId } skipped: MongoDB connection not ready (state: ${ mongoose . connection . readyState } )` ,
1572+ ) ;
15621573 return ;
15631574 }
1564- const session = await mongoose . startSession ( ) ;
1565- session . startTransaction ( ) ;
15661575
1576+ let sesh ;
15671577 try {
1578+ sesh = await mongoose . startSession ( ) ;
1579+ sesh . startTransaction ( ) ;
1580+
15681581 const userprofiles = await UserProfile . find ( { } , '_id' ) . lean ( ) ;
15691582
15701583 const recalculationPromises = userprofiles . map ( async ( userprofile ) => {
@@ -1574,15 +1587,17 @@ const timeEntrycontroller = function (TimeEntry) {
15741587 } ) ;
15751588 await Promise . all ( recalculationPromises ) ;
15761589
1577- await session . commitTransaction ( ) ;
1590+ await sesh . commitTransaction ( ) ;
15781591
15791592 const recalculationTask = recalculationTaskQueue . find ( ( task ) => task . taskId === taskId ) ;
15801593 if ( recalculationTask ) {
15811594 recalculationTask . status = 'Completed' ;
15821595 recalculationTask . completionTime = new Date ( ) . toISOString ( ) ;
15831596 }
15841597 } catch ( err ) {
1585- await session . abortTransaction ( ) ;
1598+ if ( sesh ) {
1599+ await sesh . abortTransaction ( ) ;
1600+ }
15861601 const recalculationTask = recalculationTaskQueue . find ( ( task ) => task . taskId === taskId ) ;
15871602 if ( recalculationTask ) {
15881603 recalculationTask . status = 'Failed' ;
@@ -1591,7 +1606,9 @@ const timeEntrycontroller = function (TimeEntry) {
15911606
15921607 logger . logException ( err ) ;
15931608 } finally {
1594- session . endSession ( ) ;
1609+ if ( sesh ) {
1610+ sesh . endSession ( ) ;
1611+ }
15951612 }
15961613 } ;
15971614
0 commit comments