All files / src/managers EventNotificationManager.js

100% Statements 109/109
90.24% Branches 74/82
100% Functions 16/16
100% Lines 107/107

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                                34x             7x   7x 7x 9x     7x     7x 7x 6x 6x 15x     6x     23x 6x     7x     7x 6x                       6x 4x                     6x     1x               8x 8x 8x 1x 1x       7x 7x 7x     7x 7x 7x 7x 14x       7x 7x 7x         7x 1x 1x 6x 4x 4x 2x 1x 1x   1x 1x     7x     7x 7x                     6x 6x                   6x     1x               10x     10x               10x           10x 10x 10x   10x                             10x     10x               10x           10x 10x 10x   10x 10x 2x     10x                           13x   13x 1x     12x 12x 12x   12x 2x 10x 9x   1x               4x   4x 4x 4x       4x 4x 3x 3x 6x       4x     4x 4x                     3x 2x                   3x     1x               6x     6x               6x           6x 6x 6x   6x                 6x
/**
 * EventNotificationManager - Handles Discord message formatting and channel notifications
 * 
 * Manages event notifications to appropriate regional and local Discord channels,
 * ensuring community members are informed about relevant events in their areas.
 * 
 * Design rationale:
 * - Targeted notifications: Events are sent to region/location channels to reduce noise
 * - Rich formatting: Uses Discord embeds and structured formatting for better readability
 * - Channel auto-discovery: Automatically finds appropriate channels based on naming conventions
 * - Timezone awareness: All times are displayed in UK timezone for consistency
 * - Multiple notification types: Supports creation, reminder, and cancellation notifications
 * - Error resilience: Gracefully handles missing channels or notification failures
 */
class EventNotificationManager {
    constructor(bot) {
        this.bot = bot;
    }
 
    /**
     * Send event notification to appropriate channels
     */
    async sendEventNotification(guild, event, regionRole, locationRole) {
        try {
            // Find regional channel
            const regionChannelName = `regional-${event.region.toLowerCase().replace(/\s+/g, '-')}`;
            const regionChannel = guild.channels.cache.find(channel => 
                channel.name === regionChannelName && channel.type === 0 // Text channel
            );
 
            console.log(`🔍 Looking for regional channel: ${regionChannelName} - Found: ${regionChannel ? regionChannel.name : 'NOT FOUND'}`);
 
            // Find local channel if location specified
            let locationChannel = null;
            if (event.location) {
                const locationChannelName = `local-${event.location.toLowerCase().replace(/\s+/g, '-').replace(/\//g, '-')}`;
                locationChannel = guild.channels.cache.find(channel => 
                    channel.name === locationChannelName && channel.type === 0
                );
                
                console.log(`🔍 Looking for location channel: ${locationChannelName} - Found: ${locationChannel ? locationChannel.name : 'NOT FOUND'}`);
                
                // Debug: show all available local channels
                const localChannels = guild.channels.cache.filter(ch => ch.name.startsWith('local-')).map(ch => ch.name);
                console.log(`🔍 Available local channels: ${localChannels.join(', ')}`);
            }
 
            const eventMessage = this.formatEventMessage(event);
 
            // Send to regional channel
            if (regionChannel) {
                await regionChannel.send({
                    content: `${regionRole} - New event in your region!`,
                    embeds: [{
                        title: '🎉 New Regional Event',
                        description: eventMessage,
                        color: 0x00ff00,
                        timestamp: new Date().toISOString()
                    }]
                });
            }
 
            // Send to location channel if exists
            if (locationChannel && locationRole) {
                await locationChannel.send({
                    content: `${locationRole} - New event in your area!`,
                    embeds: [{
                        title: '🎉 New Local Event',
                        description: eventMessage,
                        color: 0x00ff00,
                        timestamp: new Date().toISOString()
                    }]
                });
            }
 
            console.log(`Event notification sent for: ${event.name}`);
 
        } catch (error) {
            console.error('Error sending event notification:', error);
        }
    }
 
