Skip to content

Commit

Permalink
feat(reset): send weekly statistics on resend command
Browse files Browse the repository at this point in the history
Merge pull request #8 from xmnlz/fix/event-pause
  • Loading branch information
xmnlz authored Dec 9, 2023
2 parents 5803940 + c9332c3 commit 6801b6d
Show file tree
Hide file tree
Showing 2 changed files with 98 additions and 18 deletions.
2 changes: 1 addition & 1 deletion src/commands/eventsmode/panel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -209,7 +209,7 @@ export class Command {
template: `$1 $2 ивент $3`,
replaceArgs: [
userWithNameAndId(ctx.user),
!isPaused ? 'снял с паузы' : 'поставил на паузу',
!isPaused ? 'поставил на паузу' : 'снял с паузы',
event.category + ' | ' + event.name,
],
}),
Expand Down
114 changes: 97 additions & 17 deletions src/commands/moderator/reset.ts
Original file line number Diff line number Diff line change
@@ -1,25 +1,23 @@
import {
ActionRowBuilder,
bold,
ButtonBuilder,
ButtonComponentData,
ButtonInteraction,
ButtonStyle,
CommandInteraction,
MessageActionRowComponentBuilder,
ModalBuilder,
ModalSubmitInteraction,
StringSelectMenuBuilder,
TextInputBuilder,
TextInputStyle,
} from 'discord.js';
import { codeBlock, CommandInteraction, EmbedBuilder, Snowflake } from 'discord.js';
import { Discord, Guard, Slash } from 'discordx';
import moment from 'moment-timezone';
import { injectable } from 'tsyringe';
import { EventHistory } from '../../feature/event/event-history/event-history.entity.js';
import { Eventsmode } from '../../feature/eventsmode/eventsmode.entity.js';
import { EventsmodeService } from '../../feature/eventsmode/eventsmode.service.js';
import { LoggerService } from '../../feature/guild/guild-logger.service.js';
import { ModeratorGuard } from '../../guards/moderator.guard.js';
import { Colors } from '../../lib/constants.js';
import { embedResponse } from '../../lib/embed-response.js';
import { userWithNameAndId } from '../../lib/log-formatter.js';
import { CommandError } from '../../lib/errors/command.error.js';
import { humanizeMinutes } from '../../lib/humanize-duration.js';
import {
interpolate,
specialWeekInterval,
userWithMentionAndId,
userWithNameAndId,
} from '../../lib/log-formatter.js';
import { chunks } from '../../lib/pagination.js';

@Discord()
@injectable()
Expand All @@ -31,6 +29,8 @@ export class Command {
) {}
@Slash({ description: 'Reset weekly statistics' })
async reset(ctx: CommandInteraction<'cached'>) {
await ctx.deferReply();

await this.eventsmodeService.resetWeekly(ctx.guild.id);

await this.loggerService.log({
Expand All @@ -42,6 +42,86 @@ export class Command {
}),
});

await ctx.reply({ content: 'Недельная статистика была успешно сброшенна! ', ephemeral: true });
const rawTopWeekUser = await Eventsmode.query(
`
SELECT user_id, top FROM (
SELECT user_id, is_hired, RANK() OVER (ORDER BY weekly_time DESC) as top
FROM public.eventsmode) AS x
WHERE is_hired = TRUE
LIMIT 1`,
);

const [startOfTheWeek, endOfTheWeek] = specialWeekInterval();

const title = `${moment(startOfTheWeek).format('dddd, MMMM Do, h:mm:ss a')} - ${moment(
endOfTheWeek,
).format('dddd, MMMM Do, h:mm:ss a')}`;

const topWeekUserId: string = rawTopWeekUser[0].user_id;

const eventsmode: {
userId: Snowflake;
weeklyTime: number;
weeklySalary: number;
eventCount: number;
}[] = await EventHistory.query(
`
SELECT eventsmode.user_id as "userId",
eventsmode.weekly_time as "weeklyTime",
eventsmode.weekly_salary as "weeklySalary",
count(*) as "eventCount"
FROM public.event_history
LEFT JOIN guild ON event_history.guild_id = guild.id
LEFT JOIN eventsmode ON event_history.eventsmode_id = eventsmode.id
WHERE event_history.guild_id = $1 AND started_at BETWEEN $2 AND $3
GROUP BY eventsmode.user_id, eventsmode.weekly_time, eventsmode.weekly_salary
ORDER BY eventsmode.weekly_time DESC, COUNT(*) DESC
`,
[ctx.guild.id, startOfTheWeek, endOfTheWeek],
);

if (!eventsmode.length) {
throw new CommandError({
ctx,
content: embedResponse({
template: `Статистика пуста.`,
replaceArgs: [],
ephemeral: true,
status: Colors.DANGER,
}),
});
}

const generalStatistics = `Топ 1 за неделю: ${userWithMentionAndId(topWeekUserId)}`;

const textChunks = chunks(
eventsmode.map(({ userId, weeklyTime, weeklySalary, eventCount }, index) =>
interpolate(
`${index + 1}. $1 - Недельная Зарплата: $2, Время за неделю: $3, Количество ивентов: $4`,
[
userWithMentionAndId(userId),
weeklyTime.toString(),
humanizeMinutes(weeklySalary),
eventCount.toString(),
],
),
),
35,
);

const embeds = textChunks.map((textArray) => {
const embed = new EmbedBuilder();
embed.setColor(Colors.INFO);
embed.setDescription(codeBlock(title) + generalStatistics + `\n${textArray.join('\n')}`);
return embed;
});

await this.loggerService.log({
guildId: ctx.guild.id,
bot: ctx.client,
message: { embeds },
});

await ctx.editReply({ content: 'Недельная статистика была успешно сброшенна! ' });
}
}

0 comments on commit 6801b6d

Please sign in to comment.