changes/fixes

master
Matthew 2021-07-08 16:48:19 -04:00
parent f74a0fd07e
commit d7895cb8c7
No known key found for this signature in database
GPG Key ID: 210AF32ADE3B5C4B
4 changed files with 984 additions and 980 deletions

File diff suppressed because it is too large Load Diff

View File

@ -1,185 +1,193 @@
/* eslint-disable no-await-in-loop */
/* eslint-disable no-eval */
import Bull from 'bull';
import cron from 'cron';
import { TextableChannel, TextChannel } from 'eris';
import { Client, RichEmbed } from '.';
import { ScoreInterface, InqType as InquiryType } from '../models';
import { apply as Apply } from '../commands';
export default class Queue {
public client: Client;
public queues: { score: Bull.Queue };
constructor(client: Client) {
this.client = client;
this.queues = {
score: new Bull('score', { prefix: 'queue::score' }),
};
this.setProcessors();
this.setCronJobs();
}
protected setCronJobs() {
const historialCommunityReportJob = new cron.CronJob('0 20 * * *', async () => {
try {
const reports = await this.client.db.Score.find().lean().exec();
const startDate = new Date();
for (const report of reports) {
const inqs = await this.client.db.Inquiry.find({ userID: report.userID });
const data = new this.client.db.ScoreHistorical({
userID: report.userID,
report,
inquiries: inqs.map((inq) => inq._id),
date: startDate,
});
await data.save();
}
} catch (err) {
this.client.util.handleError(err);
}
});
const clearOldHistoricalReportsJob = new cron.CronJob('0 22 * * *', async () => {
this.client.db.ScoreHistorical.remove({ date: { $lt: new Date(Date.now() - 30 * 24 * 60 * 60 * 1000) } });
});
historialCommunityReportJob.start();
clearOldHistoricalReportsJob.start();
}
public async jobCounts() {
const data = {
waiting: 0,
active: 0,
completed: 0,
failed: 0,
delayed: 0,
};
for (const entry of Object.entries(this.queues)) {
// eslint-disable-next-line no-await-in-loop
const counts = await entry[1].getJobCounts();
data.waiting += counts.waiting;
data.active += counts.active;
data.completed += counts.completed;
data.failed += counts.failed;
data.delayed += counts.delayed;
}
return data;
}
protected listeners() {
this.queues.score.on('active', (job) => {
this.client.util.signale.pending(`${job.id} has become active.`);
});
this.queues.score.on('completed', (job) => {
this.client.util.signale.success(`Job with id ${job.id} has been completed`);
});
this.queues.score.on('error', async (err) => {
this.client.util.handleError(err);
});
}
protected setProcessors() {
this.queues.score.process('score::inquiry', async (job: Bull.Job<{ inqID: string, userID: string, name: string, type: InquiryType, reason?: string }>) => {
const member = this.client.util.resolveMember(job.data.userID, this.client.guilds.get(this.client.config.guildID));
const report = await this.client.db.Score.findOne({ userID: job.data.userID }).lean().exec();
const embed = new RichEmbed();
if (job.data.type === InquiryType.HARD) {
embed.setTitle('Inquiry Notification');
embed.setDescription(job.data.inqID);
embed.setColor('#800080');
embed.addField('Member', `${member.user.username}#${member.user.discriminator} | <@${job.data.userID}>`, true);
embed.addField('Type', 'HARD', true);
embed.addField('Department/Service', job.data.name.toUpperCase(), true);
embed.addField('Reason', job.data.reason ?? 'N/A', true);
embed.setTimestamp();
embed.setFooter(this.client.user.username, this.client.user.avatarURL);
if (report.notify === true) {
await this.client.getDMChannel(job.data.userID).then((chan) => {
chan.createMessage(`__**Community Score - Hard Pull Notification**__\n*You have signed up to be notified whenever your hard score has been pulled. See \`?score\` for more information.*\n\n**Department/Service:** ${job.data.name.toUpperCase()}`);
}).catch(() => {});
}
} else {
embed.setTitle('Inquiry Notification');
embed.setColor('#00FFFF');
embed.addField('Member', `${member.user.username}#${member.user.discriminator} | <@${job.data.userID}>`, true);
embed.addField('Type', 'SOFT', true);
embed.addField('Department/Service', job.data.name.toUpperCase(), true);
embed.setTimestamp();
embed.setFooter(this.client.user.username, this.client.user.avatarURL);
}
const log = <TextChannel> this.client.guilds.get(this.client.config.guildID).channels.get('611584771356622849');
log.createMessage({ embed }).catch(() => {});
});
this.queues.score.process('score::update', async (job: Bull.Job<{ score: ScoreInterface, total: number, activity: number, roles: number, moderation: number, cloudServices: number, other: number, staff: number }>) => {
await this.client.db.Score.updateOne({ userID: job.data.score.userID }, { $set: { total: job.data.total, activity: job.data.activity, roles: job.data.roles, moderation: job.data.moderation, cloudServices: job.data.cloudServices, other: job.data.other, staff: job.data.staff, lastUpdate: new Date() } });
if (!job.data.score.pin || job.data.score.pin?.length < 1) {
await this.client.db.Score.updateOne({ userID: job.data.score.userID }, { $set: { pin: [this.client.util.randomNumber(100, 999), this.client.util.randomNumber(10, 99), this.client.util.randomNumber(1000, 9999)] } });
}
});
this.queues.score.process('score::apply', async (job: Bull.Job<{ channelInformation: { messageID: string, guildID: string, channelID: string }, url: string, userID: string, func?: string }>) => {
const application = await Apply.apply(this.client, job.data.url, job.data.userID);
const guild = this.client.guilds.get(job.data.channelInformation.guildID);
const channel = <TextableChannel> guild.channels.get(job.data.channelInformation.channelID);
const message = await channel.getMessage(job.data.channelInformation.messageID);
const member = guild.members.get(job.data.userID);
await message.delete();
const embed = new RichEmbed();
embed.setTitle('Application Decision');
if (member) {
embed.setAuthor(member.username, member.avatarURL);
}
if (application.decision === 'APPROVED') {
embed.setColor('#50c878');
} else if (application.decision === 'DECLINED') {
embed.setColor('#fe0000');
} else if (application.decision === 'PRE-DECLINE') {
embed.setColor('#ffa500');
} else {
embed.setColor('#eeeeee');
}
const chan = await this.client.getDMChannel(job.data.userID);
if (chan) {
let description = `This application was processed by __${application.processedBy}__ on behalf of the vendor, department, or service who operates this application. Please contact the vendor for further information about your application if needed.`;
if (application.token) description += `\n\n*This document provides detailed information about the decision given to you by EDS.*: https://eds.libraryofcode.org/dec/${application.token}`;
embed.setDescription(description);
embed.addField('Status', application.decision, true);
embed.addField('User ID', job.data.userID, true);
embed.addField('Application ID', application.id, true);
embed.addField('Job ID', job.id.toString(), true);
embed.setFooter(`${this.client.user.username} via Electronic Decision Service [EDS]`, this.client.user.avatarURL);
embed.setTimestamp();
try {
await chan.createMessage({ embed });
} catch {
await channel.createMessage('**We were not able to send the decision of your application to your DMs. Please contact the Staff Team for further information.**');
}
await channel.createMessage({ embed: new RichEmbed().setTitle('Application Decision').setDescription('The decision of your application has been sent to your DMs.\n\n*Please view the PDF document for further information regarding the decision. For reconsiderations or questions, please contact us.*').setFooter(`${this.client.user.username} via Electronic Decision Service [EDS]`, this.client.user.avatarURL)
.setTimestamp() });
} else {
await channel.createMessage('**We were not able to send the decision of your application to your DMs. Please contact the Staff Team for further information.**');
}
if (job.data.func) {
const func = eval(job.data.func);
if (application.status === 'SUCCESS' && application.decision === 'APPROVED') await func(this.client, job.data.userID);
}
});
}
public addInquiry(inqID: string, userID: string, name: string, type: InquiryType, reason?: string) {
return this.queues.score.add('score::inquiry', { inqID, userID, name, type, reason });
}
public updateScore(score: ScoreInterface, total: number, activity: number, roles: number, moderation: number, cloudServices: number, other: number, staff: number) {
return this.queues.score.add('score::update', { score, total, activity, roles, moderation, cloudServices, other, staff });
}
public processApplication(channelInformation: { messageID: string, guildID: string, channelID: string }, url: string, userID: string, func?: string) {
return this.queues.score.add('score::apply', { channelInformation, url, userID, func });
}
}
/* eslint-disable no-await-in-loop */
/* eslint-disable no-eval */
import Bull from 'bull';
import cron from 'cron';
import { TextableChannel, TextChannel } from 'eris';
import { Client, RichEmbed } from '.';
import { ScoreInterface, InqType as InquiryType } from '../models';
import { apply as Apply } from '../commands';
export default class Queue {
public client: Client;
public queues: { score: Bull.Queue };
constructor(client: Client) {
this.client = client;
this.queues = {
score: new Bull('score', { prefix: 'queue::score' }),
};
this.setProcessors();
this.setCronJobs();
}
protected setCronJobs() {
const historialCommunityReportJob = new cron.CronJob('0 20 * * *', async () => {
try {
const reports = await this.client.db.Score.find().lean().exec();
const startDate = new Date();
for (const report of reports) {
const inqs = await this.client.db.Inquiry.find({ userID: report.userID });
const data = new this.client.db.ScoreHistorical({
userID: report.userID,
report: {
total: report.total,
activity: report.activity,
roles: report.roles,
moderation: report.moderation,
cloudServices: report.cloudServices,
staff: report.staff,
other: report.other,
},
inquiries: inqs.map((inq) => inq._id),
date: startDate,
});
await data.save();
}
} catch (err) {
this.client.util.handleError(err);
}
});
const clearOldHistoricalReportsJob = new cron.CronJob('0 22 * * *', async () => {
this.client.db.ScoreHistorical.remove({ date: { $lt: new Date(Date.now() - 30 * 24 * 60 * 60 * 1000) } });
});
historialCommunityReportJob.start();
clearOldHistoricalReportsJob.start();
}
public async jobCounts() {
const data = {
waiting: 0,
active: 0,
completed: 0,
failed: 0,
delayed: 0,
};
for (const entry of Object.entries(this.queues)) {
// eslint-disable-next-line no-await-in-loop
const counts = await entry[1].getJobCounts();
data.waiting += counts.waiting;
data.active += counts.active;
data.completed += counts.completed;
data.failed += counts.failed;
data.delayed += counts.delayed;
}
return data;
}
protected listeners() {
this.queues.score.on('active', (job) => {
this.client.util.signale.pending(`${job.id} has become active.`);
});
this.queues.score.on('completed', (job) => {
this.client.util.signale.success(`Job with id ${job.id} has been completed`);
});
this.queues.score.on('error', async (err) => {
this.client.util.handleError(err);
});
}
protected setProcessors() {
this.queues.score.process('score::inquiry', async (job: Bull.Job<{ inqID: string, userID: string, name: string, type: InquiryType, reason?: string }>) => {
const member = this.client.util.resolveMember(job.data.userID, this.client.guilds.get(this.client.config.guildID));
const report = await this.client.db.Score.findOne({ userID: job.data.userID }).lean().exec();
const embed = new RichEmbed();
if (job.data.type === InquiryType.HARD) {
embed.setTitle('Inquiry Notification');
embed.setDescription(job.data.inqID);
embed.setColor('#800080');
embed.addField('Member', `${member.user.username}#${member.user.discriminator} | <@${job.data.userID}>`, true);
embed.addField('Type', 'HARD', true);
embed.addField('Department/Service', job.data.name.toUpperCase(), true);
embed.addField('Reason', job.data.reason ?? 'N/A', true);
embed.setTimestamp();
embed.setFooter(this.client.user.username, this.client.user.avatarURL);
if (report.notify === true) {
await this.client.getDMChannel(job.data.userID).then((chan) => {
chan.createMessage(`__**Community Score - Hard Pull Notification**__\n*You have signed up to be notified whenever your hard score has been pulled. See \`?score\` for more information.*\n\n**Department/Service:** ${job.data.name.toUpperCase()}`);
}).catch(() => {});
}
} else {
embed.setTitle('Inquiry Notification');
embed.setColor('#00FFFF');
embed.addField('Member', `${member.user.username}#${member.user.discriminator} | <@${job.data.userID}>`, true);
embed.addField('Type', 'SOFT', true);
embed.addField('Department/Service', job.data.name.toUpperCase(), true);
embed.setTimestamp();
embed.setFooter(this.client.user.username, this.client.user.avatarURL);
}
const log = <TextChannel> this.client.guilds.get(this.client.config.guildID).channels.get('611584771356622849');
log.createMessage({ embed }).catch(() => {});
});
this.queues.score.process('score::update', async (job: Bull.Job<{ score: ScoreInterface, total: number, activity: number, roles: number, moderation: number, cloudServices: number, other: number, staff: number }>) => {
await this.client.db.Score.updateOne({ userID: job.data.score.userID }, { $set: { total: job.data.total, activity: job.data.activity, roles: job.data.roles, moderation: job.data.moderation, cloudServices: job.data.cloudServices, other: job.data.other, staff: job.data.staff, lastUpdate: new Date() } });
if (!job.data.score.pin || job.data.score.pin?.length < 1) {
await this.client.db.Score.updateOne({ userID: job.data.score.userID }, { $set: { pin: [this.client.util.randomNumber(100, 999), this.client.util.randomNumber(10, 99), this.client.util.randomNumber(1000, 9999)] } });
}
});
this.queues.score.process('score::apply', async (job: Bull.Job<{ channelInformation: { messageID: string, guildID: string, channelID: string }, url: string, userID: string, func?: string }>) => {
const application = await Apply.apply(this.client, job.data.url, job.data.userID);
const guild = this.client.guilds.get(job.data.channelInformation.guildID);
const channel = <TextableChannel> guild.channels.get(job.data.channelInformation.channelID);
const message = await channel.getMessage(job.data.channelInformation.messageID);
const member = guild.members.get(job.data.userID);
await message.delete();
const embed = new RichEmbed();
embed.setTitle('Application Decision');
if (member) {
embed.setAuthor(member.username, member.avatarURL);
}
if (application.decision === 'APPROVED') {
embed.setColor('#50c878');
} else if (application.decision === 'DECLINED') {
embed.setColor('#fe0000');
} else if (application.decision === 'PRE-DECLINE') {
embed.setColor('#ffa500');
} else {
embed.setColor('#eeeeee');
}
const chan = await this.client.getDMChannel(job.data.userID);
if (chan) {
let description = `This application was processed by __${application.processedBy}__ on behalf of the vendor, department, or service who operates this application. Please contact the vendor for further information about your application if needed.`;
if (application.token) description += `\n\n*This document provides detailed information about the decision given to you by EDS.*: https://eds.libraryofcode.org/dec/${application.token}`;
embed.setDescription(description);
embed.addField('Status', application.decision, true);
embed.addField('User ID', job.data.userID, true);
embed.addField('Application ID', application.id, true);
embed.addField('Job ID', job.id.toString(), true);
embed.setFooter(`${this.client.user.username} via Electronic Decision Service [EDS]`, this.client.user.avatarURL);
embed.setTimestamp();
try {
await chan.createMessage({ embed });
} catch {
await channel.createMessage('**We were not able to send the decision of your application to your DMs. Please contact the Staff Team for further information.**');
}
await channel.createMessage({ embed: new RichEmbed().setTitle('Application Decision').setDescription('The decision of your application has been sent to your DMs.\n\n*Please view the PDF document for further information regarding the decision. For reconsiderations or questions, please contact us.*').setFooter(`${this.client.user.username} via Electronic Decision Service [EDS]`, this.client.user.avatarURL)
.setTimestamp() });
} else {
await channel.createMessage('**We were not able to send the decision of your application to your DMs. Please contact the Staff Team for further information.**');
}
if (job.data.func) {
const func = eval(job.data.func);
if (application.status === 'SUCCESS' && application.decision === 'APPROVED') await func(this.client, job.data.userID);
}
});
}
public addInquiry(inqID: string, userID: string, name: string, type: InquiryType, reason?: string) {
return this.queues.score.add('score::inquiry', { inqID, userID, name, type, reason });
}
public updateScore(score: ScoreInterface, total: number, activity: number, roles: number, moderation: number, cloudServices: number, other: number, staff: number) {
return this.queues.score.add('score::update', { score, total, activity, roles, moderation, cloudServices, other, staff });
}
public processApplication(channelInformation: { messageID: string, guildID: string, channelID: string }, url: string, userID: string, func?: string) {
return this.queues.score.add('score::apply', { channelInformation, url, userID, func });
}
}

