feat: add daily cleanup job for orphaned tasks
							parent
							
								
									e877e14325
								
							
						
					
					
						commit
						54c723449f
					
				| @ -0,0 +1,26 @@ | |||||||
|  | import { cleanupOrphanedTasks } from '../services/cleanupService'; | ||||||
|  | 
 | ||||||
|  | export function startCleanupJob() { | ||||||
|  |   // Run daily at 2 AM
 | ||||||
|  |   const cleanupInterval = 24 * 60 * 60 * 1000; // 24 hours
 | ||||||
|  |   const initialDelay = calculateInitialDelay(); | ||||||
|  | 
 | ||||||
|  |   setTimeout(() => { | ||||||
|  |     // Run immediately after delay
 | ||||||
|  |     cleanupOrphanedTasks(); | ||||||
|  |     // Then set up the daily interval
 | ||||||
|  |     setInterval(cleanupOrphanedTasks, cleanupInterval); | ||||||
|  |   }, initialDelay); | ||||||
|  | } | ||||||
|  | 
 | ||||||
|  | function calculateInitialDelay(): number { | ||||||
|  |   const now = new Date(); | ||||||
|  |   const target = new Date(now); | ||||||
|  |   target.setHours(2, 0, 0, 0); // 2 AM
 | ||||||
|  |    | ||||||
|  |   if (now > target) { | ||||||
|  |     target.setDate(target.getDate() + 1); | ||||||
|  |   } | ||||||
|  |    | ||||||
|  |   return target.getTime() - now.getTime(); | ||||||
|  | } | ||||||
| @ -0,0 +1,32 @@ | |||||||
|  | import { query, execute } from '../database/db'; | ||||||
|  | import { Task } from '../models/task'; | ||||||
|  | 
 | ||||||
|  | // Find and clean up orphaned tasks
 | ||||||
|  | export function cleanupOrphanedTasks() { | ||||||
|  |   try { | ||||||
|  |     // Find tasks assigned to non-existent users
 | ||||||
|  |     const orphanedTasks = query(` | ||||||
|  |       SELECT t.id  | ||||||
|  |       FROM tasks t | ||||||
|  |       LEFT JOIN users u ON t.assigned_to = u.phone_number | ||||||
|  |       WHERE t.assigned_to != ''  | ||||||
|  |         AND u.phone_number IS NULL | ||||||
|  |     `);
 | ||||||
|  | 
 | ||||||
|  |     if (orphanedTasks.length > 0) { | ||||||
|  |       console.log(`Found ${orphanedTasks.length} orphaned tasks, cleaning up...`); | ||||||
|  |        | ||||||
|  |       // Unassign the tasks
 | ||||||
|  |       execute(` | ||||||
|  |         UPDATE tasks  | ||||||
|  |         SET assigned_to = '' | ||||||
|  |         WHERE id IN (${orphanedTasks.map(t => t.id).join(',')}) | ||||||
|  |       `);
 | ||||||
|  |     } | ||||||
|  | 
 | ||||||
|  |     return orphanedTasks.length; | ||||||
|  |   } catch (error) { | ||||||
|  |     console.error('Error during cleanup:', error); | ||||||
|  |     return 0; | ||||||
|  |   } | ||||||
|  | } | ||||||
					Loading…
					
					
				
		Reference in New Issue