    /**
     * Send event reminder to channels
     */
    async sendEventReminder(event, reminderType, intervalMs, isAfterCreation = false) {
        try {
            const guild = this.bot.client.guilds.cache.get(event.guild_id);
            if (!guild) {
                console.error(`Guild ${event.guild_id} not found for reminder`);
                return;
            }
 
            // Find channels
            const regionChannelName = `regional-${event.region.toLowerCase().replace(/\s+/g, '-')}`;
            const regionChannel = guild.channels.cache.find(channel => 
                channel.name === regionChannelName && channel.type === 0
            );
 
            let locationChannel = null;
            Eif (event.location) {
                const locationChannelName = `local-${event.location.toLowerCase().replace(/\s+/g, '-').replace(/\//g, '-')}`;
                locationChannel = guild.channels.cache.find(channel => 
                    channel.name === locationChannelName && channel.type === 0
                );
            }
 
            const eventDate = new Date(event.event_date);
            const now = new Date();
            const timeUntil = this.getTimeUntilEvent(eventDate, now);
 
            let reminderTitle;
            let reminderColor;
            
            if (reminderType === 'week') {
                reminderTitle = '📅 Event Reminder - One Week';
                reminderColor = 0xffff00; // Yellow
            } else if (reminderType === 'day') {
                reminderTitle = '⏰ Event Reminder - Tomorrow';
                reminderColor = 0xff9900; // Orange
            } else if (reminderType === 'soon') {
                reminderTitle = '🚨 Event Starting Soon';
                reminderColor = 0xff0000; // Red
            } else {
                reminderTitle = '📅 Event Reminder';
                reminderColor = 0x0099ff; // Blue
            }
 
            const reminderMessage = this.formatReminderMessage(event, timeUntil, isAfterCreation);
 
            // Send to regional channel
            Eif (regionChannel) {
                await regionChannel.send({
                    embeds: [{
                        title: reminderTitle,
                        description: reminderMessage,
                        color: reminderColor,
                        timestamp: new Date().toISOString()
                    }]
                });
            }
 
            // Send to location channel if exists
            Eif (locationChannel) {
                await locationChannel.send({
                    embeds: [{
                        title: reminderTitle,
                        description: reminderMessage,
                        color: reminderColor,
                        timestamp: new Date().toISOString()
                    }]
                });
            }
 
            console.log(`${reminderType} reminder sent for event: ${event.name}`);
 
        } catch (error) {
            console.error(`Error sending ${reminderType} reminder:`, error);
        }
    }
 
    /**
     * Format event message for notifications
     */
    formatEventMessage(event) {
        const eventDate = new Date(event.event_date);
        
        // Use consistent date/time formatting to avoid cross-platform issues
        const dateOptions = {
            weekday: 'long',
            year: 'numeric',
            month: 'long',
            day: 'numeric',
            timeZone: 'Europe/London'
        };
        
        const timeOptions = {
            hour: '2-digit',
            minute: '2-digit',
            timeZone: 'Europe/London'
        };
        
        const datePart = eventDate.toLocaleDateString('en-GB', dateOptions);
        const timePart = eventDate.toLocaleTimeString('en-GB', timeOptions);
        const formattedDate = `${datePart} at ${timePart}`;
 
        return `🎉 **New Event Added!**\n\n` +
            `**${event.name}**\n` +
            `📅 **Date:** ${formattedDate}\n` +
            `📍 **Region:** ${event.region}\n` +
            `${event.location ? `🏘️ **Location:** ${event.location}\n` : ''}` +
            `${event.description ? `📝 **Description:** ${event.description}\n` : ''}` +
            `${event.link ? `🔗 **Link:** <${event.link}>\n` : ''}` +
            `👤 **Organized by:** <@${event.created_by}>\n\n` +
            `💬 React with ✅ if you're interested in attending!`;
    }
 
    /**
     * Format reminder message for events
     */
    formatReminderMessage(event, timeUntil, isAfterCreation) {
        const eventDate = new Date(event.event_date);
        
        // Use consistent date/time formatting to avoid cross-platform issues
        const dateOptions = {
            weekday: 'long',
            year: 'numeric',
            month: 'long',
            day: 'numeric',
            timeZone: 'Europe/London'
        };
        
        const timeOptions = {
            hour: '2-digit',
            minute: '2-digit',
            timeZone: 'Europe/London'
        };
        
        const datePart = eventDate.toLocaleDateString('en-GB', dateOptions);
        const timePart = eventDate.toLocaleTimeString('en-GB', timeOptions);
        const formattedDate = `${datePart} at ${timePart}`;
 
        let timeText = timeUntil;
        if (isAfterCreation) {
            timeText = `Starting in ${timeUntil}`;
        }
 
        return `**${event.name}**\n` +
            `📅 **Date:** ${formattedDate}\n` +
            `⏰ **${timeText}**\n` +
            `📍 **Region:** ${event.region}\n` +
            `${event.location ? `🏘️ **Location:** ${event.location}\n` : ''}` +
            `${event.description ? `📝 **Description:** ${event.description}\n` : ''}` +
            `${event.link ? `🔗 **Link:** <${event.link}>\n` : ''}` +
            `👤 **Organized by:** <@${event.created_by}>`;
    }
 
