|
| 1 | +import type { DB } from "~/db.server"; |
| 2 | +import db from "~/db.server"; |
| 3 | + |
| 4 | +type MessageStats = DB["message_stats"]; |
| 5 | + |
| 6 | +export async function getTopParticipants( |
| 7 | + guildId: MessageStats["guild_id"], |
| 8 | + intervalStart: string, |
| 9 | + intervalEnd: string, |
| 10 | + channels: string[], |
| 11 | + channelCategories: string[], |
| 12 | +) { |
| 13 | + const config = { |
| 14 | + count: 100, |
| 15 | + messageThreshold: 250, |
| 16 | + wordThreshold: 2200, |
| 17 | + }; |
| 18 | + |
| 19 | + const baseQuery = db |
| 20 | + .selectFrom("message_stats") |
| 21 | + .selectAll() |
| 22 | + .select(({ fn, val, eb }) => [ |
| 23 | + fn("date", [eb("sent_at", "/", "1000"), val("unixepoch")]).as("date"), |
| 24 | + ]) |
| 25 | + .where(({ between, and, or, eb }) => |
| 26 | + and([ |
| 27 | + between( |
| 28 | + "sent_at", |
| 29 | + new Date(intervalStart).getTime().toString(), |
| 30 | + new Date(intervalEnd).getTime().toString(), |
| 31 | + ), |
| 32 | + or([ |
| 33 | + eb("channel_id", "in", channels), |
| 34 | + eb("channel_category", "in", channelCategories), |
| 35 | + ]), |
| 36 | + ]), |
| 37 | + ); |
| 38 | + |
| 39 | + // get shortlist, volume threshold of 1000 words |
| 40 | + const topMembersQuery = db |
| 41 | + .with("interval_message_stats", () => baseQuery) |
| 42 | + .selectFrom("interval_message_stats") |
| 43 | + .select(({ fn }) => [ |
| 44 | + "author_id", |
| 45 | + fn.sum<number>("word_count").as("total_word_count"), |
| 46 | + fn.count<number>("author_id").as("message_count"), |
| 47 | + fn.sum<number>("react_count").as("total_reaction_count"), |
| 48 | + fn.count<number>("channel_category").distinct().as("category_count"), |
| 49 | + fn.count<number>("channel_id").distinct().as("channel_count"), |
| 50 | + ]) |
| 51 | + .orderBy("message_count desc") |
| 52 | + .groupBy("author_id") |
| 53 | + .having(({ eb, or, fn }) => |
| 54 | + or([ |
| 55 | + eb(fn.count("author_id"), ">=", config.messageThreshold), |
| 56 | + eb(fn.sum("word_count"), ">=", config.wordThreshold), |
| 57 | + ]), |
| 58 | + ) |
| 59 | + .limit(config.count); |
| 60 | + console.log(topMembersQuery.compile().sql); |
| 61 | + const topMembers = await topMembersQuery.execute(); |
| 62 | + |
| 63 | + const dailyParticipationQuery = db |
| 64 | + .with("interval_message_stats", () => baseQuery) |
| 65 | + .selectFrom("interval_message_stats") |
| 66 | + .select(({ fn }) => [ |
| 67 | + "author_id", |
| 68 | + "date", |
| 69 | + fn.count<number>("author_id").as("message_count"), |
| 70 | + fn.sum<number>("word_count").as("word_count"), |
| 71 | + fn.count<number>("channel_id").distinct().as("channel_count"), |
| 72 | + fn.count<number>("channel_category").distinct().as("category_count"), |
| 73 | + ]) |
| 74 | + .distinct() |
| 75 | + .groupBy("date") |
| 76 | + .groupBy("author_id") |
| 77 | + .where( |
| 78 | + "author_id", |
| 79 | + "in", |
| 80 | + topMembers.map((m) => m.author_id), |
| 81 | + ); |
| 82 | + console.log(dailyParticipationQuery.compile().sql); |
| 83 | + const dailyParticipation = fillDateGaps( |
| 84 | + groupByAuthor(await dailyParticipationQuery.execute()), |
| 85 | + intervalStart, |
| 86 | + intervalEnd, |
| 87 | + ); |
| 88 | + |
| 89 | + return topMembers.map((m) => scoreMember(m, dailyParticipation[m.author_id])); |
| 90 | +} |
| 91 | + |
| 92 | +// copy-pasted out of TopMembers query result |
| 93 | +type MemberData = { |
| 94 | + author_id: string; |
| 95 | + total_word_count: number; |
| 96 | + message_count: number; |
| 97 | + total_reaction_count: number; |
| 98 | + category_count: number; |
| 99 | + channel_count: number; |
| 100 | +}; |
| 101 | +function isBetween(test: number, a: number, b: number) { |
| 102 | + return test >= a && test < b; |
| 103 | +} |
| 104 | +function scoreValue(test: number, lookup: [number, number][], x?: string) { |
| 105 | + return lookup.reduce((score, _, i, list) => { |
| 106 | + const check = isBetween( |
| 107 | + test, |
| 108 | + list[i][0] ?? Infinity, |
| 109 | + list[i + 1]?.[0] ?? Infinity, |
| 110 | + ); |
| 111 | + if (check && x) |
| 112 | + console.log( |
| 113 | + test, |
| 114 | + "is between", |
| 115 | + list[i][0], |
| 116 | + "and", |
| 117 | + list[i + 1]?.[0] ?? Infinity, |
| 118 | + "scoring", |
| 119 | + list[i][1], |
| 120 | + ); |
| 121 | + return check ? list[i][1] : score; |
| 122 | + }, 0); |
| 123 | +} |
| 124 | +function median(list: number[]) { |
| 125 | + const mid = list.length / 2; |
| 126 | + return list.length % 2 === 1 |
| 127 | + ? (list[Math.floor(mid)] + list[Math.ceil(mid)]) / 2 |
| 128 | + : list[mid]; |
| 129 | +} |
| 130 | +const scoreLookups = { |
| 131 | + words: [ |
| 132 | + [0, 0], |
| 133 | + [2000, 1], |
| 134 | + [5000, 2], |
| 135 | + [7500, 3], |
| 136 | + [20000, 4], |
| 137 | + ], |
| 138 | + messages: [ |
| 139 | + [0, 0], |
| 140 | + [150, 1], |
| 141 | + [350, 2], |
| 142 | + [800, 3], |
| 143 | + [1500, 4], |
| 144 | + ], |
| 145 | + channels: [ |
| 146 | + [0, 0], |
| 147 | + [3, 1], |
| 148 | + [7, 2], |
| 149 | + [9, 3], |
| 150 | + ], |
| 151 | +} as Record<string, [number, number][]>; |
| 152 | +function scoreMember(member: MemberData, participation: ParticipationData[]) { |
| 153 | + return { |
| 154 | + score: { |
| 155 | + channelScore: scoreValue(member.channel_count, scoreLookups.channels), |
| 156 | + messageScore: scoreValue(member.message_count, scoreLookups.messages), |
| 157 | + wordScore: scoreValue( |
| 158 | + member.total_word_count, |
| 159 | + scoreLookups.words, |
| 160 | + "words", |
| 161 | + ), |
| 162 | + consistencyScore: Math.ceil( |
| 163 | + median(participation.map((p) => p.category_count)), |
| 164 | + ), |
| 165 | + }, |
| 166 | + metadata: { |
| 167 | + percentZeroDays: |
| 168 | + participation.reduce( |
| 169 | + (count, val) => (val.message_count === 0 ? count + 1 : count), |
| 170 | + 0, |
| 171 | + ) / participation.length, |
| 172 | + }, |
| 173 | + data: { |
| 174 | + participation, |
| 175 | + member, |
| 176 | + }, |
| 177 | + }; |
| 178 | +} |
| 179 | + |
| 180 | +type RawParticipationData = { |
| 181 | + author_id: string; |
| 182 | + // hack fix for weird types coming out of query |
| 183 | + date: string | unknown; |
| 184 | + message_count: number; |
| 185 | + word_count: number; |
| 186 | + channel_count: number; |
| 187 | + category_count: number; |
| 188 | +}; |
| 189 | + |
| 190 | +type ParticipationData = { |
| 191 | + date: string; |
| 192 | + message_count: number; |
| 193 | + word_count: number; |
| 194 | + channel_count: number; |
| 195 | + category_count: number; |
| 196 | +}; |
| 197 | + |
| 198 | +type GroupedResult = Record<string, ParticipationData[]>; |
| 199 | + |
| 200 | +function groupByAuthor(records: RawParticipationData[]): GroupedResult { |
| 201 | + return records.reduce((acc, record) => { |
| 202 | + const { author_id, date } = record; |
| 203 | + |
| 204 | + if (!acc[author_id]) { |
| 205 | + acc[author_id] = []; |
| 206 | + } |
| 207 | + |
| 208 | + // hack fix for weird types coming out of query |
| 209 | + acc[author_id].push({ ...record, date: date as string }); |
| 210 | + |
| 211 | + return acc; |
| 212 | + }, {} as GroupedResult); |
| 213 | +} |
| 214 | + |
| 215 | +const generateDateRange = (start: string, end: string): string[] => { |
| 216 | + const dates: string[] = []; |
| 217 | + let currentDate = new Date(start); |
| 218 | + |
| 219 | + while (currentDate <= new Date(end)) { |
| 220 | + dates.push(currentDate.toISOString().split("T")[0]); |
| 221 | + currentDate.setDate(currentDate.getDate() + 1); |
| 222 | + } |
| 223 | + return dates; |
| 224 | +}; |
| 225 | + |
| 226 | +function fillDateGaps( |
| 227 | + groupedResult: GroupedResult, |
| 228 | + startDate: string, |
| 229 | + endDate: string, |
| 230 | +): GroupedResult { |
| 231 | + // Helper to generate a date range in YYYY-MM-DD format |
| 232 | + |
| 233 | + const dateRange = generateDateRange(startDate, endDate); |
| 234 | + |
| 235 | + const filledResult: GroupedResult = {}; |
| 236 | + |
| 237 | + for (const authorId in groupedResult) { |
| 238 | + const authorData = groupedResult[authorId]; |
| 239 | + const dateToEntryMap: Record<string, typeof authorData[number]> = {}; |
| 240 | + |
| 241 | + // Map existing entries by date |
| 242 | + authorData.forEach((entry) => { |
| 243 | + dateToEntryMap[entry.date] = entry; |
| 244 | + }); |
| 245 | + |
| 246 | + // Fill missing dates with zeroed-out data |
| 247 | + filledResult[authorId] = dateRange.map((date) => { |
| 248 | + return ( |
| 249 | + dateToEntryMap[date] || { |
| 250 | + date, |
| 251 | + message_count: 0, |
| 252 | + word_count: 0, |
| 253 | + channel_count: 0, |
| 254 | + category_count: 0, |
| 255 | + } |
| 256 | + ); |
| 257 | + }); |
| 258 | + } |
| 259 | + |
| 260 | + return filledResult; |
| 261 | +} |
0 commit comments