diff --git a/src/bot/bot.ts b/src/bot/bot.ts index 667937c..c8682e0 100644 --- a/src/bot/bot.ts +++ b/src/bot/bot.ts @@ -1,5 +1,6 @@ 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 = new Set(); @@ -17,6 +18,9 @@ export async function startBot() { linkedGroups.add(group.id); } - await fetchGroups(communityId); // Ensure this function is imported - await configureWebhook(webhookUrl); // Ensure this function is imported + await fetchGroups(communityId); + await configureWebhook(webhookUrl); + + // Start the cleanup job + startCleanupJob(); } diff --git a/src/jobs/cleanupJob.ts b/src/jobs/cleanupJob.ts new file mode 100644 index 0000000..06c1857 --- /dev/null +++ b/src/jobs/cleanupJob.ts @@ -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(); +} diff --git a/src/services/cleanupService.ts b/src/services/cleanupService.ts new file mode 100644 index 0000000..b8fdaca --- /dev/null +++ b/src/services/cleanupService.ts @@ -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; + } +}