feat: add daily cleanup job for orphaned tasks

main
brobert (aider) 3 months ago
parent e877e14325
commit 54c723449f

@ -1,5 +1,6 @@
import { query } from '../database/db'; import { query } from '../database/db';
import { fetchGroups, configureWebhook } from './utils/api'; // Add this import import { fetchGroups, configureWebhook } from './utils/api';
import { startCleanupJob } from '../jobs/cleanupJob';
export const linkedGroups: Set<string> = new Set(); export const linkedGroups: Set<string> = new Set();
@ -17,6 +18,9 @@ export async function startBot() {
linkedGroups.add(group.id); linkedGroups.add(group.id);
} }
await fetchGroups(communityId); // Ensure this function is imported await fetchGroups(communityId);
await configureWebhook(webhookUrl); // Ensure this function is imported await configureWebhook(webhookUrl);
// Start the cleanup job
startCleanupJob();
} }

@ -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…
Cancel
Save