All files / src/handlers EventHandlers.js

93.56% Statements 218/233
91.47% Branches 118/129
95.23% Functions 20/21
93.27% Lines 208/223

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 5098x 8x                               88x 88x       1x       1x                           5x     5x 1x 1x     4x     4x                                                 11x 11x         10x 10x       10x 2x 2x     8x   7x   7x 4x   4x 2x 2x 2x 2x 2x     3x       2x           12x 12x   10x 10x 7x 4x   3x           4x 4x     4x 4x 1x 1x         3x   3x     3x     1x         3x 3x   1x         8x   8x 8x 1x   8x 1x     8x 1x     8x 8x 1x 1x     7x 7x 7x   7x     7x     7x 7x 1x 1x 1x     6x   6x 6x   4x 3x 1x 1x       3x             17x   17x 3x 3x     14x     14x 1x 1x         11x 1x 1x       10x   2x 1x     1x 1x           9x 1x 1x       8x 8x 8x 8x   8x 2x 2x       6x 2x 2x 2x   2x         2x                           4x 4x   2x               19x 10x   9x             7x   7x     7x   7x             7x         7x 7x 1x 1x       6x   6x 6x 6x 6x   6x   4x 3x 3x 3x   2x 2x 2x     5x   5x 3x 3x     2x   2x 2x 2x               2x   2x 2x 2x 2x 1x   2x     2x   2x     1x 1x               8x   8x 8x   8x 1x 1x             7x   5x   5x 2x 2x       16x 3x     3x   3x 7x 7x               7x   7x 7x 7x 7x 1x   7x     3x 1x   3x   3x     2x 2x                 22x 4x     18x 18x   18x   3x 3x 3x   3x 2x 1x 1x             15x 15x   15x 8x 2x       8x
const { ChannelType } = require('discord.js');
const ActionExecutor = require('../processors/ActionExecutor');
 
/**
 * EventHandlers - Central Discord event processor and router
 * 
 * Handles all incoming Discord events (reactions, messages) and routes them to appropriate processors.
 * Coordinates between the legacy reaction role system and the new proposal/voting system.
 * Acts as the primary interface between Discord.js events and bot functionality.
 * 
 * Design rationale:
 * - Centralizes event handling to prevent duplicate listeners and ensure consistent processing
 * - Separates concerns by delegating to specialized processors based on event context
 * - Provides a unified error handling approach for all Discord interactions
 */
class EventHandlers {
    constructor(bot) {
        this.bot = bot;
        this.actionExecutor = new ActionExecutor(bot);
    }
 
    async handleReactionAdd(reaction, user) {
        await this.processReaction(reaction, user, 'add');
    }
 
    async handleReactionRemove(reaction, user) {
        await this.processReaction(reaction, user, 'remove');
    }
 
    /**
     * Core reaction processing logic
     * 
     * Processes reactions for both reaction roles and proposal systems simultaneously.
     * This dual-processing approach ensures backward compatibility while enabling new features.
     * 
     * @param {MessageReaction} reaction - Discord reaction object
     * @param {User} user - User who added/removed the reaction
     * @param {string} type - 'add' or 'remove'
     */
    async processReaction(reaction, user, type) {
        console.log(`[RAW REACTION EVENT] Reaction ${type}: ${reaction.emoji.name} by ${user.tag} on message ${reaction.message.id}`);
        
        // Ignore bot reactions to prevent infinite loops and unintended role assignments
        if (this.bot.getUserValidator().isBot(user)) {
            console.log('Ignoring bot reaction');
            return;
        }
 
        try {
            // Process reactions through both systems simultaneously for comprehensive handling
            // Legacy reaction role system for configured messages + new proposal system
            await Promise.all([
                this.handleReaction(reaction, user, type),
                this.handleProposalReaction(reaction, user, type)
            ]);
        } catch (error) {
            console.error('Error processing reaction:', error);
        }
    }
 
