All files / app-leaderboard/src/scores reassign.ts

100% Statements 6/6
100% Branches 0/0
100% Functions 2/2
100% Lines 5/5

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                            5x         63x 5x 5x 5x    
import { eq } from 'drizzle-orm';
import { refreshPlayedChartListings } from '../charts.ts';
import type { Database } from '../db/client.ts';
import { score } from '../db/schema.ts';
import { reassignCourseScores } from '../courses/bests.ts';
import { rebuildBestScores } from './bests.ts';
 
/**
 * Moves every play (and every course run) of one account to another, rebuilds the receiver's personal bests on the affected charts and lists
 * the charts the receiver now counts towards. Used when a guest is merged into another account (docs/leaderboard.md
 * section 3); the guest account's own best rows go with the account when Better Auth deletes
 * it.
 */
export async function reassignScores(db: Database, fromUserId: string, toUserId: string): Promise<void> {
  const moved = await db
    .update(score)
    .set({ userId: toUserId })
    .where(eq(score.userId, fromUserId))
    .returning({ chartFingerprint: score.chartFingerprint });
  const charts = [...new Set(moved.map((row) => row.chartFingerprint))];
  await rebuildBestScores(db, toUserId, charts, Date.now());
  await refreshPlayedChartListings(db, toUserId);
  await reassignCourseScores(db, fromUserId, toUserId);
}