    /**
     * Calculate time until event in human-readable format
     */
    getTimeUntilEvent(eventDate, now = new Date()) {
        const timeDiff = eventDate.getTime() - now.getTime();
        
        if (timeDiff <= 0) {
            return 'Event has started';
        }
 
        const days = Math.floor(timeDiff / (1000 * 60 * 60 * 24));
        const hours = Math.floor((timeDiff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
        const minutes = Math.floor((timeDiff % (1000 * 60 * 60)) / (1000 * 60));
 
        if (days > 0) {
            return `${days} day${days !== 1 ? 's' : ''}${hours > 0 ? ` and ${hours} hour${hours !== 1 ? 's' : ''}` : ''}`;
        } else if (hours > 0) {
            return `${hours} hour${hours !== 1 ? 's' : ''}${minutes > 0 ? ` and ${minutes} minute${minutes !== 1 ? 's' : ''}` : ''}`;
        } else {
            return `${minutes} minute${minutes !== 1 ? 's' : ''}`;
        }
    }
 
    /**
     * Send event cancellation notification
     */
    async sendCancellationNotification(guild, event) {
        try {
            // Find regional channel
            const regionChannelName = `regional-${event.region.toLowerCase().replace(/\s+/g, '-')}`;
            const regionChannel = guild.channels.cache.find(channel => 
                channel.name === regionChannelName && channel.type === 0
            );
 
            // Find local channel if location specified
            let locationChannel = null;
            if (event.location) {
                const locationChannelName = `local-${event.location.toLowerCase().replace(/\s+/g, '-').replace(/\//g, '-')}`;
                locationChannel = guild.channels.cache.find(channel => 
                    channel.name === locationChannelName && channel.type === 0
                );
            }
 
            const cancellationMessage = this.formatCancellationMessage(event);
 
            // Send to regional channel
            Eif (regionChannel) {
                await regionChannel.send({
                    embeds: [{
                        title: '❌ Event Cancelled',
                        description: cancellationMessage,
                        color: 0xff0000, // Red
                        timestamp: new Date().toISOString()
                    }]
                });
            }
 
            // Send to location channel if exists
            if (locationChannel) {
                await locationChannel.send({
                    embeds: [{
                        title: '❌ Event Cancelled',
                        description: cancellationMessage,
                        color: 0xff0000, // Red
                        timestamp: new Date().toISOString()
                    }]
                });
            }
 
            console.log(`Cancellation notification sent for: ${event.name}`);
 
        } catch (error) {
            console.error('Error sending cancellation notification:', error);
        }
    }
 
    /**
     * Format cancellation message
     */
    formatCancellationMessage(event) {
        const eventDate = new Date(event.event_date);
        
        // Use consistent date/time formatting to avoid cross-platform issues
        const dateOptions = {
            weekday: 'long',
            year: 'numeric',
            month: 'long',
            day: 'numeric',
            timeZone: 'Europe/London'
        };
        
        const timeOptions = {
            hour: '2-digit',
            minute: '2-digit',
            timeZone: 'Europe/London'
        };
        
        const datePart = eventDate.toLocaleDateString('en-GB', dateOptions);
        const timePart = eventDate.toLocaleTimeString('en-GB', timeOptions);
        const formattedDate = `${datePart} at ${timePart}`;
 
        return `**${event.name}**\n` +
            `📅 **Was scheduled for:** ${formattedDate}\n` +
            `📍 **Region:** ${event.region}\n` +
            `${event.location ? `🏘️ **Location:** ${event.location}\n` : ''}` +
            `👤 **Organized by:** <@${event.created_by}>\n\n` +
            `❌ **This event has been cancelled.**`;
    }
}
 
module.exports = EventNotificationManager;