    /**
     * Handle proposal system reactions
     * 
     * Routes reactions to appropriate proposal processors based on channel context.
     * Supports both proposal support gathering and vote counting.
     * 
     * Channel-based routing rationale:
     * - Debate channels: Support gathering for proposals to reach voting threshold
     * - Vote channels: Vote counting for active proposals
     * - Resolution channels: Read-only archive, no processing needed
     * 
     * @param {MessageReaction} reaction - Discord reaction object
     * @param {User} user - User who reacted
     * @param {string} type - 'add' or 'remove'
     */
    async handleProposalReaction(reaction, user, type) {
        try {
            console.log(`handleProposalReaction: ${reaction.emoji.name} ${type} by ${user.tag} on message ${reaction.message.id}`);
            
            // Note: Partial fetching is already handled in the parallel call from processReaction
            // No need to duplicate the fetching logic here
 
            const message = reaction.message;
            const emoji = reaction.emoji.name;
 
            // Verify this reaction is in the correct Discord server
            // Prevents cross-server interference if bot serves multiple guilds
            if (message.guild?.id !== this.bot.getGuildId()) {
                console.log(`Wrong guild: ${message.guild?.id} vs ${this.bot.getGuildId()}`);
                return;
            }
 
            console.log(`Message channel: ${message.channel.id}`);
            
            const channelType = this.getProposalChannelType(message.channel.id);
            
            if (channelType) {
                console.log(`Message is in a monitored ${channelType} channel`);
                
                if (channelType === 'debate' && emoji === '✅') {
                    console.log('Processing support reaction in debate channel');
                    await this.handleSupportReaction(message);
                } else Eif (channelType === 'vote' && (emoji === '✅' || emoji === '❌')) {
                    console.log('Processing vote reaction in vote channel');
                    await this.handleVotingReaction(message, emoji, type);
                }
            } else {
                console.log(`Reaction not in monitored proposal channels. Channel: ${message.channel.id}, Emoji: ${emoji}`);
            }
 
        } catch (error) {
            console.error('Error handling proposal reaction:', error);
        }
    }
 
    // Helper method to determine what type of proposal channel this is
    getProposalChannelType(channelId) {
        const proposalConfig = this.bot.getProposalManager().proposalConfig;
        if (!proposalConfig) return null;
 
        for (const config of Object.values(proposalConfig)) {
            if (config.debateChannelId === channelId) return 'debate';
            if (config.voteChannelId === channelId) return 'vote';
            if (config.resolutionsChannelId === channelId) return 'resolutions';
        }
        return null;
    }
 
    // Process support reactions that could advance proposals to voting
    // Counts ✅ reactions and forwards to proposal manager for threshold checking
    async handleSupportReaction(message) {
        try {
            console.log(`handleSupportReaction called for message ${message.id} in channel ${message.channel.id}`);
            
            // Get the ✅ reaction object from Discord's cache
            const supportReaction = message.reactions.cache.get('✅');
            if (!supportReaction) {
                console.log('No ✅ reaction found on message');
                return;
            }
 
            // Calculate actual user support count by excluding the bot's own reaction
            // Bot automatically adds reactions to vote messages, so we subtract those
            const supportCount = Math.max(0, supportReaction.count - (supportReaction.me ? 1 : 0));
            
            console.log(`Support reaction count for message ${message.id}: ${supportCount} (total: ${supportReaction.count}, bot reacted: ${supportReaction.me})`);
 
            // Delegate to proposal manager for threshold evaluation and advancement logic
            await this.bot.getProposalManager().handleSupportReaction(message, supportCount);
 
        } catch (error) {
            console.error('Error handling support reaction:', error);
        }
    }
 
    async handleVotingReaction(message, emoji, type) {
        try {
            await this.bot.getProposalManager().handleVoteReaction(message, emoji, type === 'add');
        } catch (error) {
            console.error('Error handling voting reaction:', error);
        }
    }
 