View File

@ -1,184 +1,185 @@
/* eslint-disable no-await-in-loop */
/* eslint-disable no-continue */
/* eslint-disable default-case */
import moment from 'moment';
import { median, mode, mean } from 'mathjs';
import { createPaginationEmbed } from 'eris-pagination';
import { Message } from 'eris';
import { Client, Command, RichEmbed } from '../class';
import { getTotalMessageCount } from '../intervals/score';
import { InquiryInterface } from '../models';
export default class Score_Hist extends Command {
constructor(client: Client) {
super(client);
this.name = 'hist';
this.description = 'Pulls a Community Report history for a user.';
this.usage = `${this.client.config.prefix}score hist <member>`;
this.permissions = 4;
this.guildOnly = false;
this.enabled = true;
}
public async run(message: Message, args: string[]) {
try {
if (!args[0]) return this.client.commands.get('help').run(message, [this.name]);
let user = this.client.util.resolveMember(args[0], this.mainGuild)?.user;
if (!user) {
const sc = await this.client.db.Score.findOne({ pin: [Number(args[0].split('-')[0]), Number(args[0].split('-')[1]), Number(args[0].split('-')[2])] });
user = this.client.util.resolveMember(sc.userID, this.mainGuild)?.user;
}
if (!user) return this.error(message.channel, 'Member not found.');
const hists = await this.client.db.ScoreHistorical.find({ userID: user.id }).limit(31).lean().exec();
if (!hists) return this.error(message.channel, 'No history found.');
if (hists.length < 1) return this.error(message.channel, 'No history found.');
const histArray: [{ name: string, value: string }?] = [];
const totalArray: number[] = [];
const activityArray: number[] = [];
const moderationArray: number[] = [];
const roleArray: number[] = [];
const cloudServicesArray: number[] = [];
const otherArray: number[] = [];
const miscArray: number[] = [];
for (const hist of hists.reverse()) {
totalArray.push(hist.report.total);
activityArray.push(hist.report.activity);
moderationArray.push(hist.report.moderation);
roleArray.push(hist.report.roles);
cloudServicesArray.push(hist.report.cloudServices);
otherArray.push(hist.report.other);
miscArray.push(hist.report.staff);
let totalScore = '0';
let activityScore = '0';
let moderationScore = '0';
let roleScore = '0';
let cloudServicesScore = '0';
let otherScore = '0';
let miscScore = '0';
if (hist.report.total < 200) totalScore = '---';
else if (hist.report.total > 800) totalScore = '800';
else totalScore = `${hist.report.total}`;
if (hist.report.activity < 10) activityScore = '---';
else if (hist.report.activity > Math.floor((Math.log1p(getTotalMessageCount(this.client)) * 12))) activityScore = String(Math.floor((Math.log1p(getTotalMessageCount(this.client)) * 12)));
else activityScore = `${hist.report.activity}`;
if (hist.report.roles <= 0) roleScore = '---';
else if (hist.report.roles > 54) roleScore = '54';
else roleScore = `${hist.report.roles}`;
moderationScore = `${hist.report.moderation}`;
if (hist.report.other === 0) otherScore = '---';
else otherScore = `${hist.report.other}`;
if (hist.report.staff <= 0) miscScore = '---';
else miscScore = `${hist.report.staff}`;
if (hist.report.cloudServices === 0) cloudServicesScore = '---';
else if (hist.report.cloudServices > 10) cloudServicesScore = '10';
else cloudServicesScore = `${hist.report.cloudServices}`;
let data = '';
let hardInquiries = 0;
const inquiries: InquiryInterface[] = [];
if (hist.inquiries?.length > 0) {
for (const h of hist.inquiries) {
const inq = await this.client.db.Inquiry.findOne({ _id: h });
inquiries.push(inq);
}
}
if (inquiries?.length > 0) {
inquiries.forEach((inq) => {
const testDate = (new Date(new Date(inq.date).setHours(1460)));
// eslint-disable-next-line no-plusplus
if (testDate > new Date()) hardInquiries++;
});
data += `__CommScore™:__ ${totalScore}\n__Activity:__ ${activityScore}\n__Roles:__ ${roleScore}\n__Moderation:__ ${moderationScore}\n__Cloud Services:__ ${cloudServicesScore}\n__Other:__ ${otherScore}\n__Misc:__ ${miscScore}\n\n__Hard Inquiries:__ ${hardInquiries}\n__Soft Inquiries:__ ${hist.report.softInquiries?.length ?? '0'}`;
histArray.push({ name: moment(hist.date).calendar(), value: data });
}
}
const stat = {
totalMean: mean(totalArray),
totalMode: mode(totalArray),
totalMedian: median(totalArray),
activityMean: mean(activityArray),
rolesMean: mean(roleArray),
moderationMean: mean(moderationArray),
cloudServicesMean: mean(cloudServicesArray),
otherMean: mean(otherArray),
miscMean: mean(miscArray),
};
const splitHist = this.client.util.splitFields(histArray);
const cmdPages: RichEmbed[] = [];
splitHist.forEach((split) => {
const embed = new RichEmbed();
embed.setTitle('Historical Community Report');
let totalMean = '0';
let totalMedian = '0';
let totalMode = '0';
let activityMean = '0';
let moderationMean = '0';
let roleMean = '0';
let cloudServicesMean = '0';
let otherMean = '0';
let miscMean = '0';
if (stat.totalMean < 200) totalMean = '---';
else if (stat.totalMean > 800) totalMean = '800';
else totalMean = `${stat.totalMean}`;
if (stat.totalMedian < 200) totalMedian = '---';
else if (stat.totalMedian > 800) totalMedian = '800';
else totalMedian = `${stat.totalMedian}`;
if (stat.totalMode < 200) totalMode = '---';
else if (stat.totalMode > 800) totalMode = '800';
else totalMode = `${stat.totalMode}`;
if (stat.activityMean < 10) activityMean = '---';
else if (stat.activityMean > Math.floor((Math.log1p(getTotalMessageCount(this.client)) * 12))) activityMean = String(Math.floor((Math.log1p(getTotalMessageCount(this.client)) * 12)));
else activityMean = `${stat.activityMean}`;
if (stat.rolesMean <= 0) roleMean = '---';
else if (stat.rolesMean > 54) roleMean = '54';
else roleMean = `${stat.rolesMean}`;
moderationMean = `${stat.moderationMean}`;
if (stat.otherMean === 0) otherMean = '---';
else otherMean = `${stat.otherMean}`;
if (stat.miscMean <= 0) miscMean = '---';
else miscMean = `${stat.miscMean}`;
if (stat.cloudServicesMean === 0) cloudServicesMean = '---';
else if (stat.cloudServicesMean > 10) cloudServicesMean = '10';
else cloudServicesMean = `${stat.cloudServicesMean}`;
embed.setDescription(`__**Statistical Averages**__\n**CommScore™ Mean:** ${totalMean} | **CommScore™ Mode:** ${totalMode} | **CommScore™ Median:** ${totalMedian}\n\n**Activity Mean:** ${activityMean}\n**Roles Mean:** ${roleMean}\n**Moderation Mean:** ${moderationMean}\n**Cloud Services Mean:** ${cloudServicesMean}\n**Other Mean:** ${otherMean}\n**Misc Mean:** ${miscMean}`);
embed.setAuthor(user.username, user.avatarURL);
embed.setThumbnail(user.avatarURL);
embed.setTimestamp();
embed.setFooter(this.client.user.username, this.client.user.avatarURL);
split.forEach((c) => embed.addField(c.name, c.value));
return cmdPages.push(embed);
});
let name = '';
for (const role of this.client.util.resolveMember(message.author.id, this.mainGuild).roles.map((r) => this.mainGuild.roles.get(r)).sort((a, b) => b.position - a.position)) {
name = `Library of Code sp-us | ${role.name} - [HISTORICAL]`;
break;
}
await this.client.report.createInquiry(user.id, name, 1);
if (cmdPages.length === 1) return message.channel.createMessage({ embed: cmdPages[0] });
return createPaginationEmbed(message, cmdPages);
} catch (err) {
return this.client.util.handleError(err, message, this);
}
}
}
/* eslint-disable no-await-in-loop */
/* eslint-disable no-continue */
/* eslint-disable default-case */
import moment from 'moment';
import { median, mode, mean } from 'mathjs';
import { createPaginationEmbed } from 'eris-pagination';
import { Message } from 'eris';
import { Client, Command, RichEmbed } from '../class';
import { getTotalMessageCount } from '../intervals/score';
import { InquiryInterface } from '../models';
export default class Score_Hist extends Command {
constructor(client: Client) {
super(client);
this.name = 'hist';
this.description = 'Pulls a Community Report history for a user.';
this.usage = `${this.client.config.prefix}score hist <member>`;
this.permissions = 4;
this.guildOnly = false;
this.enabled = true;
}
public async run(message: Message, args: string[]) {
try {
if (!args[0]) return this.client.commands.get('help').run(message, [this.name]);
let user = this.client.util.resolveMember(args[0], this.mainGuild)?.user;
if (!user) {
const sc = await this.client.db.Score.findOne({ pin: [Number(args[0].split('-')[0]), Number(args[0].split('-')[1]), Number(args[0].split('-')[2])] });
user = this.client.util.resolveMember(sc.userID, this.mainGuild)?.user;
}
const score = await this.client.db.Score.findOne({ userID: user.id }).lean().exec();
if (!user) return this.error(message.channel, 'Member not found.');
const hists = await this.client.db.ScoreHistorical.find({ userID: user.id }).limit(31).lean().exec();
if (!hists) return this.error(message.channel, 'No history found.');
if (hists.length < 1) return this.error(message.channel, 'No history found.');
const histArray: [{ name: string, value: string }?] = [];
const totalArray: number[] = [];
const activityArray: number[] = [];
const moderationArray: number[] = [];
const roleArray: number[] = [];
const cloudServicesArray: number[] = [];
const otherArray: number[] = [];
const miscArray: number[] = [];
for (const hist of hists.reverse()) {
totalArray.push(hist.report.total);
activityArray.push(hist.report.activity);
moderationArray.push(hist.report.moderation);
roleArray.push(hist.report.roles);
cloudServicesArray.push(hist.report.cloudServices);
otherArray.push(hist.report.other);
miscArray.push(hist.report.staff);
let totalScore = '0';
let activityScore = '0';
let moderationScore = '0';
let roleScore = '0';
let cloudServicesScore = '0';
let otherScore = '0';
let miscScore = '0';
if (hist.report.total < 200) totalScore = '---';
else if (hist.report.total > 800) totalScore = '800';
else totalScore = `${hist.report.total}`;
if (hist.report.activity < 10) activityScore = '---';
else if (hist.report.activity > Math.floor((Math.log1p(getTotalMessageCount(this.client)) * 12))) activityScore = String(Math.floor((Math.log1p(getTotalMessageCount(this.client)) * 12)));
else activityScore = `${hist.report.activity}`;
if (hist.report.roles <= 0) roleScore = '---';
else if (hist.report.roles > 54) roleScore = '54';
else roleScore = `${hist.report.roles}`;
moderationScore = `${hist.report.moderation}`;
if (hist.report.other === 0) otherScore = '---';
else otherScore = `${hist.report.other}`;
if (hist.report.staff <= 0) miscScore = '---';
else miscScore = `${hist.report.staff}`;
if (hist.report.cloudServices === 0) cloudServicesScore = '---';
else if (hist.report.cloudServices > 10) cloudServicesScore = '10';
else cloudServicesScore = `${hist.report.cloudServices}`;
let data = '';
let hardInquiries = 0;
const inquiries: InquiryInterface[] = [];
if (hist.inquiries?.length > 0) {
for (const h of hist.inquiries) {
const inq = await this.client.db.Inquiry.findOne({ _id: h });
inquiries.push(inq);
}
}
if (inquiries?.length > 0) {
inquiries.forEach((inq) => {
const testDate = (new Date(new Date(inq.date).setHours(1460)));
// eslint-disable-next-line no-plusplus
if (testDate > new Date()) hardInquiries++;
});
data += `__CommScore™:__ ${totalScore}\n__Activity:__ ${activityScore}\n__Roles:__ ${roleScore}\n__Moderation:__ ${moderationScore}\n__Cloud Services:__ ${cloudServicesScore}\n__Other:__ ${otherScore}\n__Misc:__ ${miscScore}\n\n__Hard Inquiries:__ ${hardInquiries}\n__Soft Inquiries:__ ${score.softInquiries?.length ?? '0'}`;
histArray.push({ name: moment(hist.date).calendar(), value: data });
}
}
const stat = {
totalMean: mean(totalArray),
totalMode: mode(totalArray),
totalMedian: median(totalArray),
activityMean: mean(activityArray),
rolesMean: mean(roleArray),
moderationMean: mean(moderationArray),
cloudServicesMean: mean(cloudServicesArray),
otherMean: mean(otherArray),
miscMean: mean(miscArray),
};
const splitHist = this.client.util.splitFields(histArray);
const cmdPages: RichEmbed[] = [];
splitHist.forEach((split) => {
const embed = new RichEmbed();
embed.setTitle('Historical Community Report');
let totalMean = '0';
let totalMedian = '0';
let totalMode = '0';
let activityMean = '0';
let moderationMean = '0';
let roleMean = '0';
let cloudServicesMean = '0';
let otherMean = '0';
let miscMean = '0';
if (stat.totalMean < 200) totalMean = '---';
else if (stat.totalMean > 800) totalMean = '800';
else totalMean = `${stat.totalMean}`;
if (stat.totalMedian < 200) totalMedian = '---';
else if (stat.totalMedian > 800) totalMedian = '800';
else totalMedian = `${stat.totalMedian}`;
if (stat.totalMode < 200) totalMode = '---';
else if (stat.totalMode > 800) totalMode = '800';
else totalMode = `${stat.totalMode}`;
if (stat.activityMean < 10) activityMean = '---';
else if (stat.activityMean > Math.floor((Math.log1p(getTotalMessageCount(this.client)) * 12))) activityMean = String(Math.floor((Math.log1p(getTotalMessageCount(this.client)) * 12)));
else activityMean = `${stat.activityMean}`;
if (stat.rolesMean <= 0) roleMean = '---';
else if (stat.rolesMean > 54) roleMean = '54';
else roleMean = `${stat.rolesMean}`;
moderationMean = `${stat.moderationMean}`;
if (stat.otherMean === 0) otherMean = '---';
else otherMean = `${stat.otherMean}`;
if (stat.miscMean <= 0) miscMean = '---';
else miscMean = `${stat.miscMean}`;
if (stat.cloudServicesMean === 0) cloudServicesMean = '---';
else if (stat.cloudServicesMean > 10) cloudServicesMean = '10';
else cloudServicesMean = `${stat.cloudServicesMean}`;
embed.setDescription(`__**Statistical Averages**__\n**CommScore™ Mean:** ${totalMean} | **CommScore™ Mode:** ${totalMode} | **CommScore™ Median:** ${totalMedian}\n\n**Activity Mean:** ${activityMean}\n**Roles Mean:** ${roleMean}\n**Moderation Mean:** ${moderationMean}\n**Cloud Services Mean:** ${cloudServicesMean}\n**Other Mean:** ${otherMean}\n**Misc Mean:** ${miscMean}`);
embed.setAuthor(user.username, user.avatarURL);
embed.setThumbnail(user.avatarURL);
embed.setTimestamp();
embed.setFooter(this.client.user.username, this.client.user.avatarURL);
split.forEach((c) => embed.addField(c.name, c.value));
return cmdPages.push(embed);
});
let name = '';
for (const role of this.client.util.resolveMember(message.author.id, this.mainGuild).roles.map((r) => this.mainGuild.roles.get(r)).sort((a, b) => b.position - a.position)) {
name = `Library of Code sp-us | ${role.name} - [HISTORICAL]`;
break;
}
await this.client.report.createInquiry(user.id, name, 1);
if (cmdPages.length === 1) return message.channel.createMessage({ embed: cmdPages[0] });
return createPaginationEmbed(message, cmdPages);
} catch (err) {
return this.client.util.handleError(err, message, this);
}
}
}