All files / app-leaderboard/src/courses ranking.ts

94.73% Statements 18/19
68.75% Branches 11/16
100% Functions 4/4
100% Lines 17/17

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135                                                                              246x         246x 246x 246x                       11x                                                             11x   11x   11x   13x             13x 13x 13x               11x         109x         109x         121x         121x    
import { and, asc, count, desc, eq, gt, type SQL } from 'drizzle-orm';
import type { RulesetId } from '@be-music/player-engine/replay';
import { avatarURL } from '../avatars.ts';
import type { Database } from '../db/client.ts';
import { courseBestScore, courseScoreResult, profile, user } from '../db/schema.ts';
 
/** A course ranking's filters, as `RankingFilter` for charts. */
export interface CourseRankingFilter {
  courseFingerprint: string;
  ruleset: RulesetId;
  assisted: boolean;
  /** Include anonymous players. Off by default. */
  includeAnonymous: boolean;
  /** Only players who ran the course under this ruleset at least once. */
  playedHereOnly: boolean;
}
 
export interface CourseRankingEntry {
  rank: number;
  handle: string;
  displayName: string;
  anonymous: boolean;
  avatarUrl: string;
  exScore: number;
  exScoreId: string;
  /** The course's judgment notes under the ruleset (the best EX run's), the DJ LEVEL's scale. */
  noteCount: number;
  clearLamp: number;
  missCount: number;
  playCount: number;
  playedHere: boolean;
  achievedAt: number;
  /** The best trophy and the run that earned it. */
  trophy: string | null;
  trophyScoreId: string | null;
}
 
/** The conditions of a course ranking's filters, over `course_best_score` joined to `user`. */
export function courseFilterConditions(filter: CourseRankingFilter): SQL[] {
  const conditions: SQL[] = [
    eq(courseBestScore.courseFingerprint, filter.courseFingerprint),
    eq(courseBestScore.ruleset, filter.ruleset),
    eq(courseBestScore.assisted, filter.assisted),
  ];
  if (!filter.includeAnonymous) conditions.push(eq(user.isAnonymous, false));
  Iif (filter.playedHereOnly) conditions.push(eq(courseBestScore.playedHere, true));
  return conditions;
}
 
/**
 * One page of a course's ranking by best EX score, ranked like a chart's: ties share a rank (1, 1, 3), and within a tie
 * the earlier achievement is listed first.
 */
export async function loadCourseRanking(
  db: Database,
  filter: CourseRankingFilter,
  page: { offset: number; limit: number },
): Promise<{ entries: CourseRankingEntry[]; players: number }> {
  const rowsQuery = db
    .select({
      handle: profile.handle,
      displayName: profile.displayName,
      anonymous: user.isAnonymous,
      avatarKey: profile.avatarKey,
      exScore: courseBestScore.bestEx,
      exScoreId: courseBestScore.bestExScoreId,
      noteCount: courseScoreResult.noteCount,
      clearLamp: courseBestScore.bestLamp,
      missCount: courseBestScore.minMiss,
      playCount: courseBestScore.playCount,
      playedHere: courseBestScore.playedHere,
      achievedAt: courseBestScore.bestExAt,
      trophy: courseBestScore.bestTrophy,
      trophyScoreId: courseBestScore.bestTrophyScoreId,
    })
    .from(courseBestScore)
    .innerJoin(user, eq(user.id, courseBestScore.userId))
    .innerJoin(profile, eq(profile.userId, courseBestScore.userId))
    .innerJoin(
      courseScoreResult,
      and(
        eq(courseScoreResult.courseScoreId, courseBestScore.bestExScoreId),
        eq(courseScoreResult.ruleset, courseBestScore.ruleset),
      ),
    )
    .where(and(...courseFilterConditions(filter)))
    .orderBy(desc(courseBestScore.bestEx), asc(courseBestScore.bestExAt), asc(profile.handle))
    .limit(page.limit)
    .offset(page.offset);
  const [rows, players] = await Promise.all([rowsQuery, countCoursePlayers(db, filter)]);
 
  const entries: CourseRankingEntry[] = [];
  let previous: { exScore: number; rank: number } | undefined;
  for (const [index, row] of rows.entries()) {
    const rank =
      previous !== undefined && previous.exScore === row.exScore
        ? previous.rank
        : index === 0
          ? page.offset === 0
            ? 1
            : await rankOfCourseExScore(db, filter, row.exScore)
          : page.offset + index + 1;
    previous = { exScore: row.exScore, rank };
    const { avatarKey, ...rest } = row;
    entries.push({
      ...rest,
      anonymous: row.anonymous === true,
      avatarUrl: avatarURL(row.handle, avatarKey),
      achievedAt: row.achievedAt.getTime(),
      rank,
    });
  }
  return { entries, players };
}
 
/** Competition rank of a best EX score on a course: one more than the number of players strictly above it. */
export async function rankOfCourseExScore(db: Database, filter: CourseRankingFilter, exScore: number): Promise<number> {
  const [{ above }] = await db
    .select({ above: count() })
    .from(courseBestScore)
    .innerJoin(user, eq(user.id, courseBestScore.userId))
    .where(and(...courseFilterConditions(filter), gt(courseBestScore.bestEx, exScore)));
  return (above ?? 0) + 1;
}
 
/** Number of players in a course ranking. */
export async function countCoursePlayers(db: Database, filter: CourseRankingFilter): Promise<number> {
  const [{ players }] = await db
    .select({ players: count() })
    .from(courseBestScore)
    .innerJoin(user, eq(user.id, courseBestScore.userId))
    .where(and(...courseFilterConditions(filter)));
  return players ?? 0;
}