    async handleReaction(reaction, user, type) {
        try {
            // Fetch partial reactions/messages in parallel for better performance
            const fetchPromises = [];
            if (reaction.partial) {
                fetchPromises.push(reaction.fetch());
            }
            if (reaction.message.partial) {
                fetchPromises.push(reaction.message.fetch());
            }
            
            if (fetchPromises.length > 0) {
                await Promise.all(fetchPromises);
            }
 
            const message = reaction.message;
            if (message.guild?.id !== this.bot.getGuildId()) {
                console.log(`Reaction on wrong guild: ${message.guild?.id} vs ${this.bot.getGuildId()}`);
                return;
            }
 
            const emoji = reaction.emoji.name;
            const messageId = message.id;
            const userId = user.id;
 
            console.log(`Reaction ${type}: ${emoji} on message ${messageId} by user ${userId} in guild ${message.guild.id}`);
 
            // Check what config we have
            const currentConfig = this.bot.getConfigManager().getConfig();
 
            // Find matching config
            const configItem = this.bot.getConfigManager().findConfig(messageId, emoji);
            if (!configItem) {
                console.log(`No config found for message ${messageId} with emoji ${emoji}`);
                console.log(`Available configs:`, currentConfig.map(c => `${c.from}:${c.action}`));
                return;
            }
 
            console.log(`Found matching config:`, configItem);
 
            const guild = message.guild;
            const member = await guild.members.fetch(userId);
 
            if (type === 'add' && configItem.to) {
                await this.actionExecutor.executeAction(configItem.to, member, guild);
            } else Eif (type === 'remove' && configItem.unto) {
                await this.actionExecutor.executeAction(configItem.unto, member, guild);
            }
 
        } catch (error) {
            console.error('Error handling reaction:', error);
        }
    }
 
    // Process all incoming messages for bot commands
    // Filters for command prefix and authorized channels before processing
    async handleMessage(message) {
        try {
            // Null check for message object
            if (!message || !message.content || !message.channel || !message.author) {
                console.error('Invalid message object received');
                return;
            }
 
            console.log(`Message received: "${message.content}" in channel ${message.channel.id} by ${message.author.tag}`);
        
        // Ignore messages from bots to prevent command loops and spam
        if (this.bot.getUserValidator().isBot(message.author)) {
            console.log('Ignoring bot message');
            return;
        }
 
        // CRITICAL: Only process messages from the configured guild
        // This prevents cross-guild interference when multiple bot instances use the same token
        if (message.guild?.id !== this.bot.getGuildId()) {
            console.log(`Ignoring message from wrong guild: ${message.guild?.id} vs configured guild: ${this.bot.getGuildId()}`);
            return;
        }
 
        // Check if this bot is enabled - if disabled, ignore all commands except boton/botoff
        if (!this.bot.isThisBotEnabled()) {
            // Allow boton and botoff commands even when bot is disabled (admin override)
            if (message.content.startsWith('!boton ') || message.content.startsWith('!botoff ')) {
                console.log('Bot is disabled, but processing admin bot control command');
                // Continue processing the bot control command
            } else {
                console.log('Bot is disabled, ignoring all commands');
                return;
            }
        }
 
        // Only process messages that start with command prefix
        // This prevents the bot from responding to normal conversation
        if (!message.content.startsWith('!')) {
            console.log('Message does not start with !, ignoring');
            return;
        }
 
        // Restrict command processing to designated command channels or regional/local channels for !events
        const isModeratorChannel = message.channel.id === this.bot.getCommandChannelId();
        const isMemberChannel = message.channel.id === this.bot.getMemberCommandChannelId();
        const isEventsCommand = message.content.startsWith('!events');
        const isRegionalOrLocalChannel = this.isRegionalOrLocalChannel(message.channel.name);
        
        if (!isModeratorChannel && !isMemberChannel && !(isEventsCommand && isRegionalOrLocalChannel)) {
            console.log(`Message not in authorized channels for this command, ignoring`);
            return;
        }
 
        // Handle !events command specially based on channel type
        if (isEventsCommand) {
            if (isRegionalOrLocalChannel) {
                        console.log(`Processing !events command from ${message.author.tag} in regional/local channel ${message.channel.name}`);
                try {
                    // Process events and return immediately - do not continue to CommandRouter
                    await this.handleEventsCommand(message);
                } catch (error) {
                    console.error('Error in handleEventsCommand:', error);
                    await message.reply('❌ An error occurred while processing your events command.').catch(console.error);
                }
                return; // CRITICAL: Always return early for regional/local channels
            } else Eif (isModeratorChannel || isMemberChannel) {
                console.log(`Processing !events command from ${message.author.tag} in bot channel`);
                try {
                    // Process events and return immediately - do not continue to CommandRouter  
                    await this.handleAllEventsCommand(message);
                } catch (error) {
                    console.error('Error in handleAllEventsCommand:', error);
                    await message.reply('❌ An error occurred while processing your events command.').catch(console.error);
                }
                return; // CRITICAL: Always return early for bot channels
            }
        }
 
        console.log(`Processing command from ${message.author.tag}: "${message.content}" in ${isModeratorChannel ? 'moderator' : 'member'} channel`);
        await this.bot.commandRouter.handleCommand(message, isModeratorChannel);
        } catch (error) {
            console.error('Error handling message:', error);
        }
    }
 
