Compare commits

..
2 Commits
12 changed files with 109 additions and 68 deletions

No files matched your search

@@ -222,7 +222,9 @@ describe('CommunityStatsService', () => {
const setDetail = jest.fn();
const service = new CommunityStatsService(
{
getModel: async () => ({ exists: () => ({ exec: async () => null }) }),
getModel: async () => ({
exists: () => ({ exec: async () => null }),
}),
} as unknown as ConnectionService,
{
get: async () => null,
@@ -649,9 +649,8 @@ export class CommunityStatsService {
if (retryAt <= now) this.rawRecoveryRetryAfter.delete(field);
}
if (this.rawRecoveryRetryAfter.size >= 1000) {
this.rawRecoveryRetryAfter.delete(
this.rawRecoveryRetryAfter.keys().next().value!,
);
const oldest = this.rawRecoveryRetryAfter.keys().next();
if (!oldest.done) this.rawRecoveryRetryAfter.delete(oldest.value);
}
this.rawRecoveryRetryAfter.set(
key.field,
@@ -40,7 +40,10 @@ export const MATCH_STATUSES: MatchStatus[] = [
'finished',
];
export const MATCH_EVENT_TYPES = ['inhouse', 'tournament'] as const satisfies readonly MatchEventType[];
export const MATCH_EVENT_TYPES = [
'inhouse',
'tournament',
] as const satisfies readonly MatchEventType[];
export type TeamSide = 'blue' | 'red';
export const TEAM_SIDES: TeamSide[] = ['blue', 'red'];
@@ -2554,7 +2557,10 @@ MatchStatsSchema.index({
MatchStatsSchema.index({ communityId: 1, userIds: 1 });
MatchStatsSchema.index({ communityId: 1, userIds: 1, scheduledAt: -1 });
MatchStatsSchema.index({ communityId: 1, championIds: 1 });
MatchStatsSchema.index(MATCH_STATS_RIOT_MATCH_INDEX.key, MATCH_STATS_RIOT_MATCH_INDEX.options);
MatchStatsSchema.index(
MATCH_STATS_RIOT_MATCH_INDEX.key,
MATCH_STATS_RIOT_MATCH_INDEX.options,
);
export const tournamentModelDefinitions: Array<
ModelDefinition & { name: keyof TournamentModelTypes }
@@ -3,7 +3,11 @@ import { BadRequestException, ValidationPipe } from '@nestjs/common';
import { plainToInstance } from 'class-transformer';
import { validateSync } from 'class-validator';
import mongoose from 'mongoose';
import { CreateMatchDto, JoinMatchDto, UpdateMatchDto } from './create-match.dto';
import {
CreateMatchDto,
JoinMatchDto,
UpdateMatchDto,
} from './create-match.dto';
describe('CreateMatchDto game mode cutover', () => {
it('rejects the removed live bracket mode', () => {
@@ -75,7 +79,9 @@ describe('Grand final format validation', () => {
doubleEliminationGrandFinalGameCount: 2,
});
expect(validateSync(update)).toEqual([
expect.objectContaining({ property: 'doubleEliminationGrandFinalGameCount' }),
expect.objectContaining({
property: 'doubleEliminationGrandFinalGameCount',
}),
]);
});
});
@@ -93,16 +99,19 @@ describe('Match event type validation', () => {
}),
),
).toEqual([]);
expect(validateSync(plainToInstance(UpdateMatchDto, { eventType }))).toEqual(
[],
);
expect(
validateSync(plainToInstance(UpdateMatchDto, { eventType })),
).toEqual([]);
},
);
it.each(['double-elimination', null])('rejects %s as an event type', (eventType) => {
const dto = plainToInstance(UpdateMatchDto, { eventType });
expect(validateSync(dto)).toEqual([
expect.objectContaining({ property: 'eventType' }),
]);
});
it.each(['double-elimination', null])(
'rejects %s as an event type',
(eventType) => {
const dto = plainToInstance(UpdateMatchDto, { eventType });
expect(validateSync(dto)).toEqual([
expect.objectContaining({ property: 'eventType' }),
]);
},
);
});
@@ -26,7 +26,10 @@ interface PublicMatchSource {
gameCount: number;
gameMode: MatchGameMode;
roundRobinMaxRounds?: number;
doubleElimination?: { resetFinalEnabled?: boolean; grandFinalGameCount?: 1 | 3 | 5 };
doubleElimination?: {
resetFinalEnabled?: boolean;
grandFinalGameCount?: 1 | 3 | 5;
};
hostUserId?: IdLike;
participants: Array<{
userId: IdLike;
@@ -69,7 +69,12 @@ describe('MatchController partial updates', () => {
const controller = new MatchController(matchService as never);
const body = plainToInstance(UpdateMatchDto, { eventType: 'tournament' });
await controller.updateMatch(user as UserDocument, communityId, matchId, body);
await controller.updateMatch(
user as UserDocument,
communityId,
matchId,
body,
);
expect(matchService.update).toHaveBeenCalledWith({
communityId,
+2 -42
View File
@@ -6,11 +6,10 @@ import {
Route,
Routes,
useLocation,
useNavigate,
} from "react-router";
import { useState, type FormEvent, type ReactNode } from "react";
import type { ReactNode } from "react";
import { useMsal } from "@azure/msal-react";
import { LogOut, Moon, Search, Sun } from "lucide-react";
import { LogOut, Moon, Sun } from "lucide-react";
import DevAuthSwitcher from "./components/DevAuthSwitcher";
import { DEFAULT_COMMUNITY_ID, setTheme, useTheme } from "./config";
import { useCommunity, useMatch, useMe } from "./api/hooks";
@@ -123,44 +122,6 @@ function PrimaryNavLink({
);
}
/** 선수 이름으로 전적 순위표를 바로 찾는 머리글 검색. */
function HeaderPlayerSearch() {
const navigate = useNavigate();
const [value, setValue] = useState("");
function handleSubmit(event: FormEvent<HTMLFormElement>) {
event.preventDefault();
const query = value.trim();
if (!query) return;
const params = new URLSearchParams({ view: "ranking", q: query });
void navigate(
`/communities/${DEFAULT_COMMUNITY_ID}/internal-stats?${params.toString()}`,
);
setValue("");
}
return (
<form
role="search"
onSubmit={handleSubmit}
className="relative hidden w-56 min-w-0 md:block lg:w-72"
>
<Search
className="pointer-events-none absolute left-3.5 top-1/2 size-[18px] -translate-y-1/2 text-content-subtle"
aria-hidden="true"
/>
<input
type="search"
value={value}
onChange={(event) => setValue(event.target.value)}
placeholder="선수 이름 검색"
aria-label="선수 이름으로 전적 검색"
className="h-11 w-full rounded-full border border-line-strong bg-sunken pr-4 pl-10 text-[15px] text-content placeholder:text-content-muted focus-visible:bg-card focus-visible:placeholder:text-content-subtle"
/>
</form>
);
}
function AppHeader() {
const { pathname } = useLocation();
const matchId = matchPath("/match/:id/*", pathname)?.params.id;
@@ -192,7 +153,6 @@ function AppHeader() {
</span>
</Link>
<div className="contents sm:col-start-3 sm:row-start-1 sm:flex sm:min-w-0 sm:items-center sm:justify-end sm:gap-1 lg:gap-2">
{DEFAULT_COMMUNITY_ID && <HeaderPlayerSearch />}
<div className="col-start-1 row-start-1 justify-self-start sm:shrink-0">
<ThemeToggle />
</div>
+1
View File
@@ -652,6 +652,7 @@ export interface ApiInternalMatchListResponse {
export interface ApiLeaderboardRow {
userId: string;
summonerName: string;
tagLine?: string;
profileIconId: number;
games: number;
wins: number;
@@ -38,6 +38,25 @@ export function sortLeaderboardRows<
);
}
/** 검색 ID가 없는 API 응답도 표시된 선수 이름과 Riot ID로 검색할 수 있다. */
export function filterLeaderboardRows<
T extends Pick<ApiLeaderboardRow, 'userId' | 'summonerName' | 'tagLine'>,
>(rows: readonly T[], query: string, matchedUserIds?: readonly string[]): T[] {
const keyword = query.trim().toLocaleLowerCase('ko-KR');
if (!keyword) return [...rows];
if (matchedUserIds !== undefined) {
const matchedUsers = new Set(matchedUserIds);
return rows.filter((row) => matchedUsers.has(row.userId));
}
return rows.filter(({ summonerName, tagLine }) =>
(tagLine ? `${summonerName}#${tagLine}` : summonerName)
.toLocaleLowerCase('ko-KR')
.includes(keyword),
);
}
/**
* 한 라인만의 순위표. 그 라인 기록이 있는 선수만 남기고 전적을 라인 전적으로
* 바꾼 뒤 승률 순으로 놓는다. 최소 판수도 그 라인 판수로 따진다.
@@ -21,6 +21,7 @@ import {
profileIconUrl,
} from '../lib/ddragon';
import {
filterLeaderboardRows,
formatOfficialMatchResult,
getMainLane,
LEADERBOARD_MIN_GAMES,
@@ -474,13 +475,12 @@ export default function CommunityInternalStatsPage() {
sort,
);
const player = leaderboardRows.find((row) => row.userId === playerId);
const matchedUsers = leaderboardQuery.data?.matchedUserIds;
const visiblePlayers = isRanking && keyword
? leaderboardRows.filter((row) => matchedUsers?.includes(row.userId))
const visiblePlayers = isRanking
? filterLeaderboardRows(leaderboardRows, keyword, leaderboardQuery.data?.matchedUserIds)
: leaderboardRows;
const hasMatchFilters = Boolean(keyword || format || playerId);
const confirmedSideWinRate = insights?.sideWinRate.confirmed;
const title = isRanking ? '선수 순위' : '최근 내전';
const title = isRanking ? '선수 전적·순위' : '최근 내전';
if (!communityId) {
return (
@@ -562,7 +562,7 @@ export default function CommunityInternalStatsPage() {
selected={isRanking}
onClick={() => updateParam('view', 'ranking')}
>
선수 순위
선수 전적·순위
</Chip>
</div>
<label className="flex h-10 w-full items-center gap-2 rounded-full border border-line-strong bg-card px-3 text-content-muted focus-within:border-content-muted sm:w-60">
+2 -2
View File
@@ -651,9 +651,9 @@ function RankingPreview({ statsPath }: { statsPath: string }) {
actions={
<Link
to={`${statsPath}?view=ranking`}
className="inline-flex items-center gap-0.5 text-[13px] font-semibold text-content-muted hover:text-content hover:underline"
className="inline-flex items-center gap-0.5 whitespace-nowrap text-[13px] font-semibold text-content-muted hover:text-content hover:underline"
>
전체 보기
선수 전적·순위 보기
<ChevronRight className="size-4" aria-hidden="true" />
</Link>
}
@@ -1,6 +1,7 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import {
filterLeaderboardRows,
formatOfficialMatchResult,
getMainLane,
parseLeaderboardSort,
@@ -38,6 +39,42 @@ test('ranks small samples after players with enough games', () => {
]);
});
const searchablePlayers = [
{ userId: 'jang', summonerName: '장금순' },
{ userId: 'queen', summonerName: 'Choco Queen', tagLine: 'KR1' },
{ userId: 'jang2', summonerName: '장금순 팬', tagLine: 'KR2' },
];
test('finds displayed players when the API omits search match IDs', () => {
assert.deepEqual(filterLeaderboardRows(searchablePlayers, ' 장금순 '), [
searchablePlayers[0],
searchablePlayers[2],
]);
assert.deepEqual(filterLeaderboardRows(searchablePlayers, '없는 선수'), []);
assert.equal(searchablePlayers.length, 3);
});
test('searches names and available Riot tags without case sensitivity', () => {
assert.deepEqual(filterLeaderboardRows(searchablePlayers, 'choco queen#kr1'), [
searchablePlayers[1],
]);
assert.deepEqual(filterLeaderboardRows(searchablePlayers, '#kr2'), [
searchablePlayers[2],
]);
});
test('respects server matches including explicit empty results and preserves row order', () => {
assert.deepEqual(filterLeaderboardRows(searchablePlayers, '장금순', []), []);
assert.deepEqual(filterLeaderboardRows(searchablePlayers, '별칭', ['jang2', 'jang']), [
searchablePlayers[0],
searchablePlayers[2],
]);
});
test('clearing search restores all players even with prior match IDs', () => {
assert.deepEqual(filterLeaderboardRows(searchablePlayers, ' ', ['jang']), searchablePlayers);
});
test('ranks one lane by its own win rate and sample size', () => {
const player = (
id: string,