All files / src/handlers ProposalCommandHandler.js

96.47% Statements 164/170
72.5% Branches 58/80
94.44% Functions 17/18
98.77% Lines 161/163

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                                28x       3x 1x 2x 1x         6x   1x 5x 1x 4x 1x 3x 1x 2x 1x         3x   3x   2x 1x 1x       1x 1x 1x 1x     1x     1x 2x     2x     1x   1x   1x 2x 2x 2x     2x     2x 2x 2x 2x     2x   2x   2x 2x 2x 2x     1x 1x       1x     1x 1x         3x   3x   2x 1x 1x     1x   1x 1x 1x 1x     1x 1x 1x 1x     1x   1x     1x   1x 1x 1x 1x     1x 1x     1x 1x         4x 4x 4x 4x   3x 1x 1x       2x       2x 2x 2x   2x 2x 2x 2x 2x   2x                     1x 1x 1x   1x 1x     2x 1x 1x     1x   1x 2x 2x 2x 2x 2x   2x     1x   1x     1x 1x         4x 4x 1x 1x       3x   3x 3x   2x 1x 1x       1x 1x     1x 1x 1x 1x 1x   1x 1x   1x 1x 1x 1x   1x 1x 1x 1x   1x 1x 1x 1x     1x   1x   1x     1x 1x         4x 4x 1x 1x     3x 3x   3x   2x 1x   1x       1x 1x           7x
/**
 * ProposalCommandHandler - Handles all democratic governance commands
 * 
 * Provides interfaces for the community proposal and voting system, enabling democratic
 * decision-making within Discord communities. Supports viewing active governance items,
 * monitoring vote progress, and administrative oversight of the democratic process.
 * 
 * Design rationale:
 * - Transparency: Members can view all active proposals and votes to stay informed
 * - Monitoring: Vote information commands help track democratic engagement
 * - Administrative control: Moderators can force-advance stalled proposals when needed
 * - Educational: Commands provide guidance on proper proposal formats and procedures
 * - Integration: Connects Discord interface with the underlying governance engine
 */
class ProposalCommandHandler {
    constructor(bot) {
        this.bot = bot;
    }
 
    async handleModeratorCommand(message, member, content) {
        if (content.startsWith('!forcevote ')) {
            await this.handleForceVote(message, content.substring(11));
        } else if (content.startsWith('!voteinfo ')) {
            await this.handleVoteInfo(message, content.substring(10));
        }
    }
 
    async handleMemberCommand(message, member, content) {
        if (content.startsWith('!propose ')) {
            // The propose command is handled by ProposalManager when message is posted
            await message.reply('šŸ’” To create a proposal, post your message in the debate channel with the proper format. See !help for formats.');
        } else if (content === '!proposals') {
            await this.handleViewProposals(message);
        } else if (content === '!activevotes') {
            await this.handleActiveVotes(message);
        } else if (content === '!moderators') {
            await this.handleViewModerators(message);
        } else if (content.startsWith('!voteinfo ')) {
            await this.handleVoteInfo(message, content.substring(10));
        }
    }
 
    async handleViewProposals(message) {
        try {
            // Get pending proposals (gathering support) - only show proposals that haven't gone to vote yet
            const pendingProposals = await this.bot.getProposalManager().getPendingProposals();
            
            if (pendingProposals.length === 0) {
                await message.reply('šŸ“‹ No pending proposals found. Post a proposal in a debate channel to get started!');
                return;
            }
 
            // Show up to 5 proposals: 3 closest to passing + 2 most recent (if not already included)
            const sortedByProgress = [...pendingProposals].sort((a, b) => {
                const progressA = a.supportCount / a.requiredSupport;
                const progressB = b.supportCount / b.requiredSupport;
                return progressB - progressA; // Highest progress first
            });
            
            const sortedByRecent = [...pendingProposals].sort((a, b) => b.createdAt - a.createdAt);
            
            // Get top 3 closest to passing
            const closestToPass = sortedByProgress.slice(0, 3);
            const closestIds = new Set(closestToPass.map(p => p.messageId));
            
            // Get up to 2 most recent that aren't already in the closest group
            const additionalRecent = sortedByRecent.filter(p => !closestIds.has(p.messageId)).slice(0, 2);
            
            // Combine and limit to 5 total
            const topPending = [...closestToPass, ...additionalRecent].slice(0, 5);
            
            let proposalsDisplay = `šŸ“‹ **Pending Proposals** (${topPending.length}${pendingProposals.length > 5 ? ` of ${pendingProposals.length}` : ''}):\n\n`;
            
            topPending.forEach((proposal, index) => {
                const withdrawalText = proposal.isWithdrawal ? 'šŸ—‘ļø WITHDRAWAL' : 'šŸ“';
                const progress = `${proposal.supportCount}/${proposal.requiredSupport}`;
                const progressBar = this.bot.commandRouter.createProgressBar(proposal.supportCount, proposal.requiredSupport, 6);
                
                // Create clickable link to the proposal message
                const messageLink = `https://discord.com/channels/${message.guildId}/${proposal.channelId}/${proposal.messageId}`;
                
                // Extract proposal title from content (first line after the format indicator)
                const lines = proposal.content.split('\n');
                const titleLine = lines[0] || '';
                const titleMatch = titleLine.match(/\*\*(?:Policy|Governance|Moderator|Withdraw)\*\*:\s*(.+)/i);
                let rawTitle = titleMatch ? titleMatch[1] : titleLine;
                
                // Format user mentions properly (convert <@123456> to @username)
                rawTitle = this.bot.commandRouter.formatUserMentions(rawTitle, message.guild);
                
                const title = rawTitle.substring(0, 60) + (rawTitle.length > 60 ? '...' : '');
                
                proposalsDisplay += `**${index + 1}.** ${withdrawalText} **${proposal.proposalType.toUpperCase()}**\n`;
                proposalsDisplay += `   šŸ‘¤ ${proposal.author.tag}\n`;
                proposalsDisplay += `   šŸ“‹ [${title}](${messageLink})\n`;
                proposalsDisplay += `   āœ… **${progress}** ${progressBar} (${Math.round((proposal.supportCount/proposal.requiredSupport)*100)}%)\n\n`;
            });
 
            proposalsDisplay += `šŸ’” **React with āœ… on proposals to show support!**\n`;
            Iif (pendingProposals.length > 5) {
                proposalsDisplay += `\nšŸ“Š *Showing top ${topPending.length} proposals (closest to passing + most recent).*`;
            }
 
            await message.reply(proposalsDisplay);
 
        } catch (error) {
            console.error('Error viewing proposals:', error);
            await message.reply('āŒ An error occurred while retrieving proposals.');
        }
    }
 
    async handleActiveVotes(message) {
        try {
            // Fix async issue - await the promise
            const activeVotes = await this.bot.getProposalManager().getActiveVotes();
            
            if (!activeVotes || activeVotes.length === 0) {
                await message.reply('šŸ—³ļø No active votes currently running.');
                return;
            }
 
            let votesDisplay = `šŸ—³ļø **Active Votes** (${activeVotes.length} item${activeVotes.length !== 1 ? 's' : ''}):\n\n`;
            
            activeVotes.forEach((vote, index) => {
                const withdrawalText = vote.isWithdrawal ? 'šŸ—‘ļø WITHDRAWAL' : 'šŸ“';
                const voteProgress = `${vote.yesCount}āœ… / ${vote.noCount}āŒ`;
                const messageLink = `https://discord.com/channels/${message.guildId}/${vote.channelId}/${vote.messageId}`;
                
                // Extract proposal title from content (first line after the format indicator)
                const lines = vote.content.split('\n');
                const titleLine = lines[0] || '';
                const titleMatch = titleLine.match(/\*\*(?:Policy|Governance|Moderator|Withdraw)\*\*:\s*(.+)/i);
                let rawTitle = titleMatch ? titleMatch[1] : titleLine;
                
                // Format user mentions properly
                rawTitle = this.bot.commandRouter.formatUserMentions(rawTitle, message.guild);
                
                const title = rawTitle.substring(0, 50) + (rawTitle.length > 50 ? '...' : '');
                
                // Calculate time remaining
                const timeRemaining = this.bot.commandRouter.calculateTimeRemaining(vote.voteEndTime);
                
                votesDisplay += `**${index + 1}.** ${withdrawalText} **${vote.proposalType.toUpperCase()}**\n`;
                votesDisplay += `   šŸ‘¤ ${vote.author.tag}\n`;
                votesDisplay += `   šŸ“‹ [${title}](${messageLink})\n`;
                votesDisplay += `   šŸ“Š ${voteProgress} - ā° ${timeRemaining}\n\n`;
            });
 
            votesDisplay += `šŸ—³ļø **Vote on proposals using the āœ… and āŒ reactions!**`;
            await message.reply(votesDisplay);
 
        } catch (error) {
            console.error('Error viewing active votes:', error);
            await message.reply('āŒ An error occurred while retrieving active votes.');
        }
    }
 
    async handleViewModerators(message) {
        try {
            const guild = message.guild;
            const moderatorRoleId = this.bot.getModeratorRoleId();
            const moderatorRole = guild.roles.cache.get(moderatorRoleId);
            
            if (!moderatorRole) {
                await message.reply('āŒ Moderator role not found.');
                return;
            }
 
            // Get all members with the moderator role
            const moderators = moderatorRole.members
                .filter(member => !member.user.bot)
                .map(member => {
                    // Check if they also have admin permissions
                    const hasManageRoles = member.permissions.has('ManageRoles');
                    const hasAdministrator = member.permissions.has('Administrator');
                    const isOwner = member.id === guild.ownerId;
                    
                    let badge = '';
                    Iif (isOwner) badge = 'šŸ‘‘ Owner';
                    else Iif (hasAdministrator) badge = '⚔ Admin';
                    else Iif (hasManageRoles) badge = 'šŸ”§ Manager';
                    else badge = 'šŸ›”ļø Mod';
                    
                    return {
                        displayName: member.displayName,
                        username: member.user.username,
                        id: member.id,
                        badge: badge,
                        joinedTimestamp: member.joinedTimestamp
                    };
                })
                .sort((a, b) => {
                    // Sort by role hierarchy: Owner > Admin > Manager > Mod
                    // Then by join date (earliest first)
                    const roleOrder = { 'šŸ‘‘': 0, '⚔': 1, 'šŸ”§': 2, 'šŸ›”ļø': 3 };
                    const aRole = roleOrder[a.badge.charAt(0)] || 4;
                    const bRole = roleOrder[b.badge.charAt(0)] || 4;
                    
                    Iif (aRole !== bRole) return aRole - bRole;
                    return (a.joinedTimestamp || 0) - (b.joinedTimestamp || 0);
                });
 
            if (moderators.length === 0) {
                await message.reply('āŒ No moderators found with the specified role.');
                return;
            }
 
            let moderatorsList = `šŸ›”ļø **Server Moderators** (${moderators.length}):\n\n`;
            
            moderators.forEach((mod, index) => {
                moderatorsList += `**${index + 1}.** ${mod.badge} **${mod.displayName}**\n`;
                moderatorsList += `   šŸ“ @${mod.username}\n`;
                Eif (mod.joinedTimestamp) {
                    const joinedDate = new Date(mod.joinedTimestamp).toLocaleDateString();
                    moderatorsList += `   šŸ“… Joined: ${joinedDate}\n`;
                }
                moderatorsList += '\n';
            });
 
            moderatorsList += `šŸ’” **Moderators help maintain server order and facilitate governance.**`;
            
            await message.reply(moderatorsList);
 
        } catch (error) {
            console.error('Error viewing moderators:', error);
            await message.reply('āŒ An error occurred while retrieving moderator information.');
        }
    }
 
    async handleVoteInfo(message, messageId) {
        try {
            if (!messageId) {
                await message.reply('āŒ Please provide a message ID. Usage: `!voteinfo <message_id>`');
                return;
            }
 
            // Clean the message ID (remove any channel/guild prefixes)
            const cleanMessageId = messageId.split('-').pop().split('/').pop().trim();
            
            console.log(`Getting vote info for message ID: ${cleanMessageId}`);
            const voteInfo = await this.bot.getProposalManager().getVoteInfo(cleanMessageId);
            
            if (!voteInfo) {
                await message.reply('āŒ Vote not found or not currently active.');
                return;
            }
 
            // Create detailed vote information display
            const withdrawalText = voteInfo.isWithdrawal ? 'šŸ—‘ļø **WITHDRAWAL VOTE**' : 'šŸ“ **PROPOSAL VOTE**';
            const messageLink = `https://discord.com/channels/${message.guildId}/${voteInfo.channelId}/${voteInfo.messageId}`;
            
            // Extract proposal title
            const lines = voteInfo.content.split('\n');
            const titleLine = lines[0] || '';
            const titleMatch = titleLine.match(/\*\*(?:Policy|Governance|Moderator|Withdraw)\*\*:\s*(.+)/i);
            let rawTitle = titleMatch ? titleMatch[1] : titleLine;
            rawTitle = this.bot.commandRouter.formatUserMentions(rawTitle, message.guild);
            
            const timeRemaining = this.bot.commandRouter.calculateTimeRemaining(voteInfo.voteEndTime);
            const totalVotes = voteInfo.yesCount + voteInfo.noCount;
            
            let voteDisplay = `${withdrawalText}\n\n`;
            voteDisplay += `**šŸ“‹ Proposal:** [${rawTitle}](${messageLink})\n`;
            voteDisplay += `**šŸ‘¤ Author:** ${voteInfo.author.tag}\n`;
            voteDisplay += `**šŸ“Š Type:** ${voteInfo.proposalType.toUpperCase()}\n\n`;
            
            voteDisplay += `**šŸ—³ļø CURRENT RESULTS:**\n`;
            voteDisplay += `āœ… **Yes:** ${voteInfo.yesCount} votes\n`;
            voteDisplay += `āŒ **No:** ${voteInfo.noCount} votes\n`;
            voteDisplay += `šŸ“Š **Total:** ${totalVotes} votes\n\n`;
            
            Eif (totalVotes > 0) {
                const yesPercentage = Math.round((voteInfo.yesCount / totalVotes) * 100);
                const noPercentage = Math.round((voteInfo.noCount / totalVotes) * 100);
                voteDisplay += `**šŸ“ˆ Breakdown:** ${yesPercentage}% Yes, ${noPercentage}% No\n`;
            }
            
            voteDisplay += `**ā° Time Remaining:** ${timeRemaining}\n\n`;
            
            voteDisplay += `šŸ—³ļø **Cast your vote on the [original message](${messageLink}) using āœ… and āŒ reactions!**`;
            
            await message.reply(voteDisplay);
 
        } catch (error) {
            console.error('Error getting vote info:', error);
            await message.reply('āŒ An error occurred while retrieving vote information.');
        }
    }
 
    async handleForceVote(message, messageId) {
        try {
            if (!messageId) {
                await message.reply('āŒ Please provide a message ID. Usage: `!forcevote <message_id>`');
                return;
            }
 
            const cleanMessageId = messageId.split('-').pop().split('/').pop().trim();
            console.log(`Force voting on proposal: ${cleanMessageId}`);
            
            const result = await this.bot.getProposalManager().forceStartVote(cleanMessageId);
            
            if (result.success) {
                await message.reply(`āœ… Successfully forced vote to start for proposal: ${cleanMessageId}`);
            } else {
                await message.reply(`āŒ Failed to force vote: ${result.error}`);
            }
 
        } catch (error) {
            console.error('Error forcing vote:', error);
            await message.reply('āŒ An error occurred while forcing the vote.');
        }
    }
 
}
 
module.exports = ProposalCommandHandler;