    /**
     * Check if a channel name follows regional or local naming pattern
     */
    isRegionalOrLocalChannel(channelName) {
        if (!channelName || typeof channelName !== 'string') {
            return false;
        }
        return channelName.startsWith('regional-') || channelName.startsWith('local-');
    }
 
    /**
     * Handle !events command in regional/local channels
     */
    async handleEventsCommand(message) {
        try {
            // Check if user has member role - use fresh fetch to avoid cache issues
            const guild = message.guild;
            
            let member;
            try {
                // Try to fetch fresh member data first, fall back to cache if needed
                member = await guild.members.fetch(message.author.id).catch(() => 
                    guild.members.cache.get(message.author.id)
                );
            } catch (error) {
                member = null;
            }
            
            Iif (!member) {
                await message.reply('❌ Could not find your membership in this server.');
                return;
            }
 
            const isMember = this.bot.getUserValidator().hasRole(member, this.bot.getMemberRoleId());
            if (!isMember) {
                await message.reply('❌ You need the member role to use this command.');
                return;
            }
 
            // Check if user is a moderator for enhanced display
            const isModerator = this.bot.getUserValidator().canUseModerator(member, this.bot.getModeratorRoleId());
 
            const channelName = message.channel.name;
            let events = [];
            let areaName = '';
            let areaType = '';
 
            if (channelName.startsWith('regional-')) {
                // Extract region name from channel name: regional-north-east -> North East
                areaName = channelName.substring(9).replace(/-/g, ' ').replace(/\b\w/g, l => l.toUpperCase());
                areaType = 'regional';
                events = await this.bot.getEventManager().getUpcomingEventsByRegion(guild.id, areaName);
            } else if (channelName.startsWith('local-')) {
                // Extract location name from channel name: local-blyth-ashington-morpeth -> Blyth/Ashington/Morpeth  
                areaName = channelName.substring(6).replace(/-/g, '/').replace(/\b\w/g, l => l.toUpperCase());
                areaType = 'local';
                events = await this.bot.getEventManager().getUpcomingEventsByLocation(guild.id, areaName);
            }
 
            console.log(`Found ${events.length} upcoming events for ${areaType} area: ${areaName}`);
 
            if (events.length === 0) {
                await message.reply(`📅 **No upcoming events found for ${areaName}**\n\nCheck back later or suggest new events with \`!addevent\` in a moderator channel!`);
                return;
            }
            // Format events list
            let eventsDisplay = `📅 **Upcoming Events in ${areaName}** (Next ${events.length}):\n\n`;
            
            events.forEach((event, index) => {
                const eventDate = new Date(event.event_date);
                const formattedDate = eventDate.toLocaleDateString('en-GB', {
                    weekday: 'short',
                    month: 'short', 
                    day: 'numeric',
                    hour: '2-digit',
                    minute: '2-digit'
                });
 
                const timeUntil = this.getTimeUntilEvent(eventDate);
                
                eventsDisplay += `**${index + 1}.** 🎉 **${event.name}**\n`;
                eventsDisplay += `   📅 ${formattedDate} (${timeUntil})\n`;
                eventsDisplay += `   📍 ${event.region}${event.location ? ` → ${event.location}` : ''}\n`;
                if (event.link) {
                    eventsDisplay += `   🔗 <${event.link}>\n`;
                }
                eventsDisplay += `   👤 <@${event.created_by}>\n\n`;
            });
 
            eventsDisplay += `💡 **Want to add an event?** Ask a moderator to use \`!addevent\` in their bot channel!`;
 
            await message.reply(eventsDisplay);
 
        } catch (error) {
            console.error('Error handling !events command:', error);
            await message.reply('❌ An error occurred while fetching events.');
        }
    }
 
    /**
     * Handle !events command in bot channels - shows next 3 events from all regions
     */
    async handleAllEventsCommand(message) {
        try {
            // Get guild and member (member validation is handled by CommandRouter)
            const guild = message.guild;
            const member = guild.members.cache.get(message.author.id);
            
            if (!member) {
                await message.reply('❌ Could not find your membership in this server.');
                return;
            }
 
            // Skip member role validation here since CommandRouter already validates it
            // This method is called from bot channels where user permissions are pre-verified
 
            // Get all upcoming events from all regions (limit 50 to avoid performance issues)
            const allEvents = await this.bot.getEventManager().getAllUpcomingEvents(guild.id, 50);
            
            console.log(`Found ${allEvents.length} total upcoming events across all regions`);
 
            if (allEvents.length === 0) {
                await message.reply(`📅 **No upcoming events found across all regions**\n\nCheck back later or ask moderators to add events with \`!addevent\`!`);
                return;
            }
 
            // Sort by event date and take the next 3
            const sortedEvents = allEvents.sort((a, b) => new Date(a.event_date) - new Date(b.event_date));
            const nextThreeEvents = sortedEvents.slice(0, 3);
 
            // Format events list
            let eventsDisplay = `📅 **Next ${nextThreeEvents.length} Upcoming Events (All Regions):**\n\n`;
            
            nextThreeEvents.forEach((event, index) => {
                const eventDate = new Date(event.event_date);
                const formattedDate = eventDate.toLocaleDateString('en-GB', {
                    weekday: 'short',
                    month: 'short', 
                    day: 'numeric',
                    hour: '2-digit',
                    minute: '2-digit'
                });
 
                const timeUntil = this.getTimeUntilEvent(eventDate);
                
                eventsDisplay += `**${index + 1}.** 🎉 **${event.name}**\n`;
                eventsDisplay += `   📅 ${formattedDate} (${timeUntil})\n`;
                eventsDisplay += `   📍 ${event.region}${event.location ? ` → ${event.location}` : ''}\n`;
                if (event.link) {
                    eventsDisplay += `   🔗 <${event.link}>\n`;
                }
                eventsDisplay += `   👤 <@${event.created_by}>\n\n`;
            });
 
            if (allEvents.length > 3) {
                eventsDisplay += `💡 **${allEvents.length - 3} more events available** - check regional channels for area-specific events!\n`;
            }
            eventsDisplay += `\n🏘️ **Want area-specific events?** Use \`!events\` in regional/local channels!`;
 
            await message.reply(eventsDisplay);
 
        } catch (error) {
            console.error('Error handling !events command in bot channel:', error);
            await message.reply('❌ An error occurred while fetching events.');
        }
    }
 
    /**
     * Get human-readable time until/since event
     */
    getTimeUntilEvent(eventDate) {
        // Handle null, undefined, or invalid dates
        if (!eventDate || typeof eventDate.getTime !== 'function' || isNaN(eventDate.getTime())) {
            return 'Event has started';
        }
        
        const now = new Date();
        const timeDiff = eventDate.getTime() - now.getTime();
        
        if (timeDiff <= 0) {
            // Event has started - show how long ago
            const timeSinceStart = Math.abs(timeDiff);
            const hoursSince = Math.floor(timeSinceStart / (1000 * 60 * 60));
            const minutesSince = Math.floor((timeSinceStart % (1000 * 60 * 60)) / (1000 * 60));
            
            if (hoursSince >= 1) {
                return `started ${hoursSince}h ago`;
            } else if (minutesSince >= 1) {
                return `started ${minutesSince}m ago`;
            } else E{
                return 'just started';
            }
        }
        
        // Event hasn't started yet
        const days = Math.floor(timeDiff / (1000 * 60 * 60 * 24));
        const hours = Math.floor((timeDiff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
        
        if (days > 0) return `in ${days} day${days !== 1 ? 's' : ''}`;
        if (hours > 0) return `in ${hours} hour${hours !== 1 ? 's' : ''}`;
        return 'very soon';
    }
}
 
module.exports = EventHandlers;