diff --git a/modules/staff-management-system/commands/duty.js b/modules/staff-management-system/commands/duty.js index d2897d3f..86f7da0a 100644 --- a/modules/staff-management-system/commands/duty.js +++ b/modules/staff-management-system/commands/duty.js @@ -1,1274 +1,13 @@ -const { MessageFlags, EmbedBuilder, ActionRowBuilder, ButtonBuilder, ButtonStyle, StringSelectMenuBuilder, ModalBuilder, TextInputBuilder, TextInputStyle } = require('discord.js'); -const { Op, fn, col, literal } = require('sequelize'); -const { - getConfig, - applyFooter, - getSafeChannelId, - formatDuration, - buildPaginationRow, - checkStaffPermissions -} = require('../staff-management'); +const { MessageFlags } = require('discord.js'); const { localize } = require('../../../src/functions/localize'); - -function getLookbackDate(config) { - const lookback = config.leaderboardLookback || 'Weekly'; - if (lookback === 'All-time') return null; - const date = new Date(); - if (lookback === 'Weekly') date.setDate(date.getDate() - 7); - else if (lookback === 'Monthly') date.setMonth(date.getMonth() - 1); - return date; -} - -function canUseDutyAdmin(client, member) { - const generalConfig = getConfig(client, 'configuration'); - return checkStaffPermissions(member, generalConfig, 'supervisor'); -} - -function checkDutyAdminPermission(client, interaction) { - if (canUseDutyAdmin(client, interaction.member)) return null; - - const payload = { - content: localize('staff-management-system', 'err-no-perm'), - flags: MessageFlags.Ephemeral - }; - - if (interaction.deferred || interaction.replied) { - return interaction.followUp(payload); - } - return interaction.reply(payload); -} - -async function applyBreakElapsedToShift(activeShift, breakStartTime, now = new Date()) { - if (!activeShift || !breakStartTime) return; - - const breakStartedAt = new Date(breakStartTime); - if (Number.isNaN(breakStartedAt.getTime()) || breakStartedAt > now) return; - - const elapsedBreakMs = now.getTime() - breakStartedAt.getTime(); - if (elapsedBreakMs <= 0) return; - - await activeShift.update({ - startTime: new Date(new Date(activeShift.startTime).getTime() + elapsedBreakMs) - }); -} - -function getQuotaForMember(member, config) { - if (!config.enableQuotas || !config.quotas || Object.keys(config.quotas).length === 0) return null; - - let bestQuota = null; - let highestPosition = -1; - - for (const [roleId, hoursStr] of Object.entries(config.quotas)) { - const hours = parseFloat(hoursStr); - if (isNaN(hours)) continue; - - const role = member.guild.roles.cache.get(roleId); - if (role && member.roles.cache.has(roleId) && role.position > highestPosition) { - highestPosition = role.position; - bestQuota = { roleId, hours }; - } - } - - return bestQuota; -} - -async function sendShiftEndDm(client, member, shift) { - if (!member || !shift) return; - - const embed = applyFooter(client, new EmbedBuilder() - .setTitle(localize('staff-management-system', 'duty-shift-report-title')) - .setThumbnail(member.user.displayAvatarURL({dynamic: true})) - .addFields( - { - name: localize('staff-management-system', 'duty-shift-information'), - value: - `>>> **${localize('staff-management-system', 'label-shift-type')}:** ${shift.type || 'Staff'}\n` + - `**${localize('staff-management-system', 'general-start')}:** \n` + - `**${localize('staff-management-system', 'general-end')}:** \n` + - `**${localize('staff-management-system', 'label-breaks')}:** ${shift.breakCount || 0}` - }, - { - name: localize('staff-management-system', 'label-elapsed-time'), - value: `> ${formatDuration(parseInt(shift.duration) || 0)}` - } - ) - ); - - try { - await member.user.send({embeds: [embed.toJSON()]}); - } catch (e) { - client.logger.warn(localize('staff-management-system', 'log-duty-dm-fail', { - user: member.user.tag, - error: e.message - })); - } -} - -async function logShiftChange(client, action, data) { - const shiftsConfig = getConfig(client, 'shifts'); - if (!shiftsConfig?.logShiftChanges) return; - const channelId = - getSafeChannelId(shiftsConfig.logShiftChangesChannel) || - getSafeChannelId(getConfig(client, 'configuration')?.generalLogChannel); - if (!channelId) return; - - const guild = client.guilds.cache.get(client.guildID); - if (!guild) return; - const channel = await guild.channels.fetch(channelId).catch(() => null); - if (!channel) return; - - const targetUserObj = data.targetUser || await client.users.fetch(data.userId).catch(() => null); - const mention = targetUserObj ? targetUserObj.toString() : `<@${data.userId}>`; - const username = targetUserObj ? targetUserObj.username : data.userId; - - const embed = new EmbedBuilder() - .setThumbnail(targetUserObj?.displayAvatarURL({dynamic: true}) || null); - - if (action === 'start') { - embed - .setTitle(localize('staff-management-system', 'log-duty-start-title', {username})) - .setColor('Green') - .setDescription(localize('staff-management-system', 'log-duty-start-desc', {mention})) - .addFields({ - name: localize('staff-management-system', 'log-duty-info-hdr'), - value: - `**${localize('staff-management-system', 'general-start')}:** \n` + - `**${localize('staff-management-system', 'label-shift-type')}:** ${data.shiftType || 'Staff'}` - }); - } else if (action === 'break') { - embed - .setTitle(localize('staff-management-system', 'log-duty-break-title', {username})) - .setColor('Yellow') - .setDescription(localize('staff-management-system', 'log-duty-break-desc', {mention})) - .addFields({ - name: localize('staff-management-system', 'log-duty-info-hdr'), - value: - `**${localize('staff-management-system', 'general-start')}:** \n` + - `**${localize('staff-management-system', 'label-shift-type')}:** ${data.shiftType || 'Staff'}\n` + - `**${localize('staff-management-system', 'label-breaks')}:** ${data.breakCount || 0}\n` + - `**${localize('staff-management-system', 'label-elapsed-time')}:** ${formatDuration(data.elapsedSeconds || 0)}` - }); - } else if (action === 'resume') { - embed - .setTitle(localize('staff-management-system', 'log-duty-resume-title', {username})) - .setColor('Green') - .setDescription(localize('staff-management-system', 'log-duty-resume-desc', {mention})) - .addFields({ - name: localize('staff-management-system', 'log-duty-info-hdr'), - value: - `**${localize('staff-management-system', 'general-start')}:** \n` + - `**${localize('staff-management-system', 'label-shift-type')}:** ${data.shiftType || 'Staff'}\n` + - `**${localize('staff-management-system', 'label-breaks')}:** ${data.breakCount || 0}\n` + - `**${localize('staff-management-system', 'label-elapsed-time')}:** ${formatDuration(data.elapsedSeconds || 0)}` - }); - } else if (action === 'end') { - embed - .setTitle(localize('staff-management-system', 'log-duty-end-title', {username})) - .setColor('Red') - .setDescription(localize('staff-management-system', 'log-duty-end-desc', {mention})) - .addFields({ - name: localize('staff-management-system', 'log-duty-info-hdr'), - value: - `**${localize('staff-management-system', 'general-start')}:** \n` + - `**${localize('staff-management-system', 'general-end')}:** \n` + - `**${localize('staff-management-system', 'label-shift-type')}:** ${data.shiftType || 'Staff'}\n` + - `**${localize('staff-management-system', 'label-breaks')}:** ${data.breakCount || 0}\n` + - `**${localize('staff-management-system', 'label-elapsed-time')}:** ${formatDuration(data.durationSeconds || 0)}` + - (data.executorId - ? `\n**${localize('staff-management-system', 'label-ended-by')}:** <@${data.executorId}>` - : '') - }); - } else if (action === 'void') { - embed - .setTitle(localize('staff-management-system', 'log-duty-void-title', {username})) - .setColor('DarkRed') - .setDescription(localize('staff-management-system', 'log-duty-void-desc', { - mention, - executor: `<@${data.executorId}>` - })) - .addFields({ - name: localize('staff-management-system', 'log-duty-info-hdr'), - value: - `**${localize('staff-management-system', 'general-start')}:** \n` + - `**${localize('staff-management-system', 'label-shift-type')}:** ${data.shiftType || 'Staff'}\n` + - `**${localize('staff-management-system', 'label-breaks')}:** ${data.breakCount || 0}` - }); - } else { - return; - } - - applyFooter(client, embed); - - try { - await channel.send({embeds: [embed.toJSON()]}); - } catch (e) { - client.logger.error(localize('staff-management-system', 'log-duty-log-fail', { - action, - error: e.message - })); - } -} - -async function buildDutyManagePayload(client, userId, shiftType, endedShift = null) { - const Profile = client.models['staff-management-system']['StaffProfile']; - const Shift = client.models['staff-management-system']['StaffShift']; - - const user = await client.users.fetch(userId).catch(() => null); - const profile = await Profile.findByPk(userId); - - const onDuty = profile?.onDuty || false; - const onBreak = profile?.onBreak || false; - - let statusColor; - if (onDuty && onBreak) { - statusColor = 'Yellow'; - } else if (onDuty) { - statusColor = 'Green'; - } else { - statusColor = 'Red'; - } - - const completedShifts = await Shift.findAll({ - where: { - userId, - type: shiftType, - endTime: {[Op.not]: null}, - duration: {[Op.not]: null} - } - }); - const totalShifts = completedShifts.length; - const totalSeconds = completedShifts.reduce((sum, s) => sum + (parseInt(s.duration) || 0), 0); - const avgSeconds = totalShifts > 0 - ? Math.floor(totalSeconds / totalShifts) - : 0; - - const activeShift = onDuty - ? await Shift.findOne({ - where: { - userId, - endTime: null - }, - order: [['startTime', 'DESC']] - }) - : null; - - let titleKey = 'duty-panel-title'; - if (onDuty && onBreak) titleKey = 'duty-break-title'; - else if (onDuty) titleKey = 'duty-started-title'; - else if (endedShift) titleKey = 'duty-ended-title'; - - const embed = applyFooter(client, new EmbedBuilder() - .setTitle(localize('staff-management-system', titleKey, {type: shiftType})) - .setColor(statusColor) - .setThumbnail(user?.displayAvatarURL({ dynamic: true }) || null) - ); - - if (onDuty && activeShift) { - let elapsedSeconds; - if (onBreak && profile?.breakStartTime) { - elapsedSeconds = Math.max( - 0, - Math.floor( - (new Date(profile.breakStartTime).getTime() - new Date(activeShift.startTime).getTime()) / 1000 - ) - ); - } else { - elapsedSeconds = Math.max( - 0, - Math.floor((Date.now() - new Date(activeShift.startTime).getTime()) / 1000) - ); - } - - embed.addFields({ - name: localize('staff-management-system', 'duty-shift-overview'), - value: - `>>> **${localize('staff-management-system', 'label-started')}:** \n` + - `**${localize('staff-management-system', 'label-breaks')}:** ${activeShift.breakCount || 0}\n` + - `**${localize('staff-management-system', 'label-elapsed-time')}:** ${formatDuration(elapsedSeconds)}` - }); - } else if (endedShift) { - embed.addFields({ - name: localize('staff-management-system', 'duty-shift-overview'), - value: - `>>> **${localize('staff-management-system', 'label-started')}:** \n` + - `**${localize('staff-management-system', 'label-breaks')}:** ${endedShift.breakCount || 0}\n` + - `**${localize('staff-management-system', 'label-ended')}:** ` - }); - } else { - embed.addFields({ - name: localize('staff-management-system', 'duty-stats'), - value: localize('staff-management-system', 'duty-stat-desc', { - duration: formatDuration(totalSeconds), - count: totalShifts, - average: formatDuration(avgSeconds) - }) - }); - } - - const row = new ActionRowBuilder().addComponents( - new ButtonBuilder() - .setCustomId(`duty-mgmt_start_${userId}_${shiftType}`) - .setLabel(localize('staff-management-system', 'btn-duty-on')) - .setStyle(ButtonStyle.Success) - .setDisabled(onDuty), - new ButtonBuilder() - .setCustomId(`duty-mgmt_break_${userId}`) - .setLabel(onBreak - ? localize('staff-management-system', 'btn-duty-res') - : localize('staff-management-system', 'btn-duty-brk') - ) - .setStyle(ButtonStyle.Secondary) - .setDisabled(!onDuty), - new ButtonBuilder() - .setCustomId(`duty-mgmt_end_${userId}`) - .setLabel(localize('staff-management-system', 'btn-duty-off')) - .setStyle(ButtonStyle.Danger) - .setDisabled(!onDuty) - ); - - return { - embeds: [embed.toJSON()], - components: [row.toJSON()] - }; -} - -async function buildDutyTimePayload(client, interaction, shiftType) { - const config = getConfig(client, 'shifts'); - const Shift = client.models['staff-management-system']['StaffShift']; - const user = interaction.user; - - const whereClause = { - userId: user.id, - endTime: {[Op.not]: null}, - duration: {[Op.not]: null} - }; - if (shiftType !== 'All') whereClause.type = shiftType; - - const shifts = await Shift.findAll({ where: whereClause }); - - const totalSeconds = shifts.reduce((sum, s) => sum + (parseInt(s.duration) || 0), 0); - const shiftCount = shifts.length; - - let breakdownText = ''; - if (shiftType === 'All' && shiftCount > 0) { - const grouped = {}; - for (const s of shifts) { - const t = s.type || 'Staff'; - grouped[t] = (grouped[t] || 0) + (parseInt(s.duration) || 0); - } - breakdownText = `\n\n**${localize('staff-management-system', 'duty-breakdown')}:**\n` + Object.entries(grouped) - .sort((a, b) => b[1] - a[1]) - .map(([t, sec]) => `â€ĸ ${t}: ${formatDuration(sec)}`) - .join('\n'); - } - - let quotaText = ''; - const member = await interaction.guild.members.fetch(user.id).catch(() => null); - if (member) { - const quota = getQuotaForMember(member, config); - if (quota) { - const timeframe = config.quotaTimeframe || 'Weekly'; - const cutoff = new Date(); - if (timeframe === 'Weekly') cutoff.setDate(cutoff.getDate() - 7); - else cutoff.setMonth(cutoff.getMonth() - 1); - - const recentWhere = { - userId: user.id, - startTime: {[Op.gt]: cutoff}, - endTime: {[Op.not]: null}, - duration: {[Op.not]: null} - }; - if (shiftType !== 'All') recentWhere.type = shiftType; - - const recentShifts = await Shift.findAll({ where: recentWhere }); - const recentSeconds = recentShifts.reduce((sum, s) => sum + (parseInt(s.duration) || 0), 0); - const requiredSeconds = quota.hours * 3600; - const metQuota = recentSeconds >= requiredSeconds; - quotaText = localize('staff-management-system', 'duty-quota-str', { - timeframe, - duration: formatDuration(recentSeconds), - hours: quota.hours, - result: metQuota - ? localize('staff-management-system', 'quota-met') - : localize('staff-management-system', 'quota-fail') - }); - } - } - - const embed = applyFooter(client, new EmbedBuilder() - .setTitle(localize('staff-management-system', 'duty-time-title', { type: shiftType })) - .setColor('Blue') - .setThumbnail(user.displayAvatarURL({ dynamic: true })) - .setDescription(localize('staff-management-system', 'duty-time-desc', { - count: shiftCount, - duration: formatDuration(totalSeconds) - }) + breakdownText + quotaText) - ); - - const row = new ActionRowBuilder().addComponents( - new ButtonBuilder() - .setCustomId(`duty-mgmt_hist_${user.id}_1_${shiftType}`) - .setLabel(localize('staff-management-system', 'btn-hist')) - .setStyle(ButtonStyle.Secondary) - .setDisabled(shiftCount === 0) - ); - - return { - embeds: [embed.toJSON()], - components: [row.toJSON()] - }; -} - -async function buildLeaderboardPayload(client, page = 1, shiftType) { - const config = getConfig(client, 'shifts'); - const Shift = client.models['staff-management-system']['StaffShift']; - const limit = 15; - const offset = (page - 1) * limit; - - const whereClause = { - endTime: {[Op.not]: null}, - duration: {[Op.not]: null} - }; - if (shiftType !== 'All') whereClause.type = shiftType; - - const lookbackDate = getLookbackDate(config); - if (lookbackDate) whereClause.startTime = { [Op.gt]: lookbackDate }; - - const allResults = await Shift.findAll({ - attributes: [ - 'userId', - [fn('SUM', col('duration')), 'totalDuration'], - [fn('COUNT', col('id')), 'shiftCount'] - ], - where: whereClause, - group: ['userId'], - order: [[literal('totalDuration'), 'DESC']] - }); - - const total = allResults.length; - if (total === 0) return { - content: localize('staff-management-system', 'err-no-lb', { - type: shiftType - }) - }; - - const totalPages = Math.ceil(total / limit) || 1; - const paginated = allResults.slice(offset, offset + limit); - - const lines = []; - for (let i = 0; i < paginated.length; i++) { - const entry = paginated[i]; - const dur = formatDuration(parseInt(entry.dataValues.totalDuration)); - lines.push(`${offset + i + 1}. **<@${entry.userId}>** â€ĸ ${dur}`); - } - - const lookbackLabel = config.leaderboardLookback || 'Weekly'; - const embed = applyFooter(client, new EmbedBuilder() - .setTitle(localize('staff-management-system', 'duty-lb-title', { - type: shiftType - })) - .setColor('Gold') - .setDescription(localize('staff-management-system', 'duty-lb-desc', { - lookback: lookbackLabel, - lines: lines.join('\n') - })) - ); - - embed.addFields({ - name: '\u200b', - value: localize('staff-management-system', 'page-count', { - page, - total: totalPages - }) - }); - - const row = buildPaginationRow( - `duty-mgmt_lb_${page - 1}_${shiftType}`, - 'duty_lb_count', - `duty-mgmt_lb_${page + 1}_${shiftType}`, - page, totalPages, 'back', 'next' - ); - - return { - embeds: [embed.toJSON()], - components: [row.toJSON()] - }; -} - -async function buildShiftHistoryPayload(client, userId, page = 1, shiftType) { - const Shift = client.models['staff-management-system']['StaffShift']; - const limit = 10; - const offset = (page - 1) * limit; - - const whereClause = { - userId, - endTime: {[Op.not]: null}, - duration: {[Op.not]: null} - }; - if (shiftType !== 'All') whereClause.type = shiftType; - - const { count, rows } = await Shift.findAndCountAll({ - where: whereClause, - order: [['startTime', 'DESC']], - limit, - offset - }); - - if (count === 0) return { content: localize('staff-management-system', 'info-no-sh-hi') }; - const totalPages = Math.ceil(count / limit) || 1; - - const lines = rows.map((shift, i) => { - const dur = formatDuration(shift.duration); - const startTs = Math.floor(new Date(shift.startTime).getTime() / 1000); - const endTs = Math.floor(new Date(shift.endTime).getTime() / 1000); - const typeBadge = shiftType === 'All' ? ` \`[${shift.type || 'Staff'}]\`` : ''; - - return `**${offset + i + 1}. ${dur}${typeBadge}:**\nStart: | End: `; - }); - - const embed = applyFooter(client, new EmbedBuilder() - .setTitle(localize('staff-management-system', 'duty-hi-title', { - type: shiftType - })) - .setColor('Blue') - .setDescription(lines.join('\n\n')) - ); - - embed.addFields({ - name: '\u200b', - value: localize('staff-management-system', 'page-count', { - page, - total: totalPages - }) - }); - - const row = buildPaginationRow( - `duty-mgmt_hist_${userId}_${page - 1}_${shiftType}`, - 'duty_hist_count', - `duty-mgmt_hist_${userId}_${page + 1}_${shiftType}`, - page, totalPages - ); - - return { - embeds: [embed.toJSON()], - components: [row.toJSON()] - }; -} - -async function buildDutyAdminPayload(client, targetMember, requestingMember) { - const Profile = client.models['staff-management-system']['StaffProfile']; - const Shift = client.models['staff-management-system']['StaffShift']; - - const targetUser = targetMember.user; - const profile = await Profile.findByPk(targetUser.id); - - const onDuty = profile?.onDuty || false; - const onBreak = profile?.onBreak || false; - - let statusText, statusColor; - if (onDuty && onBreak) { - statusText = localize('staff-management-system', 'stat-brk'); - statusColor = 'Yellow'; - } else if (onDuty) { - statusText = localize('staff-management-system', 'stat-on'); - statusColor = 'Green'; - } else { - statusText = localize('staff-management-system', 'stat-off'); - statusColor = 'Red'; - } - - const completedShifts = await Shift.findAll({ - where: { - userId: targetUser.id, - endTime: {[Op.not]: null}, - duration: {[Op.not]: null} - } - }); - const totalShifts = completedShifts.length; - const totalSeconds = completedShifts.reduce((sum, s) => sum + (parseInt(s.duration) || 0), 0); - const avgSeconds = totalShifts > 0 - ? Math.floor(totalSeconds / totalShifts) - : 0; - - const embed = applyFooter(client, new EmbedBuilder() - .setTitle(localize('staff-management-system', 'duty-adm-title', { - user: targetUser.username - })) - .setColor(statusColor) - .setThumbnail(targetUser.displayAvatarURL({ dynamic: true })) - .setDescription(`**${statusText}**`) - .addFields( - { - name: localize('staff-management-system', 'duty-stats'), - value: localize('staff-management-system', 'duty-stat-desc', { - duration: formatDuration(totalSeconds), - count: totalShifts, - average: formatDuration(avgSeconds) - }) - } - ) - ); - - const generalConfig = client.configurations['staff-management-system']['configuration']; - const isManagement = requestingMember.roles.cache.some(r => (generalConfig.managementRoles || []).includes(r.id)) || requestingMember.permissions.has('Administrator'); - - const row = new ActionRowBuilder().addComponents( - new ButtonBuilder() - .setCustomId(`duty-mgmt_admin-forceend_${targetUser.id}`) - .setLabel(localize('staff-management-system', 'btn-f-off')) - .setEmoji('🔴') - .setStyle(ButtonStyle.Danger) - .setDisabled(!onDuty), - new ButtonBuilder() - .setCustomId(`duty-mgmt_admin-voidactive_${targetUser.id}`) - .setLabel(localize('staff-management-system', 'btn-v-act')) - .setEmoji('đŸ—‘ī¸') - .setStyle(ButtonStyle.Danger) - .setDisabled(!onDuty), - new ButtonBuilder() - .setCustomId(`duty-mgmt_admin-addtime_${targetUser.id}`) - .setLabel(localize('staff-management-system', 'btn-add-t')) - .setEmoji('âąī¸') - .setStyle(ButtonStyle.Success), - new ButtonBuilder() - .setCustomId(`duty-mgmt_admin-voidall_${targetUser.id}`) - .setLabel(localize('staff-management-system', 'btn-v-all')) - .setEmoji('âš ī¸') - .setStyle(ButtonStyle.Danger) - .setDisabled(!isManagement) - ); - - return { - embeds: [embed.toJSON()], - components: [row.toJSON()] - }; -} - -// ----- Button handlers ----- -async function handleDutyStartButton(client, interaction) { - const parts = interaction.customId.split('_'); - const userId = parts[2]; - const shiftType = parts[3] || 'Staff'; - - if (interaction.user.id !== userId) return interaction.editReply({ - content: localize('staff-management-system', 'err-not-yours'), - flags: MessageFlags.Ephemeral - }); - - const config = getConfig(client, 'shifts'); - const Profile = client.models['staff-management-system']['StaffProfile']; - const Shift = client.models['staff-management-system']['StaffShift']; - - const profile = await Profile.findByPk(userId); - if (profile?.onDuty) return interaction.followUp({ - content: localize('staff-management-system', 'err-alr-on'), - flags: MessageFlags.Ephemeral - }); - - const startTime = new Date(); - await Shift.create({ - userId, - startTime, - type: shiftType - }); - await Profile.upsert({ - userId, - onDuty: true, - onBreak: false, - lastClockIn: startTime - }); - - if (config.onDutyRole) { - const member = await interaction.guild.members.fetch(userId).catch(() => null); - if (member) await member.roles.add(config.onDutyRole).catch(() => {}); - } - - await logShiftChange(client, 'start', { - userId, - targetUser: interaction.user, - shiftType, - startTime - }); - - const payload = await buildDutyManagePayload(client, userId, shiftType); - return interaction.editReply(payload); -} - -async function handleDutyBreakButton(client, interaction) { - const userId = interaction.customId.split('_')[2]; - if (interaction.user.id !== userId) return interaction.editReply({ - content: localize('staff-management-system', 'err-not-yours'), - flags: MessageFlags.Ephemeral - }); - - const Profile = client.models['staff-management-system']['StaffProfile']; - const Shift = client.models['staff-management-system']['StaffShift']; - const profile = await Profile.findByPk(userId); - - if (!profile?.onDuty) return interaction.followUp({ - content: localize('staff-management-system', 'err-not-on'), - flags: MessageFlags.Ephemeral - }); - - const activeShift = await Shift.findOne({ - where: {userId, endTime: null} - }); - const shiftType = activeShift?.type || 'Staff'; - - const nowOnBreak = !profile.onBreak; - let breakCount = activeShift?.breakCount || 0; - if (nowOnBreak && activeShift) { - breakCount += 1; - await activeShift.update({ - breakCount - }); - } - if (!nowOnBreak && profile.breakStartTime && activeShift) { - await applyBreakElapsedToShift(activeShift, profile.breakStartTime); - } - - const elapsedSeconds = activeShift - ? Math.max( - 0, - Math.floor( - ((nowOnBreak ? new Date() : new Date(profile.breakStartTime || Date.now())).getTime() - - new Date(activeShift.startTime).getTime()) / 1000 - ) - ) - : 0; - - const breakStartTime = nowOnBreak ? new Date() : null; - await Profile.update({ - onBreak: nowOnBreak, - breakStartTime - }, { - where: {userId} - }); - - if (activeShift) { - if (nowOnBreak) { - await logShiftChange(client, 'break', { - userId, - targetUser: interaction.user, - shiftType, - startTime: activeShift.startTime, - breakCount: activeShift.breakCount || 0, - elapsedSeconds - }); - } else { - await logShiftChange(client, 'resume', { - userId, - targetUser: interaction.user, - shiftType, - startTime: activeShift.startTime, - breakCount: activeShift.breakCount || 0, - elapsedSeconds - }); - } - } - - const payload = await buildDutyManagePayload(client, userId, shiftType); - return interaction.editReply(payload); -} - -async function handleDutyEndButton(client, interaction) { - const userId = interaction.customId.split('_')[2]; - if (interaction.user.id !== userId) return interaction.editReply({ - content: localize('staff-management-system', 'err-not-yours'), - flags: MessageFlags.Ephemeral - }); - - const config = getConfig(client, 'shifts'); - const Profile = client.models['staff-management-system']['StaffProfile']; - const Shift = client.models['staff-management-system']['StaffShift']; - - const profile = await Profile.findByPk(userId); - if (!profile?.onDuty) return interaction.followUp({ - content: localize('staff-management-system', 'err-not-on'), - flags: MessageFlags.Ephemeral - }); - - const activeShifts = await Shift.findAll({ where: { userId, endTime: null } }); - const shiftType = activeShifts.length > 0 ? activeShifts[0].type : 'Staff'; - let discardedForMinimum = false; - let endedShiftForDisplay = null; - - for (const activeShift of activeShifts) { - if (profile.onBreak && profile.breakStartTime) { - await applyBreakElapsedToShift(activeShift, profile.breakStartTime); - } - - const endTime = new Date(); - const durationSeconds = Math.floor( - (endTime.getTime() - new Date(activeShift.startTime).getTime()) / 1000 - ); - - if (config.minShiftDuration && (durationSeconds / 60) < config.minShiftDuration) { - await activeShift.destroy(); - discardedForMinimum = true; - } else { - await activeShift.update({ - endTime, - duration: durationSeconds - }); - endedShiftForDisplay = activeShift; - } - } - - await Profile.update({ - onDuty: false, - onBreak: false, - breakStartTime: null - }, { - where: {userId} - }); - - const member = await interaction.guild.members.fetch(userId).catch(() => null); - if (config.onDutyRole && member) { - await member.roles.remove(config.onDutyRole).catch(() => { - }); - } - if (member && endedShiftForDisplay) { - await sendShiftEndDm(client, member, endedShiftForDisplay); - } - - if (endedShiftForDisplay) { - await logShiftChange(client, 'end', { - userId, - targetUser: interaction.user, - shiftType: endedShiftForDisplay.type || shiftType, - startTime: endedShiftForDisplay.startTime, - endTime: endedShiftForDisplay.endTime, - breakCount: endedShiftForDisplay.breakCount || 0, - durationSeconds: parseInt(endedShiftForDisplay.duration) || 0 - }); - } - - const payload = await buildDutyManagePayload(client, userId, shiftType, endedShiftForDisplay); - await interaction.editReply(payload); - - if (discardedForMinimum) { - await interaction.followUp({ - content: localize('staff-management-system', 'err-shift-too-short', { - min: config.minShiftDuration - }), - flags: MessageFlags.Ephemeral - }); - } - return; -} - -async function handleDutyHistPageButton(client, interaction) { - const parts = interaction.customId.split('_'); - const userId = parts[2]; - const page = parseInt(parts[3]); - const shiftType = parts[4] || 'Staff'; - - if (interaction.user.id !== userId) return interaction.followUp({ - content: localize('staff-management-system', 'err-hist-oth'), - flags: MessageFlags.Ephemeral - }); - - const payload = await buildShiftHistoryPayload(client, userId, page, shiftType); - if (payload.content) return interaction.followUp({ - ...payload, - flags: MessageFlags.Ephemeral - }); - - const isOnHistEmbed = interaction.message?.embeds?.[0]?.title?.startsWith(localize('staff-management-system', 'duty-hi-title', { type: '' }).replace(' - ', '')); - if (isOnHistEmbed) { - return interaction.editReply(payload); - } else { - return interaction.followUp({ - ...payload, - flags: MessageFlags.Ephemeral - }); - } -} - -async function handleDutyLbPageButton(client, interaction) { - const parts = interaction.customId.split('_'); - const page = parseInt(parts[2]); - const shiftType = parts[3] || 'Staff'; - - const payload = await buildLeaderboardPayload(client, page, shiftType); - if (payload.content) return interaction.editReply({ ...payload, flags: MessageFlags.Ephemeral }); - return interaction.editReply(payload); -} - -// ----- Admin handler ----- -async function handleDutyAdminForceEnd(client, interaction) { - const permCheck = checkDutyAdminPermission(client, interaction); - if (permCheck) return permCheck; - - const targetUserId = interaction.customId.split('_')[2]; - const config = getConfig(client, 'shifts'); - const Profile = client.models['staff-management-system']['StaffProfile']; - const Shift = client.models['staff-management-system']['StaffShift']; - const profile = await Profile.findByPk(targetUserId); - let endedShiftForDisplay = null; - - const activeShifts = await Shift.findAll({ - where: {userId: targetUserId, endTime: null} - }); - for (const activeShift of activeShifts) { - if (profile?.onBreak && profile.breakStartTime) { - await applyBreakElapsedToShift(activeShift, profile.breakStartTime); - } - - const endTime = new Date(); - const durationSeconds = Math.floor( - (endTime.getTime() - new Date(activeShift.startTime).getTime()) / 1000 - ); - - await activeShift.update({ - endTime, - duration: durationSeconds - }); - endedShiftForDisplay = activeShift; - } - - await Profile.update({ - onDuty: false, - onBreak: false, - breakStartTime: null - }, { - where: {userId: targetUserId} - }); - if (config.onDutyRole) { - const member = await interaction.guild.members.fetch(targetUserId).catch(() => null); - if (member) await member.roles.remove(config.onDutyRole).catch(() => {}); - } - - if (endedShiftForDisplay) { - await logShiftChange(client, 'end', { - userId: targetUserId, - shiftType: endedShiftForDisplay.type || 'Staff', - startTime: endedShiftForDisplay.startTime, - endTime: endedShiftForDisplay.endTime, - breakCount: endedShiftForDisplay.breakCount || 0, - durationSeconds: parseInt(endedShiftForDisplay.duration) || 0, - executorId: interaction.user.id - }); - } - - const targetMember = await interaction.guild.members.fetch(targetUserId).catch(() => null); - if (!targetMember) { - return interaction.editReply({ - content: localize('staff-management-system', 'duty-admin-target-left'), - embeds: [], - components: [] - }); - } - - const payload = await buildDutyAdminPayload(client, targetMember, interaction.member); - return interaction.editReply(payload); -} - -async function handleDutyAdminVoidActive(client, interaction) { - const permCheck = checkDutyAdminPermission(client, interaction); - if (permCheck) return permCheck; - - const targetUserId = interaction.customId.split('_')[2]; - const config = getConfig(client, 'shifts'); - const Profile = client.models['staff-management-system']['StaffProfile']; - const Shift = client.models['staff-management-system']['StaffShift']; - - const activeShifts = await Shift.findAll({ - where: { - userId: targetUserId, - endTime: null - }, - order: [['startTime', 'DESC']] - }); - const shiftForLog = activeShifts.length > 0 - ? activeShifts[0] - : null; - for (const activeShift of activeShifts) await activeShift.destroy(); - - await Profile.update({ - onDuty: false, - onBreak: false, - breakStartTime: null - }, { - where: {userId: targetUserId} - }); - if (config.onDutyRole) { - const member = await interaction.guild.members.fetch(targetUserId).catch(() => null); - if (member) await member.roles.remove(config.onDutyRole).catch(() => {}); - } - - if (shiftForLog) { - await logShiftChange(client, 'void', { - userId: targetUserId, - shiftType: shiftForLog.type || 'Staff', - startTime: shiftForLog.startTime, - breakCount: shiftForLog.breakCount || 0, - executorId: interaction.user.id - }); - } - - const targetMember = await interaction.guild.members.fetch(targetUserId).catch(() => null); - if (!targetMember) { - return interaction.editReply({ - content: localize('staff-management-system', 'duty-admin-target-left'), - embeds: [], - components: [] - }); - } - - const payload = await buildDutyAdminPayload(client, targetMember, interaction.member); - return interaction.editReply(payload); -} - -async function handleDutyAdminVoidAll(client, interaction) { - const permCheck = checkDutyAdminPermission(client, interaction); - if (permCheck) return permCheck; - - let confirmPhrase = localize('staff-management-system', 'del-conf-phrase'); - if (confirmPhrase.length > 100) { - confirmPhrase = localize('staff-management-system', 'fallback-conf-phrase'); - } - let delModalLabel = localize('staff-management-system', 'mod-del-lbl'); - if (delModalLabel.length > 45) { - delModalLabel = localize('staff-management-system', 'fallback-del-lbl'); - } - - const targetUserId = interaction.customId.split('_')[2]; - const modal = new ModalBuilder() - .setCustomId(`duty-mgmt_admin-voidall-submit_${targetUserId}`) - .setTitle(localize('staff-management-system', 'mod-v-all-title')); - - modal.addComponents( - new ActionRowBuilder().addComponents( - new TextInputBuilder() - .setCustomId('confirm') - .setLabel(delModalLabel) - .setStyle(TextInputStyle.Paragraph) - .setPlaceholder(confirmPhrase) - .setRequired(true) - ) - ); - return interaction.showModal(modal); -} - -async function handleDutyAdminVoidAllSubmit(client, interaction) { - const permCheck = checkDutyAdminPermission(client, interaction); - if (permCheck) return permCheck; - - const targetUserId = interaction.customId.split('_')[2]; - let confirmPhrase = localize('staff-management-system', 'del-conf-phrase'); - if (confirmPhrase.length > 100) { - confirmPhrase = localize('staff-management-system', 'fallback-conf-phrase'); - } - - if (interaction.fields.getTextInputValue('confirm').trim() !== confirmPhrase) { - return interaction.reply({ - content: localize('staff-management-system', 'err-conf-fail'), - flags: MessageFlags.Ephemeral - }); - } - - const config = getConfig(client, 'shifts'); - const Profile = client.models['staff-management-system']['StaffProfile']; - const Shift = client.models['staff-management-system']['StaffShift']; - - await Shift.destroy({ - where: {userId: targetUserId} - }); - await Profile.update({ - onDuty: false, - onBreak: false, - breakStartTime: null - }, { - where: {userId: targetUserId} - }); - - if (config.onDutyRole) { - const member = await interaction.guild.members.fetch(targetUserId).catch(() => null); - if (member) await member.roles.remove(config.onDutyRole).catch(() => {}); - } - - client.logger.info(localize('staff-management-system', 'log-void-all', { - target: targetUserId, - admin: interaction.user.id - })); - - return interaction.reply({ - content: localize('staff-management-system', 'succ-v-all', {user: targetUserId}), - flags: MessageFlags.Ephemeral - }); -} - -async function handleDutyAdminAddTimeButton(client, interaction) { - const permCheck = checkDutyAdminPermission(client, interaction); - if (permCheck) return permCheck; - - const targetUserId = interaction.customId.split('_')[2]; - const config = getConfig(client, 'shifts'); - const dutyTypes = config.dutyTypes && config.dutyTypes.length > 0 - ? config.dutyTypes - : ['Staff']; - - const modal = new ModalBuilder() - .setCustomId(`duty-mgmt_admin-addtime-submit_${targetUserId}`) - .setTitle(localize('staff-management-system', 'mod-add-t')); - modal.addComponents( - new ActionRowBuilder() - .addComponents( - new TextInputBuilder() - .setCustomId('minutes') - .setLabel(localize('staff-management-system', 'mod-add-min')) - .setStyle(TextInputStyle.Short) - .setPlaceholder('e.g. 60') - .setRequired(true) - ), - new ActionRowBuilder() - .addComponents( - new TextInputBuilder() - .setCustomId('type') - .setLabel(localize('staff-management-system', 'mod-add-type')) - .setStyle(TextInputStyle.Short) - .setPlaceholder(dutyTypes.join(', ')) - .setValue(dutyTypes[0]) - .setRequired(true) - ) - ); - return interaction.showModal(modal); -} - -async function handleDutyAdminAddTimeSubmit(client, interaction) { - const permCheck = checkDutyAdminPermission(client, interaction); - if (permCheck) return permCheck; - - const targetUserId = interaction.customId.split('_')[2]; - const minutesRaw = interaction.fields.getTextInputValue('minutes'); - const shiftType = interaction.fields.getTextInputValue('type'); - - const maxMinutes = 10080; - const minutes = parseInt(minutesRaw, 10); - - if (isNaN(minutes) || minutes <= 0 || minutes > maxMinutes) { - return interaction.reply({ - content: localize('staff-management-system', 'err-inv-min'), - flags: MessageFlags.Ephemeral - }); - } - - const config = getConfig(client, 'shifts'); - const dutyTypes = config.dutyTypes && config.dutyTypes.length > 0 - ? config.dutyTypes - : ['Staff']; - - if (!dutyTypes.includes(shiftType)) { - return interaction.reply({ - content: localize('staff-management-system', 'err-inv-type', { - types: dutyTypes.join(', ') - }), - flags: MessageFlags.Ephemeral - }); - } - - const Shift = client.models['staff-management-system']['StaffShift']; - - const durationSeconds = minutes * 60; - const endTime = new Date(); - const startTime = new Date(endTime.getTime() - (durationSeconds * 1000)); - - await Shift.create({ - userId: targetUserId, - startTime: startTime, - endTime: endTime, - duration: durationSeconds, - type: shiftType - }); - - client.logger.info(localize('staff-management-system', 'log-add-time', { - admin: interaction.user.tag, - min: minutes, - type: shiftType, - target: targetUserId - })); - - const targetMember = await interaction.guild.members.fetch(targetUserId).catch(() => null); - if (!targetMember) { - return interaction.reply({ - content: localize('staff-management-system', 'duty-admin-target-left'), - flags: MessageFlags.Ephemeral - }); - } - - const payload = await buildDutyAdminPayload(client, targetMember, interaction.member); - return interaction.reply({ - ...payload, - flags: MessageFlags.Ephemeral - }); -} - -// ----- Dropdown handler ----- -async function handleDutyDropdown(client, interaction, action, selectedType) { - if (action === 'manage') { - const payload = await buildDutyManagePayload(client, interaction.user.id, selectedType); - return interaction.editReply({ content: '', ...payload }); - } - if (action === 'leaderboard') { - const payload = await buildLeaderboardPayload(client, 1, selectedType); - return interaction.editReply({ content: '', ...payload }); - } - if (action === 'time') { - const payload = await buildDutyTimePayload(client, interaction, selectedType); - return interaction.editReply({ content: '', ...payload }); - } -} - -async function handleCommonDutyCommand(i, action) { - const config = getConfig(i.client, 'shifts'); - if (!config || !config.enableShifts) return i.editReply({ content: localize('staff-management-system', 'err-sh-dis') }); - - const dutyTypes = config.dutyTypes && config.dutyTypes.length > 0 ? config.dutyTypes : ['Staff']; - let shiftType = i.options.getString('type'); - - const allowedTypes = (action === 'leaderboard' || action === 'time') ? ['All', ...dutyTypes] : dutyTypes; - - if (action === 'manage') { - const Profile = i.client.models['staff-management-system']['StaffProfile']; - const Shift = i.client.models['staff-management-system']['StaffShift']; - const profile = await Profile.findByPk(i.user.id); - if (profile?.onDuty) { - const activeShift = await Shift.findOne({ where: { userId: i.user.id, endTime: null } }); - shiftType = activeShift?.type || dutyTypes[0]; - } - } - - if (!shiftType) { - if (dutyTypes.length === 1 && action === 'manage') { - shiftType = dutyTypes[0]; - } else if (dutyTypes.length === 1 && (action === 'leaderboard' || action === 'time')) { - shiftType = 'All'; - } else { - const selectMenu = new StringSelectMenuBuilder() - .setCustomId(`duty-mgmt_dropdown_${action}`) - .setPlaceholder(localize('staff-management-system', 'ph-sel-type')); - - allowedTypes.forEach(t => selectMenu.addOptions({ label: t, value: t })); - const row = new ActionRowBuilder().addComponents(selectMenu); - return i.editReply({ content: localize('staff-management-system', 'msg-sel-type'), components: [row.toJSON()] }); - } - } else if (!allowedTypes.includes(shiftType)) { - return i.editReply({ content: localize('staff-management-system', 'err-inv-type', { types: allowedTypes.join(', ') }) }); - } - - if (action === 'manage') { - const payload = await buildDutyManagePayload(i.client, i.user.id, shiftType); - await i.editReply(payload); - } else if (action === 'leaderboard') { - const payload = await buildLeaderboardPayload(i.client, 1, shiftType); - await i.editReply(payload); - } else if (action === 'time') { - const payload = await buildDutyTimePayload(i.client, i, shiftType); - await i.editReply(payload); - } -} +const { getConfig } = require('../core/localHelpers'); +const { + handleCommonDutyCommand, + buildActiveShiftsPayload, + buildDutyAdminPayload, + buttonHandlers, + _test +} = require('../core/duty'); module.exports.autoComplete = { 'manage': { @@ -1276,7 +15,7 @@ module.exports.autoComplete = { const config = getConfig(interaction.client, 'shifts'); const dutyTypes = config.dutyTypes && config.dutyTypes.length > 0 ? config.dutyTypes - : ['Staff']; + : ['Staff']; const focusedValue = interaction.value || ''; const filtered = dutyTypes.filter(choice => choice.toLowerCase().startsWith(focusedValue.toLowerCase())); @@ -1291,7 +30,7 @@ module.exports.autoComplete = { const config = getConfig(interaction.client, 'shifts'); const dutyTypes = config.dutyTypes && config.dutyTypes.length > 0 ? config.dutyTypes - : ['Staff']; + : ['Staff']; const options = ['All', ...dutyTypes]; const focusedValue = interaction.value || ''; @@ -1307,7 +46,7 @@ module.exports.autoComplete = { const config = getConfig(interaction.client, 'shifts'); const dutyTypes = config.dutyTypes && config.dutyTypes.length > 0 ? config.dutyTypes - : ['Staff']; + : ['Staff']; const options = ['All', ...dutyTypes]; const focusedValue = interaction.value || ''; @@ -1331,114 +70,8 @@ module.exports.subcommands = { await handleCommonDutyCommand(i, 'manage'); }, 'active': async function (i) { - const config = getConfig(i.client, 'shifts'); - if (!config || !config.enableShifts) return i.editReply({ - content: localize('staff-management-system', 'err-sh-dis') - }); - - const Shift = i.client.models['staff-management-system']['StaffShift']; - const Profile = i.client.models['staff-management-system']['StaffProfile']; - const activeShifts = await Shift.findAll({ - where: {endTime: null}, - order: [['startTime', 'ASC']] - }); - - if (activeShifts.length === 0) return i.editReply({ - content: localize('staff-management-system', 'info-no-act-sh') - }); - - const profiles = await Profile.findAll({ - where: { - userId: activeShifts.map(shift => shift.userId) - } - }); - const profileMap = new Map(profiles.map(profile => [profile.userId, profile])); - - const dutyTypes = config.dutyTypes && config.dutyTypes.length > 0 - ? config.dutyTypes - : ['Staff']; - - const grouped = {}; - for (const shift of activeShifts) { - const type = shift.type || dutyTypes[0]; - if (!grouped[type]) grouped[type] = []; - grouped[type].push(shift); - } - - const embed = applyFooter(i.client, new EmbedBuilder() - .setTitle(localize('staff-management-system', 'duty-act-title')) - .setColor('Green') - .setDescription(localize('staff-management-system', 'duty-act-desc', { - count: activeShifts.length - })) - ); - - let index = 1; - for (const type of dutyTypes) { - if (grouped[type]) { - const lines = []; - for (const shift of grouped[type]) { - const profile = profileMap.get(shift.userId); - const isOnBreak = profile?.onBreak && profile?.breakStartTime; - - let elapsed; - if (isOnBreak) { - elapsed = Math.floor( - (new Date(profile.breakStartTime).getTime() - new Date(shift.startTime).getTime()) / 1000 - ); - } else { - elapsed = Math.floor( - (Date.now() - new Date(shift.startTime).getTime()) / 1000 - ); - } - - const breakSuffix = isOnBreak - ? ` (${localize('staff-management-system', 'stat-brk')})` - : ''; - - lines.push(`${index}. **<@${shift.userId}>** â€ĸ ${formatDuration(elapsed)}${breakSuffix}`); - index++; - } - embed.addFields({ - name: `${type} (${grouped[type].length})`, - value: lines.join('\n') - }); - delete grouped[type]; - } - } - for (const [type, shifts] of Object.entries(grouped)) { - const lines = []; - for (const shift of shifts) { - const profile = profileMap.get(shift.userId); - const isOnBreak = profile?.onBreak && profile?.breakStartTime; - - let elapsed; - if (isOnBreak) { - elapsed = Math.floor( - (new Date(profile.breakStartTime).getTime() - new Date(shift.startTime).getTime()) / 1000 - ); - } else { - elapsed = Math.floor( - (Date.now() - new Date(shift.startTime).getTime()) / 1000 - ); - } - - const breakSuffix = isOnBreak - ? ` (${localize('staff-management-system', 'stat-brk')})` - : ''; - - lines.push(`${index}. **<@${shift.userId}>** â€ĸ ${formatDuration(elapsed)}${breakSuffix}`); - index++; - } - - embed.addFields({ - name: `${type} (${shifts.length}) [Legacy]`, - value: lines.join('\n') - }); - } - await i.editReply({ - embeds: [embed.toJSON()] - }); + const payload = await buildActiveShiftsPayload(i.client); + await i.editReply(payload); }, 'leaderboard': async function (i) { await handleCommonDutyCommand(i, 'leaderboard'); @@ -1541,26 +174,6 @@ module.exports.config = { ] }; -// Export handlers -module.exports.buttonHandlers = { - handleDutyStartButton, - handleDutyAdminAddTimeButton, - handleDutyBreakButton, - handleDutyEndButton, - handleDutyDropdown, - handleDutyHistPageButton, - handleDutyLbPageButton, - handleDutyAdminForceEnd, - handleDutyAdminVoidActive, - handleDutyAdminVoidAll, - handleDutyAdminVoidAllSubmit, - handleDutyAdminAddTimeSubmit -}; - -// Exported for unit testing of the pure duty helpers. -module.exports._test = { - getLookbackDate, - canUseDutyAdmin, - applyBreakElapsedToShift, - getQuotaForMember -}; \ No newline at end of file +// Re-export handlers & test helpers for compatibility +module.exports.buttonHandlers = buttonHandlers; +module.exports._test = _test; \ No newline at end of file diff --git a/modules/staff-management-system/commands/staff-management.js b/modules/staff-management-system/commands/staff-management.js index 1d549b0b..64b5e826 100644 --- a/modules/staff-management-system/commands/staff-management.js +++ b/modules/staff-management-system/commands/staff-management.js @@ -1,280 +1,32 @@ const { MessageFlags, EmbedBuilder, ModalBuilder, TextInputBuilder, TextInputStyle, ActionRowBuilder } = require('discord.js'); const { embedTypeV2 } = require('../../../src/functions/helpers'); const { localize } = require('../../../src/functions/localize'); +const { applyFooter } = require('../core/localHelpers'); const { - applyFooter, issueInfraction, getInfractionHistory, issueSuspension, - voidInfraction, + voidInfraction +} = require('../core/infractions'); +const { promoteUser, - getPromotionHistory, + getPromotionHistory +} = require('../core/promotions'); +const { submitReview, - getReviewHistory, + getReviewHistory +} = require('../core/reviews'); +const { + canManageChecks, startActivityCheck, - endActivityCheckProcess, - generateUserPanel -} = require('../staff-management'); - -function canManageChecks(client, member) { - if (member.permissions.has('Administrator')) return true; - const config = client.configurations['staff-management-system']['configuration'] || {}; - const supRoles = config.supervisorRoles || []; - const mgmtRoles = config.managementRoles || []; - return member.roles.cache.some(r => supRoles.includes(r.id) || mgmtRoles.includes(r.id)); -} - -async function handleProfileView(client, interaction, targetUser) { - const config = client.configurations['staff-management-system']['profiles']; - if (!config || !config.enableProfiles) return interaction.editReply({ - content: localize('staff-management-system', 'err-prof-dis') - }); - - if (!config.profileEmbedMessage) { - return interaction.editReply({ - content: localize('staff-management-system', 'err-prof-cfg') - }); - } - - const user = targetUser || interaction.user; - const member = await interaction.guild.members.fetch(user.id).catch(() => null); - if (!member) return interaction.editReply({ - content: localize('staff-management-system', 'err-no-mem') - }); - - const restrictToStaff = config.onlyAllowStaffProfile !== false; - if (restrictToStaff) { - const generalConfig = client.configurations['staff-management-system']['configuration'] || {}; - - const staffRoles = Array.isArray(generalConfig.staffRoles) - ? generalConfig.staffRoles - : (generalConfig.staffRoles - ? [generalConfig.staffRoles] - : [] - ); - const supRoles = Array.isArray(generalConfig.supervisorRoles) - ? generalConfig.supervisorRoles - : (generalConfig.supervisorRoles - ? [generalConfig.supervisorRoles] - : [] - ); - const mgmtRoles = Array.isArray(generalConfig.managementRoles) - ? generalConfig.managementRoles - : (generalConfig.managementRoles - ? [generalConfig.managementRoles] - : [] - ); - - const allStaffRoles = [...staffRoles, ...supRoles, ...mgmtRoles]; - const isAdmin = member.permissions.has('Administrator'); - const isStaff = allStaffRoles.length > 0 && member.roles.cache.some(r => allStaffRoles.includes(r.id)); - - if (!isAdmin && !isStaff) { - if (user.id === interaction.user.id) { - return interaction.editReply({ - content: localize('staff-management-system', 'err-prof-no-own') - }); - } else { - return interaction.editReply({ - content: localize('staff-management-system', 'err-prof-no-tgt') - }); - } - } - } - - const Profile = client.models['staff-management-system']['StaffProfile']; - const Review = client.models['staff-management-system']['StaffReview']; - - const [profile] = await Profile.findOrCreate({ - where: {userId: user.id} - }); - - const reviewsConfig = client.configurations['staff-management-system']['reviews']; - const reviewsEnabled = reviewsConfig && reviewsConfig.enableReviews; - - let ratingDisplay = localize('staff-management-system', 'rev-dis-text'); - if (reviewsEnabled) { - let avgRatingText = localize('staff-management-system', 'rev-no-rate'); - const allReviews = await Review.findAll({ - where: {targetId: user.id}, - attributes: ['stars'] - }); - if (allReviews.length > 0) { - avgRatingText = (allReviews.reduce((a, b) => a + b.stars, 0) / allReviews.length).toFixed(1); - } - ratingDisplay = `⭐ ${avgRatingText}`; - } - - let discordStatus = localize('staff-management-system', 'stat-offl'); - if (member.presence) { - switch (member.presence.status) { - case 'online': discordStatus = localize('staff-management-system', 'stat-onl'); break; - case 'idle': discordStatus = localize('staff-management-system', 'stat-idl'); break; - case 'dnd': discordStatus = localize('staff-management-system', 'stat-dnd'); break; - case 'offline': discordStatus = localize('staff-management-system', 'stat-offl'); break; - } - } - - const statusLines = [discordStatus]; - if (profile.onDuty) statusLines.push(localize('staff-management-system', 'stat-prof-ond')); - if (profile.activityStatus === 'LOA') statusLines.push(localize('staff-management-system', 'stat-prof-loa')); - if (profile.activityStatus === 'RA') statusLines.push(localize('staff-management-system', 'stat-prof-ra')); - - const introText = profile.customIntro || localize('staff-management-system', 'prof-no-intro'); - const nicknameText = profile.customNickname || user.username; - - const placeholders = { - '%user-mention%': user.toString(), - '%username%': user.username, - '%nickname%': nicknameText, - '%intro%': introText, - '%status%': statusLines.join('\n'), - '%rating%': ratingDisplay, - '%avatar%': user.displayAvatarURL({ - dynamic: true, - format: 'png', - size: 1024 - }) || '' - }; - - let embedTemplate = config.profileEmbedMessage; - let msgOpts = await embedTypeV2(embedTemplate, placeholders); - - if (!msgOpts) { - return interaction.editReply({ - content: localize('staff-management-system', 'err-prof-empty') - }); - } - - await interaction.editReply(msgOpts); -} - -async function handleProfileEdit(client, interaction) { - const config = client.configurations['staff-management-system']['profiles']; - if (!config || !config.enableProfiles) return interaction.reply({ - content: localize('staff-management-system', 'err-prof-dis'), - flags: MessageFlags.Ephemeral - }); - - const restrictToStaff = config.onlyAllowStaffProfile !== false; - if (restrictToStaff) { - const generalConfig = client.configurations['staff-management-system']['configuration'] || {}; - - const staffRoles = Array.isArray(generalConfig.staffRoles) - ? generalConfig.staffRoles - : (generalConfig.staffRoles - ? [generalConfig.staffRoles] - : [] - ); - const supRoles = Array.isArray(generalConfig.supervisorRoles) - ? generalConfig.supervisorRoles - : (generalConfig.supervisorRoles - ? [generalConfig.supervisorRoles] - : [] - ); - const mgmtRoles = Array.isArray(generalConfig.managementRoles) - ? generalConfig.managementRoles - : (generalConfig.managementRoles - ? [generalConfig.managementRoles] - : [] - ); - - const allStaffRoles = [ - ...staffRoles, - ...supRoles, - ...mgmtRoles - ]; - - const isAdmin = interaction.member.permissions.has('Administrator'); - const hasStaffRole = allStaffRoles.length > 0 && interaction.member.roles.cache.some(r => allStaffRoles.includes(r.id)); - - if (!isAdmin && !hasStaffRole) { - return interaction.reply({ - content: localize('staff-management-system', 'err-prof-perm'), - flags: MessageFlags.Ephemeral - }); - } - } - - const Profile = client.models['staff-management-system']['StaffProfile']; - const profile = await Profile.findByPk(interaction.user.id); - - const modal = new ModalBuilder() - .setCustomId(`staff-mgmt_profile-edit`) - .setTitle(localize('staff-management-system', 'prof-edit-title')); - - modal.addComponents( - new ActionRowBuilder() - .addComponents( - new TextInputBuilder() - .setCustomId('nickname') - .setLabel(localize('staff-management-system', 'prof-edit-nick')) - .setStyle(TextInputStyle.Short) - .setRequired(false) - .setValue(profile?.customNickname || '') - ), - new ActionRowBuilder().addComponents( - new TextInputBuilder() - .setCustomId('intro') - .setLabel(localize('staff-management-system', 'prof-edit-intro')) - .setStyle(TextInputStyle.Paragraph) - .setRequired(false) - .setValue(profile?.customIntro || '') - ) - ); - - return interaction.showModal(modal); -} - -async function handleProfileAdminWipe(client, interaction, targetUser) { - const profilesConfig = client.configurations['staff-management-system']['profiles']; - const generalConfig = client.configurations['staff-management-system']['configuration'] || {}; - - if (!profilesConfig || !profilesConfig.enableProfiles) { - return interaction.editReply({ - content: localize('staff-management-system', 'err-prof-dis') - }); - } - - const mRoles = Array.isArray(generalConfig.managementRoles) - ? generalConfig.managementRoles - : (generalConfig.managementRoles - ? [generalConfig.managementRoles] - : [] - ); - const sRoles = Array.isArray(generalConfig.supervisorRoles) - ? generalConfig.supervisorRoles - : (generalConfig.supervisorRoles - ? [generalConfig.supervisorRoles] - : [] - ); - - const requiredRoles = profilesConfig.managePermission === 'Management' - ? mRoles - : [...sRoles, ...mRoles]; - - const isAdmin = interaction.member.permissions.has('Administrator'); - const hasRequiredRole = requiredRoles.length > 0 && interaction.member.roles.cache.some(r => requiredRoles.includes(r.id)); - - if (!isAdmin && !hasRequiredRole) { - return interaction.editReply({ - content: localize('staff-management-system', 'err-no-perm') - }); - } - - const Profile = client.models['staff-management-system']['StaffProfile']; - await Profile.update({ - customNickname: null, - customIntro: null - }, - { - where: {userId: targetUser.id} - }); - - await interaction.editReply({ - content: localize('staff-management-system', 'succ-prof-wipe', {u: targetUser.username}) - }); -} + endActivityCheckProcess +} = require('../core/activityChecks'); +const { generateUserPanel } = require('../core/panels'); +const { + handleProfileView, + handleProfileEdit, + handleProfileAdminWipe +} = require('../core/profiles'); module.exports.handleProfileView = handleProfileView; diff --git a/modules/staff-management-system/commands/staff-status.js b/modules/staff-management-system/commands/staff-status.js index 9eb2b69c..fc1404af 100644 --- a/modules/staff-management-system/commands/staff-status.js +++ b/modules/staff-management-system/commands/staff-status.js @@ -1,804 +1,23 @@ -const { - MessageFlags, - EmbedBuilder, - ModalBuilder, - TextInputBuilder, - TextInputStyle, - ActionRowBuilder, - ButtonBuilder, - ButtonStyle -} = require('discord.js'); -const { Op } = require('sequelize'); -const schedule = require('node-schedule'); -const { formatDate } = require('../../../src/functions/helpers'); +const { MessageFlags } = require('discord.js'); const { localize } = require('../../../src/functions/localize'); +const { getConfig } = require('../core/localHelpers'); const { - getConfig, - getSafeChannelId, - parseDurationToDays, - buildPaginationRow, - applyFooter, - checkStaffPermissions -} = require('../staff-management'); - -// ---------- Status DM's and logging ---------- -async function sendStatusDm(user, type, dmType, data = {}) { - const label = type === 'LOA' - ? 'LoA' - : 'RA'; - const viewCmd = type === 'LOA' - ? '`/staff-status loa view`' - : '`/staff-status ra view`'; - const endFmt = data.endDate - ? `` - : ''; - - // These messages use the locales key to be easily used later - const messages = { - approved: { - title: 'dm-appr-title', - color: 'Green', - desc: 'dm-appr-desc', - params: {label, approver: data.approver, endFmt, viewCmd} - }, - denied: { - title: 'dm-deny-title', - color: 'Red', - desc: 'dm-deny-desc', - params: {label, denier: data.denier, reason: data.reason} - }, - extended: { - title: 'dm-ext-title', - color: 'Yellow', - desc: 'dm-ext-desc', - params: {label, extender: data.extender, days: data.days, endFmt, reason: data.reason, viewCmd} - }, - ended_early: { - title: 'dm-early-title', - color: 'Red', - desc: 'dm-early-desc', - params: {label, ender: data.ender, reason: data.reason} - }, - ended: { - title: 'dm-end-title', - color: 'Black', - desc: 'dm-end-desc', - params: {label} - } - }; - - const msg = messages[dmType]; - if (!msg) return; - - const embed = new EmbedBuilder() - .setTitle(localize('staff-management-system', msg.title, msg.params)) - .setDescription(localize('staff-management-system', msg.desc, msg.params)) - .setColor(msg.color); - applyFooter(user.client, embed); - - try { - await user.send({ - embeds: [embed.toJSON()] - }); - } catch (e) { - user.client.logger.error( - localize('staff-management-system', 'log-stat-dm-error', { - e: e.message, - u: user.tag - }) - ); - } -} - -function isStatusTypeEnabled(config, type) { - if (!config?.enableStatusSystem) return false; - return type === 'LOA' - ? !!config.enableLoa - : !!config.enableRa; -} - -async function logStatusChange(client, type, action, data) { - const statusConfig = getConfig(client, 'status'); - if (!statusConfig?.logStatusChanges) return; - - const channelId = getSafeChannelId(statusConfig.statusChangeLogChannel) || getSafeChannelId(getConfig(client, 'configuration')?.generalLogChannel); - if (!channelId) return; - - const guild = client.guilds.cache.get(client.guildID); - if (!guild) return; - const channel = await guild.channels.fetch(channelId).catch(() => null); - if (!channel) return; - - const label = type === 'LOA' - ? 'LoA' - : 'RA'; - const targetUserObj = data.targetUser || await client.users.fetch(data.userId).catch(() => null); - const mention = targetUserObj - ? targetUserObj.toString() - : `<@${data.userId}>`; - const username = targetUserObj - ? targetUserObj.username - : data.userId; - - const embed = new EmbedBuilder() - .setThumbnail(targetUserObj - ?.displayAvatarURL({ dynamic: true }) || null); - - if (action === 'start') { - embed.setTitle(localize('staff-management-system', 'log-start-title', { label, username })) - .setColor('Green') - .setDescription(localize('staff-management-system', 'log-start-desc', - { - label, mention, apprText: data.approverId - ? ` ${localize('staff-management-system', 'label-appr-by')}: <@${data.approverId}>.` - : '' - })) - .addFields({ - name: localize('staff-management-system', 'log-info-hdr', {label}), - value: `**${localize('staff-management-system', 'general-start')}:** \n**${localize('staff-management-system', 'general-end')}:** \n**${localize('staff-management-system', 'general-rsn')}:** ${data.reason || localize('staff-management-system', 'none-provided')}` - }); - - } else if (action === 'end') { - embed.setTitle(localize('staff-management-system', 'log-end-title', { label, username })) - .setColor('Red') - .setDescription(localize('staff-management-system', 'log-end-desc', { label, mention })) - .addFields({ - name: localize('staff-management-system', 'log-info-hdr', {label}), - value: `**${localize('staff-management-system', 'general-started')}:** \n**${localize('staff-management-system', 'general-ended')}:** \n**${localize('staff-management-system', 'general-req-reason')}:** ${data.reqReason}\n**${localize('staff-management-system', 'general-rsn')}:** ${data.reason || localize('staff-management-system', 'none-provided')}` - }); - - } else if (action === 'adjusted') { - embed.setTitle(localize('staff-management-system', 'log-adj-title', { label, username })) - .setColor('Yellow') - .setDescription(localize('staff-management-system', 'log-adj-desc', { label, mention, executor: data.executorId })) - .addFields({ - name: localize('staff-management-system', 'log-changes'), - value: data.changesText - }); - } - - applyFooter(client, embed); - try { - await channel.send({ - embeds: [embed.toJSON()] - }); - } catch (e) { - client.logger.error( - localize('staff-management-system', 'log-status-adj-error', { - e: e.message - }) - ); - } -} - -// ----- Status ----- -const getStatusMeta = (type) => ({ - isLoa: type === 'LOA', - label: type === 'LOA' - ? 'LoA' - : 'RA', - enableKey: type === 'LOA' - ? 'enableLoa' - : 'enableRa', - roleKey: type === 'LOA' - ? 'loaRole' - : 'raRole', - maxDaysKey: type === 'LOA' - ? 'loaMaxDays' - : 'raMaxDays', - color: type === 'LOA' - ? 'Green' - : 'Orange', - activeText: localize('staff-management-system', type === 'LOA' - ? 'status-active-loa' - : 'status-active-ra' - ), - histTitle: localize('staff-management-system', type === 'LOA' - ? 'status-hist-loa' - : 'status-hist-ra' - ), - actionPrefix: type === 'LOA' - ? 'loa' - : 'ra' -}); - -async function handleStatusRequest(client, interaction, type, durationInput, reason) { - const config = getConfig(client, 'status'); - const isLoa = type === 'LOA'; - if (!isStatusTypeEnabled(config, type)) - return interaction.editReply({ - content: localize('staff-management-system', 'err-status-disabled', {type}) - } - ); - - const days = parseDurationToDays(durationInput?.trim()); - if (!days || isNaN(days) || days <= 0) return interaction.editReply({ - content: localize('staff-management-system', 'err-invalid-duration') - }); - - const maxDays = (isLoa ? config.loaMaxDays : config.raMaxDays) || (isLoa ? 60 : 30); - if (days > maxDays) return interaction.editReply({ - content: localize('staff-management-system', 'err-duration-max', {max: maxDays}) - }); - - const LoaRequest = client.models['staff-management-system']['LoaRequest']; - if (await LoaRequest.findOne({ - where: { - userId: interaction.user.id, type, status: {[Op.in]: ['PENDING', 'APPROVED']}, - endDate: {[Op.gt]: new Date()} - } - })) { - return interaction.editReply({ - content: localize('staff-management-system', 'err-status-exists', {type}) - }); - } - - const startDate = new Date(); - const endDate = new Date(startDate.getTime() + days * 24 * 60 * 60 * 1000); - const needsApproval = isLoa - ? config.requireLoaApproval !== false - : config.requireRaApproval !== false; - - const req = await LoaRequest.create({ - userId: interaction.user.id, - type, - reason, - startDate, - endDate, - status: needsApproval - ? 'PENDING' - : 'APPROVED' - }); - - const logChannelId = getSafeChannelId(config.statusLogChannel); - if (logChannelId && needsApproval) { - const channel = await interaction.guild.channels.fetch(logChannelId).catch(() => null); - if (channel) { - const embed = new EmbedBuilder() - .setTitle(localize('staff-management-system', 'status-request-title', { type })) - .setColor('Blue') - .setAuthor({ name: `Request ID: ${req.id}`}) - .addFields( - { - name: localize('staff-management-system', 'status-req-user'), - value: interaction.user.toString(), - inline: true - }, - { - name: localize('staff-management-system', 'status-req-duration'), - value: `${days} ${localize('staff-management-system', 'label-days')}`, - inline: true - }, - { - name: localize('staff-management-system', 'general-rsn'), - value: reason - } - ); - - applyFooter(client, embed); - const row = new ActionRowBuilder() - .addComponents(new ButtonBuilder() - .setCustomId(`staff-mgmt_approve_${req.id}`) - .setLabel(localize('staff-management-system', 'btn-approve')) - .setStyle(ButtonStyle.Success), - new ButtonBuilder() - .setCustomId(`staff-mgmt_deny_${req.id}`) - .setLabel(localize('staff-management-system', 'btn-deny')) - .setStyle(ButtonStyle.Danger)); - channel.send({ embeds: [embed.toJSON()], components: [row.toJSON()] }).catch(()=>{}); - } - } - - if (!needsApproval) { - const roleId = config[isLoa ? 'loaRole' : 'raRole']; - if (roleId) interaction.member.roles.add(roleId).catch(()=>{}); - await logStatusChange(client, type, 'start', { - targetUser: interaction.user, - startDate, - endDate, - reason, - approverId: null - }); - } - - await interaction.editReply({ - content: localize('staff-management-system', 'success-status-request', { - type, state: needsApproval - ? localize('staff-management-system', 'state-pending') - : localize('staff-management-system', 'state-auto') - }) - }); -} - -async function handleStatusView(client, interaction, type, targetUser) { - const user = targetUser || interaction.user; - const request = await client.models['staff-management-system']['LoaRequest'].findOne({ - where: { - userId: user.id, type, status: {[Op.in]: ['APPROVED', 'PENDING']}, - endDate: {[Op.gt]: new Date()} - }, - order: [['createdAt', 'DESC']] - }); - - if (!request) return interaction.editReply({ - content: localize('staff-management-system', 'no-active-status', { - user: user.username, - type - }) - }); - - const embed = new EmbedBuilder() - .setTitle(`${type} Status: ${user.username}`) - .setColor(request.status === 'APPROVED' - ? 'Green' - : 'Yellow' - ) - .addFields( - { - name: localize('staff-management-system', 'label-stat'), - value: request.status, - inline: true - }, - { - name: localize('staff-management-system', 'label-end'), - value: formatDate(request.endDate), - inline: true - }, - { - name: localize('staff-management-system', 'general-rsn'), - value: request.reason || localize('staff-management-system', 'info-none') - }) - .setThumbnail(user.displayAvatarURL({ dynamic: true })); - applyFooter(client, embed); - await interaction.editReply({ embeds: [embed.toJSON()] }); -} - -async function handleStatusList(client, interaction, type, filter) { - const LoaRequest = client.models['staff-management-system']['LoaRequest']; - const now = new Date(); - const cutoff = new Date(); - cutoff.setDate(cutoff.getDate() - 60); - - let whereClause = { type }; - let title = `${type} List`; - - if (filter === 'active') { - whereClause.status = 'APPROVED'; - whereClause.endDate = {[Op.gt]: now}; - title += localize('staff-management-system', 'filter-active'); - } else if (filter === 'expired') { - whereClause.status = {[Op.in]: ['APPROVED', 'ENDED']}; - whereClause.endDate = {[Op.between]: [cutoff, now]}; - title += localize('staff-management-system', 'filter-expired'); - } else { - whereClause.status = {[Op.in]: ['APPROVED', 'ENDED']}; - whereClause.endDate = {[Op.between]: [cutoff, now]}; - title += localize('staff-management-system', 'filter-history'); - } - - const rows = await LoaRequest.findAll({ - where: whereClause, - order: [['endDate', 'DESC']], - limit: 25 - }); - if (rows.length === 0) { - return interaction.editReply({ - content: localize('staff-management-system', 'err-no-recs') - }); - } - - const embed = new EmbedBuilder() - .setTitle(title) - .setColor('Blue') - .setDescription( - rows.map(r => - `**<@${r.userId}>** ${r.status === 'APPROVED' ? '✅' : 'âšī¸'}\n` + - `${localize('staff-management-system', 'label-end')}: ${formatDate(r.endDate)}\n` + - `${localize('staff-management-system', 'general-rsn')}: ${r.reason || localize('staff-management-system', 'info-none')}` - ).join('\n\n') - ); - - applyFooter(client, embed); - await interaction.editReply({ embeds: [embed.toJSON()] }); -} - -async function handleStatusManage(client, interaction, targetMember, type) { - const config = getConfig(client, 'status'); - const meta = getStatusMeta(type); - if (!isStatusTypeEnabled(config, type)) - return interaction.editReply({ - content: localize('staff-management-system', 'err-status-disabled', {type}) - }); - - const generalConfig = getConfig(client, 'configuration'); - if (!checkStaffPermissions(interaction.member, generalConfig, 'supervisor')) { - return interaction.editReply({ - content: localize('staff-management-system', 'err-gen-no-perm') - })}; - - const LoaRequest = client.models['staff-management-system']['LoaRequest']; - const activeRequest = await LoaRequest.findOne({ - where: { - userId: targetMember.user.id, - type, - status: {[Op.in]: ['APPROVED', 'PENDING']}, - endDate: {[Op.gt]: new Date()} - }, - order: [['createdAt', 'DESC']] - } - ); - const totalCount = await LoaRequest.count({ - where: {userId: targetMember.user.id, type} - }); - - const embed = applyFooter(client, new EmbedBuilder() - .setTitle(localize('staff-management-system', 'manage-status-title', { - label: meta.label, - username: targetMember.user.username - })) - .setThumbnail(targetMember.user.displayAvatarURL({ dynamic: true })) - .setColor(activeRequest - ? meta.color - : 'Grey' - ) - .setDescription(localize('staff-management-system', 'manage-stat-desc', { - status: activeRequest - ? meta.activeText - : localize('staff-management-system', 'no-act-stat', { - label: meta.label - }), - label: meta.label, - count: Math.max(0, totalCount - (activeRequest ? 1 : 0)) - })) - ); - - embed.addFields({ - name: localize('staff-management-system', 'manage-active-details', {label: meta.label}), - value: activeRequest ? `**${localize('staff-management-system', 'general-start')}:** ${formatDate(activeRequest.startDate)}\n**${localize('staff-management-system', 'general-end')}:** ${formatDate(activeRequest.endDate)}\n**${localize('staff-management-system', 'label-stat')}:** ${activeRequest.status}\n**${localize('staff-management-system', 'label-appr-by')}:** ${activeRequest.approverId ? `<@${activeRequest.approverId}>` : localize('staff-management-system', 'label-auto')}\n**${localize('staff-management-system', 'general-rsn')}:** ${activeRequest.reason || localize('staff-management-system', 'info-none')}` : localize('staff-management-system', 'manage-no-active-user', {label: meta.label}) - }); - - const p = meta.actionPrefix; - const rid = activeRequest?.id ?? 'none'; - const row = new ActionRowBuilder().addComponents( - new ButtonBuilder() - .setCustomId(`staff-mgmt_${p}-end_${rid}`) - .setLabel(localize('staff-management-system', 'btn-end-early', { label: meta.label })) - .setEmoji('đŸšĢ').setStyle(ButtonStyle.Danger) - .setDisabled(!activeRequest), - new ButtonBuilder() - .setCustomId(`staff-mgmt_${p}-extend_${rid}`) - .setLabel(localize('staff-management-system', 'btn-extend', { label: meta.label })) - .setEmoji('âŗ') - .setStyle(ButtonStyle.Primary) - .setDisabled(!activeRequest), - new ButtonBuilder() - .setCustomId(`staff-mgmt_${p}-hist_${targetMember.user.id}_1`) - .setLabel(localize('staff-management-system', 'btn-view-history')) - .setEmoji('📜') - .setStyle(ButtonStyle.Secondary) - .setDisabled(totalCount === 0) - ); - await interaction.editReply({ - embeds: [embed.toJSON()], - components: [row.toJSON()] - }); -} - -async function handleStatusEnd(interaction, type) { - const meta = getStatusMeta(type); - const requestId = interaction.customId.split('_')[2]; - if (requestId === 'none') return interaction.reply({ - content: localize('staff-management-system', 'err-no-active-end', {label: meta.label}), - flags: MessageFlags.Ephemeral - }); - - const modal = new ModalBuilder() - .setCustomId(`staff-mgmt_${meta.actionPrefix}-end-submit_${requestId}`) - .setTitle(localize('staff-management-system', 'modal-end-early-title', { label: meta.label })); - modal.addComponents(new ActionRowBuilder() - .addComponents( - new TextInputBuilder() - .setCustomId('end_reason') - .setLabel(localize('staff-management-system', 'modal-end-early-reason')) - .setStyle(TextInputStyle.Paragraph) - .setRequired(true) - )); - return interaction.showModal(modal); -} - -async function handleStatusEndSubmit(client, interaction, type) { - const generalConfig = getConfig(client, 'configuration'); - if (!checkStaffPermissions(interaction.member, generalConfig, 'supervisor')) { - return interaction.reply({ - content: localize('staff-management-system', 'err-gen-no-perm'), - flags: MessageFlags.Ephemeral - }); - } - await interaction.deferUpdate(); - - const meta = getStatusMeta(type); - const request = await client.models['staff-management-system']['LoaRequest'].findByPk(interaction.customId.split('_')[2]); - if (!request || request.status === 'ENDED' || request.status === 'DENIED') return interaction.reply({ - content: localize('staff-management-system', 'err-stat-inact', {label: meta.label}), - flags: MessageFlags.Ephemeral - }); - - const reason = interaction.fields.getTextInputValue('end_reason'); - const member = await interaction.guild.members.fetch(request.userId).catch(() => null); - - if (member && getConfig(client, 'status')[meta.roleKey]) await member.roles.remove(getConfig(client, 'status')[meta.roleKey]).catch(() => {}); - - await request.update({ status: 'ENDED', endDate: new Date() }); - await client.models['staff-management-system']['StaffProfile'].update({activityStatus: 'ACTIVE'}, { - where: {userId: request.userId} - }); - - if (member) await sendStatusDm(member.user, type, 'ended_early', { - ender: interaction.user.tag, - reason - }); - await logStatusChange(client, type, 'end', { - userId: request.userId, - startDate: request.startDate, - reason: reason, - reqReason: request.reason - }); - - const updatedEmbed = EmbedBuilder.from(interaction.message.embeds[0]) - .setColor('Grey') - .setDescription(localize('staff-management-system', 'status-ended-embed-desc', { - label: meta.label, user: interaction.user.tag, reason - })) - .spliceFields(0, 1, { - name: localize('staff-management-system', 'manage-active-details', {label: meta.label}), - value: localize('staff-management-system', 'manage-no-active-user', {label: meta.label}) - }); - - const p = meta.actionPrefix; - const disabledRow = new ActionRowBuilder() - .addComponents( - new ButtonBuilder() - .setCustomId(`${p}-end-done`) - .setLabel(localize('staff-management-system', 'btn-end-early', { label: meta.label })) - .setEmoji('đŸšĢ') - .setStyle(ButtonStyle.Danger) - .setDisabled(true), - new ButtonBuilder() - .setCustomId(`${p}-extend-done`) - .setLabel(localize('staff-management-system', 'btn-extend', { label: meta.label })) - .setEmoji('âŗ') - .setStyle(ButtonStyle.Primary) - .setDisabled(true), - new ButtonBuilder() - .setCustomId(`staff-mgmt_${p}-hist_${request.userId}_1`) - .setLabel(localize('staff-management-system', 'btn-view-history')) - .setEmoji('📜') - .setStyle(ButtonStyle.Secondary) - ); - return interaction.editReply({ - embeds: [updatedEmbed.toJSON()], - components: [disabledRow.toJSON()] - }); -} - -async function handleStatusExtend(interaction, type) { - const meta = getStatusMeta(type); - const requestId = interaction.customId.split('_')[2]; - if (requestId === 'none') return interaction.reply({ - content: localize('staff-management-system', 'err-no-active-extend', {label: meta.label}), - flags: MessageFlags.Ephemeral - }); - - const modal = new ModalBuilder() - .setCustomId(`staff-mgmt_${meta.actionPrefix}-extend-submit_${requestId}`) - .setTitle(localize('staff-management-system', 'modal-extend-title', { - label: meta.label - })); - modal.addComponents( - new ActionRowBuilder() - .addComponents( - new TextInputBuilder() - .setCustomId('extend_days') - .setLabel(localize('staff-management-system', 'modal-extend-days')) - .setStyle(TextInputStyle.Short) - .setPlaceholder("7") - .setRequired(true) - ), - new ActionRowBuilder() - .addComponents( - new TextInputBuilder() - .setCustomId('extend_reason') - .setLabel(localize('staff-management-system', 'modal-extend-reason')) - .setStyle(TextInputStyle.Paragraph) - .setRequired(true) - ) - ); - return interaction.showModal(modal); -} - -function scheduleStatusExpiry(client, request) { - const jobName = `staff-mgmt-status-expiry-${request.id}`; - const existingJob = schedule.scheduledJobs[jobName]; - if (existingJob) existingJob.cancel(); - - schedule.scheduleJob(jobName, new Date(request.endDate), async () => { - try { - const req = await client.models['staff-management-system']['LoaRequest'].findByPk(request.id); - if (!req || req.status !== 'APPROVED' || new Date(req.endDate) > new Date()) return; - - await req.update({ status: 'ENDED' }); - await client.models['staff-management-system']['StaffProfile'].update( - { activityStatus: 'ACTIVE' }, - { where: { userId: req.userId } } - ); - - const member = await client.guilds.cache.get(client.guildID)?.members.fetch(req.userId).catch(() => null); - if (member) { - const roleKey = req.type === 'LOA' ? 'loaRole' : 'raRole'; - const roleId = getConfig(client, 'status')[roleKey]; - if (roleId) await member.roles.remove(roleId).catch(() => {}); - await sendStatusDm(member.user, req.type, 'ended'); - } - - await logStatusChange(client, req.type, 'end', { - userId: req.userId, - startDate: req.startDate, - reason: localize('staff-management-system', 'status-expired-auto'), - reqReason: req.reason - }); - } catch (e) { - client.logger.error(localize('staff-management-system', 'log-status-expiry-fail', { - error: e.message - })); - } - }); -} - -async function handleStatusExtendSubmit(client, interaction, type) { - const generalConfig = getConfig(client, 'configuration'); - if (!checkStaffPermissions(interaction.member, generalConfig, 'supervisor')) { - return interaction.reply({ - content: localize('staff-management-system', 'err-gen-no-perm'), - flags: MessageFlags.Ephemeral - }); - } - await interaction.deferUpdate(); - - const meta = getStatusMeta(type); - const request = await client.models['staff-management-system']['LoaRequest'].findByPk(interaction.customId.split('_')[2]); - if (!request || request.status === 'ENDED' || request.status === 'DENIED') { - return interaction.reply({ - content: localize('staff-management-system', 'err-stat-inact', { - label: meta.label - }), - flags: MessageFlags.Ephemeral - }); - } - - const days = parseInt(interaction.fields.getTextInputValue('extend_days'), 10); - const reason = interaction.fields.getTextInputValue('extend_reason'); - if (isNaN(days) || days <= 0 || days > 180) return interaction.reply({ - content: localize('staff-management-system', 'err-inv-dur'), - flags: MessageFlags.Ephemeral - }); - - const oldEndDate = new Date(request.endDate); - const newEndDate = new Date(oldEndDate.getTime() + days * 24 * 60 * 60 * 1000); - await request.update({ endDate: newEndDate }); - request.endDate = newEndDate; - scheduleStatusExpiry(client, request); - - const member = await interaction.guild.members.fetch(request.userId).catch(() => null); - if (member) await sendStatusDm(member.user, type, 'extended', { - extender: interaction.user.tag, - days, - endDate: newEndDate, - reason - }); - await logStatusChange(client, type, 'adjusted', { - userId: request.userId, - executorId: interaction.user.id, - changesText: localize('staff-management-system', 'status-adjusted-log', { - label: meta.label, - newEnd: ``, - oldEnd: ``, - reason - }) - }); - - const updatedEmbed = EmbedBuilder.from(interaction.message.embeds[0]) - .spliceFields(0, 1, { - name: localize('staff-management-system', 'manage-active-details', {label: meta.label}), - value: localize('staff-management-system', 'mod-stat-ext', { - s: formatDate(request.startDate), - e: formatDate(newEndDate), - d: days, - t: request.status, - a: request.approverId - ? `<@${request.approverId}>` - : localize('staff-management-system', 'label-auto'), - r: request.reason || localize('staff-management-system', 'info-none') - }) - }); - return interaction.editReply({ - embeds: [updatedEmbed.toJSON()], - components: interaction.message.components.map(c => c.toJSON()) - }); -} - -async function generateStatusHistoryResponse(client, targetUser, page = 1, type) { - const meta = getStatusMeta(type); - const limit = 5; - const offset = (page - 1) * limit; - - const {count, rows} = await client.models['staff-management-system']['LoaRequest'].findAndCountAll({ - where: {userId: targetUser.id, type}, - order: [['createdAt', 'DESC']], - limit, - offset - }); - if (count === 0) return { - content: localize('staff-management-system', 'info-no-status-history', {label: meta.label}), - flags: MessageFlags.Ephemeral - }; - - const totalPages = Math.ceil(count / limit) || 1; - const embed = applyFooter(client, new EmbedBuilder() - .setTitle(`${meta.histTitle} - ${targetUser.username}`) - .setThumbnail(targetUser.displayAvatarURL({ dynamic: true })) - .setColor(meta.color) - .setDescription(localize('staff-management-system', 'status-history-desc', { - count: rows.length, - total: count, - label: meta.label - } - )) - ); - - const statusIcons = { - APPROVED: '✅', - DENIED: '❌', - ENDED: 'âšī¸', - PENDING: '🕐' - }; - rows.forEach((req, index) => embed.addFields({ - name: `${statusIcons[req.status] ?? '❓'} ${meta.label} #${offset + index + 1} - ${req.status}`, - value: `**${localize('staff-management-system', 'general-start')}:** ${formatDate(req.startDate)}\n**${localize('staff-management-system', 'general-end')}:** ${formatDate(req.endDate)}\n**${localize('staff-management-system', 'label-appr-by')}:** ${req.approverId ? `<@${req.approverId}>` : localize('staff-management-system', 'label-auto')}\n**${localize('staff-management-system', 'general-rsn')}:** ${req.reason || localize('staff-management-system', 'info-none')}` })); - embed.addFields({ - name: '\u200b', - value: localize('staff-management-system', 'page-count', {page, total: totalPages}) - }); - - const row = buildPaginationRow( - `staff-mgmt_${meta.actionPrefix}-hist_${targetUser.id}_${page - 1}`, - `${meta.actionPrefix}_hist_page_count`, - `staff-mgmt_${meta.actionPrefix}-hist_${targetUser.id}_${page + 1}`, - page, - totalPages - ); - return { - embeds: [embed.toJSON()], - components: [row.toJSON()] - }; -} - -async function handleStatusHistPage(client, interaction, type) { - const parts = interaction.customId.split('_'); - const targetUser = await client.users.fetch(parts[2]).catch(() => null); - if (!targetUser) return interaction.reply({ - content: localize('staff-management-system', 'err-gen-no-user'), - flags: MessageFlags.Ephemeral - }); - - const payload = await generateStatusHistoryResponse(client, targetUser, parseInt(parts[3], 10), type); - if (payload.content) return interaction.reply({ - ...payload, - flags: MessageFlags.Ephemeral - }); - return interaction.message?.embeds?.[0]?.title?.startsWith(getStatusMeta(type).histTitle) - ? interaction.update(payload) - : interaction.reply({ ...payload, flags: MessageFlags.Ephemeral }); -} + sendStatusDm, + isStatusTypeEnabled, + logStatusChange, + getStatusMeta, + handleStatusRequest, + handleStatusView, + handleStatusList, + handleStatusManage, + handleStatusEnd, + handleStatusEndSubmit, + handleStatusExtend, + scheduleStatusExpiry, + handleStatusExtendSubmit, + generateStatusHistoryResponse, + handleStatusHistPage +} = require('../core/staffStatus'); module.exports.beforeSubcommand = async function (interaction) { if (!interaction.replied && !interaction.deferred) { diff --git a/modules/staff-management-system/context-actions.js b/modules/staff-management-system/context-actions.js index 3527f39c..57d94a36 100644 --- a/modules/staff-management-system/context-actions.js +++ b/modules/staff-management-system/context-actions.js @@ -10,11 +10,11 @@ const { const {localize} = require('../../src/functions/localize'); const { getConfig, - checkStaffPermissions, - issueInfraction, - promoteUser, - submitReview -} = require('./staff-management'); + checkStaffPermissions +} = require('./core/localHelpers'); +const { issueInfraction } = require('./core/infractions'); +const { promoteUser } = require('./core/promotions'); +const { submitReview } = require('./core/reviews'); /* * Shared core for the staff-management USER context-menu commands. Each command is a thin adapter diff --git a/modules/staff-management-system/core/activityChecks.js b/modules/staff-management-system/core/activityChecks.js new file mode 100644 index 00000000..f881dc7c --- /dev/null +++ b/modules/staff-management-system/core/activityChecks.js @@ -0,0 +1,290 @@ +/** + * Activity checks logic for the Staff Management module + * @module staff-management-system + * @author itskevinnn + */ + +const { + ActionRowBuilder, + ButtonBuilder, + ButtonStyle, + EmbedBuilder +} = require('discord.js'); +const { Op } = require('sequelize'); +const schedule = require('node-schedule'); +const { embedTypeV2, dateToDiscordTimestamp } = require('../../../src/functions/helpers'); +const { localize } = require('../../../src/functions/localize'); +const { + getConfig, + getSafeChannelId, + applyFooter, + formatRoleMentions, + getIsoWeekNumber +} = require('./localHelpers'); + +// ---------- Activity Checks ---------- +async function startActivityCheck(client, interactionOrChannel, isAutomated = false) { + const config = getConfig(client, 'activity-checks'); + const ActivityCheck = client.models['staff-management-system']['ActivityCheck']; + + if (await ActivityCheck.findOne({ + where: {status: 'ACTIVE'} + })) { + return !isAutomated && interactionOrChannel.editReply + ? interactionOrChannel.editReply({content: localize('staff-management-system', 'err-ac-act')}) + : null; + } + + const rolesToCheck = config.targetRoles?.length + ? config.targetRoles + : (getConfig(client, 'configuration')?.staffRoles || []); + if (!rolesToCheck.length) return !isAutomated && interactionOrChannel.editReply + ? interactionOrChannel.editReply({ + content: localize('staff-management-system', 'err-ac-norole') + }) + : null; + + const targetChannel = isAutomated + ? interactionOrChannel + : (interactionOrChannel.options.getChannel('channel') || interactionOrChannel.guild.channels.cache.get(getSafeChannelId(config.sendingChannel)) || interactionOrChannel.channel); + if (!targetChannel) return !isAutomated && interactionOrChannel.editReply + ? interactionOrChannel.editReply({ + content: localize('staff-management-system', 'err-ac-invchan') + }) + : null; + + const durationHours = config.timeframe || 24; + const endTime = new Date(Date.now() + durationHours * 60 * 60 * 1000); + const generalConfig = getConfig(client, 'configuration') || {}; + const initiator = isAutomated + ? localize('staff-management-system', 'label-system') + : interactionOrChannel.user.toString(); + + const responseButtonRow = new ActionRowBuilder() + .addComponents( + new ButtonBuilder() + .setCustomId('staff-mgmt_ac-respond') + .setLabel(localize('staff-management-system', 'ac-confirm-btn')) + .setStyle(ButtonStyle.Success) + .setEmoji('✅') + ) + .toJSON(); + + const msgOpts = await embedTypeV2(config.checkMessage, { + '%end-time%': dateToDiscordTimestamp(endTime, 'F'), + '%duration%': durationHours.toString(), + '%staff-mention%': formatRoleMentions(generalConfig.staffRoles), + '%supervisor-mention%': formatRoleMentions(generalConfig.supervisorRoles), + '%management-mention%': formatRoleMentions(generalConfig.managementRoles), + '%initiator%': initiator + }, { + components: [responseButtonRow] + }); + + if (msgOpts?.content?.trim() === '') delete msgOpts.content; + + try { + const checkMessage = await targetChannel.send(msgOpts); + if (!isAutomated && interactionOrChannel.editReply) await interactionOrChannel.editReply({ + content: localize('staff-management-system', 'succ-ac-start', { + channel: targetChannel.id, + hours: durationHours + }) + }); + + const record = await ActivityCheck.create({ + messageId: checkMessage.id, + channelId: targetChannel.id, + endTime, + targetRoles: JSON.stringify(rolesToCheck), + status: 'ACTIVE', + initiatorId: isAutomated ? null : interactionOrChannel.user.id, + isAutomated + }); + schedule.scheduleJob(endTime, async () => { + const currentCheck = await ActivityCheck.findByPk(record.id); + if (currentCheck && currentCheck.status === 'ACTIVE') await endActivityCheckProcess(client, currentCheck); + }); + } catch (e) { + if (!isAutomated && interactionOrChannel.editReply) interactionOrChannel.editReply({ + content: localize('staff-management-system', 'err-ac-perms', {channel: targetChannel.id}) + }); + } +} + +async function endActivityCheckProcess(client, activeCheck) { + await activeCheck.update({ status: 'ENDED' }); + const guild = client.guilds.cache.get(client.guildID); + if (!guild) return; + + const config = getConfig(client, 'activity-checks'); + const logChannel = guild.channels.cache.get(getSafeChannelId(config.logChannel) || getSafeChannelId(getConfig(client, 'configuration')?.generalLogChannel)); + if (!logChannel) return; + + const targetRoles = JSON.parse(activeCheck.targetRoles || '[]'); + const ActivityCheckResponse = client.models['staff-management-system']['ActivityCheckResponse']; + const responses = await ActivityCheckResponse.findAll({ + where: { activityCheckId: activeCheck.id }, + attributes: ['userId'] + }); + + const respondedUserIds = new Set(responses.map(response => response.userId)); + const StaffProfile = client.models['staff-management-system']['StaffProfile']; + const expectedMembers = guild.members.cache.filter(m => !m.user.bot && m.roles.cache.some(r => targetRoles.includes(r.id))); + const [responded, exceptions, failed] = [[], [], []]; + const expectedIds = [...expectedMembers.keys()]; + const profiles = await StaffProfile.findAll({ + where: { + userId: {[Op.in]: expectedIds} + } + }); + const initiator = (activeCheck.isAutomated || !activeCheck.initiatorId) + ? localize('staff-management-system', 'label-system') + : `<@${activeCheck.initiatorId}>`; + + expectedMembers.forEach(member => { + if (respondedUserIds.has(member.id)) return responded.push(member); + + let isException = false; + const prof = profiles.find(p => p.userId === member.id); + const isLoa = prof?.activityStatus === 'LOA'; + const isRa = prof?.activityStatus === 'RA'; + + if (config.exceptionsType === 'Only LoA' && isLoa) isException = true; + else if (config.exceptionsType === 'Only RA' && isRa) isException = true; + else if (config.exceptionsType === 'LoA and RA' && (isLoa || isRa)) isException = true; + else if (config.exceptionsType === 'Custom role(s)' && member.roles.cache.some(r => config.customExceptionRoles?.includes(r.id))) isException = true; + + isException + ? exceptions.push(member) + : failed.push(member); + }); + + try { + const msg = await guild.channels.cache.get(activeCheck.channelId)?.messages.fetch(activeCheck.messageId); + if (msg) { + const endTemplate = config.endCheckMessage; + const endedMessage = await embedTypeV2( + endTemplate, + { + '%end-time%': dateToDiscordTimestamp(new Date(), 'F'), + '%duration%': (config.timeframe || 24).toString(), + '%staff-mention%': formatRoleMentions(config.staffRoles), + '%supervisor-mention%': formatRoleMentions(config.supervisorRoles), + '%management-mention%': formatRoleMentions(config.managementRoles), + '%initiator%': initiator, + '%responded-count%': responded.length.toString() + }, + { + components: [] + } + ); + + if (endedMessage?.content?.trim() === '') { + delete endedMessage.content; + } + + await msg.edit(endedMessage); + } + } catch (e) { + } + + const embed = applyFooter(client, new EmbedBuilder() + .setTitle(localize('staff-management-system', 'ac-res-title')) + .setColor('Blurple') + .addFields( + { + name: localize('staff-management-system', 'ac-f-res', {count: responded.length } + ), + value: responded.length + ? responded.map(m => `<@${m.id}>`).join(', ').substring(0, 1024) + : localize('staff-management-system', 'info-none') + }, + { + name: localize('staff-management-system', 'ac-f-fail', { + count: failed.length + }), + value: failed.length + ? failed.map(m => `<@${m.id}>`).join(', ').substring(0, 1024) + : localize('staff-management-system', 'info-none') + }, + { + name: localize('staff-management-system', 'ac-f-exc', { + count: exceptions.length + }), + value: exceptions.length + ? exceptions.map(m => `<@${m.id}>`).join(', ').substring(0, 1024) + : localize('staff-management-system', 'info-none') + } + ) + ); + + const pingText = (config.pingResults && config.pingRoles?.length) + ? config.pingRoles.map(rId => `<@&${rId}>`).join(' ') + : null; + const finalMessage = { embeds: [embed.toJSON()] }; + if (pingText) finalMessage.content = pingText; + + await logChannel.send(finalMessage).catch((e) => { + client.logger.error(localize('staff-management-system', 'log-ac-send-fail', { + error: e.message + })); + }); +} + +function initActivityCheckAutomation(client) { + const config = getConfig(client, 'activity-checks'); + if (!config?.enableActivityChecks || !config?.automatedChecks) return; + + let cronString = config.automatedCheckInterval === 'Cronjob' + ? config.automatedCheckCronjob + : null; + if (!cronString) { + const dayMap = { + 'Monday': 1, + 'Tuesday': 2, + 'Wednesday': 3, + 'Thursday': 4, + 'Friday': 5, + 'Saturday': 6, + 'Sunday': 7 + }[config.automatedCheckWeekDay] || 1; + if (['Weekly', 'Biweekly'].includes(config.automatedCheckInterval)) cronString = `0 12 * * ${dayMap}`; + else if (config.automatedCheckInterval === 'Monthly') { + const startDay = [1, 8, 15, 22][(config.automatedCheckMonthWeek || 1) - 1]; + cronString = `0 12 ${startDay}-${startDay + 6} * ${dayMap}`; + } + } + if (!cronString) return; + + const jobName = 'automated-activity-check'; + const existingJob = schedule.scheduledJobs[jobName]; + if (existingJob) existingJob.cancel(); + schedule.scheduleJob(jobName, cronString, async () => { + if (config.automatedCheckInterval === 'Biweekly' && getIsoWeekNumber(new Date()) % 2 !== 0) { + return; + } + + const channel = client.guilds.cache.get(client.guildID)?.channels.cache.get(getSafeChannelId(config.sendingChannel)); + if (channel) { + client.logger.info(`[Activity Checks] Starting automated check.`); + await startActivityCheck(client, channel, true); + } + }); +} + +function canManageChecks(client, member) { + if (member.permissions.has('Administrator')) return true; + const config = client.configurations['staff-management-system']['configuration'] || {}; + const supRoles = config.supervisorRoles || []; + const mgmtRoles = config.managementRoles || []; + return member.roles.cache.some(r => supRoles.includes(r.id) || mgmtRoles.includes(r.id)); +} + +module.exports = { + canManageChecks, + startActivityCheck, + endActivityCheckProcess, + initActivityCheckAutomation, + getIsoWeekNumber +}; diff --git a/modules/staff-management-system/core/duty.js b/modules/staff-management-system/core/duty.js new file mode 100644 index 00000000..07f7cc28 --- /dev/null +++ b/modules/staff-management-system/core/duty.js @@ -0,0 +1,1454 @@ +/** + * Shift and duty tracking logic for the Staff Management module + * @module staff-management-system + * @author itskevinnn + */ + +const { + MessageFlags, + EmbedBuilder, + ActionRowBuilder, + ButtonBuilder, + ButtonStyle, + StringSelectMenuBuilder, + ModalBuilder, + TextInputBuilder, + TextInputStyle +} = require('discord.js'); +const { Op } = require('sequelize'); +const { + getConfig, + applyFooter, + getSafeChannelId, + formatDuration, + buildPaginationRow, + checkStaffPermissions +} = require('./localHelpers'); +const { localize } = require('../../../src/functions/localize'); + +function getLookbackDate(config) { + const lookback = config.leaderboardLookback || 'Weekly'; + if (lookback === 'All-time') return null; + const date = new Date(); + if (lookback === 'Weekly') date.setDate(date.getDate() - 7); + else if (lookback === 'Monthly') date.setMonth(date.getMonth() - 1); + return date; +} + +function canUseDutyAdmin(client, member) { + const generalConfig = getConfig(client, 'configuration'); + return checkStaffPermissions(member, generalConfig, 'supervisor'); +} + +function checkDutyAdminPermission(client, interaction) { + if (canUseDutyAdmin(client, interaction.member)) return null; + + const payload = { + content: localize('staff-management-system', 'err-no-perm'), + flags: MessageFlags.Ephemeral + }; + + if (interaction.deferred || interaction.replied) { + return interaction.followUp(payload); + } + return interaction.reply(payload); +} + +async function applyBreakElapsedToShift(activeShift, breakStartTime, now = new Date()) { + if (!activeShift || !breakStartTime) return; + + const breakStartedAt = new Date(breakStartTime); + if (Number.isNaN(breakStartedAt.getTime()) || breakStartedAt > now) return; + + const elapsedBreakMs = now.getTime() - breakStartedAt.getTime(); + if (elapsedBreakMs <= 0) return; + + await activeShift.update({ + startTime: new Date(new Date(activeShift.startTime).getTime() + elapsedBreakMs) + }); +} + +function getQuotaForMember(member, config) { + if (!config.enableQuotas || !config.quotas || Object.keys(config.quotas).length === 0) return null; + + let bestQuota = null; + let highestPosition = -1; + + for (const [roleId, hoursStr] of Object.entries(config.quotas)) { + const hours = parseFloat(hoursStr); + if (isNaN(hours)) continue; + + const role = member.guild.roles.cache.get(roleId); + if (role && member.roles.cache.has(roleId) && role.position > highestPosition) { + highestPosition = role.position; + bestQuota = { roleId, hours }; + } + } + + return bestQuota; +} + +async function sendShiftEndDm(client, member, shift) { + if (!member || !shift) return; + + const embed = applyFooter(client, new EmbedBuilder() + .setTitle(localize('staff-management-system', 'duty-shift-report-title')) + .setThumbnail(member.user.displayAvatarURL({dynamic: true})) + .addFields( + { + name: localize('staff-management-system', 'duty-shift-information'), + value: + `>>> **${localize('staff-management-system', 'label-shift-type')}:** ${shift.type || 'Staff'}\n` + + `**${localize('staff-management-system', 'general-start')}:** \n` + + `**${localize('staff-management-system', 'general-end')}:** \n` + + `**${localize('staff-management-system', 'label-breaks')}:** ${shift.breakCount || 0}` + }, + { + name: localize('staff-management-system', 'label-elapsed-time'), + value: `> ${formatDuration(parseInt(shift.duration) || 0)}` + } + ) + ); + + try { + await member.user.send({embeds: [embed.toJSON()]}); + } catch (e) { + client.logger.warn(localize('staff-management-system', 'log-duty-dm-fail', { + user: member.user.tag, + error: e.message + })); + } +} + +async function logShiftChange(client, action, data) { + const shiftsConfig = getConfig(client, 'shifts'); + if (!shiftsConfig?.logShiftChanges) return; + const channelId = + getSafeChannelId(shiftsConfig.logShiftChangesChannel) || + getSafeChannelId(getConfig(client, 'configuration')?.generalLogChannel); + if (!channelId) return; + + const guild = client.guilds.cache.get(client.guildID); + if (!guild) return; + const channel = await guild.channels.fetch(channelId).catch(() => null); + if (!channel) return; + + const targetUserObj = data.targetUser || await client.users.fetch(data.userId).catch(() => null); + const mention = targetUserObj ? targetUserObj.toString() : `<@${data.userId}>`; + const username = targetUserObj ? targetUserObj.username : data.userId; + + const embed = new EmbedBuilder() + .setThumbnail(targetUserObj?.displayAvatarURL({dynamic: true}) || null); + + if (action === 'start') { + embed + .setTitle(localize('staff-management-system', 'log-duty-start-title', {username})) + .setColor('Green') + .setDescription(localize('staff-management-system', 'log-duty-start-desc', {mention})) + .addFields({ + name: localize('staff-management-system', 'log-duty-info-hdr'), + value: + `**${localize('staff-management-system', 'general-start')}:** \n` + + `**${localize('staff-management-system', 'label-shift-type')}:** ${data.shiftType || 'Staff'}` + }); + } else if (action === 'break') { + embed + .setTitle(localize('staff-management-system', 'log-duty-break-title', {username})) + .setColor('Yellow') + .setDescription(localize('staff-management-system', 'log-duty-break-desc', {mention})) + .addFields({ + name: localize('staff-management-system', 'log-duty-info-hdr'), + value: + `**${localize('staff-management-system', 'general-start')}:** \n` + + `**${localize('staff-management-system', 'label-shift-type')}:** ${data.shiftType || 'Staff'}\n` + + `**${localize('staff-management-system', 'label-breaks')}:** ${data.breakCount || 0}\n` + + `**${localize('staff-management-system', 'label-elapsed-time')}:** ${formatDuration(data.elapsedSeconds || 0)}` + }); + } else if (action === 'resume') { + embed + .setTitle(localize('staff-management-system', 'log-duty-resume-title', {username})) + .setColor('Green') + .setDescription(localize('staff-management-system', 'log-duty-resume-desc', {mention})) + .addFields({ + name: localize('staff-management-system', 'log-duty-info-hdr'), + value: + `**${localize('staff-management-system', 'general-start')}:** \n` + + `**${localize('staff-management-system', 'label-shift-type')}:** ${data.shiftType || 'Staff'}\n` + + `**${localize('staff-management-system', 'label-breaks')}:** ${data.breakCount || 0}\n` + + `**${localize('staff-management-system', 'label-elapsed-time')}:** ${formatDuration(data.elapsedSeconds || 0)}` + }); + } else if (action === 'end') { + embed + .setTitle(localize('staff-management-system', 'log-duty-end-title', {username})) + .setColor('Red') + .setDescription(localize('staff-management-system', 'log-duty-end-desc', {mention})) + .addFields({ + name: localize('staff-management-system', 'log-duty-info-hdr'), + value: + `**${localize('staff-management-system', 'general-start')}:** \n` + + `**${localize('staff-management-system', 'general-end')}:** \n` + + `**${localize('staff-management-system', 'label-shift-type')}:** ${data.shiftType || 'Staff'}\n` + + `**${localize('staff-management-system', 'label-breaks')}:** ${data.breakCount || 0}\n` + + `**${localize('staff-management-system', 'label-elapsed-time')}:** ${formatDuration(data.durationSeconds || 0)}` + + (data.executorId + ? `\n**${localize('staff-management-system', 'label-ended-by')}:** <@${data.executorId}>` + : '') + }); + } else if (action === 'void') { + embed + .setTitle(localize('staff-management-system', 'log-duty-void-title', {username})) + .setColor('DarkRed') + .setDescription(localize('staff-management-system', 'log-duty-void-desc', { + mention, + executor: `<@${data.executorId}>` + })) + .addFields({ + name: localize('staff-management-system', 'log-duty-info-hdr'), + value: + `**${localize('staff-management-system', 'general-start')}:** \n` + + `**${localize('staff-management-system', 'label-shift-type')}:** ${data.shiftType || 'Staff'}\n` + + `**${localize('staff-management-system', 'label-breaks')}:** ${data.breakCount || 0}` + }); + } else { + return; + } + + applyFooter(client, embed); + + try { + await channel.send({embeds: [embed.toJSON()]}); + } catch (e) { + client.logger.error(localize('staff-management-system', 'log-duty-log-fail', { + action, + error: e.message + })); + } +} + +async function buildDutyManagePayload(client, userId, shiftType, endedShift = null) { + const Profile = client.models['staff-management-system']['StaffProfile']; + const Shift = client.models['staff-management-system']['StaffShift']; + + const user = await client.users.fetch(userId).catch(() => null); + const profile = await Profile.findByPk(userId); + + const onDuty = profile?.onDuty || false; + const onBreak = profile?.onBreak || false; + + let statusColor; + if (onDuty && onBreak) { + statusColor = 'Yellow'; + } else if (onDuty) { + statusColor = 'Green'; + } else { + statusColor = 'Red'; + } + + const completedShifts = await Shift.findAll({ + where: { + userId, + type: shiftType, + endTime: {[Op.not]: null}, + duration: {[Op.not]: null} + } + }); + const totalShifts = completedShifts.length; + const totalSeconds = completedShifts.reduce((sum, s) => sum + (parseInt(s.duration) || 0), 0); + const avgSeconds = totalShifts > 0 + ? Math.floor(totalSeconds / totalShifts) + : 0; + + const activeShift = onDuty + ? await Shift.findOne({ + where: { + userId, + endTime: null + }, + order: [['startTime', 'DESC']] + }) + : null; + + let titleKey = 'duty-panel-title'; + if (onDuty && onBreak) titleKey = 'duty-break-title'; + else if (onDuty) titleKey = 'duty-started-title'; + else if (endedShift) titleKey = 'duty-ended-title'; + + const embed = applyFooter(client, new EmbedBuilder() + .setTitle(localize('staff-management-system', titleKey, {type: shiftType})) + .setColor(statusColor) + .setThumbnail(user?.displayAvatarURL({ dynamic: true }) || null) + ); + + if (onDuty && activeShift) { + let elapsedSeconds; + if (onBreak && profile?.breakStartTime) { + elapsedSeconds = Math.max( + 0, + Math.floor( + (new Date(profile.breakStartTime).getTime() - new Date(activeShift.startTime).getTime()) / 1000 + ) + ); + } else { + elapsedSeconds = Math.max( + 0, + Math.floor((Date.now() - new Date(activeShift.startTime).getTime()) / 1000) + ); + } + + embed.addFields({ + name: localize('staff-management-system', 'duty-shift-overview'), + value: + `>>> **${localize('staff-management-system', 'label-started')}:** \n` + + `**${localize('staff-management-system', 'label-breaks')}:** ${activeShift.breakCount || 0}\n` + + `**${localize('staff-management-system', 'label-elapsed-time')}:** ${formatDuration(elapsedSeconds)}` + }); + } else if (endedShift) { + embed.addFields({ + name: localize('staff-management-system', 'duty-shift-overview'), + value: + `>>> **${localize('staff-management-system', 'label-started')}:** \n` + + `**${localize('staff-management-system', 'label-breaks')}:** ${endedShift.breakCount || 0}\n` + + `**${localize('staff-management-system', 'label-ended')}:** ` + }); + } else { + embed.addFields({ + name: localize('staff-management-system', 'duty-stats'), + value: localize('staff-management-system', 'duty-stat-desc', { + duration: formatDuration(totalSeconds), + count: totalShifts, + average: formatDuration(avgSeconds) + }) + }); + } + + const row = new ActionRowBuilder().addComponents( + new ButtonBuilder() + .setCustomId(`duty-mgmt_start_${userId}_${shiftType}`) + .setLabel(localize('staff-management-system', 'btn-duty-on')) + .setStyle(ButtonStyle.Success) + .setDisabled(onDuty), + new ButtonBuilder() + .setCustomId(`duty-mgmt_break_${userId}`) + .setLabel(onBreak + ? localize('staff-management-system', 'btn-duty-res') + : localize('staff-management-system', 'btn-duty-brk') + ) + .setStyle(ButtonStyle.Secondary) + .setDisabled(!onDuty), + new ButtonBuilder() + .setCustomId(`duty-mgmt_end_${userId}`) + .setLabel(localize('staff-management-system', 'btn-duty-off')) + .setStyle(ButtonStyle.Danger) + .setDisabled(!onDuty) + ); + + return { + embeds: [embed.toJSON()], + components: [row.toJSON()] + }; +} + +async function buildDutyTimePayload(client, interaction, shiftType) { + const config = getConfig(client, 'shifts'); + const Shift = client.models['staff-management-system']['StaffShift']; + const user = interaction.user; + + const whereClause = { + userId: user.id, + endTime: {[Op.not]: null}, + duration: {[Op.not]: null} + }; + if (shiftType !== 'All') whereClause.type = shiftType; + + const shifts = await Shift.findAll({ where: whereClause }); + + const totalSeconds = shifts.reduce((sum, s) => sum + (parseInt(s.duration) || 0), 0); + const shiftCount = shifts.length; + + let breakdownText = ''; + if (shiftType === 'All' && shiftCount > 0) { + const grouped = {}; + for (const s of shifts) { + const t = s.type || 'Staff'; + grouped[t] = (grouped[t] || 0) + (parseInt(s.duration) || 0); + } + breakdownText = `\n\n**${localize('staff-management-system', 'duty-breakdown')}:**\n` + Object.entries(grouped) + .sort((a, b) => b[1] - a[1]) + .map(([t, sec]) => `â€ĸ ${t}: ${formatDuration(sec)}`) + .join('\n'); + } + + let quotaText = ''; + const member = await interaction.guild.members.fetch(user.id).catch(() => null); + if (member) { + const quota = getQuotaForMember(member, config); + if (quota) { + const timeframe = config.quotaTimeframe || 'Weekly'; + const cutoff = new Date(); + if (timeframe === 'Weekly') cutoff.setDate(cutoff.getDate() - 7); + else cutoff.setMonth(cutoff.getMonth() - 1); + + const recentWhere = { + userId: user.id, + startTime: {[Op.gt]: cutoff}, + endTime: {[Op.not]: null}, + duration: {[Op.not]: null} + }; + if (shiftType !== 'All') recentWhere.type = shiftType; + + const recentShifts = await Shift.findAll({ where: recentWhere }); + const recentSeconds = recentShifts.reduce((sum, s) => sum + (parseInt(s.duration) || 0), 0); + const requiredSeconds = quota.hours * 3600; + const metQuota = recentSeconds >= requiredSeconds; + quotaText = localize('staff-management-system', 'duty-quota-str', { + timeframe, + duration: formatDuration(recentSeconds), + hours: quota.hours, + result: metQuota + ? localize('staff-management-system', 'quota-met') + : localize('staff-management-system', 'quota-fail') + }); + } + } + + const embed = applyFooter(client, new EmbedBuilder() + .setTitle(localize('staff-management-system', 'duty-time-title', { type: shiftType })) + .setColor('Blue') + .setThumbnail(user.displayAvatarURL({ dynamic: true })) + .setDescription(localize('staff-management-system', 'duty-time-desc', { + count: shiftCount, + duration: formatDuration(totalSeconds) + }) + breakdownText + quotaText) + ); + + const row = new ActionRowBuilder().addComponents( + new ButtonBuilder() + .setCustomId(`duty-mgmt_hist_${user.id}_1_${shiftType}`) + .setLabel(localize('staff-management-system', 'btn-hist')) + .setStyle(ButtonStyle.Secondary) + .setDisabled(shiftCount === 0) + ); + + return { + embeds: [embed.toJSON()], + components: [row.toJSON()] + }; +} + +async function buildLeaderboardPayload(client, page = 1, shiftType) { + const config = getConfig(client, 'shifts'); + const Shift = client.models['staff-management-system']['StaffShift']; + const limit = 15; + const offset = (page - 1) * limit; + + const whereClause = { + endTime: {[Op.not]: null}, + duration: {[Op.not]: null} + }; + if (shiftType !== 'All') whereClause.type = shiftType; + + const lookbackDate = getLookbackDate(config); + if (lookbackDate) whereClause.startTime = { [Op.gt]: lookbackDate }; + + const allResults = await Shift.findAll({ + attributes: [ + 'userId', + [fn('SUM', col('duration')), 'totalDuration'], + [fn('COUNT', col('id')), 'shiftCount'] + ], + where: whereClause, + group: ['userId'], + order: [[literal('totalDuration'), 'DESC']] + }); + + const total = allResults.length; + if (total === 0) return { + content: localize('staff-management-system', 'err-no-lb', { + type: shiftType + }) + }; + + const totalPages = Math.ceil(total / limit) || 1; + const paginated = allResults.slice(offset, offset + limit); + + const lines = []; + for (let i = 0; i < paginated.length; i++) { + const entry = paginated[i]; + const dur = formatDuration(parseInt(entry.dataValues.totalDuration)); + lines.push(`${offset + i + 1}. **<@${entry.userId}>** â€ĸ ${dur}`); + } + + const lookbackLabel = config.leaderboardLookback || 'Weekly'; + const embed = applyFooter(client, new EmbedBuilder() + .setTitle(localize('staff-management-system', 'duty-lb-title', { + type: shiftType + })) + .setColor('Gold') + .setDescription(localize('staff-management-system', 'duty-lb-desc', { + lookback: lookbackLabel, + lines: lines.join('\n') + })) + ); + + embed.addFields({ + name: '\u200b', + value: localize('staff-management-system', 'page-count', { + page, + total: totalPages + }) + }); + + const row = buildPaginationRow( + `duty-mgmt_lb_${page - 1}_${shiftType}`, + 'duty_lb_count', + `duty-mgmt_lb_${page + 1}_${shiftType}`, + page, + totalPages, + 'back', + 'next' + ); + + return { + embeds: [embed.toJSON()], + components: [row.toJSON()] + }; +} + +async function buildShiftHistoryPayload(client, userId, page = 1, shiftType) { + const Shift = client.models['staff-management-system']['StaffShift']; + const limit = 10; + const offset = (page - 1) * limit; + + const whereClause = { + userId, + endTime: {[Op.not]: null}, + duration: {[Op.not]: null} + }; + if (shiftType !== 'All') whereClause.type = shiftType; + + const { count, rows } = await Shift.findAndCountAll({ + where: whereClause, + order: [['startTime', 'DESC']], + limit, + offset + }); + + if (count === 0) return { content: localize('staff-management-system', 'info-no-sh-hi') }; + const totalPages = Math.ceil(count / limit) || 1; + + const lines = rows.map((shift, i) => { + const dur = formatDuration(shift.duration); + const startTs = Math.floor(new Date(shift.startTime).getTime() / 1000); + const endTs = Math.floor(new Date(shift.endTime).getTime() / 1000); + const typeBadge = shiftType === 'All' ? ` \`[${shift.type || 'Staff'}]\`` : ''; + + return `**${offset + i + 1}. ${dur}${typeBadge}:**\nStart: | End: `; + }); + + const embed = applyFooter(client, new EmbedBuilder() + .setTitle(localize('staff-management-system', 'duty-hi-title', { + type: shiftType + })) + .setColor('Blue') + .setDescription(lines.join('\n\n')) + ); + + embed.addFields({ + name: '\u200b', + value: localize('staff-management-system', 'page-count', { + page, + total: totalPages + }) + }); + + const row = buildPaginationRow( + `duty-mgmt_hist_${userId}_${page - 1}_${shiftType}`, + 'duty_hist_count', + `duty-mgmt_hist_${userId}_${page + 1}_${shiftType}`, + page, + totalPages + ); + + return { + embeds: [embed.toJSON()], + components: [row.toJSON()] + }; +} + +async function buildDutyAdminPayload(client, targetMember, requestingMember) { + const Profile = client.models['staff-management-system']['StaffProfile']; + const Shift = client.models['staff-management-system']['StaffShift']; + + const targetUser = targetMember.user; + const profile = await Profile.findByPk(targetUser.id); + + const onDuty = profile?.onDuty || false; + const onBreak = profile?.onBreak || false; + + let statusText, statusColor; + if (onDuty && onBreak) { + statusText = localize('staff-management-system', 'stat-brk'); + statusColor = 'Yellow'; + } else if (onDuty) { + statusText = localize('staff-management-system', 'stat-on'); + statusColor = 'Green'; + } else { + statusText = localize('staff-management-system', 'stat-off'); + statusColor = 'Red'; + } + + const completedShifts = await Shift.findAll({ + where: { + userId: targetUser.id, + endTime: {[Op.not]: null}, + duration: {[Op.not]: null} + } + }); + const totalShifts = completedShifts.length; + const totalSeconds = completedShifts.reduce((sum, s) => sum + (parseInt(s.duration) || 0), 0); + const avgSeconds = totalShifts > 0 + ? Math.floor(totalSeconds / totalShifts) + : 0; + + const embed = applyFooter(client, new EmbedBuilder() + .setTitle(localize('staff-management-system', 'duty-adm-title', { + user: targetUser.username + })) + .setColor(statusColor) + .setThumbnail(targetUser.displayAvatarURL({ dynamic: true })) + .setDescription(`**${statusText}**`) + .addFields( + { + name: localize('staff-management-system', 'duty-stats'), + value: localize('staff-management-system', 'duty-stat-desc', { + duration: formatDuration(totalSeconds), + count: totalShifts, + average: formatDuration(avgSeconds) + }) + } + ) + ); + + const generalConfig = client.configurations['staff-management-system']['configuration']; + const isManagement = requestingMember.roles.cache.some(r => (generalConfig.managementRoles || []).includes(r.id)) || requestingMember.permissions.has('Administrator'); + + const row = new ActionRowBuilder().addComponents( + new ButtonBuilder() + .setCustomId(`duty-mgmt_admin-forceend_${targetUser.id}`) + .setLabel(localize('staff-management-system', 'btn-f-off')) + .setEmoji('🔴') + .setStyle(ButtonStyle.Danger) + .setDisabled(!onDuty), + new ButtonBuilder() + .setCustomId(`duty-mgmt_admin-voidactive_${targetUser.id}`) + .setLabel(localize('staff-management-system', 'btn-v-act')) + .setEmoji('đŸ—‘ī¸') + .setStyle(ButtonStyle.Danger) + .setDisabled(!onDuty), + new ButtonBuilder() + .setCustomId(`duty-mgmt_admin-addtime_${targetUser.id}`) + .setLabel(localize('staff-management-system', 'btn-add-t')) + .setEmoji('âąī¸') + .setStyle(ButtonStyle.Success), + new ButtonBuilder() + .setCustomId(`duty-mgmt_admin-voidall_${targetUser.id}`) + .setLabel(localize('staff-management-system', 'btn-v-all')) + .setEmoji('âš ī¸') + .setStyle(ButtonStyle.Danger) + .setDisabled(!isManagement) + ); + + return { + embeds: [embed.toJSON()], + components: [row.toJSON()] + }; +} + +// ----- Button handlers ----- +async function handleDutyStartButton(client, interaction) { + const parts = interaction.customId.split('_'); + const userId = parts[2]; + const shiftType = parts[3] || 'Staff'; + + if (interaction.user.id !== userId) return interaction.editReply({ + content: localize('staff-management-system', 'err-not-yours'), + flags: MessageFlags.Ephemeral + }); + + const config = getConfig(client, 'shifts'); + const Profile = client.models['staff-management-system']['StaffProfile']; + const Shift = client.models['staff-management-system']['StaffShift']; + + const profile = await Profile.findByPk(userId); + if (profile?.onDuty) return interaction.followUp({ + content: localize('staff-management-system', 'err-alr-on'), + flags: MessageFlags.Ephemeral + }); + + const startTime = new Date(); + await Shift.create({ + userId, + startTime, + type: shiftType + }); + await Profile.upsert({ + userId, + onDuty: true, + onBreak: false, + lastClockIn: startTime + }); + + if (config.onDutyRole) { + const member = await interaction.guild.members.fetch(userId).catch(() => null); + if (member) await member.roles.add(config.onDutyRole).catch(() => {}); + } + + await logShiftChange(client, 'start', { + userId, + targetUser: interaction.user, + shiftType, + startTime + }); + + const payload = await buildDutyManagePayload(client, userId, shiftType); + return interaction.editReply(payload); +} + +async function handleDutyBreakButton(client, interaction) { + const userId = interaction.customId.split('_')[2]; + if (interaction.user.id !== userId) return interaction.editReply({ + content: localize('staff-management-system', 'err-not-yours'), + flags: MessageFlags.Ephemeral + }); + + const Profile = client.models['staff-management-system']['StaffProfile']; + const Shift = client.models['staff-management-system']['StaffShift']; + const profile = await Profile.findByPk(userId); + + if (!profile?.onDuty) return interaction.followUp({ + content: localize('staff-management-system', 'err-not-on'), + flags: MessageFlags.Ephemeral + }); + + const activeShift = await Shift.findOne({ + where: {userId, endTime: null} + }); + const shiftType = activeShift?.type || 'Staff'; + + const nowOnBreak = !profile.onBreak; + let breakCount = activeShift?.breakCount || 0; + if (nowOnBreak && activeShift) { + breakCount = breakCount + 1; + await activeShift.update({ + breakCount + }); + } + if (!nowOnBreak && profile.breakStartTime && activeShift) { + await applyBreakElapsedToShift(activeShift, profile.breakStartTime); + } + + const elapsedSeconds = activeShift + ? Math.max( + 0, + Math.floor( + ((nowOnBreak ? new Date() : new Date(profile.breakStartTime || Date.now())).getTime() - + new Date(activeShift.startTime).getTime()) / 1000 + ) + ) + : 0; + + const breakStartTime = nowOnBreak ? new Date() : null; + await Profile.update({ + onBreak: nowOnBreak, + breakStartTime + }, { + where: {userId} + }); + + if (activeShift) { + if (nowOnBreak) { + await logShiftChange(client, 'break', { + userId, + targetUser: interaction.user, + shiftType, + startTime: activeShift.startTime, + breakCount: activeShift.breakCount || 0, + elapsedSeconds + }); + } else { + await logShiftChange(client, 'resume', { + userId, + targetUser: interaction.user, + shiftType, + startTime: activeShift.startTime, + breakCount: activeShift.breakCount || 0, + elapsedSeconds + }); + } + } + + const payload = await buildDutyManagePayload(client, userId, shiftType); + return interaction.editReply(payload); +} + +async function handleDutyEndButton(client, interaction) { + const userId = interaction.customId.split('_')[2]; + if (interaction.user.id !== userId) return interaction.editReply({ + content: localize('staff-management-system', 'err-not-yours'), + flags: MessageFlags.Ephemeral + }); + + const config = getConfig(client, 'shifts'); + const Profile = client.models['staff-management-system']['StaffProfile']; + const Shift = client.models['staff-management-system']['StaffShift']; + + const profile = await Profile.findByPk(userId); + if (!profile?.onDuty) return interaction.followUp({ + content: localize('staff-management-system', 'err-not-on'), + flags: MessageFlags.Ephemeral + }); + + const activeShifts = await Shift.findAll({ where: { userId, endTime: null } }); + const shiftType = activeShifts.length > 0 ? activeShifts[0].type : 'Staff'; + let discardedForMinimum = false; + let endedShiftForDisplay = null; + + for (const activeShift of activeShifts) { + if (profile.onBreak && profile.breakStartTime) { + await applyBreakElapsedToShift(activeShift, profile.breakStartTime); + } + + const endTime = new Date(); + const durationSeconds = Math.floor( + (endTime.getTime() - new Date(activeShift.startTime).getTime()) / 1000 + ); + + if (config.minShiftDuration && (durationSeconds / 60) < config.minShiftDuration) { + await activeShift.destroy(); + discardedForMinimum = true; + } else { + await activeShift.update({ + endTime, + duration: durationSeconds + }); + endedShiftForDisplay = activeShift; + } + } + + await Profile.update({ + onDuty: false, + onBreak: false, + breakStartTime: null + }, { + where: {userId} + }); + + const member = await interaction.guild.members.fetch(userId).catch(() => null); + if (config.onDutyRole && member) { + await member.roles.remove(config.onDutyRole).catch(() => { + }); + } + if (member && endedShiftForDisplay) { + await sendShiftEndDm(client, member, endedShiftForDisplay); + } + + if (endedShiftForDisplay) { + await logShiftChange(client, 'end', { + userId, + targetUser: interaction.user, + shiftType: endedShiftForDisplay.type || shiftType, + startTime: endedShiftForDisplay.startTime, + endTime: endedShiftForDisplay.endTime, + breakCount: endedShiftForDisplay.breakCount || 0, + durationSeconds: parseInt(endedShiftForDisplay.duration) || 0 + }); + } + + const payload = await buildDutyManagePayload(client, userId, shiftType, endedShiftForDisplay); + await interaction.editReply(payload); + + if (discardedForMinimum) { + await interaction.followUp({ + content: localize('staff-management-system', 'err-shift-too-short', { + min: config.minShiftDuration + }), + flags: MessageFlags.Ephemeral + }); + } + return; +} + +async function handleDutyHistPageButton(client, interaction) { + const parts = interaction.customId.split('_'); + const userId = parts[2]; + const page = parseInt(parts[3]); + const shiftType = parts[4] || 'Staff'; + + if (interaction.user.id !== userId) return interaction.followUp({ + content: localize('staff-management-system', 'err-hist-oth'), + flags: MessageFlags.Ephemeral + }); + + const payload = await buildShiftHistoryPayload(client, userId, page, shiftType); + if (payload.content) return interaction.followUp({ + ...payload, + flags: MessageFlags.Ephemeral + }); + + const isOnHistEmbed = interaction.message?.embeds?.[0]?.title?.startsWith(localize('staff-management-system', 'duty-hi-title', { type: '' }).replace(' - ', '')); + if (isOnHistEmbed) { + return interaction.editReply(payload); + } else { + return interaction.followUp({ + ...payload, + flags: MessageFlags.Ephemeral + }); + } +} + +async function handleDutyLbPageButton(client, interaction) { + const parts = interaction.customId.split('_'); + const page = parseInt(parts[2]); + const shiftType = parts[3] || 'Staff'; + + const payload = await buildLeaderboardPayload(client, page, shiftType); + if (payload.content) return interaction.editReply({ ...payload, flags: MessageFlags.Ephemeral }); + return interaction.editReply(payload); +} + +// ----- Admin handler ----- +async function handleDutyAdminForceEnd(client, interaction) { + const permCheck = checkDutyAdminPermission(client, interaction); + if (permCheck) return permCheck; + + const targetUserId = interaction.customId.split('_')[2]; + const config = getConfig(client, 'shifts'); + const Profile = client.models['staff-management-system']['StaffProfile']; + const Shift = client.models['staff-management-system']['StaffShift']; + const profile = await Profile.findByPk(targetUserId); + let endedShiftForDisplay = null; + + const activeShifts = await Shift.findAll({ + where: {userId: targetUserId, endTime: null} + }); + for (const activeShift of activeShifts) { + if (profile?.onBreak && profile.breakStartTime) { + await applyBreakElapsedToShift(activeShift, profile.breakStartTime); + } + + const endTime = new Date(); + const durationSeconds = Math.floor( + (endTime.getTime() - new Date(activeShift.startTime).getTime()) / 1000 + ); + + await activeShift.update({ + endTime, + duration: durationSeconds + }); + endedShiftForDisplay = activeShift; + } + + await Profile.update({ + onDuty: false, + onBreak: false, + breakStartTime: null + }, { + where: {userId: targetUserId} + }); + if (config.onDutyRole) { + const member = await interaction.guild.members.fetch(targetUserId).catch(() => null); + if (member) await member.roles.remove(config.onDutyRole).catch(() => {}); + } + + if (endedShiftForDisplay) { + await logShiftChange(client, 'end', { + userId: targetUserId, + shiftType: endedShiftForDisplay.type || 'Staff', + startTime: endedShiftForDisplay.startTime, + endTime: endedShiftForDisplay.endTime, + breakCount: endedShiftForDisplay.breakCount || 0, + durationSeconds: parseInt(endedShiftForDisplay.duration) || 0, + executorId: interaction.user.id + }); + } + + const targetMember = await interaction.guild.members.fetch(targetUserId).catch(() => null); + if (!targetMember) { + return interaction.editReply({ + content: localize('staff-management-system', 'duty-admin-target-left'), + embeds: [], + components: [] + }); + } + + const payload = await buildDutyAdminPayload(client, targetMember, interaction.member); + return interaction.editReply(payload); +} + +async function handleDutyAdminVoidActive(client, interaction) { + const permCheck = checkDutyAdminPermission(client, interaction); + if (permCheck) return permCheck; + + const targetUserId = interaction.customId.split('_')[2]; + const config = getConfig(client, 'shifts'); + const Profile = client.models['staff-management-system']['StaffProfile']; + const Shift = client.models['staff-management-system']['StaffShift']; + + const activeShifts = await Shift.findAll({ + where: { + userId: targetUserId, + endTime: null + }, + order: [['startTime', 'DESC']] + }); + const shiftForLog = activeShifts.length > 0 + ? activeShifts[0] + : null; + for (const activeShift of activeShifts) await activeShift.destroy(); + + await Profile.update({ + onDuty: false, + onBreak: false, + breakStartTime: null + }, { + where: {userId: targetUserId} + }); + if (config.onDutyRole) { + const member = await interaction.guild.members.fetch(targetUserId).catch(() => null); + if (member) await member.roles.remove(config.onDutyRole).catch(() => {}); + } + + if (shiftForLog) { + await logShiftChange(client, 'void', { + userId: targetUserId, + shiftType: shiftForLog.type || 'Staff', + startTime: shiftForLog.startTime, + breakCount: shiftForLog.breakCount || 0, + executorId: interaction.user.id + }); + } + + const targetMember = await interaction.guild.members.fetch(targetUserId).catch(() => null); + if (!targetMember) { + return interaction.editReply({ + content: localize('staff-management-system', 'duty-admin-target-left'), + embeds: [], + components: [] + }); + } + + const payload = await buildDutyAdminPayload(client, targetMember, interaction.member); + return interaction.editReply(payload); +} + +async function handleDutyAdminVoidAll(client, interaction) { + const permCheck = checkDutyAdminPermission(client, interaction); + if (permCheck) return permCheck; + + let confirmPhrase = localize('staff-management-system', 'del-conf-phrase'); + if (confirmPhrase.length > 100) { + confirmPhrase = localize('staff-management-system', 'fallback-conf-phrase'); + } + let delModalLabel = localize('staff-management-system', 'mod-del-lbl'); + if (delModalLabel.length > 45) { + delModalLabel = localize('staff-management-system', 'fallback-del-lbl'); + } + + const targetUserId = interaction.customId.split('_')[2]; + const modal = new ModalBuilder() + .setCustomId(`duty-mgmt_admin-voidall-submit_${targetUserId}`) + .setTitle(localize('staff-management-system', 'mod-v-all-title')); + + modal.addComponents( + new ActionRowBuilder().addComponents( + new TextInputBuilder() + .setCustomId('confirm') + .setLabel(delModalLabel) + .setStyle(TextInputStyle.Paragraph) + .setPlaceholder(confirmPhrase) + .setRequired(true) + ) + ); + return interaction.showModal(modal); +} + +async function handleDutyAdminVoidAllSubmit(client, interaction) { + const permCheck = checkDutyAdminPermission(client, interaction); + if (permCheck) return permCheck; + + const targetUserId = interaction.customId.split('_')[2]; + let confirmPhrase = localize('staff-management-system', 'del-conf-phrase'); + if (confirmPhrase.length > 100) { + confirmPhrase = localize('staff-management-system', 'fallback-conf-phrase'); + } + + if (interaction.fields.getTextInputValue('confirm').trim() !== confirmPhrase) { + return interaction.reply({ + content: localize('staff-management-system', 'err-conf-fail'), + flags: MessageFlags.Ephemeral + }); + } + + const config = getConfig(client, 'shifts'); + const Profile = client.models['staff-management-system']['StaffProfile']; + const Shift = client.models['staff-management-system']['StaffShift']; + + await Shift.destroy({ + where: {userId: targetUserId} + }); + await Profile.update({ + onDuty: false, + onBreak: false, + breakStartTime: null + }, { + where: {userId: targetUserId} + }); + + if (config.onDutyRole) { + const member = await interaction.guild.members.fetch(targetUserId).catch(() => null); + if (member) await member.roles.remove(config.onDutyRole).catch(() => {}); + } + + client.logger.info(localize('staff-management-system', 'log-void-all', { + target: targetUserId, + admin: interaction.user.id + })); + + return interaction.reply({ + content: localize('staff-management-system', 'succ-v-all', {user: targetUserId}), + flags: MessageFlags.Ephemeral + }); +} + +async function handleDutyAdminAddTimeButton(client, interaction) { + const permCheck = checkDutyAdminPermission(client, interaction); + if (permCheck) return permCheck; + + const targetUserId = interaction.customId.split('_')[2]; + const config = getConfig(client, 'shifts'); + const dutyTypes = config.dutyTypes && config.dutyTypes.length > 0 + ? config.dutyTypes + : ['Staff']; + + const modal = new ModalBuilder() + .setCustomId(`duty-mgmt_admin-addtime-submit_${targetUserId}`) + .setTitle(localize('staff-management-system', 'mod-add-t')); + modal.addComponents( + new ActionRowBuilder() + .addComponents( + new TextInputBuilder() + .setCustomId('minutes') + .setLabel(localize('staff-management-system', 'mod-add-min')) + .setStyle(TextInputStyle.Short) + .setPlaceholder('e.g. 60') + .setRequired(true) + ), + new ActionRowBuilder() + .addComponents( + new TextInputBuilder() + .setCustomId('type') + .setLabel(localize('staff-management-system', 'mod-add-type')) + .setStyle(TextInputStyle.Short) + .setPlaceholder(dutyTypes.join(', ')) + .setValue(dutyTypes[0]) + .setRequired(true) + ) + ); + return interaction.showModal(modal); +} + +async function handleDutyAdminAddTimeSubmit(client, interaction) { + const permCheck = checkDutyAdminPermission(client, interaction); + if (permCheck) return permCheck; + + const targetUserId = interaction.customId.split('_')[2]; + const minutesRaw = interaction.fields.getTextInputValue('minutes'); + const shiftType = interaction.fields.getTextInputValue('type'); + + const maxMinutes = 10080; + const minutes = parseInt(minutesRaw, 10); + + if (isNaN(minutes) || minutes <= 0 || minutes > maxMinutes) { + return interaction.reply({ + content: localize('staff-management-system', 'err-inv-min'), + flags: MessageFlags.Ephemeral + }); + } + + const config = getConfig(client, 'shifts'); + const dutyTypes = config.dutyTypes && config.dutyTypes.length > 0 + ? config.dutyTypes + : ['Staff']; + + if (!dutyTypes.includes(shiftType)) { + return interaction.reply({ + content: localize('staff-management-system', 'err-inv-type', { + types: dutyTypes.join(', ') + }), + flags: MessageFlags.Ephemeral + }); + } + + const Shift = client.models['staff-management-system']['StaffShift']; + + const durationSeconds = minutes * 60; + const endTime = new Date(); + const startTime = new Date(endTime.getTime() - (durationSeconds * 1000)); + + await Shift.create({ + userId: targetUserId, + startTime: startTime, + endTime: endTime, + duration: durationSeconds, + type: shiftType + }); + + client.logger.info(localize('staff-management-system', 'log-add-time', { + admin: interaction.user.tag, + min: minutes, + type: shiftType, + target: targetUserId + })); + + const targetMember = await interaction.guild.members.fetch(targetUserId).catch(() => null); + if (!targetMember) { + return interaction.reply({ + content: localize('staff-management-system', 'duty-admin-target-left'), + flags: MessageFlags.Ephemeral + }); + } + + const payload = await buildDutyAdminPayload(client, targetMember, interaction.member); + return interaction.reply({ + ...payload, + flags: MessageFlags.Ephemeral + }); +} + +// ----- Dropdown handler ----- +async function handleDutyDropdown(client, interaction, action, selectedType) { + if (action === 'manage') { + const payload = await buildDutyManagePayload(client, interaction.user.id, selectedType); + return interaction.editReply({ content: '', ...payload }); + } + if (action === 'leaderboard') { + const payload = await buildLeaderboardPayload(client, 1, selectedType); + return interaction.editReply({ content: '', ...payload }); + } + if (action === 'time') { + const payload = await buildDutyTimePayload(client, interaction, selectedType); + return interaction.editReply({ content: '', ...payload }); + } +} + +async function handleCommonDutyCommand(i, action) { + const config = getConfig(i.client, 'shifts'); + if (!config || !config.enableShifts) return i.editReply({ content: localize('staff-management-system', 'err-sh-dis') }); + + const dutyTypes = config.dutyTypes && config.dutyTypes.length > 0 ? config.dutyTypes : ['Staff']; + let shiftType = i.options.getString('type'); + + const allowedTypes = (action === 'leaderboard' || action === 'time') ? ['All', ...dutyTypes] : dutyTypes; + + if (action === 'manage') { + const Profile = i.client.models['staff-management-system']['StaffProfile']; + const Shift = i.client.models['staff-management-system']['StaffShift']; + const profile = await Profile.findByPk(i.user.id); + if (profile?.onDuty) { + const activeShift = await Shift.findOne({ where: { userId: i.user.id, endTime: null } }); + shiftType = activeShift?.type || dutyTypes[0]; + } + } + + if (!shiftType) { + if (dutyTypes.length === 1 && action === 'manage') { + shiftType = dutyTypes[0]; + } else if (dutyTypes.length === 1 && (action === 'leaderboard' || action === 'time')) { + shiftType = 'All'; + } else { + const selectMenu = new StringSelectMenuBuilder() + .setCustomId(`duty-mgmt_dropdown_${action}`) + .setPlaceholder(localize('staff-management-system', 'ph-sel-type')); + + allowedTypes.forEach(t => selectMenu.addOptions({ label: t, value: t })); + const row = new ActionRowBuilder().addComponents(selectMenu); + return i.editReply({ content: localize('staff-management-system', 'msg-sel-type'), components: [row.toJSON()] }); + } + } else if (!allowedTypes.includes(shiftType)) { + return i.editReply({ content: localize('staff-management-system', 'err-inv-type', { types: allowedTypes.join(', ') }) }); + } + + if (action === 'manage') { + const payload = await buildDutyManagePayload(i.client, i.user.id, shiftType); + await i.editReply(payload); + } else if (action === 'leaderboard') { + const payload = await buildLeaderboardPayload(i.client, 1, shiftType); + await i.editReply(payload); + } else if (action === 'time') { + const payload = await buildDutyTimePayload(i.client, i, shiftType); + await i.editReply(payload); + } +} + + +async function buildActiveShiftsPayload(client) { + const config = getConfig(client, 'shifts'); + if (!config || !config.enableShifts) return { content: localize('staff-management-system', 'err-sh-dis') }; + + const Shift = client.models['staff-management-system']['StaffShift']; + const Profile = client.models['staff-management-system']['StaffProfile']; + const activeShifts = await Shift.findAll({ + where: { endTime: null }, + order: [['startTime', 'ASC']] + }); + + if (activeShifts.length === 0) return { content: localize('staff-management-system', 'info-no-act-sh') }; + + const profiles = await Profile.findAll({ + where: { + userId: activeShifts.map(shift => shift.userId) + } + }); + const profileMap = new Map(profiles.map(profile => [profile.userId, profile])); + + const dutyTypes = config.dutyTypes && config.dutyTypes.length > 0 + ? config.dutyTypes + : ['Staff']; + + const grouped = {}; + for (const shift of activeShifts) { + const type = shift.type || dutyTypes[0]; + if (!grouped[type]) grouped[type] = []; + grouped[type].push(shift); + } + + const embed = applyFooter(client, new EmbedBuilder() + .setTitle(localize('staff-management-system', 'duty-act-title')) + .setColor('Green') + .setDescription(localize('staff-management-system', 'duty-act-desc', { + count: activeShifts.length + })) + ); + + let index = 1; + for (const type of dutyTypes) { + if (grouped[type]) { + const lines = []; + for (const shift of grouped[type]) { + const profile = profileMap.get(shift.userId); + const isOnBreak = profile?.onBreak && profile?.breakStartTime; + + let elapsed; + if (isOnBreak) { + elapsed = Math.floor( + (new Date(profile.breakStartTime).getTime() - new Date(shift.startTime).getTime()) / 1000 + ); + } else { + elapsed = Math.floor( + (Date.now() - new Date(shift.startTime).getTime()) / 1000 + ); + } + + const breakSuffix = isOnBreak + ? ` (${localize('staff-management-system', 'stat-brk')})` + : ''; + + lines.push(`${index}. **<@${shift.userId}>** â€ĸ ${formatDuration(elapsed)}${breakSuffix}`); + index++; + } + embed.addFields({ + name: `${type} (${grouped[type].length})`, + value: lines.join('\n') + }); + delete grouped[type]; + } + } + for (const [type, shifts] of Object.entries(grouped)) { + const lines = []; + for (const shift of shifts) { + const profile = profileMap.get(shift.userId); + const isOnBreak = profile?.onBreak && profile?.breakStartTime; + + let elapsed; + if (isOnBreak) { + elapsed = Math.floor( + (new Date(profile.breakStartTime).getTime() - new Date(shift.startTime).getTime()) / 1000 + ); + } else { + elapsed = Math.floor( + (Date.now() - new Date(shift.startTime).getTime()) / 1000 + ); + } + + const breakSuffix = isOnBreak + ? ` (${localize('staff-management-system', 'stat-brk')})` + : ''; + + lines.push(`${index}. **<@${shift.userId}>** â€ĸ ${formatDuration(elapsed)}${breakSuffix}`); + index++; + } + + embed.addFields({ + name: `${type} (${shifts.length}) [Legacy]`, + value: lines.join('\n') + }); + } + + return { + embeds: [embed.toJSON()] + }; +} + + +const buttonHandlers = { + handleDutyStartButton, + handleDutyAdminAddTimeButton, + handleDutyBreakButton, + handleDutyEndButton, + handleDutyDropdown, + handleDutyHistPageButton, + handleDutyLbPageButton, + handleDutyAdminForceEnd, + handleDutyAdminVoidActive, + handleDutyAdminVoidAll, + handleDutyAdminVoidAllSubmit, + handleDutyAdminAddTimeSubmit +}; + +const _test = { + getLookbackDate, + canUseDutyAdmin, + applyBreakElapsedToShift, + getQuotaForMember +}; + +module.exports = { + getLookbackDate, + canUseDutyAdmin, + checkDutyAdminPermission, + applyBreakElapsedToShift, + getQuotaForMember, + sendShiftEndDm, + logShiftChange, + buildDutyManagePayload, + buildDutyTimePayload, + buildLeaderboardPayload, + buildShiftHistoryPayload, + buildActiveShiftsPayload, + buildDutyAdminPayload, + handleDutyStartButton, + handleDutyBreakButton, + handleDutyEndButton, + handleDutyHistPageButton, + handleDutyLbPageButton, + handleDutyAdminForceEnd, + handleDutyAdminVoidActive, + handleDutyAdminVoidAll, + handleDutyAdminVoidAllSubmit, + handleDutyAdminAddTimeButton, + handleDutyAdminAddTimeSubmit, + handleDutyDropdown, + handleCommonDutyCommand, + buttonHandlers, + _test +}; diff --git a/modules/staff-management-system/core/index.js b/modules/staff-management-system/core/index.js new file mode 100644 index 00000000..91bf0a81 --- /dev/null +++ b/modules/staff-management-system/core/index.js @@ -0,0 +1,17 @@ +/** + * Main core export for the Staff Management module + * @module staff-management-system + * @author itskevinnn + */ + +module.exports = { + ...require('./localHelpers'), + ...require('./infractions'), + ...require('./promotions'), + ...require('./panels'), + ...require('./activityChecks'), + ...require('./reviews'), + ...require('./duty'), + ...require('./staffStatus'), + ...require('./profiles') +}; diff --git a/modules/staff-management-system/core/infractions.js b/modules/staff-management-system/core/infractions.js new file mode 100644 index 00000000..ee1030c3 --- /dev/null +++ b/modules/staff-management-system/core/infractions.js @@ -0,0 +1,415 @@ +/** + * Infractions and suspensions logic for the Staff Management module + * @module staff-management-system + * @author itskevinnn + */ + +const { EmbedBuilder, MessageFlags } = require('discord.js'); +const { embedTypeV2, dateToDiscordTimestamp } = require('../../../src/functions/helpers'); +const { localize } = require('../../../src/functions/localize'); +const { + getConfig, + getSafeChannelId, + parseDurationToDays, + applyFooter, + checkStaffPermissions, + buildPaginationRow +} = require('./localHelpers'); + +// ---------- Infractions ---------- +async function issueInfraction(client, interaction, targetMember, type, reason, expiryInput) { + await interaction.deferReply({ephemeral: true}); + const config = getConfig(client, 'infractions'); + if (!config?.enableInfractions) return interaction.editReply({ + content: localize('staff-management-system', 'err-feat-disabled', {feature: 'Infractions'}) + }); + + const generalConfig = getConfig(client, 'configuration'); + const canInfract = checkStaffPermissions(interaction.member, generalConfig, 'supervisor'); + if (!canInfract) return interaction.editReply({ + content: localize('staff-management-system', 'err-gen-no-perm') + }); + + if (targetMember.id === interaction.user.id) { + return interaction.editReply({ + content: localize('staff-management-system', 'err-self-infract') + }); + } + + if (type.toLowerCase() === 'suspension') { + return interaction.editReply({ + content: localize('staff-management-system', 'err-use-susp') + }); + } + + let expiresAt = null; + if (expiryInput) { + const days = parseDurationToDays(expiryInput); + if (!days) return interaction.editReply({ + content: localize('staff-management-system', 'err-inv-dur') + }); + expiresAt = new Date(Date.now() + days * 24 * 60 * 60 * 1000); + } + + const record = await client.models['staff-management-system']['Infraction'].create({ + userId: targetMember.id, + issuerId: interaction.user.id, + type, reason, expiresAt, + active: true + }); + + const placeholders = { + '%user%': targetMember.user.toString(), + '%user-avatar%': targetMember.user.displayAvatarURL({ + dynamic: true, + format: 'png', + size: 1024 + }) || '', + '%issuer-mention%': interaction.user.toString(), + '%issuer-name%': interaction.user.username, + '%issuer-avatar%': interaction.user.displayAvatarURL({ + dynamic: true, + format: 'png', + size: 1024 + }) || '', + '%type%': type, + '%reason%': reason, + '%case-id%': record.caseId.toString(), + '%end-date%': expiresAt + ? dateToDiscordTimestamp(expiresAt, 'F') + : localize('staff-management-system', 'label-never') + }; + + const channelId = getSafeChannelId(config.infractionLogChannel); + if (channelId) { + const channel = await interaction.guild.channels.fetch(channelId).catch(() => null); + if (channel) { + const template = config.infractionMessage; + + if (template && template.embeds && !template._schema) template._schema = 'v3'; + const msgOpts = await embedTypeV2(template, placeholders); + if (msgOpts?.content?.trim() === '') delete msgOpts.content; + + if (msgOpts?.embeds?.length > 0) { + const parsedEmbed = EmbedBuilder.from(msgOpts.embeds[0]); + applyFooter(client, parsedEmbed); + msgOpts.embeds[0] = parsedEmbed.toJSON(); + } + + const sentMsg = await channel.send(msgOpts).catch(() => {}); + if (sentMsg) await record.update({ messageUrl: sentMsg.url }); + } + } + + if (config.dmInfractedUser && config.infractionDmMessage) { + const dmTemplate = config.infractionDmMessage; + if (dmTemplate && dmTemplate.embeds && !dmTemplate._schema) dmTemplate._schema = 'v3'; + const dmOpts = await embedTypeV2(dmTemplate, placeholders); + if (dmOpts?.content?.trim() === '') delete dmOpts.content; + + if (dmOpts) { + try { + await targetMember.user.send(dmOpts); + } catch (e) { + client.logger.warn(localize('staff-management-system', 'log-infract-dm-fail', { + user: targetMember.user.tag, + error: e.message + })); + } + } + } + + await interaction.editReply({ + content: localize('staff-management-system', 'succ-infract', { + type, + caseId: record.caseId, + user: targetMember.user.tag + }) + }); +} + +// ---------- Suspensions ---------- +async function issueSuspension(client, interaction, targetMember, durationInput, reason) { + await interaction.deferReply({ephemeral: true}); + const config = getConfig(client, 'infractions'); + if (!config?.enableInfractions) return interaction.editReply({ + content: localize('staff-management-system', 'err-feat-disabled', { + feature: 'Infractions' + }) + }); + + if (!config?.enableSuspensions) return interaction.editReply({ + content: localize('staff-management-system', 'err-feat-disabled', { + feature: 'Suspensions' + }) + }); + + const generalConfig = getConfig(client, 'configuration'); + const canSuspend = checkStaffPermissions(interaction.member, generalConfig, 'supervisor'); + if (!canSuspend) return interaction.editReply({ + content: localize('staff-management-system', 'err-gen-no-perm') + }); + + if (targetMember.id === interaction.user.id) { + return interaction.editReply({ + content: localize('staff-management-system', 'err-self-infract') + }); + } + + const durationDays = parseDurationToDays(durationInput); + if (!durationDays) return interaction.editReply({ + content: localize('staff-management-system', 'err-inv-dur') + }); + + const expiresAt = new Date(Date.now() + durationDays * 24 * 60 * 60 * 1000); + const durationString = `${durationDays} ${localize('staff-management-system', 'label-days')}`; + + let rolesToRemove = []; + const hierarchyRole = interaction.guild.roles.cache.get(config.suspensionHierarchyRole); + if (hierarchyRole) { + rolesToRemove = targetMember.roles.cache + .filter(r => r.position >= hierarchyRole.position && r.id !== interaction.guild.id && !r.managed) + .map(r => r.id); + + if (rolesToRemove.length) { + await targetMember.roles.remove(rolesToRemove).catch(() => {}); + } + } + + await client.models['staff-management-system']['StaffProfile'].upsert({ + userId: targetMember.id, + isSuspended: true, + suspendedRoles: JSON.stringify(rolesToRemove) + }); + if (config.suspensionRole) await targetMember.roles.add(config.suspensionRole).catch(() => {}); + + const record = await client.models['staff-management-system']['Infraction'].create({ + userId: targetMember.id, + issuerId: interaction.user.id, + type: 'Suspension', + reason, durationDays, expiresAt, + active: true + }); + + const placeholders = { + '%user%': targetMember.user.toString(), + '%user-avatar%': targetMember.user.displayAvatarURL({ + dynamic: true, + format: 'png', + size: 1024 + }) || '', + '%issuer-mention%': interaction.user.toString(), + '%issuer-name%': interaction.user.username, + '%issuer-avatar%': interaction.user.displayAvatarURL({ + dynamic: true, + format: 'png', + size: 1024 + }) || '', + '%duration%': durationString, + '%reason%': reason, + '%case-id%': record.caseId.toString(), + '%end-date%': dateToDiscordTimestamp(expiresAt, 'F') + }; + + const channelId = getSafeChannelId(config.infractionLogChannel); + if (channelId) { + const channel = await interaction.guild.channels.fetch(channelId).catch(() => null); + if (channel) { + const template = config.suspensionMessage; + + if (template && template.embeds && !template._schema) template._schema = 'v3'; + const msgOpts = await embedTypeV2(template, placeholders); + if (msgOpts?.content?.trim() === '') delete msgOpts.content; + + if (msgOpts?.embeds?.length > 0) { + const parsedEmbed = EmbedBuilder.from(msgOpts.embeds[0]); + applyFooter(client, parsedEmbed); + msgOpts.embeds[0] = parsedEmbed.toJSON(); + } + + const sentMsg = await channel.send(msgOpts).catch(() => {}); + if (sentMsg) await record.update({ messageUrl: sentMsg.url }); + } + } + + if (config.dmInfractedUser && config.suspensionDmMessage) { + const dmTemplate = config.suspensionDmMessage; + + if (dmTemplate && dmTemplate.embeds && !dmTemplate._schema) dmTemplate._schema = 'v3'; + const dmOpts = await embedTypeV2(dmTemplate, placeholders); + if (dmOpts?.content?.trim() === '') delete dmOpts.content; + + if (dmOpts) { + try { + await targetMember.user.send(dmOpts); + } catch (e) { + client.logger.warn(localize('staff-management-system', 'log-susp-dm-fail', { + user: targetMember.user.tag, + error: e.message + })); + } + } + } + + await interaction.editReply({ + content: localize('staff-management-system', 'succ-susp', { + caseId: record.caseId, + user: targetMember.user.tag, + duration: durationString + }) + }); +} + +async function resolveInfractionReference(client, reference) { + const Infraction = client.models['staff-management-system']['Infraction']; + const value = reference?.trim(); + + if (!value) return null; + + if ((/^\d+$/).test(value)) { + return await Infraction.findByPk(parseInt(value, 10)); + } + + try { + const parsed = new URL(value); + const validHosts = ['discord.com', 'canary.discord.com', 'ptb.discord.com']; + + if (!validHosts.includes(parsed.hostname)) return null; + + const parts = parsed.pathname.split('/').filter(Boolean); + if (parts.length !== 4 || parts[0] !== 'channels') return null; + + return await Infraction.findOne({ + where: {messageUrl: value} + }); + } catch (e) { + return null; + } +} + +// ----- Infractions voiding ----- +async function voidInfraction(client, interaction, reference) { + await interaction.deferReply({ephemeral: true}); + const config = getConfig(client, 'infractions'); + if (!config?.enableInfractions) return interaction.editReply({ + content: localize('staff-management-system', 'err-feat-disabled', { + feature: 'Infractions' + }) + }); + + const canManage = checkStaffPermissions(interaction.member, getConfig(client, 'configuration'), 'supervisor'); + if (!canManage) return interaction.editReply({ + content: localize('staff-management-system', 'err-gen-no-perm') + }); + + const record = await resolveInfractionReference(client, reference); + if (!record) { + return interaction.editReply({ + content: localize('staff-management-system', 'err-no-case-ref', {reference}) + }); + } + if (!record.active) { + return interaction.editReply({ + content: localize('staff-management-system', 'err-case-inact', {caseId: record.caseId}) + }); + } + + if (record.type.toLowerCase() === 'suspension') { + const Profile = client.models['staff-management-system']['StaffProfile']; + const profile = await Profile.findOne({ + where: {userId: record.userId} + }); + const member = await interaction.guild.members.fetch(record.userId).catch(() => null); + + if (member && profile && profile.isSuspended) { + try { + const rolesToRestore = JSON.parse(profile.suspendedRoles || '[]'); + if (rolesToRestore.length > 0) await member.roles.add(rolesToRestore); + if (config.suspensionRole) await member.roles.remove(config.suspensionRole); + await profile.update({ isSuspended: false, suspendedRoles: JSON.stringify([]) }); + } catch (e) { + return interaction.editReply({ + content: localize('staff-management-system', 'succ-void-fail', {caseId: record.caseId}) + }); + } + } + } + await record.update({active: false}); + await interaction.editReply({ + content: localize('staff-management-system', 'succ-void', {caseId: record.caseId}) + }); +} + +// ----- Generates infractions history embed ----- +async function generateInfractionHistoryResponse(client, targetUser, page = 1) { + const limit = 5; + const offset = (page - 1) * limit; + const {count, rows} = await client.models['staff-management-system']['Infraction'].findAndCountAll({ + where: {userId: targetUser.id}, + order: [['createdAt', 'DESC']], + limit, offset + }); + + if (count === 0) return { + content: localize('staff-management-system', 'info-clean-rec', { + username: targetUser.username + }), + flags: MessageFlags.Ephemeral + }; + + const totalPages = Math.ceil(count / limit) || 1; + const embed = applyFooter(client, new EmbedBuilder() + .setTitle(localize('staff-management-system', 'rec-title', { username: targetUser.username })) + .setThumbnail(targetUser.displayAvatarURL({ dynamic: true })) + .setColor('Red') + ); + + const desc = rows.map(r => { + const link = r.messageUrl + ? ` â€ĸ [Jump](${r.messageUrl})` + : ''; + const statusIcon = r.active + ? '🔴' + : localize('staff-management-system', 'icon-voided'); + const expiry = r.expiresAt + ? `\n**${localize('staff-management-system', 'label-exp')}:** ${dateToDiscordTimestamp(r.expiresAt, 'R')}` + : ''; + + return `**${statusIcon} ${localize('staff-management-system', 'label-case')} #${r.caseId} - ${r.type}**\n**${localize('staff-management-system', 'label-date')}:** ${dateToDiscordTimestamp(r.createdAt, 'f')}\n**${localize('staff-management-system', 'label-iss')}:** <@${r.issuerId}>\n**${localize('staff-management-system', 'general-rsn')}:** ${r.reason}${expiry}${link}`; + }).join('\n\n'); + + embed.setDescription(desc); + embed.addFields({name: '\u200b', value: localize('staff-management-system', 'page-count', { + page, + total: totalPages + }) }); + + const row = buildPaginationRow( + `staff-mgmt_inf-hist_${targetUser.id}_${page - 1}`, + 'inf_hist_count', + `staff-mgmt_inf-hist_${targetUser.id}_${page + 1}`, + page, + totalPages + ); + + return { embeds: [embed.toJSON()], components: [row.toJSON()] }; +} + +// ----- Gets infraction history ----- +async function getInfractionHistory(client, interaction, targetUser) { + await interaction.deferReply({ephemeral: true}); + const response = await generateInfractionHistoryResponse(client, targetUser, 1); + if (response.content && response.content.startsWith('â„šī¸')) return interaction.editReply(response); + await interaction.editReply({ + ...response + }); +} + +module.exports = { + issueInfraction, + issueSuspension, + resolveInfractionReference, + voidInfraction, + generateInfractionHistoryResponse, + getInfractionHistory +}; diff --git a/modules/staff-management-system/core/localHelpers.js b/modules/staff-management-system/core/localHelpers.js new file mode 100644 index 00000000..a344fdbd --- /dev/null +++ b/modules/staff-management-system/core/localHelpers.js @@ -0,0 +1,138 @@ +/** + * Local utility helpers for the Staff Management module + * @module staff-management-system + * @author itskevinnn + */ + +const { + ActionRowBuilder, + ButtonBuilder, + ButtonStyle +} = require('discord.js'); +const { safeSetFooter } = require('../../../src/functions/helpers'); +const { localize } = require('../../../src/functions/localize'); + +const getConfig = (client, file) => client.configurations['staff-management-system'][file]; + +const getSafeChannelId = (val) => (Array.isArray(val) && val.length > 0 + ? val[0] + : (typeof val === 'string' + ? val + : null + )); + +const parseDurationToDays = (input) => { + if (!input) return null; + const match = input.toString().match(/^(\d+)([dDwWmM])?$/); + if (!match) return null; + const value = parseInt(match[1], 10); + const unit = match[2]?.toLowerCase() || 'd'; + return unit === 'm' + ? value * 30 + : (unit === 'w' + ? value * 7 + : value + ); +}; + +const applyFooter = (client, embed) => { + safeSetFooter(embed, client); + if (!(client.strings && client.strings.disableFooterTimestamp)) { + embed.setTimestamp(); + } + return embed; +}; + +const formatRoleMentions = (roles) => { + const roleIds = Array.isArray(roles) + ? roles + : (roles ? [roles] : []); + + return roleIds.map(roleId => `<@&${roleId}>`).join(' '); +}; + +function checkStaffPermissions(member, config, level = 'staff') { + if (!member) return false; + if (member.permissions?.has('Administrator')) return true; + + const roleMap = { + staff: [ + ...(config?.staffRoles || []), + ...(config?.supervisorRoles || []), + ...(config?.managementRoles || []) + ], + supervisor: [ + ...(config?.supervisorRoles || []), + ...(config?.managementRoles || []) + ], + management: [ + ...(config?.managementRoles || []) + ] + }; + + const allowedRoles = roleMap[level] || roleMap.staff; + return member.roles?.cache?.some(role => allowedRoles.includes(role.id)) || false; +} + +const buildPaginationRow = (backId, countId, nextId, page, totalPages) => { + return new ActionRowBuilder().addComponents( + new ButtonBuilder() + .setCustomId(backId) + .setLabel(localize('helpers', 'back')) + .setStyle(ButtonStyle.Primary) + .setDisabled(page <= 1), + new ButtonBuilder() + .setCustomId(countId) + .setLabel(`${page}/${totalPages}`) + .setStyle(ButtonStyle.Secondary) + .setDisabled(true), + new ButtonBuilder() + .setCustomId(nextId) + .setLabel(localize('helpers', 'next')) + .setStyle(ButtonStyle.Primary) + .setDisabled(page >= totalPages) + ); +}; + +function formatDuration(seconds) { + if (!seconds || seconds <= 0) return localize('staff-management-system', 'time-zero'); + const h = Math.floor(seconds / 3600); + const m = Math.floor((seconds % 3600) / 60); + const s = seconds % 60; + const parts = []; + if (h > 0) parts.push(`${h} ${localize('staff-management-system', h !== 1 + ? 'time-hours' + : 'time-hour' + )}`); + if (m > 0) parts.push(`${m} ${localize('staff-management-system', m !== 1 + ? 'time-mins' + : 'time-min' + )}`); + if (s > 0) parts.push(`${s} ${localize('staff-management-system', s !== 1 + ? 'time-secs' + : 'time-sec' + )}`); + return parts.join(', ') || localize('staff-management-system', 'time-zero'); +} + +function getIsoWeekNumber(date = new Date()) { + const tmp = new Date(Date.UTC(date.getFullYear(), date.getMonth(), date.getDate())); + const day = tmp.getUTCDay() || 7; + + tmp.setUTCDate(tmp.getUTCDate() + 4 - day); + + const yearStart = new Date(Date.UTC(tmp.getUTCFullYear(), 0, 1)); + return Math.ceil((((tmp - yearStart) / 86400000) + 1) / 7); +} + +module.exports = { + getConfig, + getSafeChannelId, + parseDurationToDays, + applyFooter, + formatRoleMentions, + checkStaffPermissions, + buildPaginationRow, + formatDuration, + getIsoWeekNumber +}; diff --git a/modules/staff-management-system/core/panels.js b/modules/staff-management-system/core/panels.js new file mode 100644 index 00000000..46c5006d --- /dev/null +++ b/modules/staff-management-system/core/panels.js @@ -0,0 +1,690 @@ +/** + * User panel and related subpages logic for the Staff Management module + * @module staff-management-system + * @author itskevinnn + */ + +const { + EmbedBuilder, + StringSelectMenuBuilder, + StringSelectMenuOptionBuilder, + ActionRowBuilder, + ButtonBuilder, + ButtonStyle +} = require('discord.js'); +const { Op } = require('sequelize'); +const { dateToDiscordTimestamp } = require('../../../src/functions/helpers'); +const { localize } = require('../../../src/functions/localize'); +const { + getConfig, + applyFooter, + buildPaginationRow, + formatDuration +} = require('./localHelpers'); + +// ---------- User Panel ---------- +async function generatePanelSubpage(client, targetUser, type, page) { + if (type === 'infractions') return await generatePanelInfractions(client, targetUser, page); + if (type === 'promotions') return await generatePanelPromotions(client, targetUser, page); + if (type === 'reviews') return await generatePanelReviews(client, targetUser, page); + if (type === 'status') return await generatePanelStatus(client, targetUser, page); + if (type === 'activity') return await generatePanelActivity(client, targetUser, page); + return null; +} + +// Overview page +async function generateUserPanel(client, targetUser) { + const embed = applyFooter(client, new EmbedBuilder() + .setTitle(localize('staff-management-system', 'panel-title', { + username: targetUser.username + })) + .setDescription(localize('staff-management-system', 'panel-desc', { + mention: targetUser.toString(), + id: targetUser.id + })) + .setThumbnail(targetUser.displayAvatarURL({ dynamic: true })) + .setColor('Blurple') + ); + + const menu = new StringSelectMenuBuilder() + .setCustomId(`staff-mgmt_panel-menu_${targetUser.id}`) + .setPlaceholder(localize('staff-management-system', 'panel-ph')) + .addOptions( + new StringSelectMenuOptionBuilder() + .setLabel(localize('staff-management-system', 'opt-over')) + .setValue('overview') + .setEmoji('🏠'), + new StringSelectMenuOptionBuilder() + .setLabel(localize('staff-management-system', 'opt-act')) + .setValue('activity') + .setEmoji('📋'), + new StringSelectMenuOptionBuilder() + .setLabel(localize('staff-management-system', 'opt-inf')) + .setValue('infractions') + .setEmoji('âš ī¸'), + new StringSelectMenuOptionBuilder() + .setLabel(localize('staff-management-system', 'opt-prom')) + .setValue('promotions') + .setEmoji('🎉'), + new StringSelectMenuOptionBuilder() + .setLabel(localize('staff-management-system', 'opt-rev')) + .setValue('reviews') + .setEmoji('⭐'), + new StringSelectMenuOptionBuilder() + .setLabel(localize('staff-management-system', 'opt-shi')) + .setValue('shifts') + .setEmoji('âąī¸'), + new StringSelectMenuOptionBuilder() + .setLabel(localize('staff-management-system', 'opt-sta')) + .setValue('status') + .setEmoji('🌙'), + new StringSelectMenuOptionBuilder() + .setLabel(localize('staff-management-system', 'opt-del')) + .setValue('deletion') + .setEmoji('đŸ—‘ī¸') + ); + + const row = new ActionRowBuilder().addComponents(menu); + return { + embeds: [embed.toJSON()], + components: [row.toJSON()] + }; +} + +// Infractions page +async function generatePanelInfractions(client, targetUser, page = 1) { + const Infraction = client.models['staff-management-system']['Infraction']; + const allInfractions = await Infraction.findAll({ + where: {userId: targetUser.id} + }); + const count = allInfractions.length; + + let totalPages = 1; + if (count > 3) totalPages = 1 + Math.ceil((count - 3) / 5); + + const limit = page === 1 ? 3 : 5; + const offset = page === 1 ? 0 : 3 + ((page - 2) * 5); + + const typeCounts = {}; + allInfractions.forEach(inf => { typeCounts[inf.type] = (typeCounts[inf.type] || 0) + 1; }); + const typeStrings = Object.entries(typeCounts).map(([type, qty]) => `${type}: **${qty}**`).join('\n'); + + const embed = applyFooter(client, new EmbedBuilder() + .setTitle(localize('staff-management-system', 'p-inf-title', { username: targetUser.username })) + .setColor('Red') + .setThumbnail(targetUser.displayAvatarURL({ dynamic: true })) + ); + + let desc = localize('staff-management-system', 'p-inf-desc', { + count: count, types: typeStrings || localize('staff-management-system', 'info-none') + }); + + const rows = await Infraction.findAll({ + where: {userId: targetUser.id}, + order: [['createdAt', 'DESC']], + limit, + offset + }); + + if (rows.length === 0) { + desc = desc + localize('staff-management-system', 'p-no-hist'); + } else { + desc = desc + rows.map(r => { + const statusIcon = r.active ? '🔴' : localize('staff-management-system', 'icon-voided'); + const expiry = r.expiresAt ? `\n**${localize('staff-management-system', 'label-exp')}:** ${dateToDiscordTimestamp(r.expiresAt, 'R')}` : ''; + return `**${statusIcon} ${localize('staff-management-system', 'label-case')} #${r.caseId} - ${r.type}**\n**${localize('staff-management-system', 'label-date')}:** ${dateToDiscordTimestamp(r.createdAt, 'f')}\n**${localize('staff-management-system', 'general-rsn')}:** ${r.reason}${expiry}`; + }).join('\n\n'); + } + + embed.setDescription(desc); + embed.addFields({ name: '\u200b', value: localize('staff-management-system', 'page-count', { page, total: totalPages }) }); + + const menu = ActionRowBuilder.from((await generateUserPanel(client, targetUser)).components[0]); + menu.components[0].options.find(opt => opt.data.value === 'infractions').data.default = true; + + const paginationRow = buildPaginationRow( + `staff-mgmt_panel-inf_${targetUser.id}_${page - 1}`, + 'panel_inf_count', + `staff-mgmt_panel-inf_${targetUser.id}_${page + 1}`, + page, + totalPages + ); + + return { + embeds: [embed.toJSON()], + components: [menu.toJSON(), paginationRow.toJSON()] + }; +} + +// Promotions page +async function generatePanelPromotions(client, targetUser, page = 1) { + const Promotion = client.models['staff-management-system']['Promotion']; + const count = await Promotion.count({ + where: {userId: targetUser.id} + }); + + let totalPages = 1; + if (count > 3) totalPages = 1 + Math.ceil((count - 3) / 5); + + const limit = page === 1 + ? 3 + : 5; + const offset = page === 1 + ? 0 + : 3 + ((page - 2) * 5); + + const embed = applyFooter(client, new EmbedBuilder() + .setTitle(localize('staff-management-system', 'p-prom-title', { + username: targetUser.username + })) + .setColor('Gold') + .setThumbnail(targetUser.displayAvatarURL({ dynamic: true })) + ); + + let desc = localize('staff-management-system', 'p-prom-desc', { count: count }); + const rows = await Promotion.findAll({ + where: {userId: targetUser.id}, + order: [['createdAt', 'DESC']], + limit, + offset + }); + + if (rows.length === 0) { + desc = desc + localize('staff-management-system', 'p-no-hist'); + } else { + desc = desc + rows.map(r => `**${localize('staff-management-system', 'label-role')}:** <@&${r.newRole}>\n**${localize('staff-management-system', 'label-prom-by')}:** <@${r.issuerId}>\n**${localize('staff-management-system', 'label-date')}:** ${dateToDiscordTimestamp(r.createdAt, 'R')}\n**${localize('staff-management-system', 'general-rsn')}:** ${r.reason}`).join('\n\n'); + } + + embed.setDescription(desc); + embed.addFields({ name: '\u200b', value: localize('staff-management-system', 'page-count', { page, total: totalPages }) }); + + const menu = ActionRowBuilder.from((await generateUserPanel(client, targetUser)).components[0]); + menu.components[0].options.find(opt => opt.data.value === 'promotions').data.default = true; + + const paginationRow = buildPaginationRow( + `staff-mgmt_panel-prom_${targetUser.id}_${page - 1}`, + 'panel_prom_count', + `staff-mgmt_panel-prom_${targetUser.id}_${page + 1}`, + page, + totalPages + ); + + return { + embeds: [embed.toJSON()], + components: [menu.toJSON(), paginationRow.toJSON()] + }; +} + +// Reviews page +async function generatePanelReviews(client, targetUser, page = 1) { + const Review = client.models['staff-management-system']['StaffReview']; + const allReviews = await Review.findAll({ + where: {targetId: targetUser.id} + }); + const count = allReviews.length; + + let totalPages = 1; + if (count > 3) totalPages = 1 + Math.ceil((count - 3) / 5); + + const limit = page === 1 ? 3 : 5; + const offset = page === 1 ? 0 : 3 + ((page - 2) * 5); + + const avg = count + ? (allReviews.reduce((a, b) => a + b.stars, 0) / count).toFixed(1) + : 0; + + const embed = applyFooter(client, new EmbedBuilder() + .setTitle(localize('staff-management-system', 'p-rev-title', { + username: targetUser.username + })) + .setColor('Gold') + .setThumbnail(targetUser.displayAvatarURL({ dynamic: true })) + ); + + let desc = localize('staff-management-system', 'p-rev-desc', { count: count, avg: avg }); + + const rows = await Review.findAll({ + where: {targetId: targetUser.id}, + order: [['createdAt', 'DESC']], + limit, + offset + }); + if (rows.length === 0) desc = desc + localize('staff-management-system', 'p-no-hist'); + else desc = desc + rows.map(r => `**${'⭐'.repeat(r.stars)}** ${localize('staff-management-system', 'label-by')} <@${r.authorId}>\n"${r.comment}"`).join('\n\n'); + + embed.setDescription(desc); + embed.addFields({ + name: '\u200b', + value: localize('staff-management-system', 'page-count', { + page, total: totalPages + }) + }); + + const menu = ActionRowBuilder.from((await generateUserPanel(client, targetUser)).components[0]); + menu.components[0].options.find(opt => opt.data.value === 'reviews').data.default = true; + + const paginationRow = buildPaginationRow( + `staff-mgmt_panel-rev_${targetUser.id}_${page - 1}`, + 'panel_rev_count', + `staff-mgmt_panel-rev_${targetUser.id}_${page + 1}`, + page, + totalPages + ); + + return { + embeds: [embed.toJSON()], + components: [menu.toJSON(), paginationRow.toJSON()] + }; +} + +// Status page +async function generatePanelStatus(client, targetUser, page = 1) { + const LoaRequest = client.models['staff-management-system']['LoaRequest']; + const allStatuses = await LoaRequest.findAll({ + where: {userId: targetUser.id} + }); + const count = allStatuses.length; + + let totalPages = 1; + if (count > 3) totalPages = 1 + Math.ceil((count - 3) / 5); + const limit = page === 1 + ? 3 + : 5; + const offset = page === 1 + ? 0 + : 3 + ((page - 2) * 5); + + const activeStatus = allStatuses.find(s => ['APPROVED', 'PENDING'].includes(s.status) && new Date(s.endDate) > new Date()); + let activeText = localize('staff-management-system', 'info-none'); + if (activeStatus) { + activeText = `**${activeStatus.type}** (${activeStatus.status})\n${localize('staff-management-system', 'label-end')}: ${dateToDiscordTimestamp(activeStatus.endDate, 'R')}`; + } + + const embed = applyFooter(client, new EmbedBuilder() + .setTitle(localize('staff-management-system', 'p-sta-title', { + username: targetUser.username + })) + .setColor('Green') + .setThumbnail(targetUser.displayAvatarURL({ dynamic: true })) + ); + + let desc = localize('staff-management-system', 'p-sta-desc', { + count: count, active: activeText + }); + + const rows = await LoaRequest.findAll({ + where: {userId: targetUser.id}, + order: [['createdAt', 'DESC']], + limit, + offset + }); + if (rows.length === 0) desc = desc + localize('staff-management-system', 'p-no-hist'); + else { + const icons = { + APPROVED: '✅', + DENIED: '❌', + ENDED: 'âšī¸', + PENDING: '🕐' + }; + desc = desc + rows.map(r => `**${icons[r.status] || '❓'} ${r.type} - ${r.status}**\n**${localize('staff-management-system', 'general-start')}:** ${dateToDiscordTimestamp(r.startDate, 'D')}\n**${localize('staff-management-system', 'general-end')}:** ${dateToDiscordTimestamp(r.endDate, 'D')}\n**${localize('staff-management-system', 'general-rsn')}:** ${r.reason}`).join('\n\n'); + } + + embed.setDescription(desc); + embed.addFields({ + name: '\u200b', + value: localize('staff-management-system', 'page-count', { + page, + total: totalPages + }) + }); + + const menu = ActionRowBuilder.from((await generateUserPanel(client, targetUser)).components[0]); + menu.components[0].options.find(opt => opt.data.value === 'status').data.default = true; + + const paginationRow = buildPaginationRow( + `staff-mgmt_panel-stat_${targetUser.id}_${page - 1}`, + 'panel_stat_count', + `staff-mgmt_panel-stat_${targetUser.id}_${page + 1}`, + page, + totalPages + ); + + return { + embeds: [embed.toJSON()], + components: [menu.toJSON(), paginationRow.toJSON()] + }; +} + +// Activity checks page +async function generatePanelActivity(client, targetUser, page = 1) { + const ActivityCheck = client.models['staff-management-system']['ActivityCheck']; + const ActivityCheckResponse = client.models['staff-management-system']['ActivityCheckResponse']; + + const cutoff = new Date(); + cutoff.setDate(cutoff.getDate() - 90); + + const recentChecks = await ActivityCheck.findAll({ + where: { + createdAt: { [Op.gte]: cutoff } + }, + order: [['createdAt', 'DESC']] + }); + + if (recentChecks.length === 0) { + const embed = applyFooter(client, new EmbedBuilder() + .setTitle(localize('staff-management-system', 'p-act-title', { + username: targetUser.username + })) + .setColor('Blue') + .setThumbnail(targetUser.displayAvatarURL({ dynamic: true })) + .setDescription(localize('staff-management-system', 'p-act-desc', { count: 0 }) + localize('staff-management-system', 'p-no-hist')) + ); + + const menu = ActionRowBuilder.from((await generateUserPanel(client, targetUser)).components[0]); + menu.components[0].options.find(opt => opt.data.value === 'activity').data.default = true; + + return { + embeds: [embed.toJSON()], + components: [menu.toJSON()] + }; + } + + const checkIds = recentChecks.map(check => check.id); + const responses = await ActivityCheckResponse.findAll({ + where: { + activityCheckId: { [Op.in]: checkIds }, + userId: targetUser.id + }, + attributes: ['activityCheckId'] + }); + + const respondedCheckIds = new Set(responses.map(response => response.activityCheckId)); + const historyRows = recentChecks.filter(check => respondedCheckIds.has(check.id)); + + const count = historyRows.length; + let totalPages = 1; + if (count > 3) totalPages = 1 + Math.ceil((count - 3) / 5); + const limit = page === 1 + ? 3 + : 5; + const offset = page === 1 + ? 0 + : 3 + ((page - 2) * 5); + const paginatedRows = historyRows.slice(offset, offset + limit); + + const embed = applyFooter(client, new EmbedBuilder() + .setTitle(localize('staff-management-system', 'p-act-title', { + username: targetUser.username + })) + .setColor('Blue') + .setThumbnail(targetUser.displayAvatarURL({ dynamic: true })) + ); + + let desc = localize('staff-management-system', 'p-act-desc', { count }); + + if (paginatedRows.length === 0) { + desc = desc + localize('staff-management-system', 'p-no-hist'); + } else { + desc = desc + paginatedRows.map(r => `**${localize('staff-management-system', 'label-chk')} ${dateToDiscordTimestamp(r.createdAt, 'D')}**\n` + + `**${localize('staff-management-system', 'label-end')}:** ${dateToDiscordTimestamp(r.endTime, 'F')}\n` + + `**${localize('staff-management-system', 'label-chan')}:** <#${r.channelId}>` + ).join('\n\n'); + } + + embed.setDescription(desc); + embed.addFields({ + name: '\u200b', + value: localize('staff-management-system', 'page-count', { page, total: totalPages }) + }); + + const menu = ActionRowBuilder.from((await generateUserPanel(client, targetUser)).components[0]); + menu.components[0].options.find(opt => opt.data.value === 'activity').data.default = true; + + const paginationRow = buildPaginationRow( + `staff-mgmt_panel-act_${targetUser.id}_${page - 1}`, + 'panel_act_count', + `staff-mgmt_panel-act_${targetUser.id}_${page + 1}`, + page, + totalPages + ); + + return { + embeds: [embed.toJSON()], + components: [menu.toJSON(), paginationRow.toJSON()] + }; +} + +// Shifts page +async function generatePanelShifts(client, targetUser) { + const embed = applyFooter(client, new EmbedBuilder() + .setTitle(localize('staff-management-system', 'p-shi-title', { + username: targetUser.username + })) + .setColor('Purple') + .setThumbnail(targetUser.displayAvatarURL({ dynamic: true })) + ); + + try { + const Shift = client.models['staff-management-system']['StaffShift']; + const config = getConfig(client, 'shifts') || {}; + const shifts = await Shift.findAll({ + where: { + userId: targetUser.id, + endTime: {[Op.not]: null}, + duration: {[Op.not]: null} + } + }); + + const totalShifts = shifts.length; + const totalSeconds = shifts.reduce((sum, s) => sum + (parseInt(s.duration) || 0), 0); + + const breakdown = {}; + shifts.forEach(log => { + const t = log.type || 'Staff'; + breakdown[t] = (breakdown[t] || 0) + (parseInt(log.duration) || 0); + }); + const breakdownStr = Object.entries(breakdown).sort((a, b) => b[1] - a[1]).map(([type, sec]) => `â€ĸ ${type}: ${formatDuration(sec)}`).join('\n') || localize('staff-management-system', 'info-none'); + + let quotaStr = localize('staff-management-system', 'no-quota-configured'); + const guild = client.guilds.cache.get(client.guildID); + const member = await guild?.members.fetch(targetUser.id).catch(() => null); + + if (member && config.enableQuotas && config.quotas) { + let bestQuota = null; + let highestPosition = -1; + for (const [roleId, hoursStr] of Object.entries(config.quotas)) { + const hours = parseFloat(hoursStr); + const role = guild.roles.cache.get(roleId); + if (role && member.roles.cache.has(roleId) && role.position > highestPosition) { + highestPosition = role.position; + bestQuota = { hours }; + } + } + + if (bestQuota) { + const timeframe = config.quotaTimeframe || 'Weekly'; + const cutoff = new Date(); + if (timeframe === 'Weekly') cutoff.setDate(cutoff.getDate() - 7); + else cutoff.setMonth(cutoff.getMonth() - 1); + + const recentShifts = await Shift.findAll({ + where: { + userId: targetUser.id, + startTime: {[Op.gt]: cutoff}, + endTime: {[Op.not]: null}, + duration: {[Op.not]: null} + } + }); + const recentSeconds = recentShifts.reduce((sum, s) => sum + (parseInt(s.duration) || 0), 0); + const requiredSeconds = bestQuota.hours * 3600; + const isMet = recentSeconds >= requiredSeconds; + + quotaStr = localize('staff-management-system', 'duty-quota-str', { + timeframe, + duration: formatDuration(recentSeconds), + hours: bestQuota.hours, + result: isMet + ? localize('staff-management-system', 'duty-quota-met') + : localize('staff-management-system', 'duty-quota-failed') + }); + } + } + + const allResults = await Shift.findAll({ + attributes: ['userId', [Shift.sequelize.fn('SUM', Shift.sequelize.col('duration')), 'totalDuration']], + where: { endTime: { [Op.not]: null }, duration: { [Op.not]: null } }, + group: ['userId'], + order: [[Shift.sequelize.literal('totalDuration'), 'DESC']] + }); + + const lbIndex = allResults.findIndex(p => p.userId === targetUser.id); + const lbRank = lbIndex !== -1 + ? `${lbIndex + 1} / ${allResults.length}` + : localize('staff-management-system', 'label-unranked'); + + embed.setDescription(localize('staff-management-system', 'panel-shifts-desc', { + totalShifts, + totalSeconds: formatDuration(totalSeconds), + lbRank, + breakdownStr, + quotaStr + })); + + } catch (e) { + client.logger.error(`[Staff Management] User panel error: ${e.stack}`); + embed.setDescription(localize('staff-management-system', 'err-shift-data-unavailable', { error: e.message })); + } + + const menu = ActionRowBuilder.from((await generateUserPanel(client, targetUser)).components[0]); + menu.components[0].options.find(opt => opt.data.value === 'shifts').data.default = true; + + const historyBtnRow = new ActionRowBuilder().addComponents( + new ButtonBuilder() + .setCustomId(`duty-mgmt_hist_${targetUser.id}_1_All`) + .setLabel(localize('staff-management-system', 'btn-view-history')) + .setStyle(ButtonStyle.Secondary) + ); + + return { + embeds: [embed.toJSON()], + components: [menu.toJSON(), historyBtnRow.toJSON()] + }; +} + +// Deletion page +async function generatePanelDeletion(client, targetUser) { + const embed = applyFooter(client, new EmbedBuilder() + .setTitle(localize('staff-management-system', 'panel-deletion-title', { tag: targetUser.username })) + .setDescription(localize('staff-management-system', 'panel-deletion-desc', { mention: targetUser.toString() })) + .setColor('DarkRed') + .setThumbnail(targetUser.displayAvatarURL({ dynamic: true })) + ); + + const menu = new StringSelectMenuBuilder() + .setCustomId(`staff-mgmt_delete-menu_${targetUser.id}`) + .setPlaceholder(localize('staff-management-system', 'panel-deletion-placeholder')) + .addOptions( + new StringSelectMenuOptionBuilder() + .setLabel(localize('staff-management-system', 'panel-opt-back')) + .setValue('back') + .setEmoji('â—€ī¸'), + new StringSelectMenuOptionBuilder() + .setLabel(localize('staff-management-system', 'panel-opt-del-act')) + .setValue('del_activity') + .setEmoji('📋'), + new StringSelectMenuOptionBuilder() + .setLabel(localize('staff-management-system', 'panel-opt-del-inf')) + .setValue('del_infractions') + .setEmoji('âš ī¸'), + new StringSelectMenuOptionBuilder() + .setLabel(localize('staff-management-system', 'panel-opt-del-prom')) + .setValue('del_promotions') + .setEmoji('🎉'), + new StringSelectMenuOptionBuilder() + .setLabel(localize('staff-management-system', 'panel-opt-del-rev')) + .setValue('del_reviews') + .setEmoji('⭐'), + new StringSelectMenuOptionBuilder() + .setLabel(localize('staff-management-system', 'panel-opt-del-shifts')) + .setValue('del_shifts') + .setEmoji('âąī¸'), + new StringSelectMenuOptionBuilder() + .setLabel(localize('staff-management-system', 'panel-opt-del-status')) + .setValue('del_status') + .setEmoji('🌙'), + new StringSelectMenuOptionBuilder() + .setLabel(localize('staff-management-system', 'panel-opt-del-all')) + .setValue('del_all') + .setEmoji('đŸ’Ĩ') + ); + + return { + embeds: [embed.toJSON()], + components: [new ActionRowBuilder().addComponents(menu).toJSON()] + }; +} + +async function executeDataDeletion(client, targetId, dataType) { + const models = client.models['staff-management-system']; + + if (['del_infractions', 'del_all'].includes(dataType)) { + await models.Infraction.destroy({ + where: { userId: targetId } + }); + } + + if (['del_promotions', 'del_all'].includes(dataType)) { + await models.Promotion.destroy({ + where: { userId: targetId } + }); + } + + if (['del_reviews', 'del_all'].includes(dataType)) { + await models.StaffReview.destroy({ + where: { targetId } + }); + } + + const profileUpdates = {}; + if (['del_shifts', 'del_all'].includes(dataType)) { + profileUpdates.onDuty = false; + profileUpdates.onBreak = false; + profileUpdates.breakStartTime = null; + profileUpdates.lastClockIn = null; + } + + if (['del_status', 'del_all'].includes(dataType)) { + profileUpdates.activityStatus = null; + } + + if (dataType === 'del_all') { + profileUpdates.customNickname = null; + profileUpdates.customIntro = null; + profileUpdates.isSuspended = false; + profileUpdates.suspendedRoles = null; + } + + if (Object.keys(profileUpdates).length > 0) { + const profile = await models.StaffProfile.findByPk(targetId); + if (profile) await profile.update(profileUpdates); + } + + if (['del_activity', 'del_all'].includes(dataType)) { + await models.ActivityCheckResponse.destroy({ + where: { userId: targetId } + }); + } +} + +module.exports = { + generatePanelSubpage, + generateUserPanel, + generatePanelInfractions, + generatePanelPromotions, + generatePanelReviews, + generatePanelStatus, + generatePanelActivity, + generatePanelShifts, + generatePanelDeletion, + executeDataDeletion +}; diff --git a/modules/staff-management-system/core/profiles.js b/modules/staff-management-system/core/profiles.js new file mode 100644 index 00000000..e32d7cfe --- /dev/null +++ b/modules/staff-management-system/core/profiles.js @@ -0,0 +1,273 @@ +/** + * Profile management logic for the Staff Management module + * @module staff-management-system + * @author itskevinnn + */ + +const { + ActionRowBuilder, + ModalBuilder, + TextInputBuilder, + TextInputStyle, + MessageFlags +} = require('discord.js'); +const { embedTypeV2 } = require('../../../src/functions/helpers'); +const { localize } = require('../../../src/functions/localize'); + +async function handleProfileView(client, interaction, targetUser) { + const config = client.configurations['staff-management-system']['profiles']; + if (!config || !config.enableProfiles) return interaction.editReply({ + content: localize('staff-management-system', 'err-prof-dis') + }); + + if (!config.profileEmbedMessage) { + return interaction.editReply({ + content: localize('staff-management-system', 'err-prof-cfg') + }); + } + + const user = targetUser || interaction.user; + const member = await interaction.guild.members.fetch(user.id).catch(() => null); + if (!member) return interaction.editReply({ + content: localize('staff-management-system', 'err-no-mem') + }); + + const restrictToStaff = config.onlyAllowStaffProfile !== false; + if (restrictToStaff) { + const generalConfig = client.configurations['staff-management-system']['configuration'] || {}; + + const staffRoles = Array.isArray(generalConfig.staffRoles) + ? generalConfig.staffRoles + : (generalConfig.staffRoles + ? [generalConfig.staffRoles] + : [] + ); + const supRoles = Array.isArray(generalConfig.supervisorRoles) + ? generalConfig.supervisorRoles + : (generalConfig.supervisorRoles + ? [generalConfig.supervisorRoles] + : [] + ); + const mgmtRoles = Array.isArray(generalConfig.managementRoles) + ? generalConfig.managementRoles + : (generalConfig.managementRoles + ? [generalConfig.managementRoles] + : [] + ); + + const allStaffRoles = [...staffRoles, ...supRoles, ...mgmtRoles]; + const isAdmin = member.permissions.has('Administrator'); + const isStaff = allStaffRoles.length > 0 && member.roles.cache.some(r => allStaffRoles.includes(r.id)); + + if (!isAdmin && !isStaff) { + if (user.id === interaction.user.id) { + return interaction.editReply({ + content: localize('staff-management-system', 'err-prof-no-own') + }); + } else { + return interaction.editReply({ + content: localize('staff-management-system', 'err-prof-no-tgt') + }); + } + } + } + + const Profile = client.models['staff-management-system']['StaffProfile']; + const Review = client.models['staff-management-system']['StaffReview']; + + const [profile] = await Profile.findOrCreate({ + where: {userId: user.id} + }); + + const reviewsConfig = client.configurations['staff-management-system']['reviews']; + const reviewsEnabled = reviewsConfig && reviewsConfig.enableReviews; + + let ratingDisplay = localize('staff-management-system', 'rev-dis-text'); + if (reviewsEnabled) { + let avgRatingText = localize('staff-management-system', 'rev-no-rate'); + const allReviews = await Review.findAll({ + where: {targetId: user.id}, + attributes: ['stars'] + }); + if (allReviews.length > 0) { + avgRatingText = (allReviews.reduce((a, b) => a + b.stars, 0) / allReviews.length).toFixed(1); + } + ratingDisplay = `⭐ ${avgRatingText}`; + } + + let discordStatus = localize('staff-management-system', 'stat-offl'); + if (member.presence) { + switch (member.presence.status) { + case 'online': discordStatus = localize('staff-management-system', 'stat-onl'); break; + case 'idle': discordStatus = localize('staff-management-system', 'stat-idl'); break; + case 'dnd': discordStatus = localize('staff-management-system', 'stat-dnd'); break; + case 'offline': discordStatus = localize('staff-management-system', 'stat-offl'); break; + } + } + + const statusLines = [discordStatus]; + if (profile.onDuty) statusLines.push(localize('staff-management-system', 'stat-prof-ond')); + if (profile.activityStatus === 'LOA') statusLines.push(localize('staff-management-system', 'stat-prof-loa')); + if (profile.activityStatus === 'RA') statusLines.push(localize('staff-management-system', 'stat-prof-ra')); + + const introText = profile.customIntro || localize('staff-management-system', 'prof-no-intro'); + const nicknameText = profile.customNickname || user.username; + + const placeholders = { + '%user-mention%': user.toString(), + '%username%': user.username, + '%nickname%': nicknameText, + '%intro%': introText, + '%status%': statusLines.join('\n'), + '%rating%': ratingDisplay, + '%avatar%': user.displayAvatarURL({ + dynamic: true, + format: 'png', + size: 1024 + }) || '' + }; + + const embedTemplate = config.profileEmbedMessage; + const msgOpts = await embedTypeV2(embedTemplate, placeholders); + + if (!msgOpts) { + return interaction.editReply({ + content: localize('staff-management-system', 'err-prof-empty') + }); + } + + await interaction.editReply(msgOpts); +} + +async function handleProfileEdit(client, interaction) { + const config = client.configurations['staff-management-system']['profiles']; + if (!config || !config.enableProfiles) return interaction.reply({ + content: localize('staff-management-system', 'err-prof-dis'), + flags: MessageFlags.Ephemeral + }); + + const restrictToStaff = config.onlyAllowStaffProfile !== false; + if (restrictToStaff) { + const generalConfig = client.configurations['staff-management-system']['configuration'] || {}; + + const staffRoles = Array.isArray(generalConfig.staffRoles) + ? generalConfig.staffRoles + : (generalConfig.staffRoles + ? [generalConfig.staffRoles] + : [] + ); + const supRoles = Array.isArray(generalConfig.supervisorRoles) + ? generalConfig.supervisorRoles + : (generalConfig.supervisorRoles + ? [generalConfig.supervisorRoles] + : [] + ); + const mgmtRoles = Array.isArray(generalConfig.managementRoles) + ? generalConfig.managementRoles + : (generalConfig.managementRoles + ? [generalConfig.managementRoles] + : [] + ); + + const allStaffRoles = [ + ...staffRoles, + ...supRoles, + ...mgmtRoles + ]; + + const isAdmin = interaction.member.permissions.has('Administrator'); + const hasStaffRole = allStaffRoles.length > 0 && interaction.member.roles.cache.some(r => allStaffRoles.includes(r.id)); + + if (!isAdmin && !hasStaffRole) { + return interaction.reply({ + content: localize('staff-management-system', 'err-prof-perm'), + flags: MessageFlags.Ephemeral + }); + } + } + + const Profile = client.models['staff-management-system']['StaffProfile']; + const profile = await Profile.findByPk(interaction.user.id); + + const modal = new ModalBuilder() + .setCustomId(`staff-mgmt_profile-edit`) + .setTitle(localize('staff-management-system', 'prof-edit-title')); + + modal.addComponents( + new ActionRowBuilder() + .addComponents( + new TextInputBuilder() + .setCustomId('nickname') + .setLabel(localize('staff-management-system', 'prof-edit-nick')) + .setStyle(TextInputStyle.Short) + .setRequired(false) + .setValue(profile?.customNickname || '') + ), + new ActionRowBuilder().addComponents( + new TextInputBuilder() + .setCustomId('intro') + .setLabel(localize('staff-management-system', 'prof-edit-intro')) + .setStyle(TextInputStyle.Paragraph) + .setRequired(false) + .setValue(profile?.customIntro || '') + ) + ); + + return interaction.showModal(modal); +} + +async function handleProfileAdminWipe(client, interaction, targetUser) { + const profilesConfig = client.configurations['staff-management-system']['profiles']; + const generalConfig = client.configurations['staff-management-system']['configuration'] || {}; + + if (!profilesConfig || !profilesConfig.enableProfiles) { + return interaction.editReply({ + content: localize('staff-management-system', 'err-prof-dis') + }); + } + + const mRoles = Array.isArray(generalConfig.managementRoles) + ? generalConfig.managementRoles + : (generalConfig.managementRoles + ? [generalConfig.managementRoles] + : [] + ); + const sRoles = Array.isArray(generalConfig.supervisorRoles) + ? generalConfig.supervisorRoles + : (generalConfig.supervisorRoles + ? [generalConfig.supervisorRoles] + : [] + ); + + const requiredRoles = profilesConfig.managePermission === 'Management' + ? mRoles + : [...sRoles, ...mRoles]; + + const isAdmin = interaction.member.permissions.has('Administrator'); + const hasRequiredRole = requiredRoles.length > 0 && interaction.member.roles.cache.some(r => requiredRoles.includes(r.id)); + + if (!isAdmin && !hasRequiredRole) { + return interaction.editReply({ + content: localize('staff-management-system', 'err-no-perm') + }); + } + + const Profile = client.models['staff-management-system']['StaffProfile']; + await Profile.update({ + customNickname: null, + customIntro: null + }, + { + where: {userId: targetUser.id} + }); + + await interaction.editReply({ + content: localize('staff-management-system', 'succ-prof-wipe', {u: targetUser.username}) + }); +} + +module.exports = { + handleProfileView, + handleProfileEdit, + handleProfileAdminWipe +}; diff --git a/modules/staff-management-system/core/promotions.js b/modules/staff-management-system/core/promotions.js new file mode 100644 index 00000000..66418a0d --- /dev/null +++ b/modules/staff-management-system/core/promotions.js @@ -0,0 +1,213 @@ +/** + * Promotions logic for the Staff Management module + * @module staff-management-system + * @author itskevinnn + */ + +const { EmbedBuilder, MessageFlags } = require('discord.js'); +const { embedTypeV2, dateToDiscordTimestamp } = require('../../../src/functions/helpers'); +const { localize } = require('../../../src/functions/localize'); +const { + getConfig, + getSafeChannelId, + applyFooter, + checkStaffPermissions, + buildPaginationRow +} = require('./localHelpers'); + +// ---------- Promotions ---------- +async function promoteUser(client, interaction, targetMember, newRole, reason) { + await interaction.deferReply({ephemeral: true}); + const config = getConfig(client, 'promotions'); + if (!config?.enablePromotions) return interaction.editReply({ + content: localize('staff-management-system', 'err-feat-disabled', {feature: 'Promotions'}) + }); + + const generalConfig = getConfig(client, 'configuration'); + const canPromote = checkStaffPermissions(interaction.member, generalConfig, 'supervisor'); + if (!canPromote) return interaction.editReply({ + content: localize('staff-management-system', 'err-gen-no-perm') + }); + + if (targetMember.id === interaction.user.id) { + return interaction.editReply({ + content: localize('staff-management-system', 'err-self-promo') + }); + } + + const finalReason = reason && reason.trim() !== '' + ? reason + : localize('staff-management-system', 'none-provided'); + const channelOverride = interaction.options.getChannel('channel'); + + if (config.autoAddRole) { + if (interaction.guild.members.me.roles.highest.position <= newRole.position) { + return interaction.editReply({ + content: localize('staff-management-system', 'err-role-hier') + }); + } + try { + await targetMember.roles.add(newRole); + } catch (e) { + return interaction.editReply({ + content: localize('staff-management-system', 'err-add-role', {e: e.message}) + }); + } + } + + const record = await client.models['staff-management-system']['Promotion'].create({ + userId: targetMember.id, + issuerId: interaction.user.id, + newRole: newRole.id, + reason: finalReason + }); + + const placeholders = { + '%user-mention%': targetMember.user.toString(), + '%new-role-name%': newRole.name, + '%new-role-mention%': newRole.toString(), + '%promoter-mention%': interaction.user.toString(), + '%promoter-name%': interaction.user.username, + '%reason%': finalReason, + '%user-avatar%': targetMember.user.displayAvatarURL({ + dynamic: true, + format: 'png', + size: 1024 + }) || '', + '%promoter-avatar%': interaction.user.displayAvatarURL({ + dynamic: true, + format: 'png', + size: 1024 + }) || '' + }; + + const targetChannelId = channelOverride + ? channelOverride.id + : getSafeChannelId(config.promotionsChannel); + + if (targetChannelId) { + const channel = await interaction.guild.channels.fetch(targetChannelId).catch(() => null); + if (channel) { + let embedTemplate = config.promotionMessage; + if (typeof embedTemplate === 'string') { + try { + embedTemplate = JSON.parse(embedTemplate); + } catch (e) { + } + } else if (typeof embedTemplate === 'object') { + embedTemplate = JSON.parse(JSON.stringify(embedTemplate)); + } + + if (embedTemplate && embedTemplate.embeds && !embedTemplate._schema) embedTemplate._schema = 'v3'; + const msgOpts = await embedTypeV2(embedTemplate, placeholders); + if (msgOpts?.content?.trim() === '') delete msgOpts.content; + + if (msgOpts.embeds && msgOpts.embeds.length > 0) { + const parsedEmbed = EmbedBuilder.from(msgOpts.embeds[0]); + applyFooter(client, parsedEmbed); + msgOpts.embeds[0] = parsedEmbed.toJSON(); + } + + const sentMessage = await channel + .send(msgOpts) + .catch(e => { + client.logger.error(localize('staff-management-system', 'log-promo-msg-error', { + e: e.message + })); + return null; + }); + + if (sentMessage) await record.update({messageUrl: sentMessage.url}); + } + } + + if (config.dmPromotedUser && config.promotionDmMessage) { + const dmTemplate = config.promotionDmMessage; + + if (dmTemplate && dmTemplate.embeds && !dmTemplate._schema) dmTemplate._schema = 'v3'; + const dmOpts = await embedTypeV2(dmTemplate, placeholders); + if (dmOpts?.content?.trim() === '') delete dmOpts.content; + + if (dmOpts) { + try { + await targetMember.user.send(dmOpts); + } catch (e) { + client.logger.warn(localize('staff-management-system', 'log-promo-dm-fail', { + user: targetMember.user.tag, + error: e.message + })); + } + } + } + + await interaction.editReply({ + content: localize('staff-management-system', 'succ-promo', { + user: targetMember.user.tag, + role: newRole.name + }) + }); +} + +// ----- Generates promotion history & embed ----- +async function generatePromotionHistoryResponse(client, targetUser, page = 1) { + const Promotion = client.models['staff-management-system']['Promotion']; + const limit = 5; + const offset = (page - 1) * limit; + + const {count, rows} = await Promotion.findAndCountAll({ + where: { + userId: targetUser.id + }, + order: [['createdAt', 'DESC']], + limit, + offset + }); + if (count === 0) return { + content: localize('staff-management-system', 'info-no-promo', {username: targetUser.username}), + flags: MessageFlags.Ephemeral + }; + + const totalPages = Math.ceil(count / limit) || 1; + const embed = applyFooter(client, new EmbedBuilder() + .setTitle(localize('staff-management-system', 'prom-hist-title', { username: targetUser.username })) + .setThumbnail(targetUser.displayAvatarURL({ dynamic: true })) + .setColor('Gold') + ); + + const desc = rows.map((r, i) => { + const link = r.messageUrl ? ` â€ĸ [Jump](${r.messageUrl})` : ''; + return `**${offset + i + 1}. ${dateToDiscordTimestamp(r.createdAt, 'F')}**\n**${localize('staff-management-system', 'label-role')}:** <@&${r.newRole}>\n**${localize('staff-management-system', 'label-prom-by')}:** <@${r.issuerId}>\n**${localize('staff-management-system', 'general-rsn')}:** ${r.reason}${link}`; + }).join('\n\n'); + + embed.setDescription(desc); + embed.addFields({ name: '\u200b', value: localize('staff-management-system', 'page-count', { page, total: totalPages }) }); + + const row = buildPaginationRow( + `staff-mgmt_prom-hist_${targetUser.id}_${page - 1}`, + 'prom_hist_count', + `staff-mgmt_prom-hist_${targetUser.id}_${page + 1}`, + page, + totalPages + ); + + return { + embeds: [embed.toJSON()], + components: [row.toJSON()] + }; +} + +async function getPromotionHistory(client, interaction, targetUser) { + await interaction.deferReply({ephemeral: true}); + const response = await generatePromotionHistoryResponse(client, targetUser, 1); + if (response.content && response.content.startsWith('â„šī¸')) return interaction.editReply(response); + + await interaction.editReply({ + ...response + }); +} + +module.exports = { + promoteUser, + generatePromotionHistoryResponse, + getPromotionHistory +}; diff --git a/modules/staff-management-system/core/reviews.js b/modules/staff-management-system/core/reviews.js new file mode 100644 index 00000000..89ade03f --- /dev/null +++ b/modules/staff-management-system/core/reviews.js @@ -0,0 +1,151 @@ +/** + * Reviews logic for the Staff Management module + * @module staff-management-system + * @author itskevinnn + */ + +const { EmbedBuilder, MessageFlags } = require('discord.js'); +const { embedTypeV2 } = require('../../../src/functions/helpers'); +const { localize } = require('../../../src/functions/localize'); +const { + getConfig, + getSafeChannelId, + applyFooter, + buildPaginationRow +} = require('./localHelpers'); + +// ---------- Reviews ---------- +async function submitReview(client, interaction, targetUser, stars, comment) { + await interaction.deferReply({ephemeral: true}); + const config = getConfig(client, 'reviews'); + if (!config?.enableReviews) return interaction.editReply({ + content: localize('staff-management-system', 'err-feat-disabled', { + feature: 'Reviews' + }) + }); + + const targetMember = await interaction.guild.members.fetch(targetUser.id).catch(() => null); + if (!targetMember) return interaction.editReply({ + content: localize('staff-management-system', 'err-not-mem') + }); + if (!config.allowSelfRating && targetUser.id === interaction.user.id) return interaction.editReply({ + content: localize('staff-management-system', 'err-self-rate') + }); + + if (config.onlyAllowStaffReview !== false) { + const generalConfig = getConfig(client, 'configuration') || {}; + const staffRoles = Array.isArray(generalConfig.staffRoles) + ? generalConfig.staffRoles + : (generalConfig.staffRoles ? [generalConfig.staffRoles] : []); + + const hasStaffRole = staffRoles.length > 0 && targetMember.roles.cache.some(role => staffRoles.includes(role.id) + ); + + if (!hasStaffRole) { + return interaction.editReply({ + content: localize('staff-management-system', 'err-staff-rate') + }); + } + } + + const review = await client.models['staff-management-system']['StaffReview'].create({ + targetId: targetUser.id, + authorId: interaction.user.id, + stars, + comment + }); + const channelId = getSafeChannelId(config.reviewLogChannel); + + if (channelId) { + const channel = interaction.guild.channels.cache.get(channelId); + if (channel) { + const msgOpts = await embedTypeV2(config.ratingMessage, { + '%staff-mention%': targetUser.toString(), + '%reviewer-mention%': interaction.user.toString(), + '%stars%': '⭐'.repeat(stars), + '%rating%': stars.toString(), + '%comment%': comment, + '%staff-avatar%': targetUser.displayAvatarURL({dynamic: true}), + '%reviewer-avatar%': interaction.user.displayAvatarURL({dynamic: true}) + }); + if (msgOpts?.content?.trim() === '') delete msgOpts.content; + const sentMessage = await channel.send(msgOpts).catch(() => {}); + if (sentMessage) await review.update({ messageUrl: sentMessage.url }); + } + } + await interaction.editReply({ + content: localize('staff-management-system', 'succ-review', { + tag: targetUser.tag, + stars + }) + }); +} + +async function generateReviewHistoryResponse(client, targetUser, page = 1) { + if (!getConfig(client, 'reviews')?.enableReviews) return { + content: localize('staff-management-system', 'err-feat-disabled', { + feature: 'Reviews' + }), + flags: MessageFlags.Ephemeral + }; + + const limit = 8; + const offset = (page - 1) * limit; + const Review = client.models['staff-management-system']['StaffReview']; + + const {count, rows} = await Review.findAndCountAll({ + where: {targetId: targetUser.id}, + order: [['createdAt', 'DESC']], + limit, + offset + }); + const allReviews = await Review.findAll({ + where: {targetId: targetUser.id}, + attributes: ['stars'] + }); + const avg = allReviews.length + ? (allReviews.reduce((a, b) => a + b.stars, 0) / allReviews.length).toFixed(1) + : 0; + + const embed = applyFooter(client, new EmbedBuilder() + .setTitle(localize('staff-management-system', 'rev-title', { username: targetUser.username })) + .setColor('Gold') + .setDescription(localize('staff-management-system', 'rev-desc', { avg, count: allReviews.length })) + .setThumbnail(targetUser.displayAvatarURL({ dynamic: true })) + ); + + embed.addFields({name: localize('staff-management-system', 'label-hist'), + value: rows.length > 0 + ? rows.map(r => `**${'⭐'.repeat(r.stars)}** ${localize('staff-management-system', 'label-by')} <@${r.authorId}>${r.messageUrl + ? ` â€ĸ [Jump](${r.messageUrl})` + : ''}\n"${r.comment}"`).join('\n\n') + : localize('staff-management-system', 'p-no-hist') }); + + const row = buildPaginationRow( + `staff-mgmt_rev-page_${targetUser.id}_${page - 1}`, + 'page_count_disabled', + `staff-mgmt_rev-page_${targetUser.id}_${page + 1}`, + page, + Math.ceil(count / limit) || 1 + ); + return { + embeds: [embed.toJSON()], + components: [row.toJSON()] + }; +} + +async function getReviewHistory(client, interaction, targetUser) { + await interaction.deferReply({ephemeral: true}); + const response = await generateReviewHistoryResponse(client, targetUser, 1); + if (response.content && response.content.startsWith('❌')) return interaction.editReply(response); + + await interaction.editReply({ + ...response + }); +} + +module.exports = { + submitReview, + generateReviewHistoryResponse, + getReviewHistory +}; diff --git a/modules/staff-management-system/core/staffStatus.js b/modules/staff-management-system/core/staffStatus.js new file mode 100644 index 00000000..8c2cc917 --- /dev/null +++ b/modules/staff-management-system/core/staffStatus.js @@ -0,0 +1,822 @@ +/** + * Staff status tracking (LOA/RA) logic for the Staff Management module + * @module staff-management-system + * @author itskevinnn + */ + +const { + MessageFlags, + EmbedBuilder, + ModalBuilder, + TextInputBuilder, + TextInputStyle, + ActionRowBuilder, + ButtonBuilder, + ButtonStyle +} = require('discord.js'); +const { Op } = require('sequelize'); +const schedule = require('node-schedule'); +const { formatDate } = require('../../../src/functions/helpers'); +const { localize } = require('../../../src/functions/localize'); +const { + getConfig, + getSafeChannelId, + parseDurationToDays, + buildPaginationRow, + applyFooter, + checkStaffPermissions +} = require('./localHelpers'); + +// ---------- Status DM's and logging ---------- +async function sendStatusDm(user, type, dmType, data = {}) { + const label = type === 'LOA' + ? 'LoA' + : 'RA'; + const viewCmd = type === 'LOA' + ? '`/staff-status loa view`' + : '`/staff-status ra view`'; + const endFmt = data.endDate + ? `` + : ''; + + // These messages use the locales key to be easily used later + const messages = { + approved: { + title: 'dm-appr-title', + color: 'Green', + desc: 'dm-appr-desc', + params: {label, approver: data.approver, endFmt, viewCmd} + }, + denied: { + title: 'dm-deny-title', + color: 'Red', + desc: 'dm-deny-desc', + params: {label, denier: data.denier, reason: data.reason} + }, + extended: { + title: 'dm-ext-title', + color: 'Yellow', + desc: 'dm-ext-desc', + params: {label, extender: data.extender, days: data.days, endFmt, reason: data.reason, viewCmd} + }, + ended_early: { + title: 'dm-early-title', + color: 'Red', + desc: 'dm-early-desc', + params: {label, ender: data.ender, reason: data.reason} + }, + ended: { + title: 'dm-end-title', + color: 'Black', + desc: 'dm-end-desc', + params: {label} + } + }; + + const msg = messages[dmType]; + if (!msg) return; + + const embed = new EmbedBuilder() + .setTitle(localize('staff-management-system', msg.title, msg.params)) + .setDescription(localize('staff-management-system', msg.desc, msg.params)) + .setColor(msg.color); + applyFooter(user.client, embed); + + try { + await user.send({ + embeds: [embed.toJSON()] + }); + } catch (e) { + user.client.logger.error( + localize('staff-management-system', 'log-stat-dm-error', { + e: e.message, + u: user.tag + }) + ); + } +} + +function isStatusTypeEnabled(config, type) { + if (!config?.enableStatusSystem) return false; + return type === 'LOA' + ? !!config.enableLoa + : !!config.enableRa; +} + +async function logStatusChange(client, type, action, data) { + const statusConfig = getConfig(client, 'status'); + if (!statusConfig?.logStatusChanges) return; + + const channelId = getSafeChannelId(statusConfig.statusChangeLogChannel) || getSafeChannelId(getConfig(client, 'configuration')?.generalLogChannel); + if (!channelId) return; + + const guild = client.guilds.cache.get(client.guildID); + if (!guild) return; + const channel = await guild.channels.fetch(channelId).catch(() => null); + if (!channel) return; + + const label = type === 'LOA' + ? 'LoA' + : 'RA'; + const targetUserObj = data.targetUser || await client.users.fetch(data.userId).catch(() => null); + const mention = targetUserObj + ? targetUserObj.toString() + : `<@${data.userId}>`; + const username = targetUserObj + ? targetUserObj.username + : data.userId; + + const embed = new EmbedBuilder() + .setThumbnail(targetUserObj + ?.displayAvatarURL({ dynamic: true }) || null); + + if (action === 'start') { + embed.setTitle(localize('staff-management-system', 'log-start-title', { label, username })) + .setColor('Green') + .setDescription(localize('staff-management-system', 'log-start-desc', { + label, mention, apprText: data.approverId + ? ` ${localize('staff-management-system', 'label-appr-by')}: <@${data.approverId}>.` + : '' + })) + .addFields({ + name: localize('staff-management-system', 'log-info-hdr', {label}), + value: `**${localize('staff-management-system', 'general-start')}:** \n**${localize('staff-management-system', 'general-end')}:** \n**${localize('staff-management-system', 'general-rsn')}:** ${data.reason || localize('staff-management-system', 'none-provided')}` + }); + + } else if (action === 'end') { + embed.setTitle(localize('staff-management-system', 'log-end-title', { label, username })) + .setColor('Red') + .setDescription(localize('staff-management-system', 'log-end-desc', { label, mention })) + .addFields({ + name: localize('staff-management-system', 'log-info-hdr', {label}), + value: `**${localize('staff-management-system', 'general-started')}:** \n**${localize('staff-management-system', 'general-ended')}:** \n**${localize('staff-management-system', 'general-req-reason')}:** ${data.reqReason}\n**${localize('staff-management-system', 'general-rsn')}:** ${data.reason || localize('staff-management-system', 'none-provided')}` + }); + + } else if (action === 'adjusted') { + embed.setTitle(localize('staff-management-system', 'log-adj-title', { label, username })) + .setColor('Yellow') + .setDescription(localize('staff-management-system', 'log-adj-desc', { label, mention, executor: data.executorId })) + .addFields({ + name: localize('staff-management-system', 'log-changes'), + value: data.changesText + }); + } + + applyFooter(client, embed); + try { + await channel.send({ + embeds: [embed.toJSON()] + }); + } catch (e) { + client.logger.error( + localize('staff-management-system', 'log-status-adj-error', { + e: e.message + }) + ); + } +} + +// ----- Status ----- +const getStatusMeta = (type) => ({ + isLoa: type === 'LOA', + label: type === 'LOA' + ? 'LoA' + : 'RA', + enableKey: type === 'LOA' + ? 'enableLoa' + : 'enableRa', + roleKey: type === 'LOA' + ? 'loaRole' + : 'raRole', + maxDaysKey: type === 'LOA' + ? 'loaMaxDays' + : 'raMaxDays', + color: type === 'LOA' + ? 'Green' + : 'Orange', + activeText: localize('staff-management-system', type === 'LOA' + ? 'status-active-loa' + : 'status-active-ra' + ), + histTitle: localize('staff-management-system', type === 'LOA' + ? 'status-hist-loa' + : 'status-hist-ra' + ), + actionPrefix: type === 'LOA' + ? 'loa' + : 'ra' +}); + +async function handleStatusRequest(client, interaction, type, durationInput, reason) { + const config = getConfig(client, 'status'); + const isLoa = type === 'LOA'; + if (!isStatusTypeEnabled(config, type)) return interaction.editReply({ + content: localize('staff-management-system', 'err-status-disabled', {type}) + } + ); + + const days = parseDurationToDays(durationInput?.trim()); + if (!days || isNaN(days) || days <= 0) return interaction.editReply({ + content: localize('staff-management-system', 'err-invalid-duration') + }); + + const maxDays = (isLoa ? config.loaMaxDays : config.raMaxDays) || (isLoa ? 60 : 30); + if (days > maxDays) return interaction.editReply({ + content: localize('staff-management-system', 'err-duration-max', {max: maxDays}) + }); + + const LoaRequest = client.models['staff-management-system']['LoaRequest']; + if (await LoaRequest.findOne({ + where: { + userId: interaction.user.id, type, status: {[Op.in]: ['PENDING', 'APPROVED']}, + endDate: {[Op.gt]: new Date()} + } + })) { + return interaction.editReply({ + content: localize('staff-management-system', 'err-status-exists', {type}) + }); + } + + const startDate = new Date(); + const endDate = new Date(startDate.getTime() + days * 24 * 60 * 60 * 1000); + const needsApproval = isLoa + ? config.requireLoaApproval !== false + : config.requireRaApproval !== false; + + const req = await LoaRequest.create({ + userId: interaction.user.id, + type, + reason, + startDate, + endDate, + status: needsApproval + ? 'PENDING' + : 'APPROVED' + }); + + const logChannelId = getSafeChannelId(config.statusLogChannel); + if (logChannelId && needsApproval) { + const channel = await interaction.guild.channels.fetch(logChannelId).catch(() => null); + if (channel) { + const embed = new EmbedBuilder() + .setTitle(localize('staff-management-system', 'status-request-title', { type })) + .setColor('Blue') + .setAuthor({ name: `Request ID: ${req.id}`}) + .addFields( + { + name: localize('staff-management-system', 'status-req-user'), + value: interaction.user.toString(), + inline: true + }, + { + name: localize('staff-management-system', 'status-req-duration'), + value: `${days} ${localize('staff-management-system', 'label-days')}`, + inline: true + }, + { + name: localize('staff-management-system', 'general-rsn'), + value: reason + } + ); + + applyFooter(client, embed); + const row = new ActionRowBuilder() + .addComponents(new ButtonBuilder() + .setCustomId(`staff-mgmt_approve_${req.id}`) + .setLabel(localize('staff-management-system', 'btn-approve')) + .setStyle(ButtonStyle.Success), + new ButtonBuilder() + .setCustomId(`staff-mgmt_deny_${req.id}`) + .setLabel(localize('staff-management-system', 'btn-deny')) + .setStyle(ButtonStyle.Danger)); + channel.send({ embeds: [embed.toJSON()], components: [row.toJSON()] }).catch(() => {}); + } + } + + if (!needsApproval) { + const roleId = config[isLoa ? 'loaRole' : 'raRole']; + if (roleId) interaction.member.roles.add(roleId).catch(() => {}); + await logStatusChange(client, type, 'start', { + targetUser: interaction.user, + startDate, + endDate, + reason, + approverId: null + }); + } + + await interaction.editReply({ + content: localize('staff-management-system', 'success-status-request', { + type, state: needsApproval + ? localize('staff-management-system', 'state-pending') + : localize('staff-management-system', 'state-auto') + }) + }); +} + +async function handleStatusView(client, interaction, type, targetUser) { + const user = targetUser || interaction.user; + const request = await client.models['staff-management-system']['LoaRequest'].findOne({ + where: { + userId: user.id, type, status: {[Op.in]: ['APPROVED', 'PENDING']}, + endDate: {[Op.gt]: new Date()} + }, + order: [['createdAt', 'DESC']] + }); + + if (!request) return interaction.editReply({ + content: localize('staff-management-system', 'no-active-status', { + user: user.username, + type + }) + }); + + const embed = new EmbedBuilder() + .setTitle(`${type} Status: ${user.username}`) + .setColor(request.status === 'APPROVED' + ? 'Green' + : 'Yellow' + ) + .addFields( + { + name: localize('staff-management-system', 'label-stat'), + value: request.status, + inline: true + }, + { + name: localize('staff-management-system', 'label-end'), + value: formatDate(request.endDate), + inline: true + }, + { + name: localize('staff-management-system', 'general-rsn'), + value: request.reason || localize('staff-management-system', 'info-none') + }) + .setThumbnail(user.displayAvatarURL({ dynamic: true })); + applyFooter(client, embed); + await interaction.editReply({ embeds: [embed.toJSON()] }); +} + +async function handleStatusList(client, interaction, type, filter) { + const LoaRequest = client.models['staff-management-system']['LoaRequest']; + const now = new Date(); + const cutoff = new Date(); + cutoff.setDate(cutoff.getDate() - 60); + + const whereClause = { type }; + let title = `${type} List`; + + if (filter === 'active') { + whereClause.status = 'APPROVED'; + whereClause.endDate = {[Op.gt]: now}; + title = title + localize('staff-management-system', 'filter-active'); + } else if (filter === 'expired') { + whereClause.status = {[Op.in]: ['APPROVED', 'ENDED']}; + whereClause.endDate = {[Op.between]: [cutoff, now]}; + title = title + localize('staff-management-system', 'filter-expired'); + } else { + whereClause.status = {[Op.in]: ['APPROVED', 'ENDED']}; + whereClause.endDate = {[Op.between]: [cutoff, now]}; + title = title + localize('staff-management-system', 'filter-history'); + } + + const rows = await LoaRequest.findAll({ + where: whereClause, + order: [['endDate', 'DESC']], + limit: 25 + }); + if (rows.length === 0) { + return interaction.editReply({ + content: localize('staff-management-system', 'err-no-recs') + }); + } + + const embed = new EmbedBuilder() + .setTitle(title) + .setColor('Blue') + .setDescription( + rows.map(r => `**<@${r.userId}>** ${r.status === 'APPROVED' ? '✅' : 'âšī¸'}\n` + + `${localize('staff-management-system', 'label-end')}: ${formatDate(r.endDate)}\n` + + `${localize('staff-management-system', 'general-rsn')}: ${r.reason || localize('staff-management-system', 'info-none')}` + ).join('\n\n') + ); + + applyFooter(client, embed); + await interaction.editReply({ embeds: [embed.toJSON()] }); +} + +async function handleStatusManage(client, interaction, targetMember, type) { + const config = getConfig(client, 'status'); + const meta = getStatusMeta(type); + if (!isStatusTypeEnabled(config, type)) return interaction.editReply({ + content: localize('staff-management-system', 'err-status-disabled', {type}) + }); + + const generalConfig = getConfig(client, 'configuration'); + if (!checkStaffPermissions(interaction.member, generalConfig, 'supervisor')) { + return interaction.editReply({ + content: localize('staff-management-system', 'err-gen-no-perm') + }); + } + + const LoaRequest = client.models['staff-management-system']['LoaRequest']; + const activeRequest = await LoaRequest.findOne({ + where: { + userId: targetMember.user.id, + type, + status: {[Op.in]: ['APPROVED', 'PENDING']}, + endDate: {[Op.gt]: new Date()} + }, + order: [['createdAt', 'DESC']] + } + ); + const totalCount = await LoaRequest.count({ + where: {userId: targetMember.user.id, type} + }); + + const embed = applyFooter(client, new EmbedBuilder() + .setTitle(localize('staff-management-system', 'manage-status-title', { + label: meta.label, + username: targetMember.user.username + })) + .setThumbnail(targetMember.user.displayAvatarURL({ dynamic: true })) + .setColor(activeRequest + ? meta.color + : 'Grey' + ) + .setDescription(localize('staff-management-system', 'manage-stat-desc', { + status: activeRequest + ? meta.activeText + : localize('staff-management-system', 'no-act-stat', { + label: meta.label + }), + label: meta.label, + count: Math.max(0, totalCount - (activeRequest ? 1 : 0)) + })) + ); + + embed.addFields({ + name: localize('staff-management-system', 'manage-active-details', {label: meta.label}), + value: activeRequest ? `**${localize('staff-management-system', 'general-start')}:** ${formatDate(activeRequest.startDate)}\n**${localize('staff-management-system', 'general-end')}:** ${formatDate(activeRequest.endDate)}\n**${localize('staff-management-system', 'label-stat')}:** ${activeRequest.status}\n**${localize('staff-management-system', 'label-appr-by')}:** ${activeRequest.approverId ? `<@${activeRequest.approverId}>` : localize('staff-management-system', 'label-auto')}\n**${localize('staff-management-system', 'general-rsn')}:** ${activeRequest.reason || localize('staff-management-system', 'info-none')}` : localize('staff-management-system', 'manage-no-active-user', {label: meta.label}) + }); + + const p = meta.actionPrefix; + const rid = activeRequest?.id ?? 'none'; + const row = new ActionRowBuilder().addComponents( + new ButtonBuilder() + .setCustomId(`staff-mgmt_${p}-end_${rid}`) + .setLabel(localize('staff-management-system', 'btn-end-early', { label: meta.label })) + .setEmoji('đŸšĢ').setStyle(ButtonStyle.Danger) + .setDisabled(!activeRequest), + new ButtonBuilder() + .setCustomId(`staff-mgmt_${p}-extend_${rid}`) + .setLabel(localize('staff-management-system', 'btn-extend', { label: meta.label })) + .setEmoji('âŗ') + .setStyle(ButtonStyle.Primary) + .setDisabled(!activeRequest), + new ButtonBuilder() + .setCustomId(`staff-mgmt_${p}-hist_${targetMember.user.id}_1`) + .setLabel(localize('staff-management-system', 'btn-view-history')) + .setEmoji('📜') + .setStyle(ButtonStyle.Secondary) + .setDisabled(totalCount === 0) + ); + await interaction.editReply({ + embeds: [embed.toJSON()], + components: [row.toJSON()] + }); +} + +async function handleStatusEnd(interaction, type) { + const meta = getStatusMeta(type); + const requestId = interaction.customId.split('_')[2]; + if (requestId === 'none') return interaction.reply({ + content: localize('staff-management-system', 'err-no-active-end', {label: meta.label}), + flags: MessageFlags.Ephemeral + }); + + const modal = new ModalBuilder() + .setCustomId(`staff-mgmt_${meta.actionPrefix}-end-submit_${requestId}`) + .setTitle(localize('staff-management-system', 'modal-end-early-title', { label: meta.label })); + modal.addComponents(new ActionRowBuilder() + .addComponents( + new TextInputBuilder() + .setCustomId('end_reason') + .setLabel(localize('staff-management-system', 'modal-end-early-reason')) + .setStyle(TextInputStyle.Paragraph) + .setRequired(true) + )); + return interaction.showModal(modal); +} + +async function handleStatusEndSubmit(client, interaction, type) { + const generalConfig = getConfig(client, 'configuration'); + if (!checkStaffPermissions(interaction.member, generalConfig, 'supervisor')) { + return interaction.reply({ + content: localize('staff-management-system', 'err-gen-no-perm'), + flags: MessageFlags.Ephemeral + }); + } + await interaction.deferUpdate(); + + const meta = getStatusMeta(type); + const request = await client.models['staff-management-system']['LoaRequest'].findByPk(interaction.customId.split('_')[2]); + if (!request || request.status === 'ENDED' || request.status === 'DENIED') return interaction.reply({ + content: localize('staff-management-system', 'err-stat-inact', {label: meta.label}), + flags: MessageFlags.Ephemeral + }); + + const reason = interaction.fields.getTextInputValue('end_reason'); + const member = await interaction.guild.members.fetch(request.userId).catch(() => null); + + if (member && getConfig(client, 'status')[meta.roleKey]) await member.roles.remove(getConfig(client, 'status')[meta.roleKey]).catch(() => {}); + + await request.update({ status: 'ENDED', endDate: new Date() }); + await client.models['staff-management-system']['StaffProfile'].update({activityStatus: 'ACTIVE'}, { + where: {userId: request.userId} + }); + + if (member) await sendStatusDm(member.user, type, 'ended_early', { + ender: interaction.user.tag, + reason + }); + await logStatusChange(client, type, 'end', { + userId: request.userId, + startDate: request.startDate, + reason: reason, + reqReason: request.reason + }); + + const updatedEmbed = EmbedBuilder.from(interaction.message.embeds[0]) + .setColor('Grey') + .setDescription(localize('staff-management-system', 'status-ended-embed-desc', { + label: meta.label, user: interaction.user.tag, reason + })) + .spliceFields(0, 1, { + name: localize('staff-management-system', 'manage-active-details', {label: meta.label}), + value: localize('staff-management-system', 'manage-no-active-user', {label: meta.label}) + }); + + const p = meta.actionPrefix; + const disabledRow = new ActionRowBuilder() + .addComponents( + new ButtonBuilder() + .setCustomId(`${p}-end-done`) + .setLabel(localize('staff-management-system', 'btn-end-early', { label: meta.label })) + .setEmoji('đŸšĢ') + .setStyle(ButtonStyle.Danger) + .setDisabled(true), + new ButtonBuilder() + .setCustomId(`${p}-extend-done`) + .setLabel(localize('staff-management-system', 'btn-extend', { label: meta.label })) + .setEmoji('âŗ') + .setStyle(ButtonStyle.Primary) + .setDisabled(true), + new ButtonBuilder() + .setCustomId(`staff-mgmt_${p}-hist_${request.userId}_1`) + .setLabel(localize('staff-management-system', 'btn-view-history')) + .setEmoji('📜') + .setStyle(ButtonStyle.Secondary) + ); + return interaction.editReply({ + embeds: [updatedEmbed.toJSON()], + components: [disabledRow.toJSON()] + }); +} + +async function handleStatusExtend(interaction, type) { + const meta = getStatusMeta(type); + const requestId = interaction.customId.split('_')[2]; + if (requestId === 'none') return interaction.reply({ + content: localize('staff-management-system', 'err-no-active-extend', {label: meta.label}), + flags: MessageFlags.Ephemeral + }); + + const modal = new ModalBuilder() + .setCustomId(`staff-mgmt_${meta.actionPrefix}-extend-submit_${requestId}`) + .setTitle(localize('staff-management-system', 'modal-extend-title', { + label: meta.label + })); + modal.addComponents( + new ActionRowBuilder() + .addComponents( + new TextInputBuilder() + .setCustomId('extend_days') + .setLabel(localize('staff-management-system', 'modal-extend-days')) + .setStyle(TextInputStyle.Short) + .setPlaceholder('7') + .setRequired(true) + ), + new ActionRowBuilder() + .addComponents( + new TextInputBuilder() + .setCustomId('extend_reason') + .setLabel(localize('staff-management-system', 'modal-extend-reason')) + .setStyle(TextInputStyle.Paragraph) + .setRequired(true) + ) + ); + return interaction.showModal(modal); +} + +function scheduleStatusExpiry(client, request) { + const jobName = `staff-mgmt-status-expiry-${request.id}`; + const existingJob = schedule.scheduledJobs[jobName]; + if (existingJob) existingJob.cancel(); + + schedule.scheduleJob(jobName, new Date(request.endDate), async () => { + try { + const req = await client.models['staff-management-system']['LoaRequest'].findByPk(request.id); + if (!req || req.status !== 'APPROVED' || new Date(req.endDate) > new Date()) return; + + await req.update({ status: 'ENDED' }); + await client.models['staff-management-system']['StaffProfile'].update( + { activityStatus: 'ACTIVE' }, + { where: { userId: req.userId } } + ); + + const member = await client.guilds.cache.get(client.guildID)?.members.fetch(req.userId).catch(() => null); + if (member) { + const roleKey = req.type === 'LOA' ? 'loaRole' : 'raRole'; + const roleId = getConfig(client, 'status')[roleKey]; + if (roleId) await member.roles.remove(roleId).catch(() => {}); + await sendStatusDm(member.user, req.type, 'ended'); + } + + await logStatusChange(client, req.type, 'end', { + userId: req.userId, + startDate: req.startDate, + reason: localize('staff-management-system', 'status-expired-auto'), + reqReason: req.reason + }); + } catch (e) { + client.logger.error(localize('staff-management-system', 'log-status-expiry-fail', { + error: e.message + })); + } + }); +} + +async function handleStatusExtendSubmit(client, interaction, type) { + const generalConfig = getConfig(client, 'configuration'); + if (!checkStaffPermissions(interaction.member, generalConfig, 'supervisor')) { + return interaction.reply({ + content: localize('staff-management-system', 'err-gen-no-perm'), + flags: MessageFlags.Ephemeral + }); + } + await interaction.deferUpdate(); + + const meta = getStatusMeta(type); + const request = await client.models['staff-management-system']['LoaRequest'].findByPk(interaction.customId.split('_')[2]); + if (!request || request.status === 'ENDED' || request.status === 'DENIED') { + return interaction.reply({ + content: localize('staff-management-system', 'err-stat-inact', { + label: meta.label + }), + flags: MessageFlags.Ephemeral + }); + } + + const days = parseInt(interaction.fields.getTextInputValue('extend_days'), 10); + const reason = interaction.fields.getTextInputValue('extend_reason'); + if (isNaN(days) || days <= 0 || days > 180) return interaction.reply({ + content: localize('staff-management-system', 'err-inv-dur'), + flags: MessageFlags.Ephemeral + }); + + const oldEndDate = new Date(request.endDate); + const newEndDate = new Date(oldEndDate.getTime() + days * 24 * 60 * 60 * 1000); + await request.update({ endDate: newEndDate }); + request.endDate = newEndDate; + scheduleStatusExpiry(client, request); + + const member = await interaction.guild.members.fetch(request.userId).catch(() => null); + if (member) await sendStatusDm(member.user, type, 'extended', { + extender: interaction.user.tag, + days, + endDate: newEndDate, + reason + }); + await logStatusChange(client, type, 'adjusted', { + userId: request.userId, + executorId: interaction.user.id, + changesText: localize('staff-management-system', 'status-adjusted-log', { + label: meta.label, + newEnd: ``, + oldEnd: ``, + reason + }) + }); + + const updatedEmbed = EmbedBuilder.from(interaction.message.embeds[0]) + .spliceFields(0, 1, { + name: localize('staff-management-system', 'manage-active-details', {label: meta.label}), + value: localize('staff-management-system', 'mod-stat-ext', { + s: formatDate(request.startDate), + e: formatDate(newEndDate), + d: days, + t: request.status, + a: request.approverId + ? `<@${request.approverId}>` + : localize('staff-management-system', 'label-auto'), + r: request.reason || localize('staff-management-system', 'info-none') + }) + }); + return interaction.editReply({ + embeds: [updatedEmbed.toJSON()], + components: interaction.message.components.map(c => c.toJSON()) + }); +} + +async function generateStatusHistoryResponse(client, targetUser, page = 1, type) { + const meta = getStatusMeta(type); + const limit = 5; + const offset = (page - 1) * limit; + + const {count, rows} = await client.models['staff-management-system']['LoaRequest'].findAndCountAll({ + where: {userId: targetUser.id, type}, + order: [['createdAt', 'DESC']], + limit, + offset + }); + if (count === 0) return { + content: localize('staff-management-system', 'info-no-status-history', {label: meta.label}), + flags: MessageFlags.Ephemeral + }; + + const totalPages = Math.ceil(count / limit) || 1; + const embed = applyFooter(client, new EmbedBuilder() + .setTitle(`${meta.histTitle} - ${targetUser.username}`) + .setThumbnail(targetUser.displayAvatarURL({ dynamic: true })) + .setColor(meta.color) + .setDescription(localize('staff-management-system', 'status-history-desc', { + count: rows.length, + total: count, + label: meta.label + } + )) + ); + + const statusIcons = { + APPROVED: '✅', + DENIED: '❌', + ENDED: 'âšī¸', + PENDING: '🕐' + }; + rows.forEach((req, index) => embed.addFields({name: `${statusIcons[req.status] ?? '❓'} ${meta.label} #${offset + index + 1} - ${req.status}`, + value: `**${localize('staff-management-system', 'general-start')}:** ${formatDate(req.startDate)}\n**${localize('staff-management-system', 'general-end')}:** ${formatDate(req.endDate)}\n**${localize('staff-management-system', 'label-appr-by')}:** ${req.approverId ? `<@${req.approverId}>` : localize('staff-management-system', 'label-auto')}\n**${localize('staff-management-system', 'general-rsn')}:** ${req.reason || localize('staff-management-system', 'info-none')}` })); + embed.addFields({ + name: '\u200b', + value: localize('staff-management-system', 'page-count', {page, total: totalPages}) + }); + + const row = buildPaginationRow( + `staff-mgmt_${meta.actionPrefix}-hist_${targetUser.id}_${page - 1}`, + `${meta.actionPrefix}_hist_page_count`, + `staff-mgmt_${meta.actionPrefix}-hist_${targetUser.id}_${page + 1}`, + page, + totalPages + ); + return { + embeds: [embed.toJSON()], + components: [row.toJSON()] + }; +} + +async function handleStatusHistPage(client, interaction, type) { + const parts = interaction.customId.split('_'); + const targetUser = await client.users.fetch(parts[2]).catch(() => null); + if (!targetUser) return interaction.reply({ + content: localize('staff-management-system', 'err-gen-no-user'), + flags: MessageFlags.Ephemeral + }); + + const payload = await generateStatusHistoryResponse(client, targetUser, parseInt(parts[3], 10), type); + if (payload.content) return interaction.reply({ + ...payload, + flags: MessageFlags.Ephemeral + }); + return interaction.message?.embeds?.[0]?.title?.startsWith(getStatusMeta(type).histTitle) + ? interaction.update(payload) + : interaction.reply({ ...payload, flags: MessageFlags.Ephemeral }); +} + + +module.exports = { + sendStatusDm, + isStatusTypeEnabled, + logStatusChange, + getStatusMeta, + handleStatusRequest, + handleStatusView, + handleStatusList, + handleStatusManage, + handleStatusEnd, + handleStatusEndSubmit, + handleStatusExtend, + scheduleStatusExpiry, + handleStatusExtendSubmit, + generateStatusHistoryResponse, + handleStatusHistPage +}; diff --git a/modules/staff-management-system/events/botReady.js b/modules/staff-management-system/events/botReady.js index 4b0747ae..157924bc 100644 --- a/modules/staff-management-system/events/botReady.js +++ b/modules/staff-management-system/events/botReady.js @@ -1,8 +1,8 @@ const schedule = require('node-schedule'); const { localize } = require('../../../src/functions/localize'); const { Op } = require('sequelize'); -const {scheduleStatusExpiry} = require('../commands/staff-status.js'); -const { initActivityCheckAutomation } = require('../staff-management'); +const {scheduleStatusExpiry} = require('../core/staffStatus'); +const { initActivityCheckAutomation } = require('../core/activityChecks'); const suspension_check_job = 'staff-management-checks'; module.exports.run = async (client) => { diff --git a/modules/staff-management-system/events/interactionCreate.js b/modules/staff-management-system/events/interactionCreate.js index 4febea1c..97a00f0f 100644 --- a/modules/staff-management-system/events/interactionCreate.js +++ b/modules/staff-management-system/events/interactionCreate.js @@ -1,10 +1,12 @@ const { getConfig, checkStaffPermissions, - applyFooter, - generateReviewHistoryResponse, - generatePromotionHistoryResponse, - generateInfractionHistoryResponse, + applyFooter +} = require('../core/localHelpers'); +const { generateReviewHistoryResponse } = require('../core/reviews'); +const { generatePromotionHistoryResponse } = require('../core/promotions'); +const { generateInfractionHistoryResponse } = require('../core/infractions'); +const { generateUserPanel, generatePanelInfractions, generatePanelPromotions, @@ -15,7 +17,7 @@ const { generatePanelDeletion, executeDataDeletion, generatePanelSubpage -} = require('../staff-management'); +} = require('../core/panels'); const { handleStatusEnd, scheduleStatusExpiry, @@ -25,9 +27,9 @@ const { handleStatusHistPage, sendStatusDm, logStatusChange -} = require('../commands/staff-status.js'); +} = require('../core/staffStatus'); const { localize } = require('../../../src/functions/localize'); -const dutyHandlers = require('../commands/duty.js').buttonHandlers; +const { buttonHandlers: dutyHandlers } = require('../core/duty'); const { ActionRowBuilder, ButtonBuilder, ButtonStyle, ComponentType, EmbedBuilder, MessageFlags, ModalBuilder, TextInputBuilder, TextInputStyle } = require('discord.js'); module.exports.run = async (client, interaction) => { diff --git a/modules/staff-management-system/module.json b/modules/staff-management-system/module.json index 773125bd..621d3cfd 100644 --- a/modules/staff-management-system/module.json +++ b/modules/staff-management-system/module.json @@ -24,7 +24,7 @@ "administration" ], "humanReadableName": "Staff Management System", - "description": "A powerful, highly customizable staff management system designed to track activity, moderate personnel, and maintain detailed staff records seamlessly.", + "description": "The all-in-one tool to manage your staff - track duty shifts, staff activity, handle leave requests, receive reviews, promote and discipline your staff and protect your server against staff misuse.", "intents": [ "GuildMembers", "GuildPresences" diff --git a/modules/staff-management-system/staff-management.js b/modules/staff-management-system/staff-management.js deleted file mode 100644 index 18483c53..00000000 --- a/modules/staff-management-system/staff-management.js +++ /dev/null @@ -1,1774 +0,0 @@ -/** - * Logic for the Staff Management module - * @module staff-management - * @author itskevinnn - */ -const { ModalBuilder, TextInputBuilder, TextInputStyle, EmbedBuilder, StringSelectMenuBuilder, StringSelectMenuOptionBuilder, ActionRowBuilder, ButtonBuilder, ButtonStyle, MessageFlags } = require('discord.js'); -const { Op } = require('sequelize'); -const schedule = require('node-schedule'); -const {embedTypeV2, safeSetFooter, dateToDiscordTimestamp} = require('../../src/functions/helpers'); -const { localize } = require('../../src/functions/localize'); - -// --- Local helpers --- -const getConfig = (client, file) => client.configurations['staff-management-system'][file]; -const getSafeChannelId = (val) => Array.isArray(val) && val.length > 0 // Helper to get safe channel ID from config - ? val[0] - : (typeof val === 'string' - ? val - : null -); -const parseDurationToDays = (input) => { - if (!input) return null; - const match = input.toString().match(/^(\d+)([dDwWmM])?$/); - if (!match) return null; - const value = parseInt(match[1], 10); - const unit = match[2]?.toLowerCase() || 'd'; - return unit === 'm' - ? value * 30 - : (unit === 'w' - ? value * 7 - : value - ); -}; - -const applyFooter = (client, embed) => { - safeSetFooter(embed, client); - if (!(client.strings && client.strings.disableFooterTimestamp)) { - embed.setTimestamp(); - } - return embed; -}; - -const formatRoleMentions = (roles) => { - const roleIds = Array.isArray(roles) - ? roles - : (roles ? [roles] : []); - - return roleIds.map(roleId => `<@&${roleId}>`).join(' '); -}; - -function checkStaffPermissions(member, config, level = 'staff') { - if (!member) return false; - if (member.permissions?.has('Administrator')) return true; - - const roleMap = { - staff: [ - ...(config?.staffRoles || []), - ...(config?.supervisorRoles || []), - ...(config?.managementRoles || []) - ], - supervisor: [ - ...(config?.supervisorRoles || []), - ...(config?.managementRoles || []) - ], - management: [ - ...(config?.managementRoles || []) - ] - }; - - const allowedRoles = roleMap[level] || roleMap.staff; - return member.roles?.cache?.some(role => allowedRoles.includes(role.id)) || false; -} - -const buildPaginationRow = (backId, countId, nextId, page, totalPages) => { - return new ActionRowBuilder().addComponents( - new ButtonBuilder() - .setCustomId(backId) - .setLabel(localize('helpers', 'back')) - .setStyle(ButtonStyle.Primary) - .setDisabled(page <= 1), - new ButtonBuilder() - .setCustomId(countId) - .setLabel(`${page}/${totalPages}`) - .setStyle(ButtonStyle.Secondary) - .setDisabled(true), - new ButtonBuilder() - .setCustomId(nextId) - .setLabel(localize('helpers', 'next')) - .setStyle(ButtonStyle.Primary) - .setDisabled(page >= totalPages) - ); -}; - -function formatDuration(seconds) { - if (!seconds || seconds <= 0) return localize('staff-management-system', 'time-zero'); - const h = Math.floor(seconds / 3600); - const m = Math.floor((seconds % 3600) / 60); - const s = seconds % 60; - const parts = []; - if (h > 0) parts.push(`${h} ${localize('staff-management-system', h !== 1 - ? 'time-hours' - : 'time-hour' - )}`); - if (m > 0) parts.push(`${m} ${localize('staff-management-system', m !== 1 - ? 'time-mins' - : 'time-min' - )}`); - if (s > 0) parts.push(`${s} ${localize('staff-management-system', s !== 1 - ? 'time-secs' - : 'time-sec' - )}`); - return parts.join(', ') || localize('staff-management-system', 'time-zero'); -} - -// ---------- Infractions ---------- -async function issueInfraction(client, interaction, targetMember, type, reason, expiryInput) { - await interaction.deferReply({ephemeral: true}); - const config = getConfig(client, 'infractions'); - if (!config?.enableInfractions) return interaction.editReply({ - content: localize('staff-management-system', 'err-feat-disabled', {feature: 'Infractions'}) - }); - - const generalConfig = getConfig(client, 'configuration'); - const canInfract = checkStaffPermissions(interaction.member, generalConfig, 'supervisor'); - if (!canInfract) return interaction.editReply({ - content: localize('staff-management-system', 'err-gen-no-perm') - }); - - if (targetMember.id === interaction.user.id) { - return interaction.editReply({ - content: localize('staff-management-system', 'err-self-infract') - }); - } - - if (type.toLowerCase() === 'suspension') { - return interaction.editReply({ - content: localize('staff-management-system', 'err-use-susp') - }); - } - - let expiresAt = null; - if (expiryInput) { - const days = parseDurationToDays(expiryInput); - if (!days) return interaction.editReply({ - content: localize('staff-management-system', 'err-inv-dur') - }); - expiresAt = new Date(Date.now() + days * 24 * 60 * 60 * 1000); - } - - const record = await client.models['staff-management-system']['Infraction'].create({ - userId: targetMember.id, - issuerId: interaction.user.id, - type, reason, expiresAt, - active: true - }); - - const placeholders = { - '%user%': targetMember.user.toString(), - '%user-avatar%': targetMember.user.displayAvatarURL({ - dynamic: true, - format: 'png', - size: 1024 - }) || '', - '%issuer-mention%': interaction.user.toString(), - '%issuer-name%': interaction.user.username, - '%issuer-avatar%': interaction.user.displayAvatarURL({ - dynamic: true, - format: 'png', - size: 1024 - }) || '', - '%type%': type, - '%reason%': reason, - '%case-id%': record.caseId.toString(), - '%end-date%': expiresAt - ? dateToDiscordTimestamp(expiresAt, 'F') - : localize('staff-management-system', 'label-never') - }; - - const channelId = getSafeChannelId(config.infractionLogChannel); - if (channelId) { - const channel = await interaction.guild.channels.fetch(channelId).catch(() => null); - if (channel) { - let template = config.infractionMessage; - - if (template && template.embeds && !template._schema) template._schema = 'v3'; - let msgOpts = await embedTypeV2(template, placeholders); - if (msgOpts?.content?.trim() === '') delete msgOpts.content; - - if (msgOpts?.embeds?.length > 0) { - const parsedEmbed = EmbedBuilder.from(msgOpts.embeds[0]); - applyFooter(client, parsedEmbed); - msgOpts.embeds[0] = parsedEmbed.toJSON(); - } - - const sentMsg = await channel.send(msgOpts).catch(()=>{}); - if (sentMsg) await record.update({ messageUrl: sentMsg.url }); - } - } - - if (config.dmInfractedUser && config.infractionDmMessage) { - let dmTemplate = config.infractionDmMessage; - if (dmTemplate && dmTemplate.embeds && !dmTemplate._schema) dmTemplate._schema = 'v3'; - const dmOpts = await embedTypeV2(dmTemplate, placeholders); - if (dmOpts?.content?.trim() === '') delete dmOpts.content; - - if (dmOpts) { - try { - await targetMember.user.send(dmOpts); - } catch (e) { - client.logger.warn(localize('staff-management-system', 'log-infract-dm-fail', { - user: targetMember.user.tag, - error: e.message - })); - } - } - } - - await interaction.editReply({ - content: localize('staff-management-system', 'succ-infract', { - type, - caseId: record.caseId, - user: targetMember.user.tag - }) - }); -} - -// ---------- Suspensions ---------- -async function issueSuspension(client, interaction, targetMember, durationInput, reason) { - await interaction.deferReply({ephemeral: true}); - const config = getConfig(client, 'infractions'); - if (!config?.enableInfractions) - return interaction.editReply({ - content: localize('staff-management-system', 'err-feat-disabled', { - feature: 'Infractions' - }) - }); - - if (!config?.enableSuspensions) - return interaction.editReply({ - content: localize('staff-management-system', 'err-feat-disabled', { - feature: 'Suspensions' - }) - }); - - const generalConfig = getConfig(client, 'configuration'); - const canSuspend = checkStaffPermissions(interaction.member, generalConfig, 'supervisor'); - if (!canSuspend) return interaction.editReply({ - content: localize('staff-management-system', 'err-gen-no-perm') - }); - - if (targetMember.id === interaction.user.id) { - return interaction.editReply({ - content: localize('staff-management-system', 'err-self-infract') - }); - } - - const durationDays = parseDurationToDays(durationInput); - if (!durationDays) - return interaction.editReply({ - content: localize('staff-management-system', 'err-inv-dur') - }); - - const expiresAt = new Date(Date.now() + durationDays * 24 * 60 * 60 * 1000); - const durationString = `${durationDays} ${localize('staff-management-system', 'label-days')}`; - - let rolesToRemove = []; - const hierarchyRole = interaction.guild.roles.cache.get(config.suspensionHierarchyRole); - if (hierarchyRole) { - rolesToRemove = targetMember.roles.cache - .filter(r => r.position >= hierarchyRole.position && r.id !== interaction.guild.id && !r.managed) - .map(r => r.id); - - if (rolesToRemove.length) { - await targetMember.roles.remove(rolesToRemove).catch(() => {}); - } - } - - await client.models['staff-management-system']['StaffProfile'].upsert({ - userId: targetMember.id, - isSuspended: true, - suspendedRoles: JSON.stringify(rolesToRemove) - }); - if (config.suspensionRole) await targetMember.roles.add(config.suspensionRole).catch(() => {}); - - const record = await client.models['staff-management-system']['Infraction'].create({ - userId: targetMember.id, - issuerId: interaction.user.id, - type: 'Suspension', - reason, durationDays, expiresAt, - active: true - }); - - const placeholders = { - '%user%': targetMember.user.toString(), - '%user-avatar%': targetMember.user.displayAvatarURL({ - dynamic: true, - format: 'png', - size: 1024 - }) || '', - '%issuer-mention%': interaction.user.toString(), - '%issuer-name%': interaction.user.username, - '%issuer-avatar%': interaction.user.displayAvatarURL({ - dynamic: true, - format: 'png', - size: 1024 - }) || '', - '%duration%': durationString, - '%reason%': reason, - '%case-id%': record.caseId.toString(), - '%end-date%': dateToDiscordTimestamp(expiresAt, 'F') - }; - - const channelId = getSafeChannelId(config.infractionLogChannel); - if (channelId) { - const channel = await interaction.guild.channels.fetch(channelId).catch(() => null); - if (channel) { - let template = config.suspensionMessage; - - if (template && template.embeds && !template._schema) template._schema = 'v3'; - let msgOpts = await embedTypeV2(template, placeholders); - if (msgOpts?.content?.trim() === '') delete msgOpts.content; - - if (msgOpts?.embeds?.length > 0) { - const parsedEmbed = EmbedBuilder.from(msgOpts.embeds[0]); - applyFooter(client, parsedEmbed); - msgOpts.embeds[0] = parsedEmbed.toJSON(); - } - - const sentMsg = await channel.send(msgOpts).catch(()=>{}); - if (sentMsg) await record.update({ messageUrl: sentMsg.url }); - } - } - - if (config.dmInfractedUser && config.suspensionDmMessage) { - let dmTemplate = config.suspensionDmMessage; - - if (dmTemplate && dmTemplate.embeds && !dmTemplate._schema) dmTemplate._schema = 'v3'; - const dmOpts = await embedTypeV2(dmTemplate, placeholders); - if (dmOpts?.content?.trim() === '') delete dmOpts.content; - - if (dmOpts) { - try { - await targetMember.user.send(dmOpts); - } catch (e) { - client.logger.warn(localize('staff-management-system', 'log-susp-dm-fail', { - user: targetMember.user.tag, - error: e.message - })); - } - } - } - - await interaction.editReply({ - content: localize('staff-management-system', 'succ-susp', { - caseId: record.caseId, - user: targetMember.user.tag, - duration: durationString - }) - }); -} - -async function resolveInfractionReference(client, reference) { - const Infraction = client.models['staff-management-system']['Infraction']; - const value = reference?.trim(); - - if (!value) return null; - - if (/^\d+$/.test(value)) { - return await Infraction.findByPk(parseInt(value, 10)); - } - - try { - const parsed = new URL(value); - const validHosts = ['discord.com', 'canary.discord.com', 'ptb.discord.com']; - - if (!validHosts.includes(parsed.hostname)) return null; - - const parts = parsed.pathname.split('/').filter(Boolean); - if (parts.length !== 4 || parts[0] !== 'channels') return null; - - return await Infraction.findOne({ - where: {messageUrl: value} - }); - } catch (e) { - return null; - } -} - -// ----- Infractions voiding ----- -async function voidInfraction(client, interaction, reference) { - await interaction.deferReply({ephemeral: true}); - const config = getConfig(client, 'infractions'); - if (!config?.enableInfractions) return interaction.editReply({ - content: localize('staff-management-system', 'err-feat-disabled', { - feature: 'Infractions' - }) - }); - - const canManage = checkStaffPermissions(interaction.member, getConfig(client, 'configuration'), 'supervisor'); - if (!canManage) return interaction.editReply({ - content: localize('staff-management-system', 'err-gen-no-perm') - }); - - const record = await resolveInfractionReference(client, reference); - if (!record) { - return interaction.editReply({ - content: localize('staff-management-system', 'err-no-case-ref', {reference}) - }); - } - if (!record.active) { - return interaction.editReply({ - content: localize('staff-management-system', 'err-case-inact', {caseId: record.caseId}) - }); - } - - if (record.type.toLowerCase() === 'suspension') { - const Profile = client.models['staff-management-system']['StaffProfile']; - const profile = await Profile.findOne({ - where: {userId: record.userId} - }); - const member = await interaction.guild.members.fetch(record.userId).catch(() => null); - - if (member && profile && profile.isSuspended) { - try { - const rolesToRestore = JSON.parse(profile.suspendedRoles || '[]'); - if (rolesToRestore.length > 0) await member.roles.add(rolesToRestore); - if (config.suspensionRole) await member.roles.remove(config.suspensionRole); - await profile.update({ isSuspended: false, suspendedRoles: JSON.stringify([]) }); - } catch (e) { - return interaction.editReply({ - content: localize('staff-management-system', 'succ-void-fail', {caseId: record.caseId}) - }); - } - } - } - await record.update({active: false}); - await interaction.editReply({ - content: localize('staff-management-system', 'succ-void', {caseId: record.caseId}) - }); -} - -// ----- Generates infractions history embed ----- -async function generateInfractionHistoryResponse(client, targetUser, page = 1) { - const limit = 5; - const offset = (page - 1) * limit; - const {count, rows} = await client.models['staff-management-system']['Infraction'].findAndCountAll({ - where: {userId: targetUser.id}, - order: [['createdAt', 'DESC']], - limit, offset - }); - - if (count === 0) - return { - content: localize('staff-management-system', 'info-clean-rec', { - username: targetUser.username - }), - flags: MessageFlags.Ephemeral - }; - - const totalPages = Math.ceil(count / limit) || 1; - const embed = applyFooter(client, new EmbedBuilder() - .setTitle(localize('staff-management-system', 'rec-title', { username: targetUser.username })) - .setThumbnail(targetUser.displayAvatarURL({ dynamic: true })) - .setColor('Red') - ); - - const desc = rows.map(r => { - const link = r.messageUrl - ? ` â€ĸ [Jump](${r.messageUrl})` - : ''; - const statusIcon = r.active - ? '🔴' - : localize('staff-management-system', 'icon-voided'); - const expiry = r.expiresAt - ? `\n**${localize('staff-management-system', 'label-exp')}:** ${dateToDiscordTimestamp(r.expiresAt, 'R')}` - : ''; - - return `**${statusIcon} ${localize('staff-management-system', 'label-case')} #${r.caseId} - ${r.type}**\n**${localize('staff-management-system', 'label-date')}:** ${dateToDiscordTimestamp(r.createdAt, 'f')}\n**${localize('staff-management-system', 'label-iss')}:** <@${r.issuerId}>\n**${localize('staff-management-system', 'general-rsn')}:** ${r.reason}${expiry}${link}`; - }).join('\n\n'); - - embed.setDescription(desc); - embed.addFields({ - name: '\u200b', value: localize('staff-management-system', 'page-count', { - page, - total: totalPages - }) }); - - const row = buildPaginationRow( - `staff-mgmt_inf-hist_${targetUser.id}_${page - 1}`, - 'inf_hist_count', - `staff-mgmt_inf-hist_${targetUser.id}_${page + 1}`, - page, totalPages - ); - - return { embeds: [embed.toJSON()], components: [row.toJSON()] }; -} - -// ----- Gets infraction history ----- -async function getInfractionHistory(client, interaction, targetUser) { - await interaction.deferReply({ephemeral: true}); - const response = await generateInfractionHistoryResponse(client, targetUser, 1); - if (response.content && response.content.startsWith('â„šī¸')) return interaction.editReply(response); - await interaction.editReply({ - ...response - }); -} - -// ---------- Promotions ---------- -async function promoteUser(client, interaction, targetMember, newRole, reason) { - await interaction.deferReply({ephemeral: true}); - const config = getConfig(client, 'promotions'); - if (!config?.enablePromotions) return interaction.editReply({ - content: localize('staff-management-system', 'err-feat-disabled', {feature: 'Promotions'}) - }); - - const generalConfig = getConfig(client, 'configuration'); - const canPromote = checkStaffPermissions(interaction.member, generalConfig, 'supervisor'); - if (!canPromote) return interaction.editReply({ - content: localize('staff-management-system', 'err-gen-no-perm') - }); - - if (targetMember.id === interaction.user.id) { - return interaction.editReply({ - content: localize('staff-management-system', 'err-self-promo') - }); - } - - const finalReason = reason && reason.trim() !== '' - ? reason - : localize('staff-management-system', 'none-provided'); - const channelOverride = interaction.options.getChannel('channel'); - - if (config.autoAddRole) { - if (interaction.guild.members.me.roles.highest.position <= newRole.position) { - return interaction.editReply({ - content: localize('staff-management-system', 'err-role-hier') - }); - } - try { - await targetMember.roles.add(newRole); - } catch (e) { - return interaction.editReply({ - content: localize('staff-management-system', 'err-add-role', {e: e.message}) - }); } - } - - const record = await client.models['staff-management-system']['Promotion'].create({ - userId: targetMember.id, - issuerId: interaction.user.id, - newRole: newRole.id, - reason: finalReason - }); - - const placeholders = { - '%user-mention%': targetMember.user.toString(), - '%new-role-name%': newRole.name, - '%new-role-mention%': newRole.toString(), - '%promoter-mention%': interaction.user.toString(), - '%promoter-name%': interaction.user.username, - '%reason%': finalReason, - '%user-avatar%': targetMember.user.displayAvatarURL({ - dynamic: true, - format: 'png', - size: 1024 - }) || '', - '%promoter-avatar%': interaction.user.displayAvatarURL({ - dynamic: true, - format: 'png', - size: 1024 - }) || '' - }; - - const targetChannelId = channelOverride - ? channelOverride.id - : getSafeChannelId(config.promotionsChannel); - - if (targetChannelId) { - const channel = await interaction.guild.channels.fetch(targetChannelId).catch(() => null); - if (channel) { - let embedTemplate = config.promotionMessage; - if (typeof embedTemplate === 'string') { - try { - embedTemplate = JSON.parse(embedTemplate); - } catch (e) { - } - } else if (typeof embedTemplate === 'object') { - embedTemplate = JSON.parse(JSON.stringify(embedTemplate)); - } - - if (embedTemplate && embedTemplate.embeds && !embedTemplate._schema) embedTemplate._schema = 'v3'; - let msgOpts = await embedTypeV2(embedTemplate, placeholders); - if (msgOpts?.content?.trim() === '') delete msgOpts.content; - - if (msgOpts.embeds && msgOpts.embeds.length > 0) { - const parsedEmbed = EmbedBuilder.from(msgOpts.embeds[0]); - applyFooter(client, parsedEmbed); - msgOpts.embeds[0] = parsedEmbed.toJSON(); - } - - const sentMessage = await channel - .send(msgOpts) - .catch(e => { - client.logger.error(localize('staff-management-system', 'log-promo-msg-error', { - e: e.message, - })); - return null; - }); - - if (sentMessage) await record.update({messageUrl: sentMessage.url}); - } - } - - if (config.dmPromotedUser && config.promotionDmMessage) { - let dmTemplate = config.promotionDmMessage; - - if (dmTemplate && dmTemplate.embeds && !dmTemplate._schema) dmTemplate._schema = 'v3'; - const dmOpts = await embedTypeV2(dmTemplate, placeholders); - if (dmOpts?.content?.trim() === '') delete dmOpts.content; - - if (dmOpts) { - try { - await targetMember.user.send(dmOpts); - } catch (e) { - client.logger.warn(localize('staff-management-system', 'log-promo-dm-fail', { - user: targetMember.user.tag, - error: e.message - })); - } - } - } - - await interaction.editReply({ - content: localize('staff-management-system', 'succ-promo', { - user: targetMember.user.tag, - role: newRole.name - }) - }); -} - -// ----- Generates promotion history & embed ----- -async function generatePromotionHistoryResponse(client, targetUser, page = 1) { - const Promotion = client.models['staff-management-system']['Promotion']; - const limit = 5; - const offset = (page - 1) * limit; - - const {count, rows} = await Promotion.findAndCountAll({ - where: { - userId: targetUser.id - }, - order: [['createdAt', 'DESC']], - limit, - offset - }); - if (count === 0) return { - content: localize('staff-management-system', 'info-no-promo', {username: targetUser.username}), - flags: MessageFlags.Ephemeral - }; - - const totalPages = Math.ceil(count / limit) || 1; - const embed = applyFooter(client, new EmbedBuilder() - .setTitle(localize('staff-management-system', 'prom-hist-title', { username: targetUser.username })) - .setThumbnail(targetUser.displayAvatarURL({ dynamic: true })) - .setColor('Gold') - ); - - const desc = rows.map((r, i) => { - const link = r.messageUrl ? ` â€ĸ [Jump](${r.messageUrl})` : ''; - return `**${offset + i + 1}. ${dateToDiscordTimestamp(r.createdAt, 'F')}**\n**${localize('staff-management-system', 'label-role')}:** <@&${r.newRole}>\n**${localize('staff-management-system', 'label-prom-by')}:** <@${r.issuerId}>\n**${localize('staff-management-system', 'general-rsn')}:** ${r.reason}${link}`; - }).join('\n\n'); - - embed.setDescription(desc); - embed.addFields({ name: '\u200b', value: localize('staff-management-system', 'page-count', { page, total: totalPages }) }); - - const row = buildPaginationRow( - `staff-mgmt_prom-hist_${targetUser.id}_${page - 1}`, - 'prom_hist_count', - `staff-mgmt_prom-hist_${targetUser.id}_${page + 1}`, - page, totalPages - ); - - return { - embeds: [embed.toJSON()], - components: [row.toJSON()] - }; -} - -async function getPromotionHistory(client, interaction, targetUser) { - await interaction.deferReply({ephemeral: true}); - const response = await generatePromotionHistoryResponse(client, targetUser, 1); - if (response.content && response.content.startsWith('â„šī¸')) return interaction.editReply(response); - - await interaction.editReply({ - ...response - }); -} - -// ---------- User Panel ---------- -async function generatePanelSubpage(client, targetUser, type, page) { - if (type === 'infractions') return await generatePanelInfractions(client, targetUser, page); - if (type === 'promotions') return await generatePanelPromotions(client, targetUser, page); - if (type === 'reviews') return await generatePanelReviews(client, targetUser, page); - if (type === 'status') return await generatePanelStatus(client, targetUser, page); - if (type === 'activity') return await generatePanelActivity(client, targetUser, page); - return null; -} - -// Overview page -async function generateUserPanel(client, targetUser) { - const embed = applyFooter(client, new EmbedBuilder() - .setTitle(localize('staff-management-system', 'panel-title', { - username: targetUser.username - })) - .setDescription(localize('staff-management-system', 'panel-desc', { - mention: targetUser.toString(), - id: targetUser.id - })) - .setThumbnail(targetUser.displayAvatarURL({ dynamic: true })) - .setColor('Blurple') - ); - - const menu = new StringSelectMenuBuilder() - .setCustomId(`staff-mgmt_panel-menu_${targetUser.id}`) - .setPlaceholder(localize('staff-management-system', 'panel-ph')) - .addOptions( - new StringSelectMenuOptionBuilder() - .setLabel(localize('staff-management-system', 'opt-over')) - .setValue('overview') - .setEmoji('🏠'), - new StringSelectMenuOptionBuilder() - .setLabel(localize('staff-management-system', 'opt-act')) - .setValue('activity') - .setEmoji('📋'), - new StringSelectMenuOptionBuilder() - .setLabel(localize('staff-management-system', 'opt-inf')) - .setValue('infractions') - .setEmoji('âš ī¸'), - new StringSelectMenuOptionBuilder() - .setLabel(localize('staff-management-system', 'opt-prom')) - .setValue('promotions') - .setEmoji('🎉'), - new StringSelectMenuOptionBuilder() - .setLabel(localize('staff-management-system', 'opt-rev')) - .setValue('reviews') - .setEmoji('⭐'), - new StringSelectMenuOptionBuilder() - .setLabel(localize('staff-management-system', 'opt-shi')) - .setValue('shifts') - .setEmoji('âąī¸'), - new StringSelectMenuOptionBuilder() - .setLabel(localize('staff-management-system', 'opt-sta')) - .setValue('status') - .setEmoji('🌙'), - new StringSelectMenuOptionBuilder() - .setLabel(localize('staff-management-system', 'opt-del')) - .setValue('deletion') - .setEmoji('đŸ—‘ī¸') - ); - - const row = new ActionRowBuilder().addComponents(menu); - return { - embeds: [embed.toJSON()], - components: [row.toJSON()] - }; -} - -// Infractions page -async function generatePanelInfractions(client, targetUser, page = 1) { - const Infraction = client.models['staff-management-system']['Infraction']; - const allInfractions = await Infraction.findAll({ - where: {userId: targetUser.id} - }); - const count = allInfractions.length; - - let totalPages = 1; - if (count > 3) totalPages = 1 + Math.ceil((count - 3) / 5); - - const limit = page === 1 ? 3 : 5; - const offset = page === 1 ? 0 : 3 + ((page - 2) * 5); - - const typeCounts = {}; - allInfractions.forEach(inf => { typeCounts[inf.type] = (typeCounts[inf.type] || 0) + 1; }); - const typeStrings = Object.entries(typeCounts).map(([type, qty]) => `${type}: **${qty}**`).join('\n'); - - const embed = applyFooter(client, new EmbedBuilder() - .setTitle(localize('staff-management-system', 'p-inf-title', { username: targetUser.username })) - .setColor('Red') - .setThumbnail(targetUser.displayAvatarURL({ dynamic: true })) - ); - - let desc = localize('staff-management-system', 'p-inf-desc', { - count: count, types: typeStrings || localize('staff-management-system', 'info-none') - }); - - const rows = await Infraction.findAll({ - where: {userId: targetUser.id}, - order: [['createdAt', 'DESC']], - limit, - offset - }); - - if (rows.length === 0) { - desc += localize('staff-management-system', 'p-no-hist'); - } else { - desc += rows.map(r => { - const statusIcon = r.active ? '🔴' : localize('staff-management-system', 'icon-voided'); - const expiry = r.expiresAt ? `\n**${localize('staff-management-system', 'label-exp')}:** ${dateToDiscordTimestamp(r.expiresAt, 'R')}` : ''; - return `**${statusIcon} ${localize('staff-management-system', 'label-case')} #${r.caseId} - ${r.type}**\n**${localize('staff-management-system', 'label-date')}:** ${dateToDiscordTimestamp(r.createdAt, 'f')}\n**${localize('staff-management-system', 'general-rsn')}:** ${r.reason}${expiry}`; - }).join('\n\n'); - } - - embed.setDescription(desc); - embed.addFields({ name: '\u200b', value: localize('staff-management-system', 'page-count', { page, total: totalPages }) }); - - const menu = ActionRowBuilder.from((await generateUserPanel(client, targetUser)).components[0]); - menu.components[0].options.find(opt => opt.data.value === 'infractions').data.default = true; - - const paginationRow = buildPaginationRow( - `staff-mgmt_panel-inf_${targetUser.id}_${page - 1}`, - 'panel_inf_count', - `staff-mgmt_panel-inf_${targetUser.id}_${page + 1}`, - page, totalPages - ); - - return { - embeds: [embed.toJSON()], - components: [menu.toJSON(), paginationRow.toJSON()] - }; -} - -// Promotions page -async function generatePanelPromotions(client, targetUser, page = 1) { - const Promotion = client.models['staff-management-system']['Promotion']; - const count = await Promotion.count({ - where: {userId: targetUser.id} - }); - - let totalPages = 1; - if (count > 3) totalPages = 1 + Math.ceil((count - 3) / 5); - - const limit = page === 1 - ? 3 - : 5; - const offset = page === 1 - ? 0 - : 3 + ((page - 2) * 5); - - const embed = applyFooter(client, new EmbedBuilder() - .setTitle(localize('staff-management-system', 'p-prom-title', { - username: targetUser.username - })) - .setColor('Gold') - .setThumbnail(targetUser.displayAvatarURL({ dynamic: true })) - ); - - let desc = localize('staff-management-system', 'p-prom-desc', { count: count }); - const rows = await Promotion.findAll({ - where: {userId: targetUser.id}, - order: [['createdAt', 'DESC']], - limit, - offset - }); - - if (rows.length === 0) { - desc += localize('staff-management-system', 'p-no-hist'); - } else { - desc += rows.map(r => `**${localize('staff-management-system', 'label-role')}:** <@&${r.newRole}>\n**${localize('staff-management-system', 'label-prom-by')}:** <@${r.issuerId}>\n**${localize('staff-management-system', 'label-date')}:** ${dateToDiscordTimestamp(r.createdAt, 'R')}\n**${localize('staff-management-system', 'general-rsn')}:** ${r.reason}`).join('\n\n'); - } - - embed.setDescription(desc); - embed.addFields({ name: '\u200b', value: localize('staff-management-system', 'page-count', { page, total: totalPages }) }); - - const menu = ActionRowBuilder.from((await generateUserPanel(client, targetUser)).components[0]); - menu.components[0].options.find(opt => opt.data.value === 'promotions').data.default = true; - - const paginationRow = buildPaginationRow( - `staff-mgmt_panel-prom_${targetUser.id}_${page - 1}`, - 'panel_prom_count', - `staff-mgmt_panel-prom_${targetUser.id}_${page + 1}`, - page, totalPages - ); - - return { - embeds: [embed.toJSON()], - components: [menu.toJSON(), paginationRow.toJSON()] - }; -} - -// Reviews page -async function generatePanelReviews(client, targetUser, page = 1) { - const Review = client.models['staff-management-system']['StaffReview']; - const allReviews = await Review.findAll({ - where: {targetId: targetUser.id} - }); - const count = allReviews.length; - - let totalPages = 1; - if (count > 3) totalPages = 1 + Math.ceil((count - 3) / 5); - - const limit = page === 1 ? 3 : 5; - const offset = page === 1 ? 0 : 3 + ((page - 2) * 5); - - const avg = count - ? (allReviews.reduce((a, b) => a + b.stars, 0) / count).toFixed(1) - : 0; - - const embed = applyFooter(client, new EmbedBuilder() - .setTitle(localize('staff-management-system', 'p-rev-title', { - username: targetUser.username - })) - .setColor('Gold') - .setThumbnail(targetUser.displayAvatarURL({ dynamic: true })) - ); - - let desc = localize('staff-management-system', 'p-rev-desc', { count: count, avg: avg }); - - const rows = await Review.findAll({ - where: {targetId: targetUser.id}, - order: [['createdAt', 'DESC']], - limit, - offset - }); - if (rows.length === 0) desc += localize('staff-management-system', 'p-no-hist'); - else desc += rows.map(r => `**${"⭐".repeat(r.stars)}** ${localize('staff-management-system', 'label-by')} <@${r.authorId}>\n"${r.comment}"`).join('\n\n'); - - embed.setDescription(desc); - embed.addFields({ - name: '\u200b', - value: localize('staff-management-system', 'page-count', { - page, total: totalPages - }) - }); - - const menu = ActionRowBuilder.from((await generateUserPanel(client, targetUser)).components[0]); - menu.components[0].options.find(opt => opt.data.value === 'reviews').data.default = true; - - const paginationRow = buildPaginationRow( - `staff-mgmt_panel-rev_${targetUser.id}_${page - 1}`, - 'panel_rev_count', - `staff-mgmt_panel-rev_${targetUser.id}_${page + 1}`, - page, totalPages - ); - - return { - embeds: [embed.toJSON()], - components: [menu.toJSON(), paginationRow.toJSON()] - }; -} - -// Status page -async function generatePanelStatus(client, targetUser, page = 1) { - const LoaRequest = client.models['staff-management-system']['LoaRequest']; - const allStatuses = await LoaRequest.findAll({ - where: {userId: targetUser.id} - }); - const count = allStatuses.length; - - let totalPages = 1; - if (count > 3) totalPages = 1 + Math.ceil((count - 3) / 5); - const limit = page === 1 - ? 3 - : 5; - const offset = page === 1 - ? 0 - : 3 + ((page - 2) * 5); - - const activeStatus = allStatuses.find(s => ['APPROVED', 'PENDING'].includes(s.status) && new Date(s.endDate) > new Date()); - let activeText = localize('staff-management-system', 'info-none'); - if (activeStatus) { - activeText = `**${activeStatus.type}** (${activeStatus.status})\n${localize('staff-management-system', 'label-end')}: ${dateToDiscordTimestamp(activeStatus.endDate, 'R')}`; - } - - const embed = applyFooter(client, new EmbedBuilder() - .setTitle(localize('staff-management-system', 'p-sta-title', { - username: targetUser.username - })) - .setColor('Green') - .setThumbnail(targetUser.displayAvatarURL({ dynamic: true })) - ); - - let desc = localize('staff-management-system', 'p-sta-desc', { - count: count, active: activeText - }); - - const rows = await LoaRequest.findAll({ - where: {userId: targetUser.id}, - order: [['createdAt', 'DESC']], - limit, - offset - }); - if (rows.length === 0) desc += localize('staff-management-system', 'p-no-hist'); - else { - const icons = { - APPROVED: '✅', - DENIED: '❌', - ENDED: 'âšī¸', - PENDING: '🕐' - }; - desc += rows.map(r => `**${icons[r.status] || '❓'} ${r.type} - ${r.status}**\n**${localize('staff-management-system', 'general-start')}:** ${dateToDiscordTimestamp(r.startDate, 'D')}\n**${localize('staff-management-system', 'general-end')}:** ${dateToDiscordTimestamp(r.endDate, 'D')}\n**${localize('staff-management-system', 'general-rsn')}:** ${r.reason}`).join('\n\n'); - } - - embed.setDescription(desc); - embed.addFields({ - name: '\u200b', - value: localize('staff-management-system', 'page-count', { - page, - total: totalPages - }) - }); - - const menu = ActionRowBuilder.from((await generateUserPanel(client, targetUser)).components[0]); - menu.components[0].options.find(opt => opt.data.value === 'status').data.default = true; - - const paginationRow = buildPaginationRow( - `staff-mgmt_panel-stat_${targetUser.id}_${page - 1}`, - 'panel_stat_count', - `staff-mgmt_panel-stat_${targetUser.id}_${page + 1}`, - page, totalPages - ); - - return { - embeds: [embed.toJSON()], - components: [menu.toJSON(), paginationRow.toJSON()] - }; -} - -// Activity checks page -async function generatePanelActivity(client, targetUser, page = 1) { - const ActivityCheck = client.models['staff-management-system']['ActivityCheck']; - const ActivityCheckResponse = client.models['staff-management-system']['ActivityCheckResponse']; - - const cutoff = new Date(); - cutoff.setDate(cutoff.getDate() - 90); - - const recentChecks = await ActivityCheck.findAll({ - where: { - createdAt: { [Op.gte]: cutoff } - }, - order: [['createdAt', 'DESC']] - }); - - if (recentChecks.length === 0) { - const embed = applyFooter(client, new EmbedBuilder() - .setTitle(localize('staff-management-system', 'p-act-title', { - username: targetUser.username - })) - .setColor('Blue') - .setThumbnail(targetUser.displayAvatarURL({ dynamic: true })) - .setDescription(localize('staff-management-system', 'p-act-desc', { count: 0 }) + localize('staff-management-system', 'p-no-hist')) - ); - - const menu = ActionRowBuilder.from((await generateUserPanel(client, targetUser)).components[0]); - menu.components[0].options.find(opt => opt.data.value === 'activity').data.default = true; - - return { - embeds: [embed.toJSON()], - components: [menu.toJSON()] - }; - } - - const checkIds = recentChecks.map(check => check.id); - const responses = await ActivityCheckResponse.findAll({ - where: { - activityCheckId: { [Op.in]: checkIds }, - userId: targetUser.id - }, - attributes: ['activityCheckId'] - }); - - const respondedCheckIds = new Set(responses.map(response => response.activityCheckId)); - const historyRows = recentChecks.filter(check => respondedCheckIds.has(check.id)); - - const count = historyRows.length; - let totalPages = 1; - if (count > 3) totalPages = 1 + Math.ceil((count - 3) / 5); - const limit = page === 1 - ? 3 - : 5; - const offset = page === 1 - ? 0 - : 3 + ((page - 2) * 5); - const paginatedRows = historyRows.slice(offset, offset + limit); - - const embed = applyFooter(client, new EmbedBuilder() - .setTitle(localize('staff-management-system', 'p-act-title', { - username: targetUser.username - })) - .setColor('Blue') - .setThumbnail(targetUser.displayAvatarURL({ dynamic: true })) - ); - - let desc = localize('staff-management-system', 'p-act-desc', { count }); - - if (paginatedRows.length === 0) { - desc += localize('staff-management-system', 'p-no-hist'); - } else { - desc += paginatedRows.map(r => - `**${localize('staff-management-system', 'label-chk')} ${dateToDiscordTimestamp(r.createdAt, 'D')}**\n` + - `**${localize('staff-management-system', 'label-end')}:** ${dateToDiscordTimestamp(r.endTime, 'F')}\n` + - `**${localize('staff-management-system', 'label-chan')}:** <#${r.channelId}>` - ).join('\n\n'); - } - - embed.setDescription(desc); - embed.addFields({ - name: '\u200b', - value: localize('staff-management-system', 'page-count', { page, total: totalPages }) - }); - - const menu = ActionRowBuilder.from((await generateUserPanel(client, targetUser)).components[0]); - menu.components[0].options.find(opt => opt.data.value === 'activity').data.default = true; - - const paginationRow = buildPaginationRow( - `staff-mgmt_panel-act_${targetUser.id}_${page - 1}`, - 'panel_act_count', - `staff-mgmt_panel-act_${targetUser.id}_${page + 1}`, - page, - totalPages - ); - - return { - embeds: [embed.toJSON()], - components: [menu.toJSON(), paginationRow.toJSON()] - }; -} - -// Shifts page -async function generatePanelShifts(client, targetUser) { - const embed = applyFooter(client, new EmbedBuilder() - .setTitle(localize('staff-management-system', 'p-shi-title', { - username: targetUser.username - })) - .setColor('Purple') - .setThumbnail(targetUser.displayAvatarURL({ dynamic: true })) - ); - - try { - const Shift = client.models['staff-management-system']['StaffShift']; - const config = getConfig(client, 'shifts') || {}; - const shifts = await Shift.findAll({ - where: { - userId: targetUser.id, - endTime: {[Op.not]: null}, - duration: {[Op.not]: null} - } - }); - - const totalShifts = shifts.length; - const totalSeconds = shifts.reduce((sum, s) => sum + (parseInt(s.duration) || 0), 0); - - const breakdown = {}; - shifts.forEach(log => { - const t = log.type || 'Staff'; - breakdown[t] = (breakdown[t] || 0) + (parseInt(log.duration) || 0); - }); - const breakdownStr = Object.entries(breakdown).sort((a, b) => b[1] - a[1]).map(([type, sec]) => `â€ĸ ${type}: ${formatDuration(sec)}`).join('\n') || localize('staff-management-system', 'info-none'); - - let quotaStr = localize('staff-management-system', 'no-quota-configured'); - const guild = client.guilds.cache.get(client.guildID); - const member = await guild?.members.fetch(targetUser.id).catch(() => null); - - if (member && config.enableQuotas && config.quotas) { - let bestQuota = null; - let highestPosition = -1; - for (const [roleId, hoursStr] of Object.entries(config.quotas)) { - const hours = parseFloat(hoursStr); - const role = guild.roles.cache.get(roleId); - if (role && member.roles.cache.has(roleId) && role.position > highestPosition) { - highestPosition = role.position; - bestQuota = { hours }; - } - } - - if (bestQuota) { - const timeframe = config.quotaTimeframe || 'Weekly'; - const cutoff = new Date(); - if (timeframe === 'Weekly') cutoff.setDate(cutoff.getDate() - 7); - else cutoff.setMonth(cutoff.getMonth() - 1); - - const recentShifts = await Shift.findAll({ - where: { - userId: targetUser.id, - startTime: {[Op.gt]: cutoff}, - endTime: {[Op.not]: null}, - duration: {[Op.not]: null} - } - }); - const recentSeconds = recentShifts.reduce((sum, s) => sum + (parseInt(s.duration) || 0), 0); - const requiredSeconds = bestQuota.hours * 3600; - const isMet = recentSeconds >= requiredSeconds; - - quotaStr = localize('staff-management-system', 'duty-quota-str', { - timeframe, - duration: formatDuration(recentSeconds), - hours: bestQuota.hours, - result: isMet - ? localize('staff-management-system', 'duty-quota-met') - : localize('staff-management-system', 'duty-quota-failed') - }); - } - } - - const allResults = await Shift.findAll({ - attributes: ['userId', [Shift.sequelize.fn('SUM', Shift.sequelize.col('duration')), 'totalDuration']], - where: { endTime: { [Op.not]: null }, duration: { [Op.not]: null } }, - group: ['userId'], - order: [[Shift.sequelize.literal('totalDuration'), 'DESC']] - }); - - const lbIndex = allResults.findIndex(p => p.userId === targetUser.id); - const lbRank = lbIndex !== -1 - ? `${lbIndex + 1} / ${allResults.length}` - : localize('staff-management-system', 'label-unranked'); - - embed.setDescription(localize('staff-management-system', 'panel-shifts-desc', { - totalShifts, - totalSeconds: formatDuration(totalSeconds), - lbRank, - breakdownStr, - quotaStr - })); - - } catch (e) { - client.logger.error(`[Staff Management] User panel error: ${e.stack}`); - embed.setDescription(localize('staff-management-system', 'err-shift-data-unavailable', { error: e.message })); - } - - const menu = ActionRowBuilder.from((await generateUserPanel(client, targetUser)).components[0]); - menu.components[0].options.find(opt => opt.data.value === 'shifts').data.default = true; - - const historyBtnRow = new ActionRowBuilder().addComponents( - new ButtonBuilder() - .setCustomId(`duty-mgmt_hist_${targetUser.id}_1_All`) - .setLabel(localize('staff-management-system', 'btn-view-history')) - .setStyle(ButtonStyle.Secondary) - ); - - return { - embeds: [embed.toJSON()], - components: [menu.toJSON(), historyBtnRow.toJSON()] - }; -} - -// Deletion page -async function generatePanelDeletion(client, targetUser) { - const embed = applyFooter(client, new EmbedBuilder() - .setTitle(localize('staff-management-system', 'panel-deletion-title', { tag: targetUser.username })) - .setDescription(localize('staff-management-system', 'panel-deletion-desc', { mention: targetUser.toString() })) - .setColor('DarkRed') - .setThumbnail(targetUser.displayAvatarURL({ dynamic: true })) - ); - - const menu = new StringSelectMenuBuilder() - .setCustomId(`staff-mgmt_delete-menu_${targetUser.id}`) - .setPlaceholder(localize('staff-management-system', 'panel-deletion-placeholder')) - .addOptions( - new StringSelectMenuOptionBuilder() - .setLabel(localize('staff-management-system', 'panel-opt-back')) - .setValue('back') - .setEmoji('â—€ī¸'), - new StringSelectMenuOptionBuilder() - .setLabel(localize('staff-management-system', 'panel-opt-del-act')) - .setValue('del_activity') - .setEmoji('📋'), - new StringSelectMenuOptionBuilder() - .setLabel(localize('staff-management-system', 'panel-opt-del-inf')) - .setValue('del_infractions') - .setEmoji('âš ī¸'), - new StringSelectMenuOptionBuilder() - .setLabel(localize('staff-management-system', 'panel-opt-del-prom')) - .setValue('del_promotions') - .setEmoji('🎉'), - new StringSelectMenuOptionBuilder() - .setLabel(localize('staff-management-system', 'panel-opt-del-rev')) - .setValue('del_reviews') - .setEmoji('⭐'), - new StringSelectMenuOptionBuilder() - .setLabel(localize('staff-management-system', 'panel-opt-del-shifts')) - .setValue('del_shifts') - .setEmoji('âąī¸'), - new StringSelectMenuOptionBuilder() - .setLabel(localize('staff-management-system', 'panel-opt-del-status')) - .setValue('del_status') - .setEmoji('🌙'), - new StringSelectMenuOptionBuilder() - .setLabel(localize('staff-management-system', 'panel-opt-del-all')) - .setValue('del_all') - .setEmoji('đŸ’Ĩ') - ); - - return { - embeds: [embed.toJSON()], - components: [new ActionRowBuilder().addComponents(menu).toJSON()] - }; -} - -async function executeDataDeletion(client, targetId, dataType) { - const models = client.models['staff-management-system']; - - if (['del_infractions', 'del_all'].includes(dataType)) { - await models.Infraction.destroy({ - where: { userId: targetId } - }); - } - - if (['del_promotions', 'del_all'].includes(dataType)) { - await models.Promotion.destroy({ - where: { userId: targetId } - }); - } - - if (['del_reviews', 'del_all'].includes(dataType)) { - await models.StaffReview.destroy({ - where: { targetId } - }); - } - - const profileUpdates = {}; - if (['del_shifts', 'del_all'].includes(dataType)) { - profileUpdates.onDuty = false; - profileUpdates.onBreak = false; - profileUpdates.breakStartTime = null; - profileUpdates.lastClockIn = null; - } - - if (['del_status', 'del_all'].includes(dataType)) { - profileUpdates.activityStatus = null; - } - - if (dataType === 'del_all') { - profileUpdates.customNickname = null; - profileUpdates.customIntro = null; - profileUpdates.isSuspended = false; - profileUpdates.suspendedRoles = null; - } - - if (Object.keys(profileUpdates).length > 0) { - const profile = await models.StaffProfile.findByPk(targetId); - if (profile) await profile.update(profileUpdates); - } - - if (['del_activity', 'del_all'].includes(dataType)) { - await models.ActivityCheckResponse.destroy({ - where: { userId: targetId } - }); - } -} - -// ---------- Activity Checks ---------- -async function startActivityCheck(client, interactionOrChannel, isAutomated = false) { - const config = getConfig(client, 'activity-checks'); - const ActivityCheck = client.models['staff-management-system']['ActivityCheck']; - - if (await ActivityCheck.findOne({ - where: {status: 'ACTIVE'} - })) { - return !isAutomated && interactionOrChannel.editReply - ? interactionOrChannel.editReply({content: localize('staff-management-system', 'err-ac-act')}) - : null; - } - - let rolesToCheck = config.targetRoles?.length - ? config.targetRoles - : (getConfig(client, 'configuration')?.staffRoles || []); - if (!rolesToCheck.length) return !isAutomated && interactionOrChannel.editReply - ? interactionOrChannel.editReply({ - content: localize('staff-management-system', 'err-ac-norole') - }) - : null; - - const targetChannel = isAutomated - ? interactionOrChannel - : (interactionOrChannel.options.getChannel('channel') || interactionOrChannel.guild.channels.cache.get(getSafeChannelId(config.sendingChannel)) || interactionOrChannel.channel); - if (!targetChannel) return !isAutomated && interactionOrChannel.editReply - ? interactionOrChannel.editReply({ - content: localize('staff-management-system', 'err-ac-invchan') - }) - : null; - - const durationHours = config.timeframe || 24; - const endTime = new Date(Date.now() + durationHours * 60 * 60 * 1000); - const generalConfig = getConfig(client, 'configuration') || {}; - const initiator = isAutomated - ? localize('staff-management-system', 'label-system') - : interactionOrChannel.user.toString(); - - const responseButtonRow = new ActionRowBuilder() - .addComponents( - new ButtonBuilder() - .setCustomId('staff-mgmt_ac-respond') - .setLabel(localize('staff-management-system', 'ac-confirm-btn')) - .setStyle(ButtonStyle.Success) - .setEmoji('✅') - ) - .toJSON(); - - let msgOpts = await embedTypeV2(config.checkMessage, { - '%end-time%': dateToDiscordTimestamp(endTime, 'F'), - '%duration%': durationHours.toString(), - '%staff-mention%': formatRoleMentions(generalConfig.staffRoles), - '%supervisor-mention%': formatRoleMentions(generalConfig.supervisorRoles), - '%management-mention%': formatRoleMentions(generalConfig.managementRoles), - '%initiator%': initiator - }, { - components: [responseButtonRow] - }); - - if (msgOpts?.content?.trim() === '') delete msgOpts.content; - - try { - const checkMessage = await targetChannel.send(msgOpts); - if (!isAutomated && interactionOrChannel.editReply) await interactionOrChannel.editReply({ - content: localize('staff-management-system', 'succ-ac-start', { - channel: targetChannel.id, - hours: durationHours - }) - }); - - const record = await ActivityCheck.create({ - messageId: checkMessage.id, - channelId: targetChannel.id, - endTime, - targetRoles: JSON.stringify(rolesToCheck), - status: 'ACTIVE', - initiatorId: isAutomated ? null : interactionOrChannel.user.id, - isAutomated - }); - schedule.scheduleJob(endTime, async () => { - const currentCheck = await ActivityCheck.findByPk(record.id); - if (currentCheck && currentCheck.status === 'ACTIVE') await endActivityCheckProcess(client, currentCheck); - }); - } catch (e) { - if (!isAutomated && interactionOrChannel.editReply) interactionOrChannel.editReply({ - content: localize('staff-management-system', 'err-ac-perms', {channel: targetChannel.id}) - }); - } -} - -async function endActivityCheckProcess(client, activeCheck) { - await activeCheck.update({ status: 'ENDED' }); - const guild = client.guilds.cache.get(client.guildID); - if (!guild) return; - - const config = getConfig(client, 'activity-checks'); - const logChannel = guild.channels.cache.get(getSafeChannelId(config.logChannel) || getSafeChannelId(getConfig(client, 'configuration')?.generalLogChannel)); - if (!logChannel) return; - - const targetRoles = JSON.parse(activeCheck.targetRoles || '[]'); - const ActivityCheckResponse = client.models['staff-management-system']['ActivityCheckResponse']; - const responses = await ActivityCheckResponse.findAll({ - where: { activityCheckId: activeCheck.id }, - attributes: ['userId'] - }); - - const respondedUserIds = new Set(responses.map(response => response.userId)); - const StaffProfile = client.models['staff-management-system']['StaffProfile']; - const expectedMembers = guild.members.cache.filter(m => !m.user.bot && m.roles.cache.some(r => targetRoles.includes(r.id))); - const [responded, exceptions, failed] = [[], [], []]; - const expectedIds = [...expectedMembers.keys()]; - const profiles = await StaffProfile.findAll({ - where: { - userId: {[Op.in]: expectedIds} - } - }); - const initiator = (activeCheck.isAutomated || !activeCheck.initiatorId) - ? localize('staff-management-system', 'label-system') - : `<@${activeCheck.initiatorId}>`; - - expectedMembers.forEach(member => { - if (respondedUserIds.has(member.id)) return responded.push(member); - - let isException = false; - const prof = profiles.find(p => p.userId === member.id); - const isLoa = prof?.activityStatus === 'LOA'; - const isRa = prof?.activityStatus === 'RA'; - - if (config.exceptionsType === 'Only LoA' && isLoa) isException = true; - else if (config.exceptionsType === 'Only RA' && isRa) isException = true; - else if (config.exceptionsType === 'LoA and RA' && (isLoa || isRa)) isException = true; - else if (config.exceptionsType === 'Custom role(s)' && member.roles.cache.some(r => config.customExceptionRoles?.includes(r.id))) isException = true; - - isException - ? exceptions.push(member) - : failed.push(member); - }); - - try { - const msg = await guild.channels.cache.get(activeCheck.channelId)?.messages.fetch(activeCheck.messageId); - if (msg) { - const endTemplate = config.endCheckMessage; - const endedMessage = await embedTypeV2( - endTemplate, - { - '%end-time%': dateToDiscordTimestamp(new Date(), 'F'), - '%duration%': (config.timeframe || 24).toString(), - '%staff-mention%': formatRoleMentions(config.staffRoles), - '%supervisor-mention%': formatRoleMentions(config.supervisorRoles), - '%management-mention%': formatRoleMentions(config.managementRoles), - '%initiator%': initiator, - '%responded-count%': responded.length.toString() - }, - { - components: [] - } - ); - - if (endedMessage?.content?.trim() === '') { - delete endedMessage.content; - } - - await msg.edit(endedMessage); - } - } catch (e) { - } - - const embed = applyFooter(client, new EmbedBuilder() - .setTitle(localize('staff-management-system', 'ac-res-title')) - .setColor('Blurple') - .addFields( - { - name: localize('staff-management-system', 'ac-f-res', { - count: responded.length } - ), - value: responded.length - ? responded.map(m => `<@${m.id}>`).join(', ').substring(0, 1024) - : localize('staff-management-system', 'info-none') - }, - { - name: localize('staff-management-system', 'ac-f-fail', { - count: failed.length - }), - value: failed.length - ? failed.map(m => `<@${m.id}>`).join(', ').substring(0, 1024) - : localize('staff-management-system', 'info-none') - }, - { - name: localize('staff-management-system', 'ac-f-exc', { - count: exceptions.length - }), - value: exceptions.length - ? exceptions.map(m => `<@${m.id}>`).join(', ').substring(0, 1024) - : localize('staff-management-system', 'info-none') - } - ) - ); - - const pingText = (config.pingResults && config.pingRoles?.length) - ? config.pingRoles.map(rId => `<@&${rId}>`).join(' ') - : null; - const finalMessage = { embeds: [embed.toJSON()] }; - if (pingText) finalMessage.content = pingText; - - await logChannel.send(finalMessage).catch((e) => { - client.logger.error(localize('staff-management-system', 'log-ac-send-fail', { - error: e.message - })); -}); -} - -function getIsoWeekNumber(date = new Date()) { - const tmp = new Date(Date.UTC(date.getFullYear(), date.getMonth(), date.getDate())); - const day = tmp.getUTCDay() || 7; - - tmp.setUTCDate(tmp.getUTCDate() + 4 - day); - - const yearStart = new Date(Date.UTC(tmp.getUTCFullYear(), 0, 1)); - return Math.ceil((((tmp - yearStart) / 86400000) + 1) / 7); -} - -function initActivityCheckAutomation(client) { - const config = getConfig(client, 'activity-checks'); - if (!config?.enableActivityChecks || !config?.automatedChecks) return; - - let cronString = config.automatedCheckInterval === 'Cronjob' - ? config.automatedCheckCronjob - : null; - if (!cronString) { - const dayMap = { - 'Monday': 1, - 'Tuesday': 2, - 'Wednesday': 3, - 'Thursday': 4, - 'Friday': 5, - 'Saturday': 6, - 'Sunday': 7 - }[config.automatedCheckWeekDay] || 1; - if (['Weekly', 'Biweekly'].includes(config.automatedCheckInterval)) cronString = `0 12 * * ${dayMap}`; - else if (config.automatedCheckInterval === 'Monthly') { - const startDay = [1, 8, 15, 22][(config.automatedCheckMonthWeek || 1) - 1]; - cronString = `0 12 ${startDay}-${startDay + 6} * ${dayMap}`; - } - } - if (!cronString) return; - - const jobName = 'automated-activity-check'; - const existingJob = schedule.scheduledJobs[jobName]; - if (existingJob) existingJob.cancel(); - schedule.scheduleJob(jobName, cronString, async () => { - if (config.automatedCheckInterval === 'Biweekly' && getIsoWeekNumber(new Date()) % 2 !== 0) { - return; - } - - const channel = client.guilds.cache.get(client.guildID)?.channels.cache.get(getSafeChannelId(config.sendingChannel)); - if (channel) { - client.logger.info(`[Activity Checks] Starting automated check.`); - await startActivityCheck(client, channel, true); - } - }); -} - -// ---------- Reviews ---------- -async function submitReview(client, interaction, targetUser, stars, comment) { - await interaction.deferReply({ephemeral: true}); - const config = getConfig(client, 'reviews'); - if (!config?.enableReviews) return interaction.editReply({ - content: localize('staff-management-system', 'err-feat-disabled', { - feature: 'Reviews' - }) - }); - - const targetMember = await interaction.guild.members.fetch(targetUser.id).catch(() => null); - if (!targetMember) return interaction.editReply({ - content: localize('staff-management-system', 'err-not-mem') - }); - if (!config.allowSelfRating && targetUser.id === interaction.user.id) return interaction.editReply({ - content: localize('staff-management-system', 'err-self-rate') - }); - - if (config.onlyAllowStaffReview !== false) { - const generalConfig = getConfig(client, 'configuration') || {}; - const staffRoles = Array.isArray(generalConfig.staffRoles) - ? generalConfig.staffRoles - : (generalConfig.staffRoles ? [generalConfig.staffRoles] : []); - - const hasStaffRole = staffRoles.length > 0 && targetMember.roles.cache.some(role => - staffRoles.includes(role.id) - ); - - if (!hasStaffRole) { - return interaction.editReply({ - content: localize('staff-management-system', 'err-staff-rate') - }); - } - } - - const review = await client.models['staff-management-system']['StaffReview'].create({ - targetId: targetUser.id, - authorId: interaction.user.id, - stars, - comment - }); - const channelId = getSafeChannelId(config.reviewLogChannel); - - if (channelId) { - const channel = interaction.guild.channels.cache.get(channelId); - if (channel) { - let msgOpts = await embedTypeV2(config.ratingMessage, { - '%staff-mention%': targetUser.toString(), - '%reviewer-mention%': interaction.user.toString(), - '%stars%': '⭐'.repeat(stars), - '%rating%': stars.toString(), - '%comment%': comment, - '%staff-avatar%': targetUser.displayAvatarURL({dynamic: true}), - '%reviewer-avatar%': interaction.user.displayAvatarURL({dynamic: true}) - }); - if (msgOpts?.content?.trim() === '') delete msgOpts.content; - const sentMessage = await channel.send(msgOpts).catch(()=>{}); - if (sentMessage) await review.update({ messageUrl: sentMessage.url }); - } - } - await interaction.editReply({ - content: localize('staff-management-system', 'succ-review', { - tag: targetUser.tag, - stars - }) - }); -} - -async function generateReviewHistoryResponse(client, targetUser, page = 1) { - if (!getConfig(client, 'reviews')?.enableReviews) return { - content: localize('staff-management-system', 'err-feat-disabled', { - feature: 'Reviews' - }), - flags: MessageFlags.Ephemeral - }; - - const limit = 8; - const offset = (page - 1) * limit; - const Review = client.models['staff-management-system']['StaffReview']; - - const {count, rows} = await Review.findAndCountAll({ - where: {targetId: targetUser.id}, - order: [['createdAt', 'DESC']], - limit, - offset - }); - const allReviews = await Review.findAll({ - where: {targetId: targetUser.id}, - attributes: ['stars'] - }); - const avg = allReviews.length - ? (allReviews.reduce((a, b) => a + b.stars, 0) / allReviews.length).toFixed(1) - : 0; - - const embed = applyFooter(client, new EmbedBuilder() - .setTitle(localize('staff-management-system', 'rev-title', { username: targetUser.username })) - .setColor('Gold') - .setDescription(localize('staff-management-system', 'rev-desc', { avg, count: allReviews.length })) - .setThumbnail(targetUser.displayAvatarURL({ dynamic: true })) - ); - - embed.addFields({ - name: localize('staff-management-system', 'label-hist'), - value: rows.length > 0 - ? rows.map(r => `**${"⭐".repeat(r.stars)}** ${localize('staff-management-system', 'label-by')} <@${r.authorId}>${r.messageUrl - ? ` â€ĸ [Jump](${r.messageUrl})` - : ''}\n"${r.comment}"`).join('\n\n') - : localize('staff-management-system', 'p-no-hist') }); - - const row = buildPaginationRow( - `staff-mgmt_rev-page_${targetUser.id}_${page - 1}`, - 'page_count_disabled', - `staff-mgmt_rev-page_${targetUser.id}_${page + 1}`, - page, - Math.ceil(count / limit) || 1 - ); - return { - embeds: [embed.toJSON()], - components: [row.toJSON()] - }; -} - -async function getReviewHistory(client, interaction, targetUser) { - await interaction.deferReply({ephemeral: true}); - const response = await generateReviewHistoryResponse(client, targetUser, 1); - if (response.content && response.content.startsWith('❌')) return interaction.editReply(response); - - await interaction.editReply({ - ...response - }); -} - -module.exports = { - getConfig, - getSafeChannelId, - parseDurationToDays, - applyFooter, - checkStaffPermissions, - buildPaginationRow, - formatDuration, - issueInfraction, - issueSuspension, - getInfractionHistory, - voidInfraction, - generateInfractionHistoryResponse, - promoteUser, - generatePromotionHistoryResponse, - getPromotionHistory, - generateUserPanel, - generatePanelInfractions, - generatePanelPromotions, - generatePanelActivity, - generatePanelReviews, - generatePanelStatus, - generatePanelShifts, - generatePanelDeletion, - executeDataDeletion, - generatePanelSubpage, - startActivityCheck, - initActivityCheckAutomation, - endActivityCheckProcess, - submitReview, - getReviewHistory, - generateReviewHistoryResponse, - getIsoWeekNumber -}; diff --git a/tests/staff-management-system/activityChecks.test.js b/tests/staff-management-system/activityChecks.test.js index 1b8f939e..3816d78e 100644 --- a/tests/staff-management-system/activityChecks.test.js +++ b/tests/staff-management-system/activityChecks.test.js @@ -31,7 +31,7 @@ jest.mock('node-schedule', () => ({ })); const schedule = require('node-schedule'); -const mgmt = require('../../modules/staff-management-system/staff-management'); +const mgmt = require('../../modules/staff-management-system/core/activityChecks'); function modelStub(methods = {}) { return { diff --git a/tests/staff-management-system/commandWiring.test.js b/tests/staff-management-system/commandWiring.test.js index 72ca37eb..e70fdca0 100644 --- a/tests/staff-management-system/commandWiring.test.js +++ b/tests/staff-management-system/commandWiring.test.js @@ -15,27 +15,59 @@ * command layer's plumbing. */ -jest.mock('../../modules/staff-management-system/staff-management', () => ({ +const mockLocalHelpers = { getConfig: (client, file) => client.configurations['staff-management-system'][file], applyFooter: (client, embed) => embed, - checkStaffPermissions: jest.fn(() => true), + checkStaffPermissions: jest.fn(() => true) +}; + +const mockInfractions = { issueInfraction: jest.fn().mockResolvedValue(), issueSuspension: jest.fn().mockResolvedValue(), voidInfraction: jest.fn().mockResolvedValue(), - getInfractionHistory: jest.fn().mockResolvedValue(), + getInfractionHistory: jest.fn().mockResolvedValue() +}; + +const mockPromotions = { promoteUser: jest.fn().mockResolvedValue(), - getPromotionHistory: jest.fn().mockResolvedValue(), + getPromotionHistory: jest.fn().mockResolvedValue() +}; + +const mockPanels = { generateUserPanel: jest.fn().mockResolvedValue({ embeds: [], components: [] - }), + }) +}; + +const { canManageChecks } = jest.requireActual('../../modules/staff-management-system/core/activityChecks'); + +const mockActivityChecks = { + canManageChecks, startActivityCheck: jest.fn().mockResolvedValue(), - endActivityCheckProcess: jest.fn().mockResolvedValue(), + endActivityCheckProcess: jest.fn().mockResolvedValue() +}; + +const mockReviews = { submitReview: jest.fn().mockResolvedValue(), getReviewHistory: jest.fn().mockResolvedValue() -})); +}; + +jest.mock('../../modules/staff-management-system/core/localHelpers', () => mockLocalHelpers); +jest.mock('../../modules/staff-management-system/core/infractions', () => mockInfractions); +jest.mock('../../modules/staff-management-system/core/promotions', () => mockPromotions); +jest.mock('../../modules/staff-management-system/core/panels', () => mockPanels); +jest.mock('../../modules/staff-management-system/core/activityChecks', () => mockActivityChecks); +jest.mock('../../modules/staff-management-system/core/reviews', () => mockReviews); -const mgmt = require('../../modules/staff-management-system/staff-management'); +const mgmt = { + ...mockLocalHelpers, + ...mockInfractions, + ...mockPromotions, + ...mockPanels, + ...mockActivityChecks, + ...mockReviews +}; const cmd = require('../../modules/staff-management-system/commands/staff-management'); function makeInteraction(opts = {}) { diff --git a/tests/staff-management-system/contextCommands.test.js b/tests/staff-management-system/contextCommands.test.js index bbefa473..bace53b9 100644 --- a/tests/staff-management-system/contextCommands.test.js +++ b/tests/staff-management-system/contextCommands.test.js @@ -14,11 +14,17 @@ const mockPromoteUser = jest.fn().mockResolvedValue('promo'); const mockSubmitReview = jest.fn().mockResolvedValue('rev'); const mockState = {supervisor: true}; -jest.mock('../../modules/staff-management-system/staff-management', () => ({ +jest.mock('../../modules/staff-management-system/core/localHelpers', () => ({ getConfig: (client, file) => (client.configurations['staff-management-system'][file]), - checkStaffPermissions: () => mockState.supervisor, - issueInfraction: mockIssueInfraction, - promoteUser: mockPromoteUser, + checkStaffPermissions: () => mockState.supervisor +})); +jest.mock('../../modules/staff-management-system/core/infractions', () => ({ + issueInfraction: mockIssueInfraction +})); +jest.mock('../../modules/staff-management-system/core/promotions', () => ({ + promoteUser: mockPromoteUser +})); +jest.mock('../../modules/staff-management-system/core/reviews', () => ({ submitReview: mockSubmitReview })); diff --git a/tests/staff-management-system/helpers.test.js b/tests/staff-management-system/helpers.test.js index 656b46d2..370775fd 100644 --- a/tests/staff-management-system/helpers.test.js +++ b/tests/staff-management-system/helpers.test.js @@ -1,6 +1,6 @@ /* * Pure-logic tests for the staff-management-system helper functions exported - * from staff-management.js: + * from core/localHelpers.js: * - checkStaffPermissions(): admin shortcut, per-level role gating * (staff/supervisor/management), and the no-member / no-roles defaults * - parseDurationToDays(): parses "5d"/"2w"/"3m" duration strings to days, @@ -19,7 +19,7 @@ const { getSafeChannelId, formatDuration, getIsoWeekNumber -} = require('../../modules/staff-management-system/staff-management'); +} = require('../../modules/staff-management-system/core/localHelpers'); function member(roleIds, {admin = false} = {}) { return { diff --git a/tests/staff-management-system/issueActions.test.js b/tests/staff-management-system/issueActions.test.js index 7e21f0fc..8516fa74 100644 --- a/tests/staff-management-system/issueActions.test.js +++ b/tests/staff-management-system/issueActions.test.js @@ -26,7 +26,10 @@ jest.mock('../../src/functions/helpers', () => ({ dateToDiscordTimestamp: jest.fn(() => '') })); -const mgmt = require('../../modules/staff-management-system/staff-management'); +const mgmt = { + ...require('../../modules/staff-management-system/core/infractions'), + ...require('../../modules/staff-management-system/core/promotions') +}; function modelStub(methods = {}) { return { diff --git a/tests/staff-management-system/managementLogic.test.js b/tests/staff-management-system/managementLogic.test.js index e630757f..98865bcc 100644 --- a/tests/staff-management-system/managementLogic.test.js +++ b/tests/staff-management-system/managementLogic.test.js @@ -29,7 +29,12 @@ jest.mock('../../src/functions/helpers', () => ({ formatDiscordUserName: (u) => (u && u.tag) || 'user' })); -const mgmt = require('../../modules/staff-management-system/staff-management'); +const mgmt = { + ...require('../../modules/staff-management-system/core/infractions'), + ...require('../../modules/staff-management-system/core/promotions'), + ...require('../../modules/staff-management-system/core/reviews'), + ...require('../../modules/staff-management-system/core/panels') +}; function makeUser(overrides = {